Skip to content

Instantly share code, notes, and snippets.

@ShigeoTejima
Created January 22, 2017 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShigeoTejima/7b00d5f0e6859c71efb6c010195a36c4 to your computer and use it in GitHub Desktop.
Save ShigeoTejima/7b00d5f0e6859c71efb6c010195a36c4 to your computer and use it in GitHub Desktop.
Simple Tag and Builder
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class Tag {
private final String tagName;
private Map<String, String> attributes;
private String text;
private List<Tag> children;
Tag(String tagName) {
this.tagName = tagName;
}
public String getTagName() {
return tagName;
}
public Map<String, String> getAttributes() {
return attributes == null ? Collections.emptyMap() : Collections.unmodifiableMap(attributes);
}
void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public String getText() {
return text;
}
void setText(String text) {
this.text = text;
}
public List<Tag> getChildren() {
return children == null ? Collections.emptyList() : Collections.unmodifiableList(children);
}
public Tag append(Tag child) {
if (children == null) {
children = new ArrayList<>();
}
children.add(child);
return this;
}
public void write(OutputStream stream) throws IOException {
stream.write(String.format("<%s", tagName).getBytes());
for (Map.Entry<String, String> attr : getAttributes().entrySet()) {
stream.write(String.format(" %s=\"%s\"", attr.getKey(), attr.getValue()).getBytes());
}
stream.write(">".getBytes());
if (text != null) {
stream.write(text.getBytes());
}
for (Tag child : getChildren()) {
child.write(stream);
}
stream.write(String.format("</%s>", tagName).getBytes());
}
}
import java.util.HashMap;
import java.util.Map;
public class TagBuilder {
private final String tagName;
private Map<String, String> attributes;
private String text;
public TagBuilder(String tagName) {
this.tagName = tagName;
}
public TagBuilder attribute(String name, String value) {
attributes(new HashMap<String, String>() {
{
put(name, value);
}
});
return this;
}
public TagBuilder attributes(Map<String, String> attributes) {
if (this.attributes == null) {
this.attributes = new HashMap<>();
}
this.attributes.putAll(attributes);
return this;
}
public TagBuilder text(String text) {
this.text = text;
return this;
}
public Tag build() {
Tag tag = new Tag(tagName);
if (attributes != null && !attributes.isEmpty()) {
tag.setAttributes(attributes);
}
if (text != null) {
tag.setText(text);
}
return tag;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment