YoutrackUnmarshaller.java
3.1 KB
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
package pl.itcrowd.youtrack.api;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import pl.itcrowd.youtrack.api.exceptions.YoutrackAPIException;
import pl.itcrowd.youtrack.api.rest.ErrorType;
import pl.itcrowd.youtrack.api.rest.ObjectFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
public final class YoutrackUnmarshaller {
private static Log LOG = LogFactory.getLog(YoutrackUnmarshaller.class);
private YoutrackUnmarshaller()
{
}
public static String unmarshalError(String string) throws JAXBException, IOException
{
return unmarshalError(new StringReader(string));
}
public static String unmarshalError(Reader reader) throws JAXBException, IOException
{
String content = IOUtils.toString(reader);
try {
JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
@SuppressWarnings("unchecked")
final JAXBElement<ErrorType> element = (JAXBElement<ErrorType>) jaxbContext.createUnmarshaller().unmarshal(new StringReader(content));
final ErrorType value = element.getValue();
final int contentSize = value.getContent().size();
if (contentSize == 0) {
return "";
} else if (contentSize == 1) {
final Serializable serializable = value.getContent().get(0);
if (serializable instanceof JAXBElement) {
if ("message".equals(((JAXBElement) serializable).getName().getLocalPart())) {
final Object messageValue = ((JAXBElement) serializable).getValue();
return messageValue == null ? "" : messageValue.toString();
}
} else {
return serializable == null ? "" : serializable.toString();
}
} else if (contentSize == 2) {
for (Serializable serializable : value.getContent()) {
if (serializable instanceof JAXBElement) {
if ("message".equals(((JAXBElement) serializable).getName().getLocalPart())) {
final Object messageValue = ((JAXBElement) serializable).getValue();
return messageValue == null ? "" : messageValue.toString();
}
}
}
}
throw new YoutrackAPIException("Cannot unserialize error.\n" + content);
} catch (JAXBException e) {
LOG.error("Cannot unmarshal error.\n" + content, e);
throw e;
}
}
public static Object unmarshall(String string) throws JAXBException
{
return unmarshall(new StringReader(string));
}
public static Object unmarshall(Reader reader) throws JAXBException
{
return JAXBContext.newInstance(ObjectFactory.class).createUnmarshaller().unmarshal(reader);
}
}