com.fujitsu.dc.test.jersey.AbstractCase.java Source code

Java tutorial

Introduction

Here is the source code for com.fujitsu.dc.test.jersey.AbstractCase.java

Source

/**
 * personium.io
 * Copyright 2014 FUJITSU LIMITED
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.fujitsu.dc.test.jersey;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.ByteArrayInputStream;
import java.text.ParseException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.MediaType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.odata4j.core.ODataConstants;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.fujitsu.dc.core.DcCoreConfig;
import com.fujitsu.dc.core.model.Box;
import com.fujitsu.dc.core.model.Cell;
import com.fujitsu.dc.test.unit.core.UrlUtils;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;

/**
 * JerseyTestFramework??.
 */
@RunWith(DcRunner.class)
@Ignore
public class AbstractCase extends JerseyTest {

    /** . */
    private Log log;

    /** . */
    public static final String MASTER_TOKEN_NAME = DcCoreConfig.getMasterToken();
    /** (Bearer + MASTER_TOKEN_NAME). */
    public static final String BEARER_MASTER_TOKEN = "Bearer " + MASTER_TOKEN_NAME;
    /**  xml. */
    public static final String QUERY_FORMAT_ATOM = "$format=atom";
    /**  json. */
    public static final String QUERY_FORMAT_JSON = "$format=json";
    /** __published. */
    public static final String PUBLISHED = "__published";
    /** __updated. */
    public static final String UPDATED = "__updated";
    /** __metadata. */
    public static final String METADATA = "__metadata";

    /** ??Cell. */
    public static final String TYPE_CELL = "UnitCtl.Cell";

    /** 128?. */
    public static final String STRING_LENGTH_128 = "1234567890123456789012345678901234567890"
            + "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567x";

    /** 128?. */
    public static final String STRING_LENGTH_129 = "1234567890123456789012345678901234567890"
            + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678x";

    /** . */
    private HashMap<String, String> headers;

    /**
     * .
     */
    protected AbstractCase() {
        log.debug("AbstractCase constructer");
    }

    /**
     * .
     * @param value 
     */
    public AbstractCase(final String value) {
        super(value);
        log = LogFactory.getLog(AbstractCase.class);
        log.debug("======================" + this.getClass().getName() + "======================");
    }

    /**
     * .
     * @param build WebAppDescriptor
     */
    public AbstractCase(WebAppDescriptor build) {
        super(build);
        log = LogFactory.getLog(AbstractCase.class);
        log.debug("======================" + this.getClass().getName() + "======================");
    }

    /**
     * ?.
     * @param newHeaders ??HashMap
     */
    public final void setHeaders(final HashMap<String, String> newHeaders) {
        this.headers = newHeaders;
    }

    /**
     * Cell?.
     * @param cellName Cell??
     * @return Cell???
     */
    @SuppressWarnings("unchecked")
    public final DcResponse createCell(final String cellName) {
        DcRestAdapter rest = new DcRestAdapter();
        DcResponse res = null;

        // 
        HashMap<String, String> requestheaders = new HashMap<String, String>();
        requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);

        // ?
        JSONObject requestBody = new JSONObject();
        requestBody.put("Name", cellName);
        String data = requestBody.toJSONString();

        // 
        try {
            res = rest.post(UrlUtils.unitCtl(Cell.EDM_TYPE_NAME), data, requestheaders);
        } catch (Exception e) {
            fail(e.getMessage());
        }
        return res;
    }

    /**
     * Box?.
     * @param cellName cell??
     * @param boxName Box??
     * @return Box???
     */
    @SuppressWarnings("unchecked")
    public final DcResponse createBox(final String cellName, final String boxName) {
        DcRestAdapter rest = new DcRestAdapter();
        DcResponse res = null;

        // 
        HashMap<String, String> requestheaders = new HashMap<String, String>();
        requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);

        // ?
        JSONObject requestBody = new JSONObject();
        requestBody.put("Name", boxName);
        String data = requestBody.toJSONString();

        // 
        try {
            res = rest.post(UrlUtils.cellCtl(cellName, Box.EDM_TYPE_NAME), data, requestheaders);
        } catch (Exception e) {
            fail(e.getMessage());
        }
        return res;
    }

    /**
     * URL??GET??.
     * @param url ?URL
     * @return ?
     */
    public final DcResponse restGet(final String url) {
        DcRestAdapter rest = new DcRestAdapter();
        DcResponse res = null;

        if (this.headers == null) {
            // setHeaders????????
            this.headers = new HashMap<String, String>();
            this.headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
            this.headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
        }
        try {
            // 
            res = rest.getAcceptEncodingGzip(url, this.headers);
            // res = rest.get(url, headers);
        } catch (Exception e) {
            fail(e.getMessage());
        }
        return res;
    }

    /**
     * URL??POST??.
     * @param url ?URL
     * @param data post
     * @return ?
     */
    public final DcResponse restPost(final String url, final String data) {
        DcRestAdapter rest = new DcRestAdapter();
        DcResponse res = null;

        // 
        HashMap<String, String> requestheaders = new HashMap<String, String>();
        requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);

        try {
            // 
            res = rest.post(url, data, requestheaders);
        } catch (Exception e) {
            fail(e.getMessage());
        }
        return res;
    }

    /**
     * URL??PUT??.
     * @param url ?URL
     * @param data 
     * @return ?
     */
    public final DcResponse restPut(final String url, final String data) {
        DcRestAdapter rest = new DcRestAdapter();
        DcResponse res = null;

        // 
        HashMap<String, String> requestheaders = new HashMap<String, String>();
        requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);

        try {
            // 
            res = rest.put(url, requestheaders, new ByteArrayInputStream(data.getBytes()));
        } catch (Exception e) {
            fail(e.getMessage());
        }
        return res;
    }

    /**
     * URL??DELETE??.
     * @param url ?URL
     * @return ?
     */
    public final DcResponse restDelete(final String url) {
        DcRestAdapter rest = new DcRestAdapter();
        DcResponse res = null;

        // 
        HashMap<String, String> requestheaders = new HashMap<String, String>();
        requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
        requestheaders.put(HttpHeaders.IF_MATCH, "*");

        try {
            // 
            res = rest.del(url, requestheaders);
        } catch (Exception e) {
            fail(e.getMessage());
        }
        return res;
    }

    /**
     * DcRequest??.
     * @param req 
     * @return res
     */
    public static DcResponse request(DcRequest req) {
        DcRestAdapter rest = new DcRestAdapter();
        DcResponse res = null;
        String method = req.getMethod();
        try {
            // 
            if (method.equals(HttpMethod.GET)) {
                res = rest.getAcceptEncodingGzip(req.getUrl(), req.getHeaders());
            } else if (method.equals(HttpMethod.PUT)) {
                res = rest.put(req.getUrl(), req.getBody(), req.getHeaders());
            } else if (method.equals(HttpMethod.POST)) {
                res = rest.post(req.getUrl(), req.getBody(), req.getHeaders());
            } else if (method.equals(HttpMethod.DELETE)) {
                res = rest.del(req.getUrl(), req.getHeaders());
            } else {
                res = rest.request(method, req.getUrl(), req.getBody(), req.getHeaders());
            }
        } catch (Exception e) {
            fail(e.getMessage());
        }
        return res;
    }

    /**
     * DOM??????????.
     * @param doc Document
     * @param name ?????
     * @return ???Node?????null)
     */
    private Node getElementByTagName(final Document doc, final String name) {
        NodeList nl = doc.getElementsByTagName(name);
        if (nl.getLength() > 0) {
            return nl.item(0);
        } else {
            return null;
        }
    }

    /**
     * ?????DOM????.
     * @param doc Document
     * @param name ?????
     * @param ns ?????
     * @return ???Node
     */
    private Node getElementByTagNameNS(final Document doc, final String name, final String ns) {
        NodeList nl = doc.getElementsByTagNameNS(ns, name);
        if (nl.getLength() > 0) {
            return nl.item(0);
        } else {
            return null;
        }
    }

    /**
     * Node?????.
     * @param node ???(Node)
     * @param name ????
     * @return ???
     */
    private String getAttributeValue(final Node node, final String name) {
        NamedNodeMap nnm = node.getAttributes();
        Node attr = nnm.getNamedItem(name);
        if (attr != null) {
            return attr.getNodeValue();
        } else {
            return "";
        }
    }

    /**
     * ?????Node?????.
     * @param node ???(Node)
     * @param name ????
     * @param ns ?????
     * @return ???
     */
    private String getAttributeValueNS(final Node node, final String name, final String ns) {
        NamedNodeMap nnm = node.getAttributes();
        Node attr = nnm.getNamedItemNS(ns, name);
        if (attr != null) {
            return attr.getNodeValue();
        } else {
            return "";
        }
    }

    /**
     * Cell?URL?.
     * @param curCellId cell?id
     * @return cell??URL
     */
    public String getUrl(final String curCellId) {
        return getUrl(curCellId, null);
    }

    /**
     * Cell?URL?.
     * @param curCellId cell?id
     * @param reqQuery query
     * @return cell??URL
     */
    public String getUrl(final String curCellId, final String reqQuery) {
        StringBuilder url = new StringBuilder(UrlUtils.unitCtl(Cell.EDM_TYPE_NAME));
        url.append("('");
        url.append(curCellId);
        url.append("')");

        if (reqQuery != null) {
            url.append("?");
            url.append(reqQuery);
        }
        return url.toString();
    }

    /**
     * Cell?URL?.
     * @param curCellId cell?id
     * @param reqQuery query
     * @return cell??URL
     */
    public String getUrlWithOutQuote(final String curCellId, final String reqQuery) {
        StringBuilder url = new StringBuilder(UrlUtils.unitCtl(Cell.EDM_TYPE_NAME));
        url.append("(");
        url.append(curCellId);
        url.append(")");

        if (reqQuery != null) {
            url.append("?");
            url.append(reqQuery);
        }
        return url.toString();
    }

    /**
     * ????????????.
     * @param src ??
     * @return true:??false?????
     */
    private Boolean validISO8601a(final String src) {
        // FastDateFormat fastDateFormat =
        // org.apache.commons.lang.time.DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT;
        String[] patterns = { "yyyy-MM-dd'T'HH:mm:ss'Z'" };
        try {
            org.apache.commons.lang.time.DateUtils.parseDate(src, patterns);
        } catch (ParseException e) {
            return false;
        }
        return true;
    }

    /**
     * ????????????.
     * @param src ??
     * @return true:??false?????
     */
    private Boolean validISO8601b(final String src) {
        String[] patterns = { "yyyy-MM-dd'T'HH:mm:ss.SSS" };
        try {
            org.apache.commons.lang.time.DateUtils.parseDate(src, patterns);
        } catch (ParseException e) {
            return false;
        }
        return true;
    }

    /**
     * ???????.
     * @param date ??
     * @return boolean ?
     */
    public static Boolean validDate(final String date) {
        String dateformat = "Date\\([0-9]+\\)";
        Pattern pattern = Pattern.compile(dateformat);
        Matcher dateformatmatch = pattern.matcher(date);
        return dateformatmatch.find();
    }

    /** XML????????. */
    protected static final String MS_DS = "http://schemas.microsoft.com/ado/2007/08/dataservices";

    /** XML????????. */
    protected static final String MS_MD = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

    /**
     * Cell?XML???.
     * @param doc Document
     */
    public final void checkCellXML(final Document doc) {
        this.checkCellResponse(doc);
    }

    /**
     * Cell?Json???.
     * @param doc JSONObject
     * @param locationHeader LOCATION
     */
    public final void checkCellJson(final JSONObject doc, final String locationHeader) {
        this.checkCellResponse(doc, locationHeader);
    }

    /**
     * Domain?Json???.
     * @param doc JSONObject
     * @param locationHeader LOCATION
     */
    public final void checkDomainJson(final JSONObject doc, final String locationHeader) {
        this.checkDomainResponse(doc, locationHeader);
    }

    /**
     * Cell?XML???.
     * @param doc Document
     */
    public final void checkCellResponse(final Document doc) {
        Node elm;

        // id?
        elm = getElementByTagName(doc, "id");
        assertNotNull(elm);
        // id??????
        assertTrue(elm.getTextContent().length() > 0);

        // title?
        elm = getElementByTagName(doc, "title");
        assertNotNull(elm);
        // type?"text"??
        assertEquals("text", getAttributeValue(elm, "type"));

        // updated?
        elm = getElementByTagName(doc, "updated");
        assertNotNull(elm);
        // updated?????????
        assertTrue(validISO8601a(elm.getTextContent()));

        // Name???
        elm = getElementByTagName(doc, "Name");
        assertNotNull(elm);

        // link?
        elm = getElementByTagName(doc, "link");
        assertNotNull(elm);
        assertEquals("edit", getAttributeValue(elm, "rel"));
        assertEquals("Cell", getAttributeValue(elm, "title"));
        assertTrue(getAttributeValue(elm, "href").length() > 0);

        // category?
        elm = getElementByTagName(doc, "category");
        assertNotNull(elm);
        assertEquals(TYPE_CELL, getAttributeValue(elm, "term"));
        assertEquals("http://schemas.microsoft.com/ado/2007/08/dataservices/scheme",
                getAttributeValue(elm, "scheme"));

        // content?
        elm = getElementByTagName(doc, "content");
        assertNotNull(elm);
        assertEquals("application/xml", getAttributeValue(elm, "type"));

        // d:__id?
        elm = getElementByTagNameNS(doc, "__id", MS_DS);
        assertNotNull(elm);
        // id??????
        assertTrue(elm.getTextContent().length() > 0);

        // d:Name?
        elm = getElementByTagNameNS(doc, "Name", MS_DS);
        assertNotNull(elm);
        // name??????
        assertTrue(elm.getTextContent().length() > 0);

        // d:__published?
        elm = getElementByTagNameNS(doc, "__published", MS_DS);
        assertNotNull(elm);
        // __published?????????
        assertTrue(validISO8601b(elm.getTextContent()));
        assertEquals("Edm.DateTime", getAttributeValueNS(elm, "type", MS_MD));

        // d:__updated?
        elm = getElementByTagNameNS(doc, "__updated", MS_DS);
        assertNotNull(elm);
        // __updated?????????
        assertTrue(validISO8601b(elm.getTextContent()));
        assertEquals("Edm.DateTime", getAttributeValueNS(elm, "type", MS_MD));
    }

    /**
     * Cell?Json???.
     * @param doc JSONObject
     * @param locationHeader LOCATION
     */
    public final void checkCellResponse(final JSONObject doc, final String locationHeader) {

        JSONObject results = (JSONObject) ((JSONObject) doc.get("d")).get("results");
        validateCellResponse(results, locationHeader);
    }

    /**
     * Domain?Json???.
     * @param doc JSONObject
     * @param locationHeader LOCATION
     */
    public final void checkDomainResponse(final JSONObject doc, final String locationHeader) {

        JSONObject results = (JSONObject) ((JSONObject) doc.get("d")).get("results");
        validateDomainResponse(results, locationHeader);
    }

    /**
     * Cell?Json????.
     * @param response DcResponse
     * @param contentType ??ContentType
     */
    public final void checkCellListResponse(DcResponse response, MediaType contentType) {

        // Cell????
        // 200?????
        assertEquals(HttpStatus.SC_OK, response.getStatusCode());

        // DataServiceVersion??
        Header[] resDsvHeaders = response.getResponseHeaders(ODataConstants.Headers.DATA_SERVICE_VERSION);
        assertEquals(1, resDsvHeaders.length);
        assertEquals("2.0", resDsvHeaders[0].getValue());

        // ContentType??
        Header[] resContentTypeHeaders = response.getResponseHeaders(HttpHeaders.CONTENT_TYPE);
        assertEquals(1, resContentTypeHeaders.length);
        String value = resContentTypeHeaders[0].getValue();
        String[] values = value.split(";");
        assertEquals(contentType.toString(), values[0]);

        if (contentType == MediaType.APPLICATION_JSON_TYPE) {
            // ??Json???
            checkCellListResponse(response.bodyAsJson());

        } else if (contentType == MediaType.APPLICATION_ATOM_XML_TYPE) {
            // TODO ???
            fail("Not Implemented.");
            // checkCellXML(response.bodyAsXml());
        }
    }

    /**
     * Domain?Json????.
     * @param response DcResponse
     * @param contentType ??ContentType
     */
    public final void checkDomainListResponse(DcResponse response, MediaType contentType) {

        // Cell????
        // 200?????
        assertEquals(HttpStatus.SC_OK, response.getStatusCode());

        // DataServiceVersion??
        Header[] resDsvHeaders = response.getResponseHeaders(ODataConstants.Headers.DATA_SERVICE_VERSION);
        assertEquals(1, resDsvHeaders.length);
        assertEquals("2.0", resDsvHeaders[0].getValue());

        // ContentType??
        Header[] resContentTypeHeaders = response.getResponseHeaders(HttpHeaders.CONTENT_TYPE);
        assertEquals(1, resContentTypeHeaders.length);
        String value = resContentTypeHeaders[0].getValue();
        String[] values = value.split(";");
        assertEquals(contentType.toString(), values[0]);

        if (contentType == MediaType.APPLICATION_JSON_TYPE) {
            // ??Json???
            checkDomainListResponse(response.bodyAsJson());

        } else if (contentType == MediaType.APPLICATION_ATOM_XML_TYPE) {
            // ???
            fail("Not Implemented.");
            // checkCellXML(response.bodyAsXml());
        }
    }

    /**
     * Cell?Json????.
     * @param doc JSONObject
     */
    public final void checkCellListResponse(JSONObject doc) {

        JSONArray arResults = (JSONArray) ((JSONObject) doc.get("d")).get("results");

        for (Object obj : arResults) {
            JSONObject results = (JSONObject) obj;
            validateCellResponse(results, null);
        }

    }

    /**
     * Domain?Json????.
     * @param doc JSONObject
     */
    public final void checkDomainListResponse(JSONObject doc) {

        JSONArray arResults = (JSONArray) ((JSONObject) doc.get("d")).get("results");

        for (Object obj : arResults) {
            JSONObject results = (JSONObject) obj;
            validateDomainResponse(results, null);
        }

    }

    /**
     * Cell?Json???.
     * @param results JSONObject
     * @param locationHeader LOCATION
     */
    public final void validateCellResponse(final JSONObject results, final String locationHeader) {
        String value;

        // d:Name?
        value = (String) results.get("Name");
        assertNotNull(value);
        // Name??????
        assertTrue(value.length() > 0);

        // d:__published?
        value = (String) results.get("__published");
        assertNotNull(value);
        // __published?????????
        assertTrue(validDate(value));

        // d:__updated?
        value = (String) results.get("__updated");
        assertNotNull(value);
        // __updated?????????
        assertTrue(validDate(value));

        // __metadata?
        JSONObject metadata = (JSONObject) results.get("__metadata");
        // uri?
        value = (String) metadata.get("uri");
        assertNotNull(value);
        if (locationHeader != null) {
            // LOCATION?????
            assertEquals(value, locationHeader);
        }

        // type?
        value = (String) metadata.get("type");
        assertNotNull(value);
        assertEquals(value, TYPE_CELL);

        // etag?
        value = (String) metadata.get("etag");
        assertNotNull(value);
        // etag??????
        assertTrue(value.length() > 0);
    }

    /**
     * Domain?Json???.
     * @param results JSONObject
     * @param locationHeader LOCATION
     */
    public final void validateDomainResponse(final JSONObject results, final String locationHeader) {
        String value;

        // d:Name?
        value = (String) results.get("Name");
        assertNotNull(value);
        // Name??????
        assertTrue(value.length() > 0);

        // d:__published?
        value = (String) results.get("__published");
        assertNotNull(value);
        // __published?????????
        assertTrue(validDate(value));

        // d:__updated?
        value = (String) results.get("__updated");
        assertNotNull(value);
        // __updated?????????
        assertTrue(validDate(value));

        // __metadata?
        JSONObject metadata = (JSONObject) results.get("__metadata");
        // uri?
        value = (String) metadata.get("uri");
        assertNotNull(value);
        if (locationHeader != null) {
            // LOCATION?????
            assertEquals(value, locationHeader);
        }

        // type?
        value = (String) metadata.get("type");
        assertNotNull(value);

        // etag?
        value = (String) metadata.get("etag");
        assertNotNull(value);
        // etag??????
        assertTrue(value.length() > 0);
    }

    /**
     * Cell?XML???.
     * @param doc Document
     * @param code 
     */
    public final void checkErrorResponseXML(final Document doc, final String code) {
        this.checkErrorResponse(doc, code);
    }

    /**
     * Cell?XML???.
     * @param doc Document
     * @param code 
     */
    public final void checkErrorResponse(final Document doc, final String code) {
        Node elm;

        // code?
        elm = getElementByTagName(doc, "code");
        assertNotNull(elm);
        // code?????
        assertEquals(code, elm.getTextContent());

        // message?
        elm = getElementByTagName(doc, "message");
        assertNotNull(elm);
        // message?????????
        // ?????????
    }

    /**
     * ??.
     * @param doc JSONObject
     * @param code 
     */
    public final void checkErrorResponse(JSONObject doc, String code) {
        checkErrorResponse(doc, code, null);
    }

    /**
     * ??.
     * @param doc JSONObject
     * @param code 
     * @param message 
     */
    public final void checkErrorResponse(JSONObject doc, String code, String message) {

        String value;
        JSONObject error = doc;

        // code?
        value = (String) error.get("code");
        assertNotNull(value);
        // code?????
        assertEquals(code, value);

        // __metadata?
        JSONObject metadata = (JSONObject) error.get("message");
        // lang?
        value = (String) metadata.get("lang");
        assertNotNull(value);

        // value?
        value = (String) metadata.get("value");
        if (message == null) {
            assertNotNull(value);
        } else {
            assertEquals(message, value);
        }
    }

    /**
     * ??XML???.
     * @param doc Document
     * @param errorCode 
     */
    public final void checkErrorXML(final Document doc, final String errorCode) {
        Node elm;

        // error?
        elm = getElementByTagName(doc, "error");
        assertNotNull(elm);

        // code?
        elm = getElementByTagName(doc, "code");
        assertNotNull(elm);
        assertEquals(elm.getTextContent(), errorCode);

        // message?
        elm = getElementByTagName(doc, "message");
        assertNotNull(elm);
        assertTrue(elm.getTextContent().length() > 0);
    }

}