proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/threeD/Camera.java
Camera
getContext
class Camera extends Component { private final Center center; private final Up up; private final Eye eye; private Camera(CameraBuilder builder) { this.eye = builder.eye; this.up = builder.up; this.center = builder.center; } @Override protected Map<String, Object> getContext() {<FILL_FUNCTION_BODY>} @Override public String asJavascript() { return asJavascript("camera_template.html"); } public CameraBuilder cameraBuilder() { return new CameraBuilder(); } public static class CameraBuilder { private Center center; private Up up; private Eye eye; public CameraBuilder xAxis(Center center) { this.center = center; return this; } public CameraBuilder yAxis(Up up) { this.up = up; return this; } public CameraBuilder zAxis(Eye eye) { this.eye = eye; return this; } public Camera build() { return new Camera(this); } } }
Map<String, Object> context = new HashMap<>(); context.put("up", up); context.put("eye", eye); context.put("center", center); return context;
299
54
353
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/threeD/CameraComponent.java
CameraComponent
getContext
class CameraComponent extends Component { private final double x; private final double y; private final double z; CameraComponent(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } @Override public String asJavascript() { return asJSON(); } @Override protected Map<String, Object> getJSONContext() { return getContext(); } @Override protected Map<String, Object> getContext() {<FILL_FUNCTION_BODY>} }
Map<String, Object> context = new HashMap<>(); context.put("x", x); context.put("y", y); context.put("z", z); return context;
156
53
209
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/components/threeD/Scene.java
Scene
asJavascript
class Scene extends Component { private final Axis xAxis; private final Axis yAxis; private final Axis zAxis; private final Camera camera; private Scene(SceneBuilder builder) { this.xAxis = builder.xAxis; this.yAxis = builder.yAxis; this.zAxis = builder.zAxis; this.camera = builder.camera; } protected Map<String, Object> getContext() { Map<String, Object> context = new HashMap<>(); if (xAxis != null) { context.put("xAxis", xAxis); } if (yAxis != null) { context.put("yAxis", yAxis); } if (zAxis != null) { context.put("zAxis", zAxis); } if (camera != null) { context.put("camera", camera); } return context; } public static Scene.SceneBuilder sceneBuilder() { return new Scene.SceneBuilder(); } @Override public String asJavascript() {<FILL_FUNCTION_BODY>} public static class SceneBuilder { private Axis xAxis; private Axis yAxis; private Axis zAxis; private Camera camera; public SceneBuilder xAxis(Axis axis) { this.xAxis = axis; return this; } public SceneBuilder yAxis(Axis axis) { this.yAxis = axis; return this; } public SceneBuilder zAxis(Axis axis) { this.zAxis = axis; return this; } public SceneBuilder camera(Camera camera) { this.camera = camera; return this; } public Scene build() { return new Scene(this); } } }
Writer writer = new StringWriter(); PebbleTemplate compiledTemplate; try { compiledTemplate = getEngine().getTemplate("scene_template.html"); compiledTemplate.evaluate(writer, getContext()); } catch (PebbleException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new UncheckedIOException(e); } return writer.toString();
499
109
608
<methods>public non-sealed void <init>() ,public java.lang.String asJSON() ,public abstract java.lang.String asJavascript() ,public java.lang.String toString() <variables>private final PebbleEngine engine,protected static final ObjectMapper mapper
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/display/Browser.java
Browser
browse
class Browser { public static void main(String[] args) throws Exception { if (Desktop.isDesktopSupported()) { Desktop.getDesktop().browse(new URI("http://www.example.com")); } } public void browse(File file) throws IOException {<FILL_FUNCTION_BODY>} }
if (Desktop.isDesktopSupported()) { Desktop.getDesktop().browse(file.toURI()); } else { throw new UnsupportedOperationException("Browser not supported."); }
87
52
139
<no_super_class>
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/event/HoverBroadcastBody.java
HoverBroadcastBody
asJavascript
class HoverBroadcastBody implements EventHandlerBody { private final String[] subPlots; private final int nTraces; public static HoverBroadcastBuilder builder() { return new HoverBroadcastBuilder(); } private HoverBroadcastBody(HoverBroadcastBuilder builder) { this.subPlots = builder.subPlots; this.nTraces = builder.nTraces; } @Override public String asJavascript(String targetName, String divName, String eventData) {<FILL_FUNCTION_BODY>} public static class HoverBroadcastBuilder { private String[] subPlots; private int nTraces; public HoverBroadcastBuilder subPlots(String[] subPlots) { this.subPlots = subPlots; return this; } public HoverBroadcastBuilder numTraces(int nTraces) { this.nTraces = nTraces; return this; } public HoverBroadcastBody build() { return new HoverBroadcastBody(this); } } }
StringBuilder builder = new StringBuilder(); builder.append(String.format("\tvar pointIndex = %s.points[0].pointNumber;", eventData)); builder.append(System.lineSeparator()); builder.append(String.format("\tPlotly.Fx.hover('%s',[ ", divName)); builder.append(System.lineSeparator()); for (int i = 0; i < nTraces; i++) { builder.append(String.format("\t\t{ curveNumber: %d, pointNumber: pointIndex }", i)); if (i < nTraces - 1) { builder.append(", "); } builder.append(System.lineSeparator()); } builder.append("\t\t]"); if (subPlots.length > 0) { builder.append(", ["); for (int i = 0; i < subPlots.length; i++) { builder.append(String.format("'%s'", subPlots[i])); if (i < subPlots.length - 1) { builder.append(", "); } } builder.append("]"); builder.append(System.lineSeparator()); } builder.append("\t);"); builder.append(System.lineSeparator()); return builder.toString();
296
342
638
<no_super_class>
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/event/HoverEventHandler.java
HoverEventHandler
asJavascript
class HoverEventHandler implements EventHandler { private final EventHandlerBody body; private final String eventDataVarName = "eventData"; public static HoverEventHanlderBuilder builder() { return new HoverEventHanlderBuilder(); } private HoverEventHandler(HoverEventHanlderBuilder builder) { this.body = builder.body; } /** * Returns a string of Javascript code that implements a plotly hover event handler * * @param targetName name of the target document * @param divName target document id * @return A string that can be rendered in javascript */ @Override public String asJavascript(String targetName, String divName) {<FILL_FUNCTION_BODY>} public static class HoverEventHanlderBuilder { private EventHandlerBody body; public HoverEventHanlderBuilder body(EventHandlerBody body) { this.body = body; return this; } public HoverEventHandler build() { return new HoverEventHandler(this); } } }
StringBuilder builder = new StringBuilder(); builder.append( String.format("%s.on('plotly_hover', function(%s){", targetName, eventDataVarName)); builder.append(System.lineSeparator()); builder.append(body.asJavascript(targetName, divName, eventDataVarName)); builder.append("});"); builder.append(System.lineSeparator()); return builder.toString();
287
115
402
<no_super_class>
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/traces/AbstractTrace.java
AbstractTrace
getContext
class AbstractTrace implements Trace { protected static final double DEFAULT_OPACITY = 1.0; protected static final Visibility DEFAULT_VISIBILITY = Visibility.TRUE; protected final PebbleEngine engine = TemplateUtils.getNewEngine(); public enum Visibility { TRUE("True"), FALSE("False"), LEGEND_ONLY("legendonly"); private final String value; Visibility(String value) { this.value = value; } @Override public String toString() { return value; } } protected final String type; private final Visibility visible; /** Determines whether or not an item corresponding to this trace is shown in the legend. */ private final Boolean showLegend; /** * Sets the legend group for this trace. Traces part of the same legend group hide/show at the * same time when toggling legend items. */ private final String legendGroup; /** Sets the opacity of the trace. */ private final double opacity; // number between or equal to 0 and 1 /** Sets the trace name. The trace name appear as the legend item and on hover. */ private final String name; /** * Assigns id labels to each datum. These ids for object constancy of data points during * animation. Should be an array of strings, not numbers or any other type. */ private final String[] ids; /** * Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If *x* , the x * coordinates refer to `layout.xaxis`. If *x2*, the x coordinates refer to `layout.xaxis2`, and * so on. */ private final String xAxis; /** * Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* , the y * coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and * so on. */ private final String yAxis; private final HoverLabel hoverLabel; public AbstractTrace(TraceBuilder builder) { this.type = builder.getType(); this.name = builder.name; this.showLegend = builder.showLegend; this.legendGroup = builder.legendGroup; this.visible = builder.visible; this.ids = builder.ids; this.hoverLabel = builder.hoverLabel; this.opacity = builder.opacity; this.xAxis = builder.xAxis; this.yAxis = builder.yAxis; } @Override public String name() { return name; } @Override public String toString() { Writer writer = new StringWriter(); PebbleTemplate compiledTemplate; try { compiledTemplate = engine.getTemplate("trace_template.html"); compiledTemplate.evaluate(writer, getContext()); } catch (PebbleException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new UncheckedIOException(e); } return writer.toString(); } protected Map<String, Object> getContext() {<FILL_FUNCTION_BODY>} public HoverLabel hoverLabel() { return hoverLabel; } public boolean showLegend() { return showLegend; } }
Map<String, Object> context = new HashMap<>(); context.put("type", type); context.put("name", name); if (showLegend != null) { context.put("showLegend", showLegend); } context.put("legendGroup", legendGroup); if (!visible.equals(DEFAULT_VISIBILITY)) { context.put("visible", visible); } context.put("ids", ids); context.put("hoverLable", hoverLabel); if (opacity != DEFAULT_OPACITY) { context.put("opacity", opacity); } context.put("xAxis", xAxis); context.put("yAxis", yAxis); return context;
885
194
1,079
<no_super_class>
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/traces/BarTrace.java
BarTrace
asJavascript
class BarTrace extends AbstractTrace { private final Object[] x; private final double[] y; private final Orientation orientation; private final Marker marker; private BarTrace(BarBuilder builder) { super(builder); this.orientation = builder.orientation; this.x = builder.x; this.y = builder.y; this.marker = builder.marker; } public static BarBuilder builder(Object[] x, double[] y) { return new BarBuilder(x, y); } public static BarBuilder builder(CategoricalColumn<?> x, NumericColumn<? extends Number> y) { return new BarBuilder(x, y); } @Override public String asJavascript(int i) {<FILL_FUNCTION_BODY>} private Map<String, Object> getContext(int i) { Map<String, Object> context = super.getContext(); context.put("variableName", "trace" + i); if (orientation == Orientation.HORIZONTAL) { context.put("x", dataAsString(y)); context.put("y", dataAsString(x)); } else { context.put("y", dataAsString(y)); context.put("x", dataAsString(x)); } context.put("orientation", orientation.value); if (marker != null) { context.put("marker", marker); } return context; } public enum Orientation { VERTICAL("v"), HORIZONTAL("h"); private final String value; Orientation(String value) { this.value = value; } @Override public String toString() { return value; } } public static class BarBuilder extends TraceBuilder { private final String type = "bar"; private final Object[] x; private final double[] y; private Orientation orientation = Orientation.VERTICAL; private Marker marker; BarBuilder(Object[] x, double[] y) { this.x = x; this.y = y; } BarBuilder(CategoricalColumn<?> x, NumericColumn<? extends Number> y) { this.x = TraceBuilder.columnToStringArray(x); this.y = y.asDoubleArray(); } public BarTrace build() { return new BarTrace(this); } /** * Sets the orientation of the bars. With "v" ("h"), the value of the each bar spans along the * vertical (horizontal). */ public BarBuilder orientation(Orientation orientation) { this.orientation = orientation; return this; } @Override public BarBuilder opacity(double opacity) { super.opacity(opacity); return this; } @Override public BarBuilder name(String name) { super.name(name); return this; } @Override public BarBuilder showLegend(boolean b) { super.showLegend(b); return this; } public BarBuilder marker(Marker marker) { this.marker = marker; return this; } @Override public BarBuilder xAxis(String xAxis) { super.xAxis(xAxis); return this; } @Override public BarBuilder yAxis(String yAxis) { super.yAxis(yAxis); return this; } @Override protected String getType() { return type; } } }
Writer writer = new StringWriter(); PebbleTemplate compiledTemplate; try { compiledTemplate = engine.getTemplate("trace_template.html"); compiledTemplate.evaluate(writer, getContext(i)); } catch (PebbleException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new UncheckedIOException(e); } return writer.toString();
946
110
1,056
<methods>public void <init>(tech.tablesaw.plotly.traces.TraceBuilder) ,public tech.tablesaw.plotly.components.HoverLabel hoverLabel() ,public java.lang.String name() ,public boolean showLegend() ,public java.lang.String toString() <variables>protected static final double DEFAULT_OPACITY,protected static final tech.tablesaw.plotly.traces.AbstractTrace.Visibility DEFAULT_VISIBILITY,protected final PebbleEngine engine,private final non-sealed tech.tablesaw.plotly.components.HoverLabel hoverLabel,private final non-sealed java.lang.String[] ids,private final non-sealed java.lang.String legendGroup,private final non-sealed java.lang.String name,private final non-sealed double opacity,private final non-sealed java.lang.Boolean showLegend,protected final non-sealed java.lang.String type,private final non-sealed tech.tablesaw.plotly.traces.AbstractTrace.Visibility visible,private final non-sealed java.lang.String xAxis,private final non-sealed java.lang.String yAxis
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/traces/BoxTrace.java
BoxTrace
builder
class BoxTrace extends AbstractTrace { private final Object[] x; private final double[] y; private BoxTrace(BoxBuilder builder) { super(builder); this.x = builder.x; this.y = builder.y; } public static BoxBuilder builder(Object[] x, double[] y) { return new BoxBuilder(x, y); } public static BoxBuilder builder(CategoricalColumn<?> x, NumericColumn<? extends Number> y) { return new BoxBuilder(x, y); } public static BoxBuilder builder(double[] x, double[] y) {<FILL_FUNCTION_BODY>} @Override public String asJavascript(int i) { Writer writer = new StringWriter(); PebbleTemplate compiledTemplate; try { compiledTemplate = engine.getTemplate("trace_template.html"); compiledTemplate.evaluate(writer, getContext(i)); } catch (PebbleException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new UncheckedIOException(e); } return writer.toString(); } private Map<String, Object> getContext(int i) { Map<String, Object> context = super.getContext(); context.put("variableName", "trace" + i); context.put("y", dataAsString(y)); context.put("x", dataAsString(x)); return context; } public static class BoxBuilder extends TraceBuilder { private static final String type = "box"; private final Object[] x; private final double[] y; BoxBuilder(Object[] x, double[] y) { this.x = x; this.y = y; } @Override public BoxBuilder name(String name) { super.name(name); return this; } BoxBuilder(CategoricalColumn<?> x, NumericColumn<? extends Number> y) { this.x = columnToStringArray(x); this.y = y.asDoubleArray(); } public BoxTrace build() { return new BoxTrace(this); } @Override public BoxBuilder xAxis(String xAxis) { super.xAxis(xAxis); return this; } @Override public BoxBuilder yAxis(String yAxis) { super.yAxis(yAxis); return this; } @Override protected String getType() { return type; } } }
Double[] xObjs = new Double[x.length]; for (int i = 0; i < x.length; i++) { xObjs[i] = x[i]; } return new BoxBuilder(xObjs, y);
664
66
730
<methods>public void <init>(tech.tablesaw.plotly.traces.TraceBuilder) ,public tech.tablesaw.plotly.components.HoverLabel hoverLabel() ,public java.lang.String name() ,public boolean showLegend() ,public java.lang.String toString() <variables>protected static final double DEFAULT_OPACITY,protected static final tech.tablesaw.plotly.traces.AbstractTrace.Visibility DEFAULT_VISIBILITY,protected final PebbleEngine engine,private final non-sealed tech.tablesaw.plotly.components.HoverLabel hoverLabel,private final non-sealed java.lang.String[] ids,private final non-sealed java.lang.String legendGroup,private final non-sealed java.lang.String name,private final non-sealed double opacity,private final non-sealed java.lang.Boolean showLegend,protected final non-sealed java.lang.String type,private final non-sealed tech.tablesaw.plotly.traces.AbstractTrace.Visibility visible,private final non-sealed java.lang.String xAxis,private final non-sealed java.lang.String yAxis
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/traces/ContourTrace.java
ContourTrace
getContext
class ContourTrace extends AbstractTrace { private final Object[] x; private final Object[] y; private final double[][] z; private final String type; public ContourTrace(ContourBuilder builder) { super(builder); this.x = builder.x; this.y = builder.y; this.z = builder.z; this.type = builder.getType(); } @Override public String asJavascript(int i) { Writer writer = new StringWriter(); PebbleTemplate compiledTemplate; try { compiledTemplate = engine.getTemplate("trace_template.html"); compiledTemplate.evaluate(writer, getContext()); } catch (PebbleException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new UncheckedIOException(e); } return writer.toString(); } @Override protected Map<String, Object> getContext() {<FILL_FUNCTION_BODY>} public static ContourTrace.ContourBuilder builder(Object[] x, Object[] y, double[][] z) { return new ContourTrace.ContourBuilder(x, y, z); } public static class ContourBuilder extends TraceBuilder { private static final String type = "contour"; private final Object[] x; private final Object[] y; private final double[][] z; ContourBuilder(Object[] x, Object[] y, double[][] z) { this.x = x; this.y = y; this.z = z; } @Override public ContourTrace.ContourBuilder xAxis(String xAxis) { super.xAxis(xAxis); return this; } @Override public ContourTrace.ContourBuilder yAxis(String yAxis) { super.yAxis(yAxis); return this; } public ContourTrace build() { return new ContourTrace(this); } @Override protected String getType() { return type; } } }
Map<String, Object> context = super.getContext(); context.put("variableName", "trace0"); context.put("x", dataAsString(x)); context.put("y", dataAsString(y)); context.put("z", dataAsString(z)); context.put("type", type); return context;
542
89
631
<methods>public void <init>(tech.tablesaw.plotly.traces.TraceBuilder) ,public tech.tablesaw.plotly.components.HoverLabel hoverLabel() ,public java.lang.String name() ,public boolean showLegend() ,public java.lang.String toString() <variables>protected static final double DEFAULT_OPACITY,protected static final tech.tablesaw.plotly.traces.AbstractTrace.Visibility DEFAULT_VISIBILITY,protected final PebbleEngine engine,private final non-sealed tech.tablesaw.plotly.components.HoverLabel hoverLabel,private final non-sealed java.lang.String[] ids,private final non-sealed java.lang.String legendGroup,private final non-sealed java.lang.String name,private final non-sealed double opacity,private final non-sealed java.lang.Boolean showLegend,protected final non-sealed java.lang.String type,private final non-sealed tech.tablesaw.plotly.traces.AbstractTrace.Visibility visible,private final non-sealed java.lang.String xAxis,private final non-sealed java.lang.String yAxis
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/traces/HeatmapTrace.java
HeatmapTrace
getContext
class HeatmapTrace extends AbstractTrace { private final Object[] x; private final Object[] y; private final double[][] z; private final String type; private HeatmapTrace(HeatmapBuilder builder) { super(builder); this.x = builder.x; this.y = builder.y; this.z = builder.z; this.type = builder.getType(); } @Override public String asJavascript(int i) { Writer writer = new StringWriter(); PebbleTemplate compiledTemplate; try { compiledTemplate = engine.getTemplate("trace_template.html"); compiledTemplate.evaluate(writer, getContext()); } catch (PebbleException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new UncheckedIOException(e); } return writer.toString(); } @Override protected Map<String, Object> getContext() {<FILL_FUNCTION_BODY>} public static HeatmapBuilder builder(Object[] x, Object[] y, double[][] z) { return new HeatmapBuilder(x, y, z); } public static class HeatmapBuilder extends TraceBuilder { private static final String type = "heatmap"; private final Object[] x; private final Object[] y; private final double[][] z; HeatmapBuilder(Object[] x, Object[] y, double[][] z) { this.x = x; this.y = y; this.z = z; } @Override public HeatmapBuilder xAxis(String xAxis) { super.xAxis(xAxis); return this; } @Override public HeatmapBuilder yAxis(String yAxis) { super.yAxis(yAxis); return this; } public HeatmapTrace build() { return new HeatmapTrace(this); } @Override protected String getType() { return type; } } }
Map<String, Object> context = super.getContext(); context.put("variableName", "trace0"); context.put("x", dataAsString(x)); context.put("y", dataAsString(y)); context.put("z", dataAsString(z)); context.put("type", type); return context;
527
89
616
<methods>public void <init>(tech.tablesaw.plotly.traces.TraceBuilder) ,public tech.tablesaw.plotly.components.HoverLabel hoverLabel() ,public java.lang.String name() ,public boolean showLegend() ,public java.lang.String toString() <variables>protected static final double DEFAULT_OPACITY,protected static final tech.tablesaw.plotly.traces.AbstractTrace.Visibility DEFAULT_VISIBILITY,protected final PebbleEngine engine,private final non-sealed tech.tablesaw.plotly.components.HoverLabel hoverLabel,private final non-sealed java.lang.String[] ids,private final non-sealed java.lang.String legendGroup,private final non-sealed java.lang.String name,private final non-sealed double opacity,private final non-sealed java.lang.Boolean showLegend,protected final non-sealed java.lang.String type,private final non-sealed tech.tablesaw.plotly.traces.AbstractTrace.Visibility visible,private final non-sealed java.lang.String xAxis,private final non-sealed java.lang.String yAxis
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/traces/Histogram2DTrace.java
Histogram2DTrace
getContext
class Histogram2DTrace extends AbstractTrace { private final double[] x; private final double[] y; public static Histogram2DBuilder builder(double[] x, double[] y) { return new Histogram2DBuilder(x, y); } public static Histogram2DBuilder builder( NumericColumn<? extends Number> x, NumericColumn<? extends Number> y) { return new Histogram2DBuilder(x.asDoubleArray(), y.asDoubleArray()); } private Histogram2DTrace(Histogram2DBuilder builder) { super(builder); this.x = builder.x; this.y = builder.y; } @Override public String asJavascript(int i) { Writer writer = new StringWriter(); PebbleTemplate compiledTemplate; try { compiledTemplate = engine.getTemplate("trace_template.html"); compiledTemplate.evaluate(writer, getContext(i)); } catch (PebbleException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new UncheckedIOException(e); } return writer.toString(); } private Map<String, Object> getContext(int i) {<FILL_FUNCTION_BODY>} public static class Histogram2DBuilder extends TraceBuilder { private final String type = "histogram2d"; /* private int bins; private String barMode; private String histFunction; private String histNorm; */ private final double[] x; private final double[] y; private Histogram2DBuilder(double[] x, double[] y) { this.x = x; this.y = y; } /* public Histogram2DBuilder setBins(int bins) { this.bins = bins; return this; } public Histogram2DBuilder barMode(String barMode) { this.barMode = barMode; return this; } public Histogram2DBuilder histFunction(String histFunction) { this.histFunction = histFunction; return this; } public Histogram2DBuilder histNorm(String histNorm) { this.histNorm = histNorm; return this; } */ public Histogram2DTrace build() { return new Histogram2DTrace(this); } @Override protected String getType() { return type; } } }
Map<String, Object> context = super.getContext(); context.put("variableName", "trace" + i); context.put("x", Utils.dataAsString(x)); context.put("y", Utils.dataAsString(y)); return context;
646
73
719
<methods>public void <init>(tech.tablesaw.plotly.traces.TraceBuilder) ,public tech.tablesaw.plotly.components.HoverLabel hoverLabel() ,public java.lang.String name() ,public boolean showLegend() ,public java.lang.String toString() <variables>protected static final double DEFAULT_OPACITY,protected static final tech.tablesaw.plotly.traces.AbstractTrace.Visibility DEFAULT_VISIBILITY,protected final PebbleEngine engine,private final non-sealed tech.tablesaw.plotly.components.HoverLabel hoverLabel,private final non-sealed java.lang.String[] ids,private final non-sealed java.lang.String legendGroup,private final non-sealed java.lang.String name,private final non-sealed double opacity,private final non-sealed java.lang.Boolean showLegend,protected final non-sealed java.lang.String type,private final non-sealed tech.tablesaw.plotly.traces.AbstractTrace.Visibility visible,private final non-sealed java.lang.String xAxis,private final non-sealed java.lang.String yAxis
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/traces/HistogramTrace.java
HistogramBuilder
doublesToObjects
class HistogramBuilder extends TraceBuilder { private final String type = "histogram"; private int nBinsX; private int nBinsY; private boolean autoBinX; private boolean autoBinY; private boolean horizontal = false; private Object[] x; private Object[] y; private Marker marker; private HistNorm histNorm = HistNorm.NONE; private HistFunc histFunc = HistFunc.COUNT; private HistogramBuilder(double[] values) { this.x = doublesToObjects(values); } private HistogramBuilder(Object[] xValues, double[] yValues) { this.x = xValues; this.y = doublesToObjects(yValues); } /** * Specifies the maximum number of desired bins. This value will be used in an algorithm that * will decide the optimal bin size such that the histogram best visualizes the distribution of * the data. */ public HistogramBuilder nBinsX(int bins) { this.nBinsX = bins; return this; } public HistogramBuilder nBinsY(int bins) { this.nBinsY = bins; return this; } /** * Determines whether or not the x axis bin attributes are picked by an algorithm. Note that * this should be set to False if you want to manually set the number of bins using the * attributes in xbins. * * <p>Note also that this should be true (default) to use nbinsx to suggest a bin count */ public HistogramBuilder autoBinX(boolean autoBinX) { this.autoBinX = autoBinX; return this; } public HistogramBuilder autoBinY(boolean autoBinY) { this.autoBinY = autoBinY; return this; } public HistogramBuilder marker(Marker marker) { this.marker = marker; return this; } @Override public HistogramBuilder opacity(double opacity) { super.opacity(opacity); return this; } public HistogramBuilder horizontal(boolean horizontal) { this.horizontal = horizontal; return this; } @Override public HistogramBuilder showLegend(boolean b) { super.showLegend(b); return this; } /** * Specifies the type of normalization used for this histogram trace. If "", the span of each * bar corresponds to the number of occurrences (i.e. the number of data points lying inside the * bins). If "percent" / "probability", the span of each bar corresponds to the percentage / * fraction of occurrences with respect to the total number of sample points (here, the sum of * all bin HEIGHTS equals 100% / 1). If "density", the span of each bar corresponds to the * number of occurrences in a bin divided by the size of the bin interval (here, the sum of all * bin AREAS equals the total number of sample points). If "probability density", the area of * each bar corresponds to the probability that an event will fall into the corresponding bin * (here, the sum of all bin AREAS equals 1). * * @param histNorm The normalization type for the histogram * @return This HistogramBuilder */ public HistogramBuilder histNorm(HistNorm histNorm) { this.histNorm = histNorm; return this; } /** * Specifies the binning function used for this histogram trace. If "count", the histogram * values are computed by counting the number of values lying inside each bin. If "sum", "avg", * "min", "max", the histogram values are computed using the sum, the average, the minimum or * the maximum of the values lying inside each bin respectively. * * @param histFunc The function type * @return This HistogramBuilder */ public HistogramBuilder histFunc(HistFunc histFunc) { this.histFunc = histFunc; return this; } @Override public HistogramBuilder name(String name) { super.name(name); return this; } @Override public HistogramBuilder xAxis(String xAxis) { super.xAxis(xAxis); return this; } @Override public HistogramBuilder yAxis(String yAxis) { super.yAxis(yAxis); return this; } public HistogramBuilder y(double[] y) { this.y = doublesToObjects(y); return this; } public HistogramBuilder y(NumericColumn<? extends Number> values) { this.y = values.asObjectArray(); return this; } public HistogramTrace build() { return new HistogramTrace(this); } @Override protected String getType() { return type; } } private static Object[] doublesToObjects(double[] doubles) {<FILL_FUNCTION_BODY>
Object[] objects = new Object[doubles.length]; for (int i = 0; i < doubles.length; i++) { objects[i] = doubles[i]; } return objects;
1,292
58
1,350
<methods>public void <init>(tech.tablesaw.plotly.traces.TraceBuilder) ,public tech.tablesaw.plotly.components.HoverLabel hoverLabel() ,public java.lang.String name() ,public boolean showLegend() ,public java.lang.String toString() <variables>protected static final double DEFAULT_OPACITY,protected static final tech.tablesaw.plotly.traces.AbstractTrace.Visibility DEFAULT_VISIBILITY,protected final PebbleEngine engine,private final non-sealed tech.tablesaw.plotly.components.HoverLabel hoverLabel,private final non-sealed java.lang.String[] ids,private final non-sealed java.lang.String legendGroup,private final non-sealed java.lang.String name,private final non-sealed double opacity,private final non-sealed java.lang.Boolean showLegend,protected final non-sealed java.lang.String type,private final non-sealed tech.tablesaw.plotly.traces.AbstractTrace.Visibility visible,private final non-sealed java.lang.String xAxis,private final non-sealed java.lang.String yAxis
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/traces/PieTrace.java
PieTrace
asJavascript
class PieTrace extends AbstractTrace { private final double[] values; private final Object[] labels; private final Domain domain; private PieTrace(PieBuilder builder) { super(builder); this.values = builder.values; this.labels = builder.labels; this.domain = builder.domain; } @Override public String asJavascript(int i) {<FILL_FUNCTION_BODY>} private Map<String, Object> getContext(int i) { Map<String, Object> context = super.getContext(); context.put("variableName", "trace" + i); context.put("values", Utils.dataAsString(values)); if (labels != null) { context.put("labels", Utils.dataAsString(labels)); } if (domain != null) { context.put("domain", domain.asJavascript()); } return context; } public static PieBuilder builder(Object[] labels, double[] values) { return new PieBuilder(labels, values); } public static PieBuilder builder(Column<?> labels, NumericColumn<? extends Number> values) { return new PieBuilder(TraceBuilder.columnToStringArray(labels), values.asDoubleArray()); } public static class PieBuilder extends TraceBuilder { private final String type = "pie"; private final double[] values; private final Object[] labels; private Domain domain; private PieBuilder(Object[] labels, double[] values) { this.labels = labels; this.values = values; } public PieBuilder domain(Domain domain) { this.domain = domain; return this; } public PieTrace build() { return new PieTrace(this); } @Override protected String getType() { return type; } @Override public PieTrace.PieBuilder showLegend(boolean b) { super.showLegend(b); return this; } } }
Writer writer = new StringWriter(); PebbleTemplate compiledTemplate; try { compiledTemplate = engine.getTemplate("pie_trace_template.html"); compiledTemplate.evaluate(writer, getContext(i)); } catch (PebbleException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new UncheckedIOException(e); } return writer.toString();
539
112
651
<methods>public void <init>(tech.tablesaw.plotly.traces.TraceBuilder) ,public tech.tablesaw.plotly.components.HoverLabel hoverLabel() ,public java.lang.String name() ,public boolean showLegend() ,public java.lang.String toString() <variables>protected static final double DEFAULT_OPACITY,protected static final tech.tablesaw.plotly.traces.AbstractTrace.Visibility DEFAULT_VISIBILITY,protected final PebbleEngine engine,private final non-sealed tech.tablesaw.plotly.components.HoverLabel hoverLabel,private final non-sealed java.lang.String[] ids,private final non-sealed java.lang.String legendGroup,private final non-sealed java.lang.String name,private final non-sealed double opacity,private final non-sealed java.lang.Boolean showLegend,protected final non-sealed java.lang.String type,private final non-sealed tech.tablesaw.plotly.traces.AbstractTrace.Visibility visible,private final non-sealed java.lang.String xAxis,private final non-sealed java.lang.String yAxis
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/traces/Scatter3DTrace.java
Scatter3DTrace
asJavascript
class Scatter3DTrace extends AbstractTrace { private final double[] y; private final double[] x; private final double[] z; private final String[] text; private final Mode mode; private final HoverLabel hoverLabel; private final Marker marker; public static Scatter3DBuilder builder(double[] x, double[] y, double[] z) { return new Scatter3DBuilder(x, y, z); } public static Scatter3DBuilder builder( NumericColumn<? extends Number> x, NumericColumn<? extends Number> y, NumericColumn<? extends Number> z) { return new Scatter3DBuilder(x, y, z); } private Scatter3DTrace(Scatter3DBuilder builder) { super(builder); this.mode = builder.mode; this.y = builder.y; this.x = builder.x; this.z = builder.z; this.text = builder.text; this.hoverLabel = builder.hoverLabel; this.marker = builder.marker; } private Map<String, Object> getContext(int i) { Map<String, Object> context = super.getContext(); context.put("variableName", "trace" + i); context.put("mode", mode); context.put("y", dataAsString(y)); context.put("x", dataAsString(x)); context.put("z", dataAsString(z)); if (marker != null) { context.put("marker", marker); } if (hoverLabel != null) { context.put("hoverlabel", hoverLabel.asJavascript()); } if (text != null) { context.put("text", dataAsString(text)); } return context; } @Override public String asJavascript(int i) {<FILL_FUNCTION_BODY>} public enum Mode { LINE("line"), MARKERS("markers"), LINE_AND_MARKERS("line + markers"), LINE_AND_TEXT("line + text"), TEXT_AND_MARKERS("text + text"), LINE_TEXT_AND_MARKERS("line + text + markers"), TEXT("text"), NONE("none"); final String value; Mode(String value) { this.value = value; } @Override public String toString() { return value; } } public static class Scatter3DBuilder extends TraceBuilder { private String type = "scatter3d"; private Mode mode = Mode.MARKERS; private final double[] x; private final double[] y; private final double[] z; private String[] text; private Marker marker; private Scatter3DBuilder(double[] x, double[] y, double[] z) { this.x = x; this.y = y; this.z = z; } private Scatter3DBuilder( NumericColumn<? extends Number> x, NumericColumn<? extends Number> y, NumericColumn<? extends Number> z) { this.x = x.asDoubleArray(); this.y = y.asDoubleArray(); this.z = z.asDoubleArray(); } public Scatter3DBuilder mode(Mode mode) { this.mode = mode; return this; } public Scatter3DBuilder type(String kind) { this.type = kind; return this; } public Scatter3DBuilder text(String[] text) { this.text = text; return this; } public Scatter3DTrace build() { return new Scatter3DTrace(this); } protected String getType() { return type; } @Override public Scatter3DBuilder name(String name) { return (Scatter3DBuilder) super.name(name); } @Override public Scatter3DBuilder opacity(double n) { Preconditions.checkArgument(n >= 0 && n <= 1); return (Scatter3DBuilder) super.opacity(n); } @Override public Scatter3DBuilder legendGroup(String group) { return (Scatter3DBuilder) super.legendGroup(group); } public Scatter3DBuilder marker(Marker marker) { this.marker = marker; return this; } @Override public Scatter3DBuilder showLegend(boolean showLegend) { return (Scatter3DBuilder) super.showLegend(showLegend); } @Override public Scatter3DBuilder visible(Visibility visibility) { return (Scatter3DBuilder) super.visible(visibility); } @Override public Scatter3DBuilder hoverLabel(HoverLabel hoverLabel) { return (Scatter3DBuilder) super.hoverLabel(hoverLabel); } } }
Writer writer = new StringWriter(); PebbleTemplate compiledTemplate; try { compiledTemplate = engine.getTemplate("trace_template.html"); Map<String, Object> context = getContext(i); compiledTemplate.evaluate(writer, context); } catch (PebbleException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new UncheckedIOException(e); } return writer.toString();
1,315
122
1,437
<methods>public void <init>(tech.tablesaw.plotly.traces.TraceBuilder) ,public tech.tablesaw.plotly.components.HoverLabel hoverLabel() ,public java.lang.String name() ,public boolean showLegend() ,public java.lang.String toString() <variables>protected static final double DEFAULT_OPACITY,protected static final tech.tablesaw.plotly.traces.AbstractTrace.Visibility DEFAULT_VISIBILITY,protected final PebbleEngine engine,private final non-sealed tech.tablesaw.plotly.components.HoverLabel hoverLabel,private final non-sealed java.lang.String[] ids,private final non-sealed java.lang.String legendGroup,private final non-sealed java.lang.String name,private final non-sealed double opacity,private final non-sealed java.lang.Boolean showLegend,protected final non-sealed java.lang.String type,private final non-sealed tech.tablesaw.plotly.traces.AbstractTrace.Visibility visible,private final non-sealed java.lang.String xAxis,private final non-sealed java.lang.String yAxis
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/traces/TraceBuilder.java
TraceBuilder
columnToStringArray
class TraceBuilder { protected AbstractTrace.Visibility visible = AbstractTrace.DEFAULT_VISIBILITY; /** Determines whether or not an item corresponding to this trace is shown in the legend. */ protected Boolean showLegend = null; /** * Sets the legend group for this trace. Traces part of the same legend group hide/show at the * same time when toggling legend items. */ protected String legendGroup = ""; /** Sets the opacity of the trace. */ protected double opacity = AbstractTrace.DEFAULT_OPACITY; // number between or equal to 0 and 1 /** Sets the trace name. The trace name appear as the legend item and on hover. */ protected String name; /** * Assigns id labels to each datum. These ids for object constancy of data points during * animation. Should be an array of strings, not numbers or any other type. */ protected String[] ids; protected HoverLabel hoverLabel; /** * Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If *x* (the * default value), the x coordinates refer to `layout.xaxis`. If *x2*, the x coordinates refer to * `layout.xaxis2`, and so on. */ protected String xAxis = "x"; /** * Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the * default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to * `layout.yaxis2`, and so on. */ protected String yAxis = "y"; TraceBuilder() {} protected abstract String getType(); public TraceBuilder name(String name) { this.name = name; return this; } public TraceBuilder opacity(double n) { Preconditions.checkArgument(n >= 0 && n <= 1); this.opacity = n; return this; } public TraceBuilder legendGroup(String group) { this.legendGroup = group; return this; } protected TraceBuilder showLegend(boolean showLegend) { this.showLegend = showLegend; return this; } protected TraceBuilder visible(AbstractTrace.Visibility visibility) { this.visible = visibility; return this; } protected TraceBuilder hoverLabel(HoverLabel hoverLabel) { this.hoverLabel = hoverLabel; return this; } protected static String[] columnToStringArray(Column<?> column) {<FILL_FUNCTION_BODY>} public TraceBuilder xAxis(String xAxis) { Preconditions.checkArgument(xAxis.matches("^x[0-9]*$")); this.xAxis = xAxis; return this; } public TraceBuilder yAxis(String yAxis) { Preconditions.checkArgument(yAxis.matches("^y[0-9]*$")); this.yAxis = yAxis; return this; } }
String[] x = new String[column.size()]; for (int i = 0; i < column.size(); i++) { x[i] = column.getString(i); } return x;
800
57
857
<no_super_class>
jtablesaw_tablesaw
tablesaw/jsplot/src/main/java/tech/tablesaw/plotly/traces/ViolinTrace.java
ViolinTrace
asJavascript
class ViolinTrace extends AbstractTrace { private final Object[] x; private final double[] y; private final boolean showBoxPlot; private final boolean showMeanLine; private ViolinTrace(ViolinBuilder builder) { super(builder); this.x = builder.x; this.y = builder.y; this.showMeanLine = builder.showMeanLine; this.showBoxPlot = builder.showBoxPlot; } public static ViolinBuilder builder(Object[] x, double[] y) { return new ViolinBuilder(x, y); } public static ViolinBuilder builder(CategoricalColumn<?> x, NumericColumn<? extends Number> y) { return new ViolinBuilder(x, y); } public static ViolinBuilder builder(double[] x, double[] y) { Double[] xObjs = new Double[x.length]; for (int i = 0; i < x.length; i++) { xObjs[i] = x[i]; } return new ViolinBuilder(xObjs, y); } @Override public String asJavascript(int i) {<FILL_FUNCTION_BODY>} private Map<String, Object> getContext(int i) { Map<String, Object> context = super.getContext(); context.put("variableName", "trace" + i); context.put("y", dataAsString(y)); context.put("x", dataAsString(x)); if (showBoxPlot){ context.put("box", "{visible: true}"); } if (showMeanLine){ context.put("meanLine", "{visible: true}"); } return context; } public static class ViolinBuilder extends TraceBuilder { private static final String type = "violin"; private final Object[] x; private final double[] y; private boolean showBoxPlot; private boolean showMeanLine; ViolinBuilder(Object[] x, double[] y) { this.x = x; this.y = y; } @Override public ViolinBuilder name(String name) { super.name(name); return this; } ViolinBuilder(CategoricalColumn<?> x, NumericColumn<? extends Number> y) { this.x = columnToStringArray(x); this.y = y.asDoubleArray(); } public ViolinBuilder boxPlot(boolean show) { this.showBoxPlot = show; return this; } public ViolinBuilder meanLine(boolean show) { this.showMeanLine = show; return this; } public ViolinTrace build() { return new ViolinTrace(this); } @Override public ViolinBuilder xAxis(String xAxis) { super.xAxis(xAxis); return this; } @Override public ViolinBuilder yAxis(String yAxis) { super.yAxis(yAxis); return this; } @Override protected String getType() { return type; } } }
Writer writer = new StringWriter(); PebbleTemplate compiledTemplate; try { compiledTemplate = engine.getTemplate("trace_template.html"); compiledTemplate.evaluate(writer, getContext(i)); } catch (PebbleException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new UncheckedIOException(e); } return writer.toString();
850
110
960
<methods>public void <init>(tech.tablesaw.plotly.traces.TraceBuilder) ,public tech.tablesaw.plotly.components.HoverLabel hoverLabel() ,public java.lang.String name() ,public boolean showLegend() ,public java.lang.String toString() <variables>protected static final double DEFAULT_OPACITY,protected static final tech.tablesaw.plotly.traces.AbstractTrace.Visibility DEFAULT_VISIBILITY,protected final PebbleEngine engine,private final non-sealed tech.tablesaw.plotly.components.HoverLabel hoverLabel,private final non-sealed java.lang.String[] ids,private final non-sealed java.lang.String legendGroup,private final non-sealed java.lang.String name,private final non-sealed double opacity,private final non-sealed java.lang.Boolean showLegend,protected final non-sealed java.lang.String type,private final non-sealed tech.tablesaw.plotly.traces.AbstractTrace.Visibility visible,private final non-sealed java.lang.String xAxis,private final non-sealed java.lang.String yAxis
jtablesaw_tablesaw
tablesaw/saw/src/main/java/tech/tablesaw/io/saw/ColumnMetadata.java
ColumnMetadata
equals
class ColumnMetadata { private String id; private String name; private String type; // number of unique values in column - not all columns will provide this as it can be expensive private int cardinality; // these attributes are specific to string columns private String stringColumnKeySize; private int nextStringKey; private int uncompressedByteSize; // these attributes are specific to boolean columns private int trueBytesLength; private int falseBytesLength; private int missingBytesLength; ColumnMetadata(Column<?> column) { this.id = SawUtils.makeName(column.name()); this.name = column.name(); this.type = column.type().name(); if (column instanceof StringColumn) { StringColumn stringColumn = (StringColumn) column; cardinality = stringColumn.countUnique(); DictionaryMap lookupTable = stringColumn.getDictionary(); nextStringKey = lookupTable.nextKeyWithoutIncrementing(); if (lookupTable.getClass().equals(IntDictionaryMap.class)) { stringColumnKeySize = Integer.class.getSimpleName(); } else if (lookupTable.getClass().equals(ByteDictionaryMap.class)) { stringColumnKeySize = Byte.class.getSimpleName(); } else if (lookupTable.getClass().equals(ShortDictionaryMap.class)) { stringColumnKeySize = Short.class.getSimpleName(); } else { stringColumnKeySize = ""; } } else { stringColumnKeySize = ""; if (column instanceof BooleanColumn) { BooleanColumn bc = (BooleanColumn) column; trueBytesLength = bc.trueBytes().length; falseBytesLength = bc.falseBytes().length; missingBytesLength = bc.missingBytes().length; uncompressedByteSize = trueBytesLength + falseBytesLength + missingBytesLength; } } } /** * Constructs an instance of ColumnMetaData * * <p>NB: This constructor is used by Jackson JSON parsing code so it must be retained even though * it isn't explicitly called */ protected ColumnMetadata() {} @Override public String toString() { return "ColumnMetadata{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", type=" + type + '}'; } public String getId() { return id; } public String getName() { return name; } public String getType() { return type; } public int getUncompressedByteSize() { return uncompressedByteSize; } public String getStringColumnKeySize() { return stringColumnKeySize; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hashCode(getId(), getName(), getType(), getStringColumnKeySize()); } public int getNextStringKey() { return nextStringKey; } public int getCardinality() { return cardinality; } /** * For BooleanColumn only Returns the length of the byte array used for true values before it is * compressed */ public int getTrueBytesLength() { return trueBytesLength; } /** * For BooleanColumn only Returns the length of the byte array used for false values before it is * compressed */ public int getFalseBytesLength() { return falseBytesLength; } /** * For BooleanColumn only Returns the length of the byte array used for missing values before it * is compressed */ public int getMissingBytesLength() { return missingBytesLength; } public void setUncompressedByteSize(int uncompressedByteSize) { this.uncompressedByteSize = uncompressedByteSize; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ColumnMetadata that = (ColumnMetadata) o; return Objects.equal(getId(), that.getId()) && Objects.equal(getName(), that.getName()) && Objects.equal(getType(), that.getType()) && Objects.equal(getStringColumnKeySize(), that.getStringColumnKeySize());
1,016
111
1,127
<no_super_class>
jtablesaw_tablesaw
tablesaw/saw/src/main/java/tech/tablesaw/io/saw/SawMetadata.java
SawMetadata
toJson
class SawMetadata { // The name of the file that this data is written to static final String METADATA_FILE_NAME = "Metadata.json"; // The version of the Saw Storage system used to write the file private static final int SAW_VERSION = 3; private static final ObjectMapper objectMapper = new ObjectMapper(); private TableMetadata tableMetadata; private int version; private CompressionType compressionType; private EncryptionType encryptionType; /** * Returns a SawMetadata instance derived from the json-formatted Metadata.json file in the * directory specified by sawPath * * @param sawPath The path to the folder containing the Saw metadata file and table data */ static SawMetadata readMetadata(Path sawPath) { Path resolvePath = sawPath.resolve(METADATA_FILE_NAME); byte[] encoded; try { encoded = Files.readAllBytes(resolvePath); } catch (IOException e) { throw new UncheckedIOException( "Unable to read Saw Metadata file at " + resolvePath.toString(), e); } return SawMetadata.fromJson(new String(encoded, StandardCharsets.UTF_8)); } public SawMetadata(Table table, SawWriteOptions options) { this.tableMetadata = new TableMetadata(table); this.version = SAW_VERSION; this.compressionType = options.getCompressionType(); this.encryptionType = options.getEncryptionType(); } /** Default constructor for Jackson json serialization */ protected SawMetadata() {} /** * Returns an instance of TableMetadata constructed from the provided json string * * @param jsonString A json-formatted String consistent with those output by the toJson() method */ static SawMetadata fromJson(String jsonString) { try { return objectMapper.readValue(jsonString, SawMetadata.class); } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Returns a JSON string that represents this object * * @see static methdod fromJson() which constructs a SawMetadata object from this JSON output */ String toJson() {<FILL_FUNCTION_BODY>} public TableMetadata getTableMetadata() { return tableMetadata; } /** Returns the saw file format version used to create this file */ public int getVersion() { return version; } public CompressionType getCompressionType() { return compressionType; } public EncryptionType getEncryptionType() { return encryptionType; } @JsonIgnore public List<ColumnMetadata> getColumnMetadataList() { return tableMetadata.getColumnMetadataList(); } @JsonIgnore public Table structure() { return tableMetadata.structure(); } @JsonIgnore public String getTableName() { return tableMetadata.getName(); } @JsonIgnore public List<String> columnNames() { return tableMetadata.columnNames(); } @JsonIgnore public int getRowCount() { return tableMetadata.getRowCount(); } public int columnCount() { return tableMetadata.columnCount(); } public String shape() { return tableMetadata.shape(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SawMetadata that = (SawMetadata) o; return getVersion() == that.getVersion() && Objects.equal(getTableMetadata(), that.getTableMetadata()) && getCompressionType() == that.getCompressionType(); } @Override public int hashCode() { return Objects.hashCode(getTableMetadata(), getVersion(), getCompressionType()); } }
try { return objectMapper.writeValueAsString(this); } catch (JsonProcessingException e) { throw new UncheckedIOException(e); }
1,003
46
1,049
<no_super_class>
jtablesaw_tablesaw
tablesaw/saw/src/main/java/tech/tablesaw/io/saw/SawUtils.java
SawUtils
makeName
class SawUtils { private static final Pattern WHITE_SPACE_PATTERN = Pattern.compile("\\s+"); private static final String FILE_EXTENSION = "saw"; private static final Pattern SEPARATOR_PATTERN = Pattern.compile(Pattern.quote(FileSystems.getDefault().getSeparator())); private SawUtils() {} static final String FLOAT = "FLOAT"; static final String DOUBLE = "DOUBLE"; static final String INTEGER = "INTEGER"; static final String LONG = "LONG"; static final String SHORT = "SHORT"; static final String STRING = "STRING"; static final String TEXT = "TEXT"; static final String INSTANT = "INSTANT"; static final String LOCAL_DATE = "LOCAL_DATE"; static final String LOCAL_TIME = "LOCAL_TIME"; static final String LOCAL_DATE_TIME = "LOCAL_DATE_TIME"; static final String BOOLEAN = "BOOLEAN"; static String makeName(String name) {<FILL_FUNCTION_BODY>} }
// remove whitespace from table name String nm = WHITE_SPACE_PATTERN.matcher(name).replaceAll(""); nm = SEPARATOR_PATTERN.matcher(nm).replaceAll("_"); // remove path separators from name return nm + '.' + FILE_EXTENSION;
291
79
370
<no_super_class>
jtablesaw_tablesaw
tablesaw/saw/src/main/java/tech/tablesaw/io/saw/TableMetadata.java
TableMetadata
equals
class TableMetadata { @JsonProperty("columnMetadata") private final List<ColumnMetadata> columnMetadataList = new ArrayList<>(); // The name of the table private String name; // The number of rows in the table private int rowCount; @JsonIgnore private Map<String, ColumnMetadata> columnMetadataMap = new HashMap<>(); TableMetadata(Relation table) { this.name = table.name(); this.rowCount = table.rowCount(); for (Column<?> column : table.columns()) { ColumnMetadata metadata = new ColumnMetadata(column); columnMetadataList.add(metadata); columnMetadataMap.put(column.name(), metadata); } } /** Default constructor for Jackson json serialization */ protected TableMetadata() {} @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hashCode(getColumnMetadataList(), getName(), getRowCount()); } /** Returns the name of the table */ @SuppressWarnings("WeakerAccess") public String getName() { return name; } /** Returns the number of rows in the table */ @SuppressWarnings("WeakerAccess") public int getRowCount() { return rowCount; } /** Returns a list of ColumnMetadata objects, one for each Column in the table */ List<ColumnMetadata> getColumnMetadataList() { return columnMetadataList; } public Map<String, ColumnMetadata> getColumnMetadataMap() { return columnMetadataMap; } /** Returns the number of columns in the table */ public int columnCount() { return getColumnMetadataList().size(); } /** * Returns a string describing the number of rows and columns in the table. This is analogous to * the shape() method defined on Relation. */ public String shape() { return getName() + ": " + getRowCount() + " rows X " + columnCount() + " cols"; } /** Returns a List of the names of all the columns in this table */ public List<String> columnNames() { return columnMetadataList.stream().map(ColumnMetadata::getName).collect(toList()); } /** Returns a table that describes the columns in this table */ public Table structure() { Table t = Table.create("Structure of " + getName()); IntColumn index = IntColumn.indexColumn("Index", columnCount(), 0); StringColumn columnName = StringColumn.create("Column Name", columnCount()); StringColumn columnType = StringColumn.create("Column Type", columnCount()); t.addColumns(index); t.addColumns(columnName); t.addColumns(columnType); for (int i = 0; i < columnCount(); i++) { ColumnMetadata column = columnMetadataList.get(i); columnType.set(i, column.getType()); columnName.set(i, columnNames().get(i)); } return t; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TableMetadata metadata = (TableMetadata) o; return getRowCount() == metadata.getRowCount() && Objects.equal(getColumnMetadataList(), metadata.getColumnMetadataList()) && Objects.equal(getName(), metadata.getName());
781
95
876
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-jakarta/src/main/java/org/thymeleaf/examples/core/gtvg/jakarta/business/entities/repositories/OrderRepository.java
OrderRepository
findByCustomerId
class OrderRepository { private static final OrderRepository INSTANCE = new OrderRepository(); private final Map<Integer,Order> ordersById; private final Map<Integer,List<Order>> ordersByCustomerId; public static OrderRepository getInstance() { return INSTANCE; } private OrderRepository() { super(); this.ordersById = new LinkedHashMap<Integer, Order>(); this.ordersByCustomerId = new LinkedHashMap<Integer, List<Order>>(); final Customer cust1 = CustomerRepository.getInstance().findById(Integer.valueOf(1)); this.ordersByCustomerId.put(cust1.getId(), new ArrayList<Order>()); final Customer cust4 = CustomerRepository.getInstance().findById(Integer.valueOf(4)); this.ordersByCustomerId.put(cust4.getId(), new ArrayList<Order>()); final Customer cust6 = CustomerRepository.getInstance().findById(Integer.valueOf(6)); this.ordersByCustomerId.put(cust6.getId(), new ArrayList<Order>()); final Product prod1 = ProductRepository.getInstance().findById(Integer.valueOf(1)); final Product prod2 = ProductRepository.getInstance().findById(Integer.valueOf(2)); final Product prod3 = ProductRepository.getInstance().findById(Integer.valueOf(3)); final Product prod4 = ProductRepository.getInstance().findById(Integer.valueOf(4)); final Order order1 = new Order(); order1.setId(Integer.valueOf(1)); order1.setCustomer(cust4); order1.setDate(CalendarUtil.calendarFor(2009, 1, 12, 10, 23)); this.ordersById.put(order1.getId(), order1); this.ordersByCustomerId.get(cust4.getId()).add(order1); final OrderLine orderLine11 = new OrderLine(); orderLine11.setProduct(prod2); orderLine11.setAmount(Integer.valueOf(2)); orderLine11.setPurchasePrice(new BigDecimal("0.99")); order1.getOrderLines().add(orderLine11); final OrderLine orderLine12 = new OrderLine(); orderLine12.setProduct(prod3); orderLine12.setAmount(Integer.valueOf(4)); orderLine12.setPurchasePrice(new BigDecimal("2.50")); order1.getOrderLines().add(orderLine12); final OrderLine orderLine13 = new OrderLine(); orderLine13.setProduct(prod4); orderLine13.setAmount(Integer.valueOf(1)); orderLine13.setPurchasePrice(new BigDecimal("15.50")); order1.getOrderLines().add(orderLine13); final Order order2 = new Order(); order2.setId(Integer.valueOf(2)); order2.setCustomer(cust6); order2.setDate(CalendarUtil.calendarFor(2010, 6, 9, 21, 01)); this.ordersById.put(order2.getId(), order2); this.ordersByCustomerId.get(cust6.getId()).add(order2); final OrderLine orderLine21 = new OrderLine(); orderLine21.setProduct(prod1); orderLine21.setAmount(Integer.valueOf(5)); orderLine21.setPurchasePrice(new BigDecimal("3.75")); order2.getOrderLines().add(orderLine21); final OrderLine orderLine22 = new OrderLine(); orderLine22.setProduct(prod4); orderLine22.setAmount(Integer.valueOf(2)); orderLine22.setPurchasePrice(new BigDecimal("17.99")); order2.getOrderLines().add(orderLine22); final Order order3 = new Order(); order3.setId(Integer.valueOf(3)); order3.setCustomer(cust1); order3.setDate(CalendarUtil.calendarFor(2010, 7, 18, 22, 32)); this.ordersById.put(order3.getId(), order3); this.ordersByCustomerId.get(cust4.getId()).add(order3); final OrderLine orderLine32 = new OrderLine(); orderLine32.setProduct(prod1); orderLine32.setAmount(Integer.valueOf(8)); orderLine32.setPurchasePrice(new BigDecimal("5.99")); order3.getOrderLines().add(orderLine32); } public List<Order> findAll() { return new ArrayList<Order>(this.ordersById.values()); } public Order findById(final Integer id) { return this.ordersById.get(id); } public List<Order> findByCustomerId(final Integer customerId) {<FILL_FUNCTION_BODY>} }
final List<Order> ordersForCustomerId = this.ordersByCustomerId.get(customerId); if (ordersForCustomerId == null) { return new ArrayList<Order>(); } return ordersForCustomerId;
1,331
59
1,390
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-jakarta/src/main/java/org/thymeleaf/examples/core/gtvg/jakarta/business/util/CalendarUtil.java
CalendarUtil
calendarFor
class CalendarUtil { public static Calendar calendarFor( final int year, final int month, final int day, final int hour, final int minute) {<FILL_FUNCTION_BODY>} private CalendarUtil() { super(); } }
final Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month - 1); cal.set(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal;
78
133
211
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-jakarta/src/main/java/org/thymeleaf/examples/core/gtvg/jakarta/web/controller/HomeController.java
HomeController
process
class HomeController implements IGTVGController { public HomeController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); ctx.setVariable("today", Calendar.getInstance()); templateEngine.process("home", ctx, writer);
79
58
137
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-jakarta/src/main/java/org/thymeleaf/examples/core/gtvg/jakarta/web/controller/OrderDetailsController.java
OrderDetailsController
process
class OrderDetailsController implements IGTVGController { public OrderDetailsController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
final Integer orderId = Integer.valueOf(webExchange.getRequest().getParameterValue("orderId")); final OrderService orderService = new OrderService(); final Order order = orderService.findById(orderId); final WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); ctx.setVariable("order", order); templateEngine.process("order/details", ctx, writer);
81
115
196
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-jakarta/src/main/java/org/thymeleaf/examples/core/gtvg/jakarta/web/controller/OrderListController.java
OrderListController
process
class OrderListController implements IGTVGController { public OrderListController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
final OrderService orderService = new OrderService(); final List<Order> allOrders = orderService.findAll(); final WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); ctx.setVariable("orders", allOrders); templateEngine.process("order/list", ctx, writer);
81
91
172
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-jakarta/src/main/java/org/thymeleaf/examples/core/gtvg/jakarta/web/controller/ProductCommentsController.java
ProductCommentsController
process
class ProductCommentsController implements IGTVGController { public ProductCommentsController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
final Integer prodId = Integer.valueOf(webExchange.getRequest().getParameterValue("prodId")); final ProductService productService = new ProductService(); final Product product = productService.findById(prodId); final WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); ctx.setVariable("prod", product); templateEngine.process("product/comments", ctx, writer);
83
115
198
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-jakarta/src/main/java/org/thymeleaf/examples/core/gtvg/jakarta/web/controller/ProductListController.java
ProductListController
process
class ProductListController implements IGTVGController { public ProductListController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
final ProductService productService = new ProductService(); final List<Product> allProducts = productService.findAll(); final WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); ctx.setVariable("prods", allProducts); templateEngine.process("product/list", ctx, writer);
81
92
173
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-jakarta/src/main/java/org/thymeleaf/examples/core/gtvg/jakarta/web/controller/SubscribeController.java
SubscribeController
process
class SubscribeController implements IGTVGController { public SubscribeController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); templateEngine.process("subscribe", ctx, writer);
81
42
123
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-jakarta/src/main/java/org/thymeleaf/examples/core/gtvg/jakarta/web/controller/UserProfileController.java
UserProfileController
process
class UserProfileController implements IGTVGController { public UserProfileController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
final WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); templateEngine.process("userprofile", ctx, writer);
81
44
125
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-jakarta/src/main/java/org/thymeleaf/examples/core/gtvg/jakarta/web/filter/GTVGFilter.java
GTVGFilter
process
class GTVGFilter implements Filter { private ITemplateEngine templateEngine; private JakartaServletWebApplication application; public GTVGFilter() { super(); } private static void addUserToSession(final HttpServletRequest request) { // Simulate a real user session by adding a user object request.getSession(true).setAttribute("user", new User("John", "Apricot", "Antarctica", null)); } public void init(final FilterConfig filterConfig) throws ServletException { this.application = JakartaServletWebApplication.buildApplication(filterConfig.getServletContext()); this.templateEngine = buildTemplateEngine(this.application); } public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { addUserToSession((HttpServletRequest)request); if (!process((HttpServletRequest)request, (HttpServletResponse)response)) { chain.doFilter(request, response); } } public void destroy() { // nothing to do } private boolean process(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {<FILL_FUNCTION_BODY>} private static ITemplateEngine buildTemplateEngine(final IWebApplication application) { final WebApplicationTemplateResolver templateResolver = new WebApplicationTemplateResolver(application); // HTML is the default mode, but we will set it anyway for better understanding of code templateResolver.setTemplateMode(TemplateMode.HTML); // This will convert "home" to "/WEB-INF/templates/home.html" templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); // Set template cache TTL to 1 hour. If not set, entries would live in cache until expelled by LRU templateResolver.setCacheTTLMs(Long.valueOf(3600000L)); // Cache is set to true by default. Set to false if you want templates to // be automatically updated when modified. templateResolver.setCacheable(true); final TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); return templateEngine; } }
try { final IWebExchange webExchange = this.application.buildExchange(request, response); final IWebRequest webRequest = webExchange.getRequest(); // This prevents triggering engine executions for resource URLs if (webRequest.getPathWithinApplication().startsWith("/css") || webRequest.getPathWithinApplication().startsWith("/images") || webRequest.getPathWithinApplication().startsWith("/favicon")) { return false; } /* * Query controller/URL mapping and obtain the controller * that will process the request. If no controller is available, * return false and let other filters/servlets process the request. */ final IGTVGController controller = ControllerMappings.resolveControllerForRequest(webRequest); if (controller == null) { return false; } /* * Write the response headers */ response.setContentType("text/html;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); /* * Obtain the response writer */ final Writer writer = response.getWriter(); /* * Execute the controller and process view template, * writing the results to the response writer. */ controller.process(webExchange, this.templateEngine, writer); return true; } catch (final Exception e) { try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (final IOException ignored) { // Just ignore this } throw new ServletException(e); }
599
452
1,051
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-jakarta/src/main/java/org/thymeleaf/examples/core/gtvg/jakarta/web/mapping/ControllerMappings.java
ControllerMappings
getRequestPath
class ControllerMappings { private static Map<String, IGTVGController> controllersByURL; static { controllersByURL = new HashMap<String, IGTVGController>(); controllersByURL.put("/", new HomeController()); controllersByURL.put("/product/list", new ProductListController()); controllersByURL.put("/product/comments", new ProductCommentsController()); controllersByURL.put("/order/list", new OrderListController()); controllersByURL.put("/order/details", new OrderDetailsController()); controllersByURL.put("/subscribe", new SubscribeController()); controllersByURL.put("/userprofile", new UserProfileController()); } public static IGTVGController resolveControllerForRequest(final IWebRequest request) { final String path = getRequestPath(request); return controllersByURL.get(path); } // Path within application might contain the ";jsessionid" fragment due to URL rewriting private static String getRequestPath(final IWebRequest request) {<FILL_FUNCTION_BODY>} private ControllerMappings() { super(); } }
String requestPath = request.getPathWithinApplication(); final int fragmentIndex = requestPath.indexOf(';'); if (fragmentIndex != -1) { requestPath = requestPath.substring(0, fragmentIndex); } return requestPath;
300
72
372
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-javax/src/main/java/org/thymeleaf/examples/core/gtvg/javax/business/entities/repositories/OrderRepository.java
OrderRepository
findByCustomerId
class OrderRepository { private static final OrderRepository INSTANCE = new OrderRepository(); private final Map<Integer,Order> ordersById; private final Map<Integer,List<Order>> ordersByCustomerId; public static OrderRepository getInstance() { return INSTANCE; } private OrderRepository() { super(); this.ordersById = new LinkedHashMap<Integer, Order>(); this.ordersByCustomerId = new LinkedHashMap<Integer, List<Order>>(); final Customer cust1 = CustomerRepository.getInstance().findById(Integer.valueOf(1)); this.ordersByCustomerId.put(cust1.getId(), new ArrayList<Order>()); final Customer cust4 = CustomerRepository.getInstance().findById(Integer.valueOf(4)); this.ordersByCustomerId.put(cust4.getId(), new ArrayList<Order>()); final Customer cust6 = CustomerRepository.getInstance().findById(Integer.valueOf(6)); this.ordersByCustomerId.put(cust6.getId(), new ArrayList<Order>()); final Product prod1 = ProductRepository.getInstance().findById(Integer.valueOf(1)); final Product prod2 = ProductRepository.getInstance().findById(Integer.valueOf(2)); final Product prod3 = ProductRepository.getInstance().findById(Integer.valueOf(3)); final Product prod4 = ProductRepository.getInstance().findById(Integer.valueOf(4)); final Order order1 = new Order(); order1.setId(Integer.valueOf(1)); order1.setCustomer(cust4); order1.setDate(CalendarUtil.calendarFor(2009, 1, 12, 10, 23)); this.ordersById.put(order1.getId(), order1); this.ordersByCustomerId.get(cust4.getId()).add(order1); final OrderLine orderLine11 = new OrderLine(); orderLine11.setProduct(prod2); orderLine11.setAmount(Integer.valueOf(2)); orderLine11.setPurchasePrice(new BigDecimal("0.99")); order1.getOrderLines().add(orderLine11); final OrderLine orderLine12 = new OrderLine(); orderLine12.setProduct(prod3); orderLine12.setAmount(Integer.valueOf(4)); orderLine12.setPurchasePrice(new BigDecimal("2.50")); order1.getOrderLines().add(orderLine12); final OrderLine orderLine13 = new OrderLine(); orderLine13.setProduct(prod4); orderLine13.setAmount(Integer.valueOf(1)); orderLine13.setPurchasePrice(new BigDecimal("15.50")); order1.getOrderLines().add(orderLine13); final Order order2 = new Order(); order2.setId(Integer.valueOf(2)); order2.setCustomer(cust6); order2.setDate(CalendarUtil.calendarFor(2010, 6, 9, 21, 01)); this.ordersById.put(order2.getId(), order2); this.ordersByCustomerId.get(cust6.getId()).add(order2); final OrderLine orderLine21 = new OrderLine(); orderLine21.setProduct(prod1); orderLine21.setAmount(Integer.valueOf(5)); orderLine21.setPurchasePrice(new BigDecimal("3.75")); order2.getOrderLines().add(orderLine21); final OrderLine orderLine22 = new OrderLine(); orderLine22.setProduct(prod4); orderLine22.setAmount(Integer.valueOf(2)); orderLine22.setPurchasePrice(new BigDecimal("17.99")); order2.getOrderLines().add(orderLine22); final Order order3 = new Order(); order3.setId(Integer.valueOf(3)); order3.setCustomer(cust1); order3.setDate(CalendarUtil.calendarFor(2010, 7, 18, 22, 32)); this.ordersById.put(order3.getId(), order3); this.ordersByCustomerId.get(cust4.getId()).add(order3); final OrderLine orderLine32 = new OrderLine(); orderLine32.setProduct(prod1); orderLine32.setAmount(Integer.valueOf(8)); orderLine32.setPurchasePrice(new BigDecimal("5.99")); order3.getOrderLines().add(orderLine32); } public List<Order> findAll() { return new ArrayList<Order>(this.ordersById.values()); } public Order findById(final Integer id) { return this.ordersById.get(id); } public List<Order> findByCustomerId(final Integer customerId) {<FILL_FUNCTION_BODY>} }
final List<Order> ordersForCustomerId = this.ordersByCustomerId.get(customerId); if (ordersForCustomerId == null) { return new ArrayList<Order>(); } return ordersForCustomerId;
1,331
59
1,390
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-javax/src/main/java/org/thymeleaf/examples/core/gtvg/javax/business/util/CalendarUtil.java
CalendarUtil
calendarFor
class CalendarUtil { public static Calendar calendarFor( final int year, final int month, final int day, final int hour, final int minute) {<FILL_FUNCTION_BODY>} private CalendarUtil() { super(); } }
final Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month - 1); cal.set(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal;
78
133
211
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-javax/src/main/java/org/thymeleaf/examples/core/gtvg/javax/web/controller/HomeController.java
HomeController
process
class HomeController implements IGTVGController { public HomeController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); ctx.setVariable("today", Calendar.getInstance()); templateEngine.process("home", ctx, writer);
79
58
137
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-javax/src/main/java/org/thymeleaf/examples/core/gtvg/javax/web/controller/OrderDetailsController.java
OrderDetailsController
process
class OrderDetailsController implements IGTVGController { public OrderDetailsController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
final Integer orderId = Integer.valueOf(webExchange.getRequest().getParameterValue("orderId")); final OrderService orderService = new OrderService(); final Order order = orderService.findById(orderId); final WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); ctx.setVariable("order", order); templateEngine.process("order/details", ctx, writer);
81
115
196
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-javax/src/main/java/org/thymeleaf/examples/core/gtvg/javax/web/controller/OrderListController.java
OrderListController
process
class OrderListController implements IGTVGController { public OrderListController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
final OrderService orderService = new OrderService(); final List<Order> allOrders = orderService.findAll(); final WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); ctx.setVariable("orders", allOrders); templateEngine.process("order/list", ctx, writer);
81
91
172
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-javax/src/main/java/org/thymeleaf/examples/core/gtvg/javax/web/controller/ProductCommentsController.java
ProductCommentsController
process
class ProductCommentsController implements IGTVGController { public ProductCommentsController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
final Integer prodId = Integer.valueOf(webExchange.getRequest().getParameterValue("prodId")); final ProductService productService = new ProductService(); final Product product = productService.findById(prodId); final WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); ctx.setVariable("prod", product); templateEngine.process("product/comments", ctx, writer);
83
115
198
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-javax/src/main/java/org/thymeleaf/examples/core/gtvg/javax/web/controller/ProductListController.java
ProductListController
process
class ProductListController implements IGTVGController { public ProductListController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
final ProductService productService = new ProductService(); final List<Product> allProducts = productService.findAll(); final WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); ctx.setVariable("prods", allProducts); templateEngine.process("product/list", ctx, writer);
81
92
173
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-javax/src/main/java/org/thymeleaf/examples/core/gtvg/javax/web/controller/SubscribeController.java
SubscribeController
process
class SubscribeController implements IGTVGController { public SubscribeController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); templateEngine.process("subscribe", ctx, writer);
81
42
123
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-javax/src/main/java/org/thymeleaf/examples/core/gtvg/javax/web/controller/UserProfileController.java
UserProfileController
process
class UserProfileController implements IGTVGController { public UserProfileController() { super(); } public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {<FILL_FUNCTION_BODY>} }
final WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); templateEngine.process("userprofile", ctx, writer);
81
44
125
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-javax/src/main/java/org/thymeleaf/examples/core/gtvg/javax/web/filter/GTVGFilter.java
GTVGFilter
process
class GTVGFilter implements Filter { private ITemplateEngine templateEngine; private JavaxServletWebApplication application; public GTVGFilter() { super(); } private static void addUserToSession(final HttpServletRequest request) { // Simulate a real user session by adding a user object request.getSession(true).setAttribute("user", new User("John", "Apricot", "Antarctica", null)); } public void init(final FilterConfig filterConfig) throws ServletException { this.application = JavaxServletWebApplication.buildApplication(filterConfig.getServletContext()); this.templateEngine = buildTemplateEngine(this.application); } public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { addUserToSession((HttpServletRequest)request); if (!process((HttpServletRequest)request, (HttpServletResponse)response)) { chain.doFilter(request, response); } } public void destroy() { // nothing to do } private boolean process(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {<FILL_FUNCTION_BODY>} private static ITemplateEngine buildTemplateEngine(final IWebApplication application) { final WebApplicationTemplateResolver templateResolver = new WebApplicationTemplateResolver(application); // HTML is the default mode, but we will set it anyway for better understanding of code templateResolver.setTemplateMode(TemplateMode.HTML); // This will convert "home" to "/WEB-INF/templates/home.html" templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); // Set template cache TTL to 1 hour. If not set, entries would live in cache until expelled by LRU templateResolver.setCacheTTLMs(Long.valueOf(3600000L)); // Cache is set to true by default. Set to false if you want templates to // be automatically updated when modified. templateResolver.setCacheable(true); final TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); return templateEngine; } }
try { final IWebExchange webExchange = this.application.buildExchange(request, response); final IWebRequest webRequest = webExchange.getRequest(); // This prevents triggering engine executions for resource URLs if (webRequest.getPathWithinApplication().startsWith("/css") || webRequest.getPathWithinApplication().startsWith("/images") || webRequest.getPathWithinApplication().startsWith("/favicon")) { return false; } /* * Query controller/URL mapping and obtain the controller * that will process the request. If no controller is available, * return false and let other filters/servlets process the request. */ final IGTVGController controller = ControllerMappings.resolveControllerForRequest(webRequest); if (controller == null) { return false; } /* * Write the response headers */ response.setContentType("text/html;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); /* * Obtain the response writer */ final Writer writer = response.getWriter(); /* * Execute the controller and process view template, * writing the results to the response writer. */ controller.process(webExchange, this.templateEngine, writer); return true; } catch (final Exception e) { try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (final IOException ignored) { // Just ignore this } throw new ServletException(e); }
597
452
1,049
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/core/thymeleaf-examples-gtvg-javax/src/main/java/org/thymeleaf/examples/core/gtvg/javax/web/mapping/ControllerMappings.java
ControllerMappings
getRequestPath
class ControllerMappings { private static Map<String, IGTVGController> controllersByURL; static { controllersByURL = new HashMap<String, IGTVGController>(); controllersByURL.put("/", new HomeController()); controllersByURL.put("/product/list", new ProductListController()); controllersByURL.put("/product/comments", new ProductCommentsController()); controllersByURL.put("/order/list", new OrderListController()); controllersByURL.put("/order/details", new OrderDetailsController()); controllersByURL.put("/subscribe", new SubscribeController()); controllersByURL.put("/userprofile", new UserProfileController()); } public static IGTVGController resolveControllerForRequest(final IWebRequest request) { final String path = getRequestPath(request); return controllersByURL.get(path); } // Path within application might contain the ";jsessionid" fragment due to URL rewriting private static String getRequestPath(final IWebRequest request) {<FILL_FUNCTION_BODY>} private ControllerMappings() { super(); } }
String requestPath = request.getPathWithinApplication(); final int fragmentIndex = requestPath.indexOf(';'); if (fragmentIndex != -1) { requestPath = requestPath.substring(0, fragmentIndex); } return requestPath;
299
72
371
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-extrathyme/src/main/java/org/thymeleaf/examples/spring5/extrathyme/SpringWebApplicationInitializer.java
SpringWebApplicationInitializer
getServletFilters
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { public static final String CHARACTER_ENCODING = "UTF-8"; public SpringWebApplicationInitializer() { super(); } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { SpringWebConfig.class }; } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { SpringBusinessConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>} }
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding(CHARACTER_ENCODING); encodingFilter.setForceEncoding(true); return new Filter[] { encodingFilter };
195
55
250
<methods>public void <init>() <variables>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-extrathyme/src/main/java/org/thymeleaf/examples/spring5/extrathyme/business/entities/Headline.java
Headline
compareTo
class Headline implements Comparable<Headline> { private final Calendar date; private final String text; public Headline(final Calendar date, final String text) { super(); this.date = date; this.text = text; } public Calendar getDate() { return this.date; } public String getText() { return this.text; } public int compareTo(final Headline o) {<FILL_FUNCTION_BODY>} }
if (o == null) { return 1; } return this.date.compareTo(o.date);
151
35
186
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-extrathyme/src/main/java/org/thymeleaf/examples/spring5/extrathyme/business/entities/repositories/HeadlineRepository.java
HeadlineRepository
findAllHeadlines
class HeadlineRepository { public HeadlineRepository() { super(); } public List<Headline> findAllHeadlines() {<FILL_FUNCTION_BODY>} }
final List<Headline> headlines = new ArrayList<Headline>(); headlines.add(new Headline(Calendar.getInstance(), "Spearmint Caterpillars 1 - 0 Parsley Warriors")); headlines.add(new Headline(Calendar.getInstance(), "Laurel Troglodytes 1 - 1 Rosemary 75ers")); headlines.add(new Headline(Calendar.getInstance(), "Saffron Hunters 0 - 2 Polar Corianders")); headlines.add(new Headline(Calendar.getInstance(), "Angry Red Peppers 4 - 2 Basil Dragons")); headlines.add(new Headline(Calendar.getInstance(), "Sweet Paprika Savages 1 - 3 Cinnamon Sailors")); return headlines;
62
205
267
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-extrathyme/src/main/java/org/thymeleaf/examples/spring5/extrathyme/business/entities/repositories/TeamRepository.java
TeamRepository
findAllTeams
class TeamRepository { public TeamRepository() { super(); } public List<Team> findAllTeams() {<FILL_FUNCTION_BODY>} }
final List<Team> teams = new ArrayList<Team>(); teams.add(new Team("SPC", "Spearmint Caterpillars", 73, 21, 10, 5)); teams.add(new Team("BAD", "Basil Dragons", 72, 21, 9, 6)); teams.add(new Team("SPS", "Sweet Paprika Savages", 57, 15, 12, 9)); teams.add(new Team("PAW", "Parsley Warriors", 54, 15, 9, 12)); teams.add(new Team("PCO", "Polar Corianders", 49, 11, 16, 9)); teams.add(new Team("CSA", "Cinnamon Sailors", 48, 13, 9, 14)); teams.add(new Team("LTR", "Laurel Troglodytes", 41, 10, 11, 15)); teams.add(new Team("ARP", "Angry Red Peppers", 32, 8, 8, 20)); teams.add(new Team("ROS", "Rosemary 75ers", 32, 7, 11, 18)); teams.add(new Team("SHU", "Saffron Hunters", 31, 8, 7, 21)); return teams;
59
380
439
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-extrathyme/src/main/java/org/thymeleaf/examples/spring5/extrathyme/business/util/RemarkUtil.java
RemarkUtil
getRemarkForPosition
class RemarkUtil { public static Remark getRemarkForPosition(final Integer position) {<FILL_FUNCTION_BODY>} private RemarkUtil() { super(); } }
if (position == null) { return null; } switch (position.intValue()) { case 1: return Remark.WORLD_CHAMPIONS_LEAGUE; case 2: case 3: return Remark.CONTINENTAL_PLAYOFFS; case 10: return Remark.RELEGATION; } return null;
59
106
165
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-extrathyme/src/main/java/org/thymeleaf/examples/spring5/extrathyme/dialects/score/ClassForPositionAttributeTagProcessor.java
ClassForPositionAttributeTagProcessor
doProcess
class ClassForPositionAttributeTagProcessor extends AbstractAttributeTagProcessor { private static final String ATTR_NAME = "classforposition"; private static final int PRECEDENCE = 10000; public ClassForPositionAttributeTagProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching null, // No tag name: match any tag name false, // No prefix to be applied to tag name ATTR_NAME, // Name of the attribute that will be matched true, // Apply dialect prefix to attribute name PRECEDENCE, // Precedence (inside dialect's own precedence) true); // Remove the matched attribute afterwards } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final IEngineConfiguration configuration = context.getConfiguration(); /* * Obtain the Thymeleaf Standard Expression parser */ final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration); /* * Parse the attribute value as a Thymeleaf Standard Expression */ final IStandardExpression expression = parser.parseExpression(context, attributeValue); /* * Execute the expression just parsed */ final Integer position = (Integer) expression.execute(context); /* * Obtain the remark corresponding to this position in the league table. */ final Remark remark = RemarkUtil.getRemarkForPosition(position); /* * Select the adequate CSS class for the element. */ final String newValue; if (remark == Remark.WORLD_CHAMPIONS_LEAGUE) { newValue = "wcl"; } else if (remark == Remark.CONTINENTAL_PLAYOFFS) { newValue = "cpo"; } else if (remark == Remark.RELEGATION) { newValue = "rel"; } else { newValue = null; } /* * Set the new value into the 'class' attribute (maybe appending to an existing value) */ if (newValue != null) { if (attributeValue != null) { structureHandler.setAttribute("class", attributeValue + " " + newValue); } else { structureHandler.setAttribute("class", newValue); } }
269
398
667
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-extrathyme/src/main/java/org/thymeleaf/examples/spring5/extrathyme/dialects/score/HeadlinesElementTagProcessor.java
HeadlinesElementTagProcessor
doProcess
class HeadlinesElementTagProcessor extends AbstractElementTagProcessor { private static final String TAG_NAME = "headlines"; private static final int PRECEDENCE = 1000; private final Random rand = new Random(System.currentTimeMillis()); public HeadlinesElementTagProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching TAG_NAME, // Tag name: match specifically this tag true, // Apply dialect prefix to tag name null, // No attribute name: will match by tag name false, // No prefix to be applied to attribute name PRECEDENCE); // Precedence (inside dialect's own precedence) } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
/* * Obtain the Spring application context. */ final ApplicationContext appCtx = SpringContextUtils.getApplicationContext(context); /* * Obtain the HeadlineRepository bean from the application context, and ask * it for the current list of headlines. */ final HeadlineRepository headlineRepository = appCtx.getBean(HeadlineRepository.class); final List<Headline> headlines = headlineRepository.findAllHeadlines(); /* * Read the 'order' attribute from the tag. This optional attribute in our tag * will allow us to determine whether we want to show a random headline or * only the latest one ('latest' is default). */ final String order = tag.getAttributeValue("order"); String headlineText = null; if (order != null && order.trim().toLowerCase().equals("random")) { // Order is random final int r = this.rand.nextInt(headlines.size()); headlineText = headlines.get(r).getText(); } else { // Order is "latest", only the latest headline will be shown Collections.sort(headlines); headlineText = headlines.get(headlines.size() - 1).getText(); } /* * Create the DOM structure that will be substituting our custom tag. * The headline will be shown inside a '<div>' tag, and so this must * be created first and then a Text node must be added to it. */ final IModelFactory modelFactory = context.getModelFactory(); final IModel model = modelFactory.createModel(); model.add(modelFactory.createOpenElementTag("div", "class", "headlines")); model.add(modelFactory.createText(HtmlEscape.escapeHtml5(headlineText))); model.add(modelFactory.createCloseElementTag("div")); /* * Instruct the engine to replace this entire element with the specified model. */ structureHandler.replaceWith(model, false);
264
518
782
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, java.lang.String, java.lang.String, boolean, java.lang.String, boolean, int) ,public final org.thymeleaf.processor.element.MatchingAttributeName getMatchingAttributeName() ,public final org.thymeleaf.processor.element.MatchingElementName getMatchingElementName() ,public final void process(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IProcessableElementTag, org.thymeleaf.processor.element.IElementTagStructureHandler) <variables>private final non-sealed java.lang.String dialectPrefix,private final non-sealed org.thymeleaf.processor.element.MatchingAttributeName matchingAttributeName,private final non-sealed org.thymeleaf.processor.element.MatchingElementName matchingElementName
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-extrathyme/src/main/java/org/thymeleaf/examples/spring5/extrathyme/dialects/score/MatchDayTodayModelProcessor.java
MatchDayTodayModelProcessor
checkPositionInMarkup
class MatchDayTodayModelProcessor extends AbstractAttributeModelProcessor { private static final String ATTR_NAME = "match-day-today"; private static final int PRECEDENCE = 100; public MatchDayTodayModelProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching null, // No tag name: match any tag name false, // No prefix to be applied to tag name ATTR_NAME, // Name of the attribute that will be matched true, // Apply dialect prefix to attribute name PRECEDENCE, // Precedence (inside dialect's own precedence) true); // Remove the matched attribute afterwards } protected void doProcess( final ITemplateContext context, final IModel model, final AttributeName attributeName, final String attributeValue, final IElementModelStructureHandler structureHandler) { if (!checkPositionInMarkup(context)) { throw new TemplateProcessingException( "The " + ATTR_NAME + " attribute can only be used inside a " + "markup element with class \"leaguetable\""); } final Calendar now = Calendar.getInstance(context.getLocale()); final int dayOfWeek = now.get(Calendar.DAY_OF_WEEK); // Sundays are Match Days!! if (dayOfWeek == Calendar.SUNDAY) { // The Model Factory will allow us to create new events final IModelFactory modelFactory = context.getModelFactory(); // We will be adding the "Today is Match Day" banner just after // the element we are processing for: // // <h4 class="matchday">Today is MATCH DAY!</h4> // model.add(modelFactory.createOpenElementTag("h4", "class", "matchday")); // model.add(modelFactory.createText("Today is MATCH DAY!")); model.add(modelFactory.createCloseElementTag("h4")); } } private static boolean checkPositionInMarkup(final ITemplateContext context) {<FILL_FUNCTION_BODY>} }
/* * We want to make sure this processor is being applied inside a container tag which has * class="leaguetable". So we need to check the second-to-last entry in the element stack * (the last entry is the tag being processed itself). */ final List<IProcessableElementTag> elementStack = context.getElementStack(); if (elementStack.size() < 2) { return false; } final IProcessableElementTag container = elementStack.get(elementStack.size() - 2); if (!(container instanceof IOpenElementTag)) { return false; } final String classValue = container.getAttributeValue("class"); return classValue != null && classValue.equals("leaguetable");
569
193
762
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-extrathyme/src/main/java/org/thymeleaf/examples/spring5/extrathyme/dialects/score/RemarkForPositionAttributeTagProcessor.java
RemarkForPositionAttributeTagProcessor
doProcess
class RemarkForPositionAttributeTagProcessor extends AbstractAttributeTagProcessor { private static final String ATTR_NAME = "remarkforposition"; private static final int PRECEDENCE = 12000; public RemarkForPositionAttributeTagProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching null, // No tag name: match any tag name false, // No prefix to be applied to tag name ATTR_NAME, // Name of the attribute that will be matched true, // Apply dialect prefix to attribute name PRECEDENCE, // Precedence (inside dialect's precedence) true); // Remove the matched attribute afterwards } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final IEngineConfiguration configuration = context.getConfiguration(); /* * Obtain the Thymeleaf Standard Expression parser */ final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration); /* * Parse the attribute value as a Thymeleaf Standard Expression */ final IStandardExpression expression = parser.parseExpression(context, attributeValue); /* * Execute the expression just parsed */ final Integer position = (Integer) expression.execute(context); /* * Obtain the remark corresponding to this position in the league table */ final Remark remark = RemarkUtil.getRemarkForPosition(position); /* * If no remark is to be applied, just set an empty body to this tag */ if (remark == null) { structureHandler.setBody("", false); // false == 'non-processable' return; } /* * Message should be internationalized, so we ask the engine to resolve * the message 'remarks.{REMARK}' (e.g. 'remarks.RELEGATION'). No * parameters are needed for this message. * * Also, we will specify to "use absent representation" so that, if this * message entry didn't exist in our resource bundles, an absent-message * label will be shown. */ final String i18nMessage = context.getMessage( RemarkForPositionAttributeTagProcessor.class, "remarks." + remark.toString(), new Object[0], true); /* * Set the computed message as the body of the tag, HTML-escaped and * non-processable (hence the 'false' argument) */ structureHandler.setBody(HtmlEscape.escapeHtml5(i18nMessage), false);
269
460
729
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-extrathyme/src/main/java/org/thymeleaf/examples/spring5/extrathyme/dialects/score/ScoreDialect.java
ScoreDialect
getProcessors
class ScoreDialect extends AbstractProcessorDialect { private static final String DIALECT_NAME = "Score Dialect"; public ScoreDialect() { // We will set this dialect the same "dialect processor" precedence as // the Standard Dialect, so that processor executions can interleave. super(DIALECT_NAME, "score", StandardDialect.PROCESSOR_PRECEDENCE); } /* * Two attribute processors are declared: 'classforposition' and * 'remarkforposition'. Also one element processor: the 'headlines' * tag. */ public Set<IProcessor> getProcessors(final String dialectPrefix) {<FILL_FUNCTION_BODY>} }
final Set<IProcessor> processors = new HashSet<IProcessor>(); processors.add(new ClassForPositionAttributeTagProcessor(dialectPrefix)); processors.add(new RemarkForPositionAttributeTagProcessor(dialectPrefix)); processors.add(new HeadlinesElementTagProcessor(dialectPrefix)); processors.add(new MatchDayTodayModelProcessor(dialectPrefix)); // This will remove the xmlns:score attributes we might add for IDE validation processors.add(new StandardXmlNsTagProcessor(TemplateMode.HTML, dialectPrefix)); return processors;
192
147
339
<methods>public final int getDialectProcessorPrecedence() ,public final java.lang.String getPrefix() <variables>private final non-sealed java.lang.String prefix,private final non-sealed int processorPrecedence
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-extrathyme/src/main/java/org/thymeleaf/examples/spring5/extrathyme/web/SpringWebConfig.java
SpringWebConfig
templateEngine
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; public SpringWebConfig() { super(); } public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /* * Message externalization/internationalization */ @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource(); resourceBundleMessageSource.setBasename("Messages"); return resourceBundleMessageSource; } /* **************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS */ /* TemplateResolver <- TemplateEngine <- ViewResolver */ /* **************************************************************** */ @Bean public SpringResourceTemplateResolver templateResolver(){ SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(this.applicationContext); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); // Template cache is true by default. Set to false if you want // templates to be automatically updated when modified. templateResolver.setCacheable(true); return templateResolver; } @Bean public SpringTemplateEngine templateEngine(){<FILL_FUNCTION_BODY>} @Bean public ThymeleafViewResolver viewResolver(){ ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); return viewResolver; } /* ******************************************************************* */ /* Defines callback methods to customize the Java-based configuration */ /* for Spring MVC enabled via {@code @EnableWebMvc} */ /* ******************************************************************* */ /* * Dispatcher configuration for serving static resources */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry.addResourceHandler("/images/**").addResourceLocations("/images/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); } }
SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setEnableSpringELCompiler(true); // Compiled SpringEL should speed up executions templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(new ScoreDialect()); return templateEngine;
604
75
679
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-sayhello/src/main/java/org/thymeleaf/examples/spring5/sayhello/SpringWebApplicationInitializer.java
SpringWebApplicationInitializer
getServletFilters
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { public static final String CHARACTER_ENCODING = "UTF-8"; public SpringWebApplicationInitializer() { super(); } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { SpringWebConfig.class }; } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[0]; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>} }
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding(CHARACTER_ENCODING); encodingFilter.setForceEncoding(true); return new Filter[] { encodingFilter };
190
55
245
<methods>public void <init>() <variables>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-sayhello/src/main/java/org/thymeleaf/examples/spring5/sayhello/dialect/HelloDialect.java
HelloDialect
getProcessors
class HelloDialect extends AbstractProcessorDialect { public HelloDialect() { super( "Hello Dialect", // Dialect name "hello", // Dialect prefix (hello:*) 1000); // Dialect precedence } /* * Initialize the dialect's processors. * * Note the dialect prefix is passed here because, although we set * "hello" to be the dialect's prefix at the constructor, that only * works as a default, and at engine configuration time the user * might have chosen a different prefix to be used. */ public Set<IProcessor> getProcessors(final String dialectPrefix) {<FILL_FUNCTION_BODY>} }
final Set<IProcessor> processors = new HashSet<IProcessor>(); processors.add(new SayToAttributeTagProcessor(dialectPrefix)); processors.add(new SayToPlanetAttributeTagProcessor(dialectPrefix)); // This will remove the xmlns:hello attributes we might add for IDE validation processors.add(new StandardXmlNsTagProcessor(TemplateMode.HTML, dialectPrefix)); return processors;
195
108
303
<methods>public final int getDialectProcessorPrecedence() ,public final java.lang.String getPrefix() <variables>private final non-sealed java.lang.String prefix,private final non-sealed int processorPrecedence
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-sayhello/src/main/java/org/thymeleaf/examples/spring5/sayhello/dialect/SayToPlanetAttributeTagProcessor.java
SayToPlanetAttributeTagProcessor
doProcess
class SayToPlanetAttributeTagProcessor extends AbstractAttributeTagProcessor { private static final String ATTR_NAME = "saytoplanet"; private static final int PRECEDENCE = 10000; private static final String SAYTO_PLANET_MESSAGE = "msg.helloplanet"; public SayToPlanetAttributeTagProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching null, // No tag name: match any tag name false, // No prefix to be applied to tag name ATTR_NAME, // Name of the attribute that will be matched true, // Apply dialect prefix to attribute name PRECEDENCE, // Precedence (inside dialect's precedence) true); // Remove the matched attribute afterwards } protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
/* * In order to evaluate the attribute value as a Thymeleaf Standard Expression, * we first obtain the parser, then use it for parsing the attribute value into * an expression object, and finally execute this expression object. */ final IEngineConfiguration configuration = context.getConfiguration(); final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration); final IStandardExpression expression = parser.parseExpression(context, attributeValue); final String planet = (String) expression.execute(context); /* * This 'getMessage(...)' method will first try to resolve the message * from the configured Spring Message Sources (because this is a Spring * -enabled application). * * If not found, it will try to resolve it from a classpath-bound * .properties with the same name as the specified 'origin', which * in this case is this processor's class itself. This allows resources * to be packaged if needed in the same .jar files as the processors * they are used in. */ final String i18nMessage = context.getMessage( SayToPlanetAttributeTagProcessor.class, SAYTO_PLANET_MESSAGE, new Object[] {planet}, true); /* * Set the computed message as the body of the tag, HTML-escaped and * non-processable (hence the 'false' argument) */ structureHandler.setBody(HtmlEscape.escapeHtml5(i18nMessage), false);
296
387
683
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-sayhello/src/main/java/org/thymeleaf/examples/spring5/sayhello/web/SpringWebConfig.java
SpringWebConfig
templateResolver
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; public SpringWebConfig() { super(); } public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /* * Message externalization/internationalization */ @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource(); resourceBundleMessageSource.setBasename("Messages"); return resourceBundleMessageSource; } /* **************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS */ /* TemplateResolver <- TemplateEngine <- ViewResolver */ /* **************************************************************** */ @Bean public SpringResourceTemplateResolver templateResolver(){<FILL_FUNCTION_BODY>} @Bean public SpringTemplateEngine templateEngine(){ SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setEnableSpringELCompiler(true); // Compiled SpringEL should speed up executions templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(new HelloDialect()); return templateEngine; } @Bean public ThymeleafViewResolver viewResolver(){ ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); return viewResolver; } /* ******************************************************************* */ /* Defines callback methods to customize the Java-based configuration */ /* for Spring MVC enabled via {@code @EnableWebMvc} */ /* ******************************************************************* */ /* * Dispatcher configuration for serving static resources */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry.addResourceHandler("/images/**").addResourceLocations("/images/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); } }
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(this.applicationContext); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); // Template cache is true by default. Set to false if you want // templates to be automatically updated when modified. templateResolver.setCacheable(true); return templateResolver;
559
120
679
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-sayhello/src/main/java/org/thymeleaf/examples/spring5/sayhello/web/controller/SayHelloController.java
SayHelloController
populatePlanets
class SayHelloController { public SayHelloController() { super(); } @ModelAttribute("planets") public List<String> populatePlanets() {<FILL_FUNCTION_BODY>} @RequestMapping({"/","/sayhello"}) public String showSayHello() { return "sayhello"; } }
return Arrays.asList(new String[] { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" });
99
56
155
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-springmail/src/main/java/org/thymeleaf/examples/spring5/springmail/SpringWebApplicationInitializer.java
SpringWebApplicationInitializer
getServletFilters
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { public static final String CHARACTER_ENCODING = "UTF-8"; public SpringWebApplicationInitializer() { super(); } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { SpringWebConfig.class }; } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { SpringBusinessConfig.class, SpringMailConfig.class}; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>} }
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding(CHARACTER_ENCODING); encodingFilter.setForceEncoding(true); return new Filter[] { encodingFilter };
201
55
256
<methods>public void <init>() <variables>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-springmail/src/main/java/org/thymeleaf/examples/spring5/springmail/business/SpringMailConfig.java
SpringMailConfig
textTemplateResolver
class SpringMailConfig implements ApplicationContextAware, EnvironmentAware { public static final String EMAIL_TEMPLATE_ENCODING = "UTF-8"; private static final String JAVA_MAIL_FILE = "classpath:mail/javamail.properties"; private static final String HOST = "mail.server.host"; private static final String PORT = "mail.server.port"; private static final String PROTOCOL = "mail.server.protocol"; private static final String USERNAME = "mail.server.username"; private static final String PASSWORD = "mail.server.password"; private ApplicationContext applicationContext; private Environment environment; @Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void setEnvironment(final Environment environment) { this.environment = environment; } /* * SPRING + JAVAMAIL: JavaMailSender instance, configured via .properties files. */ @Bean public JavaMailSender mailSender() throws IOException { final JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); // Basic mail sender configuration, based on emailconfig.properties mailSender.setHost(this.environment.getProperty(HOST)); mailSender.setPort(Integer.parseInt(this.environment.getProperty(PORT))); mailSender.setProtocol(this.environment.getProperty(PROTOCOL)); mailSender.setUsername(this.environment.getProperty(USERNAME)); mailSender.setPassword(this.environment.getProperty(PASSWORD)); // JavaMail-specific mail sender configuration, based on javamail.properties final Properties javaMailProperties = new Properties(); javaMailProperties.load(this.applicationContext.getResource(JAVA_MAIL_FILE).getInputStream()); mailSender.setJavaMailProperties(javaMailProperties); return mailSender; } /* * Message externalization/internationalization for emails. * * NOTE we are avoiding the use of the name 'messageSource' for this bean because that * would make the MessageSource defined in SpringWebConfig (and made available for the * web-side template engine) delegate to this one, and thus effectively merge email * messages into web messages and make both types available at the web side, which could * bring undesired collisions. * * NOTE also that given we want this specific message source to be used by our * SpringTemplateEngines for emails (and not by the web one), we will set it explicitly * into each of the TemplateEngine objects with 'setTemplateEngineMessageSource(...)' */ @Bean public ResourceBundleMessageSource emailMessageSource() { final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("mail/MailMessages"); return messageSource; } /* ******************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS FOR EMAIL */ /* TemplateResolver(3) <- TemplateEngine */ /* ******************************************************************** */ @Bean public TemplateEngine emailTemplateEngine() { final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); // Resolver for TEXT emails templateEngine.addTemplateResolver(textTemplateResolver()); // Resolver for HTML emails (except the editable one) templateEngine.addTemplateResolver(htmlTemplateResolver()); // Resolver for HTML editable emails (which will be treated as a String) templateEngine.addTemplateResolver(stringTemplateResolver()); // Message source, internationalization specific to emails templateEngine.setTemplateEngineMessageSource(emailMessageSource()); return templateEngine; } private ITemplateResolver textTemplateResolver() {<FILL_FUNCTION_BODY>} private ITemplateResolver htmlTemplateResolver() { final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setOrder(Integer.valueOf(2)); templateResolver.setResolvablePatterns(Collections.singleton("html/*")); templateResolver.setPrefix("/mail/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); templateResolver.setCharacterEncoding(EMAIL_TEMPLATE_ENCODING); templateResolver.setCacheable(false); return templateResolver; } private ITemplateResolver stringTemplateResolver() { final StringTemplateResolver templateResolver = new StringTemplateResolver(); templateResolver.setOrder(Integer.valueOf(3)); // No resolvable pattern, will simply process as a String template everything not previously matched templateResolver.setTemplateMode("HTML5"); templateResolver.setCacheable(false); return templateResolver; } }
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setOrder(Integer.valueOf(1)); templateResolver.setResolvablePatterns(Collections.singleton("text/*")); templateResolver.setPrefix("/mail/"); templateResolver.setSuffix(".txt"); templateResolver.setTemplateMode(TemplateMode.TEXT); templateResolver.setCharacterEncoding(EMAIL_TEMPLATE_ENCODING); templateResolver.setCacheable(false); return templateResolver;
1,212
130
1,342
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-springmail/src/main/java/org/thymeleaf/examples/spring5/springmail/web/SpringWebConfig.java
SpringWebConfig
templateEngine
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /* ******************************************************************* */ /* GENERAL CONFIGURATION ARTIFACTS */ /* Static Resources, i18n Messages, Formatters (Conversion Service) */ /* ******************************************************************* */ /* * Dispatcher configuration for serving static resources */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry.addResourceHandler("/images/**").addResourceLocations("/images/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); } /* * Message externalization/internationalization */ @Bean public ResourceBundleMessageSource messageSource() { final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("Messages"); return messageSource; } /* * Multipart resolver (needed for uploading attachments from web form) */ @Bean public MultipartResolver multipartResolver() { final CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(10485760); // 10MBytes return multipartResolver; } /* **************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS */ /* TemplateResolver <- TemplateEngine <- ViewResolver */ /* **************************************************************** */ @Bean public SpringResourceTemplateResolver templateResolver(){ // SpringResourceTemplateResolver automatically integrates with Spring's own // resource resolution infrastructure, which is highly recommended. final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(this.applicationContext); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); // HTML is the default value, added here for the sake of clarity. templateResolver.setTemplateMode(TemplateMode.HTML); // Template cache is true by default. Set to false if you want // templates to be automatically updated when modified. templateResolver.setCacheable(true); return templateResolver; } @Bean public SpringTemplateEngine templateEngine(){<FILL_FUNCTION_BODY>} @Bean public ThymeleafViewResolver viewResolver(){ final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); return viewResolver; } }
// SpringTemplateEngine automatically applies SpringStandardDialect and // enables Spring's own MessageSource message resolution mechanisms. final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); // Enabling the SpringEL compiler with Spring 4.2.4 or newer can // speed up execution in most scenarios, but might be incompatible // with specific cases when expressions in one template are reused // across different data types, so this flag is "false" by default // for safer backwards compatibility. templateEngine.setEnableSpringELCompiler(true); return templateEngine;
729
151
880
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-springmail/src/main/java/org/thymeleaf/examples/spring5/springmail/web/controller/ErrorController.java
ErrorController
exception
class ErrorController { @ExceptionHandler(Throwable.class) public ModelAndView exception(Throwable throwable) {<FILL_FUNCTION_BODY>} }
String errorMessage = throwable != null ? throwable.getMessage() : "Unknown error"; ModelAndView mav = new ModelAndView(); mav.getModel().put("errorMessage", errorMessage); mav.setViewName("error"); return mav;
46
71
117
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-springmail/src/main/java/org/thymeleaf/examples/spring5/springmail/web/controller/SendingController.java
SendingController
sendMailWithAttachment
class SendingController { @Autowired private EmailService emailService; /* Send plain TEXT mail */ @RequestMapping(value = "/sendMailText", method = POST) public String sendTextMail( @RequestParam("recipientName") final String recipientName, @RequestParam("recipientEmail") final String recipientEmail, final Locale locale) throws MessagingException { this.emailService.sendTextMail(recipientName, recipientEmail, locale); return "redirect:sent.html"; } /* Send HTML mail (simple) */ @RequestMapping(value = "/sendMailSimple", method = POST) public String sendSimpleMail( @RequestParam("recipientName") final String recipientName, @RequestParam("recipientEmail") final String recipientEmail, final Locale locale) throws MessagingException { this.emailService.sendSimpleMail(recipientName, recipientEmail, locale); return "redirect:sent.html"; } /* Send HTML mail with attachment. */ @RequestMapping(value = "/sendMailWithAttachment", method = POST) public String sendMailWithAttachment( @RequestParam("recipientName") final String recipientName, @RequestParam("recipientEmail") final String recipientEmail, @RequestParam("attachment") final MultipartFile attachment, final Locale locale) throws MessagingException, IOException {<FILL_FUNCTION_BODY>} /* Send HTML mail with inline image */ @RequestMapping(value = "/sendMailWithInlineImage", method = POST) public String sendMailWithInline( @RequestParam("recipientName") final String recipientName, @RequestParam("recipientEmail") final String recipientEmail, @RequestParam("image") final MultipartFile image, final Locale locale) throws MessagingException, IOException { this.emailService.sendMailWithInline( recipientName, recipientEmail, image.getName(), image.getBytes(), image.getContentType(), locale); return "redirect:sent.html"; } /* Send editable HTML mail */ @RequestMapping(value = "/sendEditableMail", method = POST) public String sendMailWithInline( @RequestParam("recipientName") final String recipientName, @RequestParam("recipientEmail") final String recipientEmail, @RequestParam("body") final String body, final Locale locale) throws MessagingException, IOException { this.emailService.sendEditableMail( recipientName, recipientEmail, body, locale); return "redirect:sent.html"; } }
this.emailService.sendMailWithAttachment( recipientName, recipientEmail, attachment.getOriginalFilename(), attachment.getBytes(), attachment.getContentType(), locale); return "redirect:sent.html";
673
59
732
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-stsm/src/main/java/org/thymeleaf/examples/spring5/stsm/SpringWebApplicationInitializer.java
SpringWebApplicationInitializer
getServletFilters
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { public static final String CHARACTER_ENCODING = "UTF-8"; public SpringWebApplicationInitializer() { super(); } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { SpringWebConfig.class }; } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { SpringBusinessConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>} }
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding(CHARACTER_ENCODING); encodingFilter.setForceEncoding(true); return new Filter[] { encodingFilter };
195
55
250
<methods>public void <init>() <variables>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-stsm/src/main/java/org/thymeleaf/examples/spring5/stsm/business/entities/Row.java
Row
toString
class Row { private Variety variety = null; private Integer seedsPerCell = null; public Row() { super(); } public Variety getVariety() { return this.variety; } public void setVariety(final Variety variety) { this.variety = variety; } public Integer getSeedsPerCell() { return this.seedsPerCell; } public void setSeedsPerCell(final Integer seedsPerCell) { this.seedsPerCell = seedsPerCell; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Row [variety=" + this.variety + ", seedsPerCell=" + this.seedsPerCell + "]";
186
36
222
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-stsm/src/main/java/org/thymeleaf/examples/spring5/stsm/business/entities/SeedStarter.java
SeedStarter
toString
class SeedStarter { private Integer id = null; private Date datePlanted = null; private Boolean covered = null; private Type type = Type.PLASTIC; private Feature[] features = null; private List<Row> rows = new ArrayList<Row>(); public SeedStarter() { super(); } public Integer getId() { return this.id; } public void setId(final Integer id) { this.id = id; } public Date getDatePlanted() { return this.datePlanted; } public void setDatePlanted(final Date datePlanted) { this.datePlanted = datePlanted; } public Boolean getCovered() { return this.covered; } public void setCovered(final Boolean covered) { this.covered = covered; } public Type getType() { return this.type; } public void setType(final Type type) { this.type = type; } public Feature[] getFeatures() { return this.features; } public void setFeatures(final Feature[] features) { this.features = features; } public List<Row> getRows() { return this.rows; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SeedStarter [id=" + this.id + ", datePlanted=" + this.datePlanted + ", covered=" + this.covered + ", type=" + this.type + ", features=" + Arrays.toString(this.features) + ", rows=" + this.rows + "]";
389
83
472
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-stsm/src/main/java/org/thymeleaf/examples/spring5/stsm/web/SpringWebConfig.java
SpringWebConfig
templateEngine
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; public SpringWebConfig() { super(); } public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /* ******************************************************************* */ /* GENERAL CONFIGURATION ARTIFACTS */ /* Static Resources, i18n Messages, Formatters (Conversion Service) */ /* ******************************************************************* */ /* * Dispatcher configuration for serving static resources */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry.addResourceHandler("/images/**").addResourceLocations("/images/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); } /* * Message externalization/internationalization */ @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("Messages"); return messageSource; } /* * Add formatter for class *.stsm.business.entities.Variety * and java.util.Date in addition to the ones registered by default */ @Override public void addFormatters(final FormatterRegistry registry) { WebMvcConfigurer.super.addFormatters(registry); registry.addFormatter(varietyFormatter()); registry.addFormatter(dateFormatter()); } @Bean public VarietyFormatter varietyFormatter() { return new VarietyFormatter(); } @Bean public DateFormatter dateFormatter() { return new DateFormatter(); } /* **************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS */ /* TemplateResolver <- TemplateEngine <- ViewResolver */ /* **************************************************************** */ @Bean public SpringResourceTemplateResolver templateResolver(){ // SpringResourceTemplateResolver automatically integrates with Spring's own // resource resolution infrastructure, which is highly recommended. SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(this.applicationContext); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); // HTML is the default value, added here for the sake of clarity. templateResolver.setTemplateMode(TemplateMode.HTML); // Template cache is true by default. Set to false if you want // templates to be automatically updated when modified. templateResolver.setCacheable(true); return templateResolver; } @Bean public SpringTemplateEngine templateEngine(){<FILL_FUNCTION_BODY>} @Bean public ThymeleafViewResolver viewResolver(){ ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); return viewResolver; } }
// SpringTemplateEngine automatically applies SpringStandardDialect and // enables Spring's own MessageSource message resolution mechanisms. SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); // Enabling the SpringEL compiler with Spring 4.2.4 or newer can // speed up execution in most scenarios, but might be incompatible // with specific cases when expressions in one template are reused // across different data types, so this flag is "false" by default // for safer backwards compatibility. templateEngine.setEnableSpringELCompiler(true); return templateEngine;
815
150
965
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-stsm/src/main/java/org/thymeleaf/examples/spring5/stsm/web/controller/SeedStarterMngController.java
SeedStarterMngController
saveSeedstarter
class SeedStarterMngController { @Autowired private VarietyService varietyService; @Autowired private SeedStarterService seedStarterService; public SeedStarterMngController() { super(); } @ModelAttribute("allTypes") public List<Type> populateTypes() { return Arrays.asList(Type.ALL); } @ModelAttribute("allFeatures") public List<Feature> populateFeatures() { return Arrays.asList(Feature.ALL); } @ModelAttribute("allVarieties") public List<Variety> populateVarieties() { return this.varietyService.findAll(); } @ModelAttribute("allSeedStarters") public List<SeedStarter> populateSeedStarters() { return this.seedStarterService.findAll(); } @RequestMapping({"/","/seedstartermng"}) public String showSeedstarters(final SeedStarter seedStarter) { seedStarter.setDatePlanted(Calendar.getInstance().getTime()); return "seedstartermng"; } @RequestMapping(value="/seedstartermng", params={"save"}) public String saveSeedstarter(final SeedStarter seedStarter, final BindingResult bindingResult, final ModelMap model) {<FILL_FUNCTION_BODY>} @RequestMapping(value="/seedstartermng", params={"addRow"}) public String addRow(final SeedStarter seedStarter, final BindingResult bindingResult) { seedStarter.getRows().add(new Row()); return "seedstartermng"; } @RequestMapping(value="/seedstartermng", params={"removeRow"}) public String removeRow(final SeedStarter seedStarter, final BindingResult bindingResult, final HttpServletRequest req) { final Integer rowId = Integer.valueOf(req.getParameter("removeRow")); seedStarter.getRows().remove(rowId.intValue()); return "seedstartermng"; } }
if (bindingResult.hasErrors()) { return "seedstartermng"; } this.seedStarterService.add(seedStarter); model.clear(); return "redirect:/seedstartermng";
568
59
627
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-stsm/src/main/java/org/thymeleaf/examples/spring5/stsm/web/conversion/DateFormatter.java
DateFormatter
createDateFormat
class DateFormatter implements Formatter<Date> { @Autowired private MessageSource messageSource; public DateFormatter() { super(); } public Date parse(final String text, final Locale locale) throws ParseException { final SimpleDateFormat dateFormat = createDateFormat(locale); return dateFormat.parse(text); } public String print(final Date object, final Locale locale) { final SimpleDateFormat dateFormat = createDateFormat(locale); return dateFormat.format(object); } private SimpleDateFormat createDateFormat(final Locale locale) {<FILL_FUNCTION_BODY>} }
final String format = this.messageSource.getMessage("date.format", null, locale); final SimpleDateFormat dateFormat = new SimpleDateFormat(format); dateFormat.setLenient(false); return dateFormat;
170
57
227
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-thvsjsp/src/main/java/org/thymeleaf/examples/spring5/thvsjsp/SpringWebApplicationInitializer.java
SpringWebApplicationInitializer
getServletFilters
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { public static final String CHARACTER_ENCODING = "UTF-8"; public SpringWebApplicationInitializer() { super(); } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { SpringWebConfig.class }; } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[0]; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>} }
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding(CHARACTER_ENCODING); encodingFilter.setForceEncoding(true); return new Filter[] { encodingFilter };
190
55
245
<methods>public void <init>() <variables>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-thvsjsp/src/main/java/org/thymeleaf/examples/spring5/thvsjsp/business/entities/Subscription.java
Subscription
toString
class Subscription { private String email; private SubscriptionType subscriptionType = SubscriptionType.ALL_EMAILS; public Subscription() { super(); } public String getEmail() { return this.email; } public void setEmail(final String email) { this.email = email; } public SubscriptionType getSubscriptionType() { return this.subscriptionType; } public void setSubscriptionType(final SubscriptionType subscriptionType) { this.subscriptionType = subscriptionType; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Subscription [email=" + this.email + ", subscriptionType=" + this.subscriptionType + "]";
186
35
221
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-thvsjsp/src/main/java/org/thymeleaf/examples/spring5/thvsjsp/web/SpringWebConfig.java
SpringWebConfig
templateEngine
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; public SpringWebConfig() { super(); } public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /* * Message externalization/internationalization */ @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource(); resourceBundleMessageSource.setBasename("Messages"); return resourceBundleMessageSource; } /* **************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS */ /* TemplateResolver <- TemplateEngine <- ViewResolver */ /* **************************************************************** */ @Bean public SpringResourceTemplateResolver templateResolver(){ SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(this.applicationContext); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); // Template cache is true by default. Set to false if you want // templates to be automatically updated when modified. templateResolver.setCacheable(true); return templateResolver; } @Bean public SpringTemplateEngine templateEngine(){<FILL_FUNCTION_BODY>} @Bean public ThymeleafViewResolver thymeleafViewResolver(){ ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setContentType("text/html;encoding=utf-8"); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setViewNames(new String[] {"index","*th"}); viewResolver.setOrder(Integer.valueOf(1)); return viewResolver; } /* **************************************************************** */ /* JSP-SPECIFIC ARTIFACTS */ /* **************************************************************** */ @Bean public InternalResourceViewResolver jspViewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/templates/"); viewResolver.setSuffix(".jsp"); viewResolver.setViewNames(new String[] {"*jsp"}); viewResolver.setOrder(Integer.valueOf(2)); return viewResolver; } /* ******************************************************************* */ /* Defines callback methods to customize the Java-based configuration */ /* for Spring MVC enabled via {@code @EnableWebMvc} */ /* ******************************************************************* */ /* * Dispatcher configuration for serving static resources */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry.addResourceHandler("/images/**").addResourceLocations("/images/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); } }
SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setEnableSpringELCompiler(true); // Compiled SpringEL should speed up executions templateEngine.setTemplateResolver(templateResolver()); return templateEngine;
822
58
880
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-thvsjsp/src/main/java/org/thymeleaf/examples/spring5/thvsjsp/web/controller/SubscribeJsp.java
SubscribeJsp
subscribe
class SubscribeJsp { private static final Logger log = LoggerFactory.getLogger(SubscribeJsp.class); public SubscribeJsp() { super(); } @ModelAttribute("allTypes") public SubscriptionType[] populateTypes() { return new SubscriptionType[] { SubscriptionType.ALL_EMAILS, SubscriptionType.DAILY_DIGEST }; } @RequestMapping({"/subscribejsp"}) public String showSubscription(final Subscription subscription) { return "subscribejsp"; } @RequestMapping(value="/subscribejsp", params={"save"}) public String subscribe(final Subscription subscription, final BindingResult bindingResult, final ModelMap model) {<FILL_FUNCTION_BODY>} }
if (bindingResult.hasErrors()) { return "subscribejsp"; } log.info("JUST ADDED SUBSCRIPTION: " + subscription); model.clear(); return "redirect:/subscribejsp";
220
61
281
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring5/thymeleaf-examples-spring5-thvsjsp/src/main/java/org/thymeleaf/examples/spring5/thvsjsp/web/controller/SubscribeTh.java
SubscribeTh
subscribe
class SubscribeTh { private static final Logger log = LoggerFactory.getLogger(SubscribeTh.class); public SubscribeTh() { super(); } @ModelAttribute("allTypes") public SubscriptionType[] populateTypes() { return new SubscriptionType[] { SubscriptionType.ALL_EMAILS, SubscriptionType.DAILY_DIGEST }; } @RequestMapping({"/subscribeth"}) public String showSubscription(final Subscription subscription) { return "subscribeth"; } @RequestMapping(value="/subscribeth", params={"save"}) public String subscribe(final Subscription subscription, final BindingResult bindingResult, final ModelMap model) {<FILL_FUNCTION_BODY>} }
if (bindingResult.hasErrors()) { return "subscribeth"; } log.info("JUST ADDED SUBSCRIPTION: " + subscription); model.clear(); return "redirect:/subscribeth";
220
63
283
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-extrathyme/src/main/java/org/thymeleaf/examples/spring6/extrathyme/SpringWebApplicationInitializer.java
SpringWebApplicationInitializer
getServletFilters
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { public static final String CHARACTER_ENCODING = "UTF-8"; public SpringWebApplicationInitializer() { super(); } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { SpringWebConfig.class }; } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { SpringBusinessConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>} }
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding(CHARACTER_ENCODING); encodingFilter.setForceEncoding(true); return new Filter[] { encodingFilter };
195
55
250
<methods>public void <init>() <variables>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-extrathyme/src/main/java/org/thymeleaf/examples/spring6/extrathyme/business/entities/Headline.java
Headline
compareTo
class Headline implements Comparable<Headline> { private final Calendar date; private final String text; public Headline(final Calendar date, final String text) { super(); this.date = date; this.text = text; } public Calendar getDate() { return this.date; } public String getText() { return this.text; } public int compareTo(final Headline o) {<FILL_FUNCTION_BODY>} }
if (o == null) { return 1; } return this.date.compareTo(o.date);
151
35
186
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-extrathyme/src/main/java/org/thymeleaf/examples/spring6/extrathyme/business/entities/repositories/HeadlineRepository.java
HeadlineRepository
findAllHeadlines
class HeadlineRepository { public HeadlineRepository() { super(); } public List<Headline> findAllHeadlines() {<FILL_FUNCTION_BODY>} }
final List<Headline> headlines = new ArrayList<Headline>(); headlines.add(new Headline(Calendar.getInstance(), "Spearmint Caterpillars 1 - 0 Parsley Warriors")); headlines.add(new Headline(Calendar.getInstance(), "Laurel Troglodytes 1 - 1 Rosemary 75ers")); headlines.add(new Headline(Calendar.getInstance(), "Saffron Hunters 0 - 2 Polar Corianders")); headlines.add(new Headline(Calendar.getInstance(), "Angry Red Peppers 4 - 2 Basil Dragons")); headlines.add(new Headline(Calendar.getInstance(), "Sweet Paprika Savages 1 - 3 Cinnamon Sailors")); return headlines;
62
205
267
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-extrathyme/src/main/java/org/thymeleaf/examples/spring6/extrathyme/business/entities/repositories/TeamRepository.java
TeamRepository
findAllTeams
class TeamRepository { public TeamRepository() { super(); } public List<Team> findAllTeams() {<FILL_FUNCTION_BODY>} }
final List<Team> teams = new ArrayList<Team>(); teams.add(new Team("SPC", "Spearmint Caterpillars", 73, 21, 10, 5)); teams.add(new Team("BAD", "Basil Dragons", 72, 21, 9, 6)); teams.add(new Team("SPS", "Sweet Paprika Savages", 57, 15, 12, 9)); teams.add(new Team("PAW", "Parsley Warriors", 54, 15, 9, 12)); teams.add(new Team("PCO", "Polar Corianders", 49, 11, 16, 9)); teams.add(new Team("CSA", "Cinnamon Sailors", 48, 13, 9, 14)); teams.add(new Team("LTR", "Laurel Troglodytes", 41, 10, 11, 15)); teams.add(new Team("ARP", "Angry Red Peppers", 32, 8, 8, 20)); teams.add(new Team("ROS", "Rosemary 75ers", 32, 7, 11, 18)); teams.add(new Team("SHU", "Saffron Hunters", 31, 8, 7, 21)); return teams;
59
380
439
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-extrathyme/src/main/java/org/thymeleaf/examples/spring6/extrathyme/business/util/RemarkUtil.java
RemarkUtil
getRemarkForPosition
class RemarkUtil { public static Remark getRemarkForPosition(final Integer position) {<FILL_FUNCTION_BODY>} private RemarkUtil() { super(); } }
if (position == null) { return null; } switch (position.intValue()) { case 1: return Remark.WORLD_CHAMPIONS_LEAGUE; case 2: case 3: return Remark.CONTINENTAL_PLAYOFFS; case 10: return Remark.RELEGATION; } return null;
59
106
165
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-extrathyme/src/main/java/org/thymeleaf/examples/spring6/extrathyme/dialects/score/ClassForPositionAttributeTagProcessor.java
ClassForPositionAttributeTagProcessor
doProcess
class ClassForPositionAttributeTagProcessor extends AbstractAttributeTagProcessor { private static final String ATTR_NAME = "classforposition"; private static final int PRECEDENCE = 10000; public ClassForPositionAttributeTagProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching null, // No tag name: match any tag name false, // No prefix to be applied to tag name ATTR_NAME, // Name of the attribute that will be matched true, // Apply dialect prefix to attribute name PRECEDENCE, // Precedence (inside dialect's own precedence) true); // Remove the matched attribute afterwards } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final IEngineConfiguration configuration = context.getConfiguration(); /* * Obtain the Thymeleaf Standard Expression parser */ final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration); /* * Parse the attribute value as a Thymeleaf Standard Expression */ final IStandardExpression expression = parser.parseExpression(context, attributeValue); /* * Execute the expression just parsed */ final Integer position = (Integer) expression.execute(context); /* * Obtain the remark corresponding to this position in the league table. */ final Remark remark = RemarkUtil.getRemarkForPosition(position); /* * Select the adequate CSS class for the element. */ final String newValue; if (remark == Remark.WORLD_CHAMPIONS_LEAGUE) { newValue = "wcl"; } else if (remark == Remark.CONTINENTAL_PLAYOFFS) { newValue = "cpo"; } else if (remark == Remark.RELEGATION) { newValue = "rel"; } else { newValue = null; } /* * Set the new value into the 'class' attribute (maybe appending to an existing value) */ if (newValue != null) { if (attributeValue != null) { structureHandler.setAttribute("class", attributeValue + " " + newValue); } else { structureHandler.setAttribute("class", newValue); } }
269
398
667
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-extrathyme/src/main/java/org/thymeleaf/examples/spring6/extrathyme/dialects/score/HeadlinesElementTagProcessor.java
HeadlinesElementTagProcessor
doProcess
class HeadlinesElementTagProcessor extends AbstractElementTagProcessor { private static final String TAG_NAME = "headlines"; private static final int PRECEDENCE = 1000; private final Random rand = new Random(System.currentTimeMillis()); public HeadlinesElementTagProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching TAG_NAME, // Tag name: match specifically this tag true, // Apply dialect prefix to tag name null, // No attribute name: will match by tag name false, // No prefix to be applied to attribute name PRECEDENCE); // Precedence (inside dialect's own precedence) } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
/* * Obtain the Spring application context. */ final ApplicationContext appCtx = SpringContextUtils.getApplicationContext(context); /* * Obtain the HeadlineRepository bean from the application context, and ask * it for the current list of headlines. */ final HeadlineRepository headlineRepository = appCtx.getBean(HeadlineRepository.class); final List<Headline> headlines = headlineRepository.findAllHeadlines(); /* * Read the 'order' attribute from the tag. This optional attribute in our tag * will allow us to determine whether we want to show a random headline or * only the latest one ('latest' is default). */ final String order = tag.getAttributeValue("order"); String headlineText = null; if (order != null && order.trim().toLowerCase().equals("random")) { // Order is random final int r = this.rand.nextInt(headlines.size()); headlineText = headlines.get(r).getText(); } else { // Order is "latest", only the latest headline will be shown Collections.sort(headlines); headlineText = headlines.get(headlines.size() - 1).getText(); } /* * Create the DOM structure that will be substituting our custom tag. * The headline will be shown inside a '<div>' tag, and so this must * be created first and then a Text node must be added to it. */ final IModelFactory modelFactory = context.getModelFactory(); final IModel model = modelFactory.createModel(); model.add(modelFactory.createOpenElementTag("div", "class", "headlines")); model.add(modelFactory.createText(HtmlEscape.escapeHtml5(headlineText))); model.add(modelFactory.createCloseElementTag("div")); /* * Instruct the engine to replace this entire element with the specified model. */ structureHandler.replaceWith(model, false);
264
518
782
<methods>public void <init>(org.thymeleaf.templatemode.TemplateMode, java.lang.String, java.lang.String, boolean, java.lang.String, boolean, int) ,public final org.thymeleaf.processor.element.MatchingAttributeName getMatchingAttributeName() ,public final org.thymeleaf.processor.element.MatchingElementName getMatchingElementName() ,public final void process(org.thymeleaf.context.ITemplateContext, org.thymeleaf.model.IProcessableElementTag, org.thymeleaf.processor.element.IElementTagStructureHandler) <variables>private final non-sealed java.lang.String dialectPrefix,private final non-sealed org.thymeleaf.processor.element.MatchingAttributeName matchingAttributeName,private final non-sealed org.thymeleaf.processor.element.MatchingElementName matchingElementName
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-extrathyme/src/main/java/org/thymeleaf/examples/spring6/extrathyme/dialects/score/MatchDayTodayModelProcessor.java
MatchDayTodayModelProcessor
checkPositionInMarkup
class MatchDayTodayModelProcessor extends AbstractAttributeModelProcessor { private static final String ATTR_NAME = "match-day-today"; private static final int PRECEDENCE = 100; public MatchDayTodayModelProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching null, // No tag name: match any tag name false, // No prefix to be applied to tag name ATTR_NAME, // Name of the attribute that will be matched true, // Apply dialect prefix to attribute name PRECEDENCE, // Precedence (inside dialect's own precedence) true); // Remove the matched attribute afterwards } protected void doProcess( final ITemplateContext context, final IModel model, final AttributeName attributeName, final String attributeValue, final IElementModelStructureHandler structureHandler) { if (!checkPositionInMarkup(context)) { throw new TemplateProcessingException( "The " + ATTR_NAME + " attribute can only be used inside a " + "markup element with class \"leaguetable\""); } final Calendar now = Calendar.getInstance(context.getLocale()); final int dayOfWeek = now.get(Calendar.DAY_OF_WEEK); // Sundays are Match Days!! if (dayOfWeek == Calendar.SUNDAY) { // The Model Factory will allow us to create new events final IModelFactory modelFactory = context.getModelFactory(); // We will be adding the "Today is Match Day" banner just after // the element we are processing for: // // <h4 class="matchday">Today is MATCH DAY!</h4> // model.add(modelFactory.createOpenElementTag("h4", "class", "matchday")); // model.add(modelFactory.createText("Today is MATCH DAY!")); model.add(modelFactory.createCloseElementTag("h4")); } } private static boolean checkPositionInMarkup(final ITemplateContext context) {<FILL_FUNCTION_BODY>} }
/* * We want to make sure this processor is being applied inside a container tag which has * class="leaguetable". So we need to check the second-to-last entry in the element stack * (the last entry is the tag being processed itself). */ final List<IProcessableElementTag> elementStack = context.getElementStack(); if (elementStack.size() < 2) { return false; } final IProcessableElementTag container = elementStack.get(elementStack.size() - 2); if (!(container instanceof IOpenElementTag)) { return false; } final String classValue = container.getAttributeValue("class"); return classValue != null && classValue.equals("leaguetable");
569
193
762
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-extrathyme/src/main/java/org/thymeleaf/examples/spring6/extrathyme/dialects/score/RemarkForPositionAttributeTagProcessor.java
RemarkForPositionAttributeTagProcessor
doProcess
class RemarkForPositionAttributeTagProcessor extends AbstractAttributeTagProcessor { private static final String ATTR_NAME = "remarkforposition"; private static final int PRECEDENCE = 12000; public RemarkForPositionAttributeTagProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching null, // No tag name: match any tag name false, // No prefix to be applied to tag name ATTR_NAME, // Name of the attribute that will be matched true, // Apply dialect prefix to attribute name PRECEDENCE, // Precedence (inside dialect's precedence) true); // Remove the matched attribute afterwards } @Override protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
final IEngineConfiguration configuration = context.getConfiguration(); /* * Obtain the Thymeleaf Standard Expression parser */ final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration); /* * Parse the attribute value as a Thymeleaf Standard Expression */ final IStandardExpression expression = parser.parseExpression(context, attributeValue); /* * Execute the expression just parsed */ final Integer position = (Integer) expression.execute(context); /* * Obtain the remark corresponding to this position in the league table */ final Remark remark = RemarkUtil.getRemarkForPosition(position); /* * If no remark is to be applied, just set an empty body to this tag */ if (remark == null) { structureHandler.setBody("", false); // false == 'non-processable' return; } /* * Message should be internationalized, so we ask the engine to resolve * the message 'remarks.{REMARK}' (e.g. 'remarks.RELEGATION'). No * parameters are needed for this message. * * Also, we will specify to "use absent representation" so that, if this * message entry didn't exist in our resource bundles, an absent-message * label will be shown. */ final String i18nMessage = context.getMessage( RemarkForPositionAttributeTagProcessor.class, "remarks." + remark.toString(), new Object[0], true); /* * Set the computed message as the body of the tag, HTML-escaped and * non-processable (hence the 'false' argument) */ structureHandler.setBody(HtmlEscape.escapeHtml5(i18nMessage), false);
269
460
729
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-extrathyme/src/main/java/org/thymeleaf/examples/spring6/extrathyme/dialects/score/ScoreDialect.java
ScoreDialect
getProcessors
class ScoreDialect extends AbstractProcessorDialect { private static final String DIALECT_NAME = "Score Dialect"; public ScoreDialect() { // We will set this dialect the same "dialect processor" precedence as // the Standard Dialect, so that processor executions can interleave. super(DIALECT_NAME, "score", StandardDialect.PROCESSOR_PRECEDENCE); } /* * Two attribute processors are declared: 'classforposition' and * 'remarkforposition'. Also one element processor: the 'headlines' * tag. */ public Set<IProcessor> getProcessors(final String dialectPrefix) {<FILL_FUNCTION_BODY>} }
final Set<IProcessor> processors = new HashSet<IProcessor>(); processors.add(new ClassForPositionAttributeTagProcessor(dialectPrefix)); processors.add(new RemarkForPositionAttributeTagProcessor(dialectPrefix)); processors.add(new HeadlinesElementTagProcessor(dialectPrefix)); processors.add(new MatchDayTodayModelProcessor(dialectPrefix)); // This will remove the xmlns:score attributes we might add for IDE validation processors.add(new StandardXmlNsTagProcessor(TemplateMode.HTML, dialectPrefix)); return processors;
192
147
339
<methods>public final int getDialectProcessorPrecedence() ,public final java.lang.String getPrefix() <variables>private final non-sealed java.lang.String prefix,private final non-sealed int processorPrecedence
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-extrathyme/src/main/java/org/thymeleaf/examples/spring6/extrathyme/web/SpringWebConfig.java
SpringWebConfig
templateResolver
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; public SpringWebConfig() { super(); } public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /* * Message externalization/internationalization */ @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource(); resourceBundleMessageSource.setBasename("Messages"); return resourceBundleMessageSource; } /* **************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS */ /* TemplateResolver <- TemplateEngine <- ViewResolver */ /* **************************************************************** */ @Bean public SpringResourceTemplateResolver templateResolver(){<FILL_FUNCTION_BODY>} @Bean public SpringTemplateEngine templateEngine(){ SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setEnableSpringELCompiler(true); // Compiled SpringEL should speed up executions templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(new ScoreDialect()); return templateEngine; } @Bean public ThymeleafViewResolver viewResolver(){ ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); return viewResolver; } /* ******************************************************************* */ /* Defines callback methods to customize the Java-based configuration */ /* for Spring MVC enabled via {@code @EnableWebMvc} */ /* ******************************************************************* */ /* * Dispatcher configuration for serving static resources */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry.addResourceHandler("/images/**").addResourceLocations("/images/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); } }
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(this.applicationContext); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); // Template cache is true by default. Set to false if you want // templates to be automatically updated when modified. templateResolver.setCacheable(true); return templateResolver;
559
120
679
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-sayhello/src/main/java/org/thymeleaf/examples/spring6/sayhello/SpringWebApplicationInitializer.java
SpringWebApplicationInitializer
getServletFilters
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { public static final String CHARACTER_ENCODING = "UTF-8"; public SpringWebApplicationInitializer() { super(); } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { SpringWebConfig.class }; } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[0]; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>} }
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding(CHARACTER_ENCODING); encodingFilter.setForceEncoding(true); return new Filter[] { encodingFilter };
190
55
245
<methods>public void <init>() <variables>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-sayhello/src/main/java/org/thymeleaf/examples/spring6/sayhello/dialect/HelloDialect.java
HelloDialect
getProcessors
class HelloDialect extends AbstractProcessorDialect { public HelloDialect() { super( "Hello Dialect", // Dialect name "hello", // Dialect prefix (hello:*) 1000); // Dialect precedence } /* * Initialize the dialect's processors. * * Note the dialect prefix is passed here because, although we set * "hello" to be the dialect's prefix at the constructor, that only * works as a default, and at engine configuration time the user * might have chosen a different prefix to be used. */ public Set<IProcessor> getProcessors(final String dialectPrefix) {<FILL_FUNCTION_BODY>} }
final Set<IProcessor> processors = new HashSet<IProcessor>(); processors.add(new SayToAttributeTagProcessor(dialectPrefix)); processors.add(new SayToPlanetAttributeTagProcessor(dialectPrefix)); // This will remove the xmlns:hello attributes we might add for IDE validation processors.add(new StandardXmlNsTagProcessor(TemplateMode.HTML, dialectPrefix)); return processors;
195
108
303
<methods>public final int getDialectProcessorPrecedence() ,public final java.lang.String getPrefix() <variables>private final non-sealed java.lang.String prefix,private final non-sealed int processorPrecedence
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-sayhello/src/main/java/org/thymeleaf/examples/spring6/sayhello/dialect/SayToPlanetAttributeTagProcessor.java
SayToPlanetAttributeTagProcessor
doProcess
class SayToPlanetAttributeTagProcessor extends AbstractAttributeTagProcessor { private static final String ATTR_NAME = "saytoplanet"; private static final int PRECEDENCE = 10000; private static final String SAYTO_PLANET_MESSAGE = "msg.helloplanet"; public SayToPlanetAttributeTagProcessor(final String dialectPrefix) { super( TemplateMode.HTML, // This processor will apply only to HTML mode dialectPrefix, // Prefix to be applied to name for matching null, // No tag name: match any tag name false, // No prefix to be applied to tag name ATTR_NAME, // Name of the attribute that will be matched true, // Apply dialect prefix to attribute name PRECEDENCE, // Precedence (inside dialect's precedence) true); // Remove the matched attribute afterwards } protected void doProcess( final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, final IElementTagStructureHandler structureHandler) {<FILL_FUNCTION_BODY>} }
/* * In order to evaluate the attribute value as a Thymeleaf Standard Expression, * we first obtain the parser, then use it for parsing the attribute value into * an expression object, and finally execute this expression object. */ final IEngineConfiguration configuration = context.getConfiguration(); final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration); final IStandardExpression expression = parser.parseExpression(context, attributeValue); final String planet = (String) expression.execute(context); /* * This 'getMessage(...)' method will first try to resolve the message * from the configured Spring Message Sources (because this is a Spring * -enabled application). * * If not found, it will try to resolve it from a classpath-bound * .properties with the same name as the specified 'origin', which * in this case is this processor's class itself. This allows resources * to be packaged if needed in the same .jar files as the processors * they are used in. */ final String i18nMessage = context.getMessage( SayToPlanetAttributeTagProcessor.class, SAYTO_PLANET_MESSAGE, new Object[] {planet}, true); /* * Set the computed message as the body of the tag, HTML-escaped and * non-processable (hence the 'false' argument) */ structureHandler.setBody(HtmlEscape.escapeHtml5(i18nMessage), false);
296
387
683
<methods><variables>private final non-sealed boolean removeAttribute
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-sayhello/src/main/java/org/thymeleaf/examples/spring6/sayhello/web/SpringWebConfig.java
SpringWebConfig
templateEngine
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; public SpringWebConfig() { super(); } public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /* * Message externalization/internationalization */ @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource(); resourceBundleMessageSource.setBasename("Messages"); return resourceBundleMessageSource; } /* **************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS */ /* TemplateResolver <- TemplateEngine <- ViewResolver */ /* **************************************************************** */ @Bean public SpringResourceTemplateResolver templateResolver(){ SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(this.applicationContext); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); // Template cache is true by default. Set to false if you want // templates to be automatically updated when modified. templateResolver.setCacheable(true); return templateResolver; } @Bean public SpringTemplateEngine templateEngine(){<FILL_FUNCTION_BODY>} @Bean public ThymeleafViewResolver viewResolver(){ ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); return viewResolver; } /* ******************************************************************* */ /* Defines callback methods to customize the Java-based configuration */ /* for Spring MVC enabled via {@code @EnableWebMvc} */ /* ******************************************************************* */ /* * Dispatcher configuration for serving static resources */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry.addResourceHandler("/images/**").addResourceLocations("/images/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); } }
SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setEnableSpringELCompiler(true); // Compiled SpringEL should speed up executions templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(new HelloDialect()); return templateEngine;
604
75
679
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-sayhello/src/main/java/org/thymeleaf/examples/spring6/sayhello/web/controller/SayHelloController.java
SayHelloController
populatePlanets
class SayHelloController { public SayHelloController() { super(); } @ModelAttribute("planets") public List<String> populatePlanets() {<FILL_FUNCTION_BODY>} @RequestMapping({"/","/sayhello"}) public String showSayHello() { return "sayhello"; } }
return Arrays.asList(new String[] { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" });
99
56
155
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-springmail/src/main/java/org/thymeleaf/examples/spring6/springmail/SpringWebApplicationInitializer.java
SpringWebApplicationInitializer
getServletFilters
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { public static final String CHARACTER_ENCODING = "UTF-8"; public SpringWebApplicationInitializer() { super(); } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { SpringWebConfig.class }; } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { SpringBusinessConfig.class, SpringMailConfig.class}; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>} /* * This is needed because apparently CommonsMultiPartResolver was removed from Spring 6 * https://docs.spring.io/spring-framework/docs/6.0.x/reference/html/web.html#mvc-multipart-resolver-standard */ @Override protected void customizeRegistration(final ServletRegistration.Dynamic registration) { // Optionally also set maxFileSize, maxRequestSize, fileSizeThreshold registration.setMultipartConfig(new MultipartConfigElement("/tmp")); super.customizeRegistration(registration); } }
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding(CHARACTER_ENCODING); encodingFilter.setForceEncoding(true); return new Filter[] { encodingFilter };
340
55
395
<methods>public void <init>() <variables>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-springmail/src/main/java/org/thymeleaf/examples/spring6/springmail/business/SpringMailConfig.java
SpringMailConfig
htmlTemplateResolver
class SpringMailConfig implements ApplicationContextAware, EnvironmentAware { public static final String EMAIL_TEMPLATE_ENCODING = "UTF-8"; private static final String JAVA_MAIL_FILE = "classpath:mail/javamail.properties"; private static final String HOST = "mail.server.host"; private static final String PORT = "mail.server.port"; private static final String PROTOCOL = "mail.server.protocol"; private static final String USERNAME = "mail.server.username"; private static final String PASSWORD = "mail.server.password"; private ApplicationContext applicationContext; private Environment environment; @Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void setEnvironment(final Environment environment) { this.environment = environment; } /* * SPRING + JAVAMAIL: JavaMailSender instance, configured via .properties files. */ @Bean public JavaMailSender mailSender() throws IOException { final JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); // Basic mail sender configuration, based on emailconfig.properties mailSender.setHost(this.environment.getProperty(HOST)); mailSender.setPort(Integer.parseInt(this.environment.getProperty(PORT))); mailSender.setProtocol(this.environment.getProperty(PROTOCOL)); mailSender.setUsername(this.environment.getProperty(USERNAME)); mailSender.setPassword(this.environment.getProperty(PASSWORD)); // JavaMail-specific mail sender configuration, based on javamail.properties final Properties javaMailProperties = new Properties(); javaMailProperties.load(this.applicationContext.getResource(JAVA_MAIL_FILE).getInputStream()); mailSender.setJavaMailProperties(javaMailProperties); return mailSender; } /* * Message externalization/internationalization for emails. * * NOTE we are avoiding the use of the name 'messageSource' for this bean because that * would make the MessageSource defined in SpringWebConfig (and made available for the * web-side template engine) delegate to this one, and thus effectively merge email * messages into web messages and make both types available at the web side, which could * bring undesired collisions. * * NOTE also that given we want this specific message source to be used by our * SpringTemplateEngines for emails (and not by the web one), we will set it explicitly * into each of the TemplateEngine objects with 'setTemplateEngineMessageSource(...)' */ @Bean public ResourceBundleMessageSource emailMessageSource() { final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("mail/MailMessages"); return messageSource; } /* ******************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS FOR EMAIL */ /* TemplateResolver(3) <- TemplateEngine */ /* ******************************************************************** */ @Bean public TemplateEngine emailTemplateEngine() { final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); // Resolver for TEXT emails templateEngine.addTemplateResolver(textTemplateResolver()); // Resolver for HTML emails (except the editable one) templateEngine.addTemplateResolver(htmlTemplateResolver()); // Resolver for HTML editable emails (which will be treated as a String) templateEngine.addTemplateResolver(stringTemplateResolver()); // Message source, internationalization specific to emails templateEngine.setTemplateEngineMessageSource(emailMessageSource()); return templateEngine; } private ITemplateResolver textTemplateResolver() { final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setOrder(Integer.valueOf(1)); templateResolver.setResolvablePatterns(Collections.singleton("text/*")); templateResolver.setPrefix("/mail/"); templateResolver.setSuffix(".txt"); templateResolver.setTemplateMode(TemplateMode.TEXT); templateResolver.setCharacterEncoding(EMAIL_TEMPLATE_ENCODING); templateResolver.setCacheable(false); return templateResolver; } private ITemplateResolver htmlTemplateResolver() {<FILL_FUNCTION_BODY>} private ITemplateResolver stringTemplateResolver() { final StringTemplateResolver templateResolver = new StringTemplateResolver(); templateResolver.setOrder(Integer.valueOf(3)); // No resolvable pattern, will simply process as a String template everything not previously matched templateResolver.setTemplateMode("HTML5"); templateResolver.setCacheable(false); return templateResolver; } }
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setOrder(Integer.valueOf(2)); templateResolver.setResolvablePatterns(Collections.singleton("html/*")); templateResolver.setPrefix("/mail/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); templateResolver.setCharacterEncoding(EMAIL_TEMPLATE_ENCODING); templateResolver.setCacheable(false); return templateResolver;
1,212
130
1,342
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-springmail/src/main/java/org/thymeleaf/examples/spring6/springmail/web/SpringWebConfig.java
SpringWebConfig
templateEngine
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /* ******************************************************************* */ /* GENERAL CONFIGURATION ARTIFACTS */ /* Static Resources, i18n Messages, Formatters (Conversion Service) */ /* ******************************************************************* */ /* * Dispatcher configuration for serving static resources */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry.addResourceHandler("/images/**").addResourceLocations("/images/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); } /* * Message externalization/internationalization */ @Bean public ResourceBundleMessageSource messageSource() { final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("Messages"); return messageSource; } /* * Multipart resolver (needed for uploading attachments from web form) */ @Bean public MultipartResolver multipartResolver() { return new StandardServletMultipartResolver(); } /* **************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS */ /* TemplateResolver <- TemplateEngine <- ViewResolver */ /* **************************************************************** */ @Bean public SpringResourceTemplateResolver templateResolver(){ // SpringResourceTemplateResolver automatically integrates with Spring's own // resource resolution infrastructure, which is highly recommended. final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(this.applicationContext); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); // HTML is the default value, added here for the sake of clarity. templateResolver.setTemplateMode(TemplateMode.HTML); // Template cache is true by default. Set to false if you want // templates to be automatically updated when modified. templateResolver.setCacheable(true); return templateResolver; } @Bean public SpringTemplateEngine templateEngine(){<FILL_FUNCTION_BODY>} @Bean public ThymeleafViewResolver viewResolver(){ final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); return viewResolver; } }
// SpringTemplateEngine automatically applies SpringStandardDialect and // enables Spring's own MessageSource message resolution mechanisms. final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); // Enabling the SpringEL compiler with Spring 4.2.4 or newer can // speed up execution in most scenarios, but might be incompatible // with specific cases when expressions in one template are reused // across different data types, so this flag is "false" by default // for safer backwards compatibility. templateEngine.setEnableSpringELCompiler(true); return templateEngine;
689
151
840
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-springmail/src/main/java/org/thymeleaf/examples/spring6/springmail/web/controller/ErrorController.java
ErrorController
exception
class ErrorController { @ExceptionHandler(Throwable.class) public ModelAndView exception(Throwable throwable) {<FILL_FUNCTION_BODY>} }
String errorMessage = throwable != null ? throwable.getMessage() : "Unknown error"; ModelAndView mav = new ModelAndView(); mav.getModel().put("errorMessage", errorMessage); mav.setViewName("error"); return mav;
46
71
117
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-springmail/src/main/java/org/thymeleaf/examples/spring6/springmail/web/controller/SendingController.java
SendingController
sendMailWithInline
class SendingController { @Autowired private EmailService emailService; /* Send plain TEXT mail */ @RequestMapping(value = "/sendMailText", method = POST) public String sendTextMail( @RequestParam("recipientName") final String recipientName, @RequestParam("recipientEmail") final String recipientEmail, final Locale locale) throws MessagingException { this.emailService.sendTextMail(recipientName, recipientEmail, locale); return "redirect:sent.html"; } /* Send HTML mail (simple) */ @RequestMapping(value = "/sendMailSimple", method = POST) public String sendSimpleMail( @RequestParam("recipientName") final String recipientName, @RequestParam("recipientEmail") final String recipientEmail, final Locale locale) throws MessagingException { this.emailService.sendSimpleMail(recipientName, recipientEmail, locale); return "redirect:sent.html"; } /* Send HTML mail with attachment. */ @RequestMapping(value = "/sendMailWithAttachment", method = POST) public String sendMailWithAttachment( @RequestParam("recipientName") final String recipientName, @RequestParam("recipientEmail") final String recipientEmail, @RequestParam("attachment") final MultipartFile attachment, final Locale locale) throws MessagingException, IOException { this.emailService.sendMailWithAttachment( recipientName, recipientEmail, attachment.getOriginalFilename(), attachment.getBytes(), attachment.getContentType(), locale); return "redirect:sent.html"; } /* Send HTML mail with inline image */ @RequestMapping(value = "/sendMailWithInlineImage", method = POST) public String sendMailWithInline( @RequestParam("recipientName") final String recipientName, @RequestParam("recipientEmail") final String recipientEmail, @RequestParam("image") final MultipartFile image, final Locale locale) throws MessagingException, IOException {<FILL_FUNCTION_BODY>} /* Send editable HTML mail */ @RequestMapping(value = "/sendEditableMail", method = POST) public String sendMailWithInline( @RequestParam("recipientName") final String recipientName, @RequestParam("recipientEmail") final String recipientEmail, @RequestParam("body") final String body, final Locale locale) throws MessagingException, IOException { this.emailService.sendEditableMail( recipientName, recipientEmail, body, locale); return "redirect:sent.html"; } }
this.emailService.sendMailWithInline( recipientName, recipientEmail, image.getName(), image.getBytes(), image.getContentType(), locale); return "redirect:sent.html";
676
56
732
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-stsm/src/main/java/org/thymeleaf/examples/spring6/stsm/SpringWebApplicationInitializer.java
SpringWebApplicationInitializer
getServletFilters
class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { public static final String CHARACTER_ENCODING = "UTF-8"; public SpringWebApplicationInitializer() { super(); } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { SpringWebConfig.class }; } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { SpringBusinessConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() {<FILL_FUNCTION_BODY>} }
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding(CHARACTER_ENCODING); encodingFilter.setForceEncoding(true); return new Filter[] { encodingFilter };
195
55
250
<methods>public void <init>() <variables>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-stsm/src/main/java/org/thymeleaf/examples/spring6/stsm/business/entities/Row.java
Row
toString
class Row { private Variety variety = null; private Integer seedsPerCell = null; public Row() { super(); } public Variety getVariety() { return this.variety; } public void setVariety(final Variety variety) { this.variety = variety; } public Integer getSeedsPerCell() { return this.seedsPerCell; } public void setSeedsPerCell(final Integer seedsPerCell) { this.seedsPerCell = seedsPerCell; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Row [variety=" + this.variety + ", seedsPerCell=" + this.seedsPerCell + "]";
186
36
222
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-stsm/src/main/java/org/thymeleaf/examples/spring6/stsm/business/entities/SeedStarter.java
SeedStarter
toString
class SeedStarter { private Integer id = null; private Date datePlanted = null; private Boolean covered = null; private Type type = Type.PLASTIC; private Feature[] features = null; private List<Row> rows = new ArrayList<Row>(); public SeedStarter() { super(); } public Integer getId() { return this.id; } public void setId(final Integer id) { this.id = id; } public Date getDatePlanted() { return this.datePlanted; } public void setDatePlanted(final Date datePlanted) { this.datePlanted = datePlanted; } public Boolean getCovered() { return this.covered; } public void setCovered(final Boolean covered) { this.covered = covered; } public Type getType() { return this.type; } public void setType(final Type type) { this.type = type; } public Feature[] getFeatures() { return this.features; } public void setFeatures(final Feature[] features) { this.features = features; } public List<Row> getRows() { return this.rows; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SeedStarter [id=" + this.id + ", datePlanted=" + this.datePlanted + ", covered=" + this.covered + ", type=" + this.type + ", features=" + Arrays.toString(this.features) + ", rows=" + this.rows + "]";
389
83
472
<no_super_class>
thymeleaf_thymeleaf
thymeleaf/examples/spring6/thymeleaf-examples-spring6-stsm/src/main/java/org/thymeleaf/examples/spring6/stsm/web/SpringWebConfig.java
SpringWebConfig
templateResolver
class SpringWebConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; public SpringWebConfig() { super(); } public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /* ******************************************************************* */ /* GENERAL CONFIGURATION ARTIFACTS */ /* Static Resources, i18n Messages, Formatters (Conversion Service) */ /* ******************************************************************* */ /* * Dispatcher configuration for serving static resources */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry.addResourceHandler("/images/**").addResourceLocations("/images/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); } /* * Message externalization/internationalization */ @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("Messages"); return messageSource; } /* * Add formatter for class *.stsm.business.entities.Variety * and java.util.Date in addition to the ones registered by default */ @Override public void addFormatters(final FormatterRegistry registry) { WebMvcConfigurer.super.addFormatters(registry); registry.addFormatter(varietyFormatter()); registry.addFormatter(dateFormatter()); } @Bean public VarietyFormatter varietyFormatter() { return new VarietyFormatter(); } @Bean public DateFormatter dateFormatter() { return new DateFormatter(); } /* **************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS */ /* TemplateResolver <- TemplateEngine <- ViewResolver */ /* **************************************************************** */ @Bean public SpringResourceTemplateResolver templateResolver(){<FILL_FUNCTION_BODY>} @Bean public SpringTemplateEngine templateEngine(){ // SpringTemplateEngine automatically applies SpringStandardDialect and // enables Spring's own MessageSource message resolution mechanisms. SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); // Enabling the SpringEL compiler with Spring 4.2.4 or newer can // speed up execution in most scenarios, but might be incompatible // with specific cases when expressions in one template are reused // across different data types, so this flag is "false" by default // for safer backwards compatibility. templateEngine.setEnableSpringELCompiler(true); return templateEngine; } @Bean public ThymeleafViewResolver viewResolver(){ ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); return viewResolver; } }
// SpringResourceTemplateResolver automatically integrates with Spring's own // resource resolution infrastructure, which is highly recommended. SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(this.applicationContext); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); // HTML is the default value, added here for the sake of clarity. templateResolver.setTemplateMode(TemplateMode.HTML); // Template cache is true by default. Set to false if you want // templates to be automatically updated when modified. templateResolver.setCacheable(true); return templateResolver;
801
164
965
<no_super_class>