aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/com/juick/tests/MessageTests.java
blob: 4ee36d36d8b2295964993386c228d210011893eb (plain) (blame)
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
package com.juick.tests;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juick.Message;
import com.juick.util.DateFormattersHolder;
import org.apache.commons.codec.CharEncoding;
import org.json.JSONObject;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.text.ParseException;
import java.util.Date;

import static org.junit.Assert.assertEquals;

public class MessageTests {
    @Test
    public void messageParserSerializer() throws ParseException, ParserConfigurationException,
            IOException, SAXException, JAXBException {
        Message msg = new Message();
        msg.parseTags("test test" + (char) 0xA0 + "2 test3");
        assertEquals("First tag must be", "test", msg.getTags().get(0).getName());
        assertEquals("Third tag must be", "test3", msg.getTags().get(2).getName());
        assertEquals("Count of tags must be", 3, msg.getTags().size());
        Date currentDate = new Date();
        msg.setDate(currentDate);
        ObjectMapper serializer = new ObjectMapper();
        String jsonMessage = serializer.writeValueAsString(msg);
        JSONObject jsonObject = new JSONObject(jsonMessage);
        assertEquals("date should be in timestamp field", DateFormattersHolder.getMessageFormatterInstance().format(currentDate),
                jsonObject.getString("timestamp"));


        JAXBContext context = JAXBContext
                .newInstance(Message.class);
        Marshaller m = context.createMarshaller();

        StringWriter sw = new StringWriter();
        m.marshal(msg, sw);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new ByteArrayInputStream(sw.toString().getBytes(CharEncoding.UTF_8)));
        Node juickNode = doc.getElementsByTagName("juick").item(0);
        NamedNodeMap attrs = juickNode.getAttributes();
        assertEquals("date should be in ts field", DateFormattersHolder.getMessageFormatterInstance().format(currentDate),
                attrs.getNamedItem("ts").getNodeValue());
    }
}