Singleton the Highlander way

Singleton Implementierungen gibt es verschiedenste, aber möchte man wirklich nur eine Instanz eines Objektes sollte man es nach der Highlander Methode machen.

Egal ob man noch auf dem Memory Modell von java < 1.5 oder eben nach dem Fix von 1.5 arbeitet, diese Methode sollte immer funktionieren.
Und wer hats erfunden? Bill Pugh in seiner arbeit an dem Java Memory Model.

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Highlander {
private Highlander() {
// Singleton
}
private static class SingletonHolder {
public static final Highlander SINGLETONHOLDER = new Highlander();
}
public static Highlander getInstance() {
return SingletonHolder.SINGLETONHOLDER;
}
}

JSF Bootstrap Message and Messages Renderer

Add the JSF Bootstrap Render to your Page to view the JSF Messages in Bootstrap Style.

view

Here you can find the Code Snippets.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package at.freelenzer.jsftest.bootstrap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.component.UIComponent;
import javax.faces.component.UIMessage;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.FacesRenderer;
import com.sun.faces.renderkit.Attribute;
import com.sun.faces.renderkit.AttributeManager;
import com.sun.faces.renderkit.RenderKitUtils;
import com.sun.faces.renderkit.html_basic.MessageRenderer;
@FacesRenderer(componentFamily = "javax.faces.Message", rendererType = "javax.faces.Message")
public class BootstrapMessageRenderer extends MessageRenderer {
private static final Attribute[] ATTRIBUTES = AttributeManager
.getAttributes(AttributeManager.Key.MESSAGESMESSAGES);
@Override
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
super.encodeBegin(context, component);
}
@Override
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
rendererParamsNotNull(context, component);
if (!shouldEncode(component))
return;
boolean mustRender = shouldWriteIdAttribute(component);
UIMessage messages = (UIMessage) component;
ResponseWriter writer = context.getResponseWriter();
assert (writer != null);
String clientId = ((UIMessage) component).getFor();
@SuppressWarnings("unchecked")
Iterator<FacesMessage> messageIter = getMessageIter(context, clientId,
component);
assert (messageIter != null);
if (!messageIter.hasNext()) {
if (mustRender) {
if ("javax_faces_developmentstage_messages".equals(component
.getId())) {
return;
}
writer.startElement("div", component);
writeIdAttributeIfNecessary(context, writer, component);
writer.endElement("div");
}
return;
}
writeIdAttributeIfNecessary(context, writer, component);
// style is rendered as a passthru attribute
RenderKitUtils.renderPassThruAttributes(context, writer, component,
ATTRIBUTES);
Map<Severity, List<FacesMessage>> msgs = new HashMap<Severity, List<FacesMessage>>();
msgs.put(FacesMessage.SEVERITY_INFO, new ArrayList<FacesMessage>()); // Bootstrap
// info
msgs.put(FacesMessage.SEVERITY_WARN, new ArrayList<FacesMessage>()); // Bootstrap
// warning
msgs.put(FacesMessage.SEVERITY_ERROR, new ArrayList<FacesMessage>()); // Bootstrap
// error
msgs.put(FacesMessage.SEVERITY_FATAL, new ArrayList<FacesMessage>()); // Bootstrap
// error
while (messageIter.hasNext()) {
FacesMessage curMessage = (FacesMessage) messageIter.next();
if (curMessage.isRendered() && !messages.isRedisplay()) {
continue;
}
msgs.get(curMessage.getSeverity()).add(curMessage);
}
List<FacesMessage> severityMessages = msgs
.get(FacesMessage.SEVERITY_FATAL);
if (severityMessages.size() > 0) {
encodeSeverityMessages(context, component, messages,
FacesMessage.SEVERITY_FATAL, severityMessages);
}
severityMessages = msgs.get(FacesMessage.SEVERITY_ERROR);
if (severityMessages.size() > 0) {
encodeSeverityMessages(context, component, messages,
FacesMessage.SEVERITY_ERROR, severityMessages);
}
severityMessages = msgs.get(FacesMessage.SEVERITY_WARN);
if (severityMessages.size() > 0) {
encodeSeverityMessages(context, component, messages,
FacesMessage.SEVERITY_WARN, severityMessages);
}
severityMessages = msgs.get(FacesMessage.SEVERITY_INFO);
if (severityMessages.size() > 0) {
encodeSeverityMessages(context, component, messages,
FacesMessage.SEVERITY_INFO, severityMessages);
}
}
private void encodeSeverityMessages(FacesContext facesContext,
UIComponent component, UIMessage uiMessages, Severity severity,
List<FacesMessage> messages) throws IOException {
ResponseWriter writer = facesContext.getResponseWriter();
String alertSeverityClass = "";
if (FacesMessage.SEVERITY_INFO.equals(severity)) {
alertSeverityClass = "alert-info";
} else if (FacesMessage.SEVERITY_WARN.equals(severity)) {
alertSeverityClass = ""; // Default alert is a warning
} else if (FacesMessage.SEVERITY_ERROR.equals(severity)) {
alertSeverityClass = "alert-error";
} else if (FacesMessage.SEVERITY_FATAL.equals(severity)) {
alertSeverityClass = "alert-error";
}
writer.startElement("div", null);
writer.writeAttribute("class", "alert " + alertSeverityClass, "alert "
+ alertSeverityClass);
for (FacesMessage msg : messages) {
String summary = msg.getSummary() != null ? msg.getSummary() : "";
String detail = msg.getDetail() != null ? msg.getDetail() : summary;
if (uiMessages.isShowSummary()) {
writer.startElement("strong", component);
writer.writeText(summary, component, null);
writer.endElement("strong");
}
if (uiMessages.isShowDetail()) {
writer.writeText(" " + detail, null);
}
msg.rendered();
}
writer.endElement("div");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package at.freelenzer.jsftest.bootstrap;
import java.io.IOException;
import java.util.Iterator;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIMessages;
import javax.faces.context.FacesContext;
import javax.faces.render.FacesRenderer;
import javax.faces.context.ResponseWriter;
import com.sun.faces.renderkit.Attribute;
import com.sun.faces.renderkit.AttributeManager;
import com.sun.faces.renderkit.RenderKitUtils;
import com.sun.faces.renderkit.html_basic.MessagesRenderer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage.Severity;
@FacesRenderer(componentFamily = "javax.faces.Messages", rendererType = "javax.faces.Messages")
public class BootstrapMessagesRenderer extends MessagesRenderer {
private static final Attribute[] ATTRIBUTES = AttributeManager
.getAttributes(AttributeManager.Key.MESSAGESMESSAGES);
@Override
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
super.encodeBegin(context, component);
}
@Override
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
rendererParamsNotNull(context, component);
if (!shouldEncode(component))
return;
boolean mustRender = shouldWriteIdAttribute(component);
UIMessages messages = (UIMessages) component;
ResponseWriter writer = context.getResponseWriter();
assert (writer != null);
String clientId = ((UIMessages) component).getFor();
if (clientId == null)
if (messages.isGlobalOnly())
clientId = "";
@SuppressWarnings("unchecked")
Iterator<FacesMessage> messageIter = getMessageIter(context, clientId,
component);
assert (messageIter != null);
if (!messageIter.hasNext()) {
if (mustRender) {
if ("javax_faces_developmentstage_messages".equals(component
.getId())) {
return;
}
writer.startElement("div", component);
writeIdAttributeIfNecessary(context, writer, component);
writer.endElement("div");
}
return;
}
writeIdAttributeIfNecessary(context, writer, component);
// style is rendered as a passthru attribute
RenderKitUtils.renderPassThruAttributes(context, writer, component,
ATTRIBUTES);
Map<Severity, List<FacesMessage>> msgs = new HashMap<Severity, List<FacesMessage>>();
msgs.put(FacesMessage.SEVERITY_INFO, new ArrayList<FacesMessage>()); // Bootstrap
// info
msgs.put(FacesMessage.SEVERITY_WARN, new ArrayList<FacesMessage>()); // Bootstrap
// warning
msgs.put(FacesMessage.SEVERITY_ERROR, new ArrayList<FacesMessage>()); // Bootstrap
// error
msgs.put(FacesMessage.SEVERITY_FATAL, new ArrayList<FacesMessage>()); // Bootstrap
// error
while (messageIter.hasNext()) {
FacesMessage curMessage = (FacesMessage) messageIter.next();
if (curMessage.isRendered() && !messages.isRedisplay()) {
continue;
}
msgs.get(curMessage.getSeverity()).add(curMessage);
}
List<FacesMessage> severityMessages = msgs
.get(FacesMessage.SEVERITY_FATAL);
if (severityMessages.size() > 0) {
encodeSeverityMessages(context, component, messages,
FacesMessage.SEVERITY_FATAL, severityMessages);
}
severityMessages = msgs.get(FacesMessage.SEVERITY_ERROR);
if (severityMessages.size() > 0) {
encodeSeverityMessages(context, component, messages,
FacesMessage.SEVERITY_ERROR, severityMessages);
}
severityMessages = msgs.get(FacesMessage.SEVERITY_WARN);
if (severityMessages.size() > 0) {
encodeSeverityMessages(context, component, messages,
FacesMessage.SEVERITY_WARN, severityMessages);
}
severityMessages = msgs.get(FacesMessage.SEVERITY_INFO);
if (severityMessages.size() > 0) {
encodeSeverityMessages(context, component, messages,
FacesMessage.SEVERITY_INFO, severityMessages);
}
}
private void encodeSeverityMessages(FacesContext facesContext,
UIComponent component, UIMessages uiMessages, Severity severity,
List<FacesMessage> messages) throws IOException {
ResponseWriter writer = facesContext.getResponseWriter();
String alertSeverityClass = "";
if (FacesMessage.SEVERITY_INFO.equals(severity)) {
alertSeverityClass = "alert-info";
} else if (FacesMessage.SEVERITY_WARN.equals(severity)) {
alertSeverityClass = ""; // Default alert is a warning
} else if (FacesMessage.SEVERITY_ERROR.equals(severity)) {
alertSeverityClass = "alert-error";
} else if (FacesMessage.SEVERITY_FATAL.equals(severity)) {
alertSeverityClass = "alert-error";
}
writer.startElement("div", null);
writer.writeAttribute("class", "alert " + alertSeverityClass, "alert "
+ alertSeverityClass);
writer.startElement("a", component);
writer.writeAttribute("class", "close", "class");
writer.writeAttribute("data-dismiss", "alert", "data-dismiss");
writer.writeAttribute("href", "#", "href");
writer.write("&times;");
writer.endElement("a");
writer.startElement("ul", null);
for (FacesMessage msg : messages) {
String summary = msg.getSummary() != null ? msg.getSummary() : "";
String detail = msg.getDetail() != null ? msg.getDetail() : summary;
writer.startElement("li", component);
if (uiMessages.isShowSummary()) {
writer.startElement("strong", component);
writer.writeText(summary, component, null);
writer.endElement("strong");
}
if (uiMessages.isShowDetail()) {
writer.writeText(" " + detail, null);
}
writer.endElement("li");
msg.rendered();
}
writer.endElement("ul");
writer.endElement("div");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
<render-kit>
<renderer>
<component-family>javax.faces.Messages</component-family>
<renderer-type>javax.faces.Messages</renderer-type>
<renderer-class>at.freelenzer.jsftest.bootstrap.BootstrapMessagesRenderer</renderer-class>
</renderer>
<renderer>
<component-family>javax.faces.Message</component-family>
<renderer-type>javax.faces.Message</renderer-type>
<renderer-class>at.freelenzer.jsftest.bootstrap.BootstrapMessageRenderer</renderer-class>
</renderer>
</render-kit>

Primefaces multifile upload in IE10

Primefaces multifile upload works in IE10.

But not out of the Box in the Community Edition. There ist a fix in the primefaces version 3.5.9.

See Group Entry

But get it work with the Community Edition is far easy.

Use the fileUpload component like you would do it in IE9.

And add the CSS styles described below.

1
2
3
4
5
<p:fileUpload fileUploadListener="#{fileUpload.handleFileUpload}"
mode="advanced" dragDropSupport="true" multiple="true"
update="messages" sizeLimit="100000" fileLimit="3"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />
<p:growl id="messages" showDetail="true" />

Fit to Parent in JavaFx

Versucht man mit JavaFx und SceneBuilder UIs zu zeichnen und die einzelnen Fragmente per Code zusammen zuführen, funktioniert das mit den Anchor nicht outofthebox. Die Anchor Attribute müssen beim einzufügenden Fragment händisch ergänzt werden.

1
2
3
<AnchorPane AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" xmlns:fx="http://javafx.com/fxml" fx:controller="at.freelenzer.dagobert.fx.accounts.AccountsPresenter">
leftSide.getChildren().add(accountsView.getView());

Java Enum#parseFrom

How the parse an enum from an constant?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("boxing")
public enum IndexStrategy {
DEFAULT(0), FASTINDEX(1), FINEGRAINED(2);
private final int value;
private IndexStrategy(int value) {
this.value = value;
}
public int getValue() {
return value;
}
private static final Map<Integer, IndexStrategy> intToEnum = new HashMap<Integer, IndexStrategy>();
static { // Initialize map from constant int to enum constant
for (IndexStrategy op : values())
intToEnum.put(op.getValue(), op);
}
// Returns Operation for int, or null if int is invalid
public static IndexStrategy fromInt(int value) {
return intToEnum.get(value);
}
}

Fast ArrayList or HashMap initialisation

Everyone knows how to initialize String Arrays.

But how can we do this with ArrayLists or with HashMaps?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private static String[] array = new String[]{"Test", "Test"};
private static List<String> arraylist = new ArrayList<String>() {
{
add("Test");
add("Test");
}
};
private static Map<String,String> map = new HashMap<String,String>() {
{
put("one","Test");
put("two","Test");
}
};

Java DeepCopy via Serialization

Sometimes you need a way to make a deepcopy of all your objects. May be not the fastest :-). You have to ensure, that all of your objects are serializeable.

1
2
3
4
5
6
public static <T> T deepCopy(T o) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new ObjectOutputStream(baos).writeObject(o);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return (T) new ObjectInputStream(bais).readObject();
}

Mockito: Mock a JspWriter

How to Mock a JspWriter to move the appended text to a StringBuilder?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
StringBuilder buffer = new StringBuilder();
JspWriter jspWriterMock = mock(JspWriter.class);
Answer<JspWriter> answer = new Answer<JspWriter>() {
@Override
public JspWriter answer(final InvocationOnMock theInvocation) throws Throwable {
Method method = theInvocation.getMethod();
Method methodImpl = StringBuilder.class.getMethod(method.getName(), method.getParameterTypes());
methodImpl.invoke(buffer, theInvocation.getArguments());
return (JspWriter) theInvocation.getMock();
}
};
Answer<Void> answerB = new Answer<Void>() {
@Override
public Void answer(final InvocationOnMock theInvocation) throws Throwable {
buffer.append(theInvocation.getArguments()[0]);
return null;
}
};
when(jspWriterMock.append(Matchers.anyChar())).thenAnswer(answer);
when(jspWriterMock.append(Matchers.anyString())).thenAnswer(answer);
when(jspWriterMock.append(Matchers.anyString(),Matchers.anyInt(),Matchers.anyInt())).thenAnswer(answer);
doAnswer(answerB).when(jspWriterMock).write(Matchers.anyString());
doAnswer(answerB).when(jspWriterMock).write((char[])Matchers.anyVararg());
doAnswer(answerB).when(jspWriterMock).write(Matchers.anyInt());

Here we are :-)