io.personium.jersey.engine.test.ScriptTestBase.java Source code

Java tutorial

Introduction

Here is the source code for io.personium.jersey.engine.test.ScriptTestBase.java

Source

/**
 * Personium
 * Copyright 2014 - 2017 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 io.personium.jersey.engine.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.json.simple.JSONObject;
import org.junit.AfterClass;
import org.junit.BeforeClass;

import io.personium.client.Accessor;
import io.personium.client.Box;
import io.personium.client.Cell;
import io.personium.client.DaoException;
import io.personium.client.PersoniumContext;
import io.personium.client.ServiceCollection;
import io.personium.client.http.PersoniumRequestBuilder;
import io.personium.client.http.PersoniumResponse;
import io.personium.client.http.HttpClientFactory;
import io.personium.engine.utils.PersoniumEngineConfig;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.spi.container.TestContainerFactory;

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

/**
 * engine?????.
 */
public abstract class ScriptTestBase extends JerseyTest {

    /** EngineUrl. */
    public static final String LOCAL_TEST_SERVICE_URL = "http://localhost:9998";
    /** ??URL. */
    public static final String DEFAULT_TARGET_URL = "http://localhost:8080/personium-core";
    /** ?URL???. */
    public static final String PROP_TARGET_URL = "io.personium.test.target";
    /** ??URL?? ??????URL?. */
    static String baseUrl = System.getProperty(PROP_TARGET_URL, DEFAULT_TARGET_URL);
    /** . */
    public static final String PROP_SERVICE_CALL_TEST_FLAG = "io.personium.test.service";
    /** ???? ?????False?. */
    static boolean isServiceTest = Boolean.parseBoolean(System.getProperty(PROP_SERVICE_CALL_TEST_FLAG, "false"));
    /** ?????Cell???Cell????. */
    public static final String PROP_UNITUSER_CELL = "io.personium.test.unituser.cell";
    /** ?Cell(URL)?? ????????. */
    private static String unitUserCell = System.getProperty(PROP_UNITUSER_CELL, "");
    /** ?Cell?. */
    public static final String PROP_UNITUSER_CELL_ACCOUNT = "io.personium.test.unituser.account";
    /** ?Cell(URL)?? ????????. */
    private static String unitUserAccount = System.getProperty(PROP_UNITUSER_CELL_ACCOUNT, "");
    /** ?Cell?. */
    public static final String PROP_UNITUSER_CELL_PASSWORD = "io.personium.test.unituser.password";
    /** ?Cell(URL)?? ????????. */
    private static String unitUserPassword = System.getProperty(PROP_UNITUSER_CELL_PASSWORD, "");
    /** URL???????. */
    protected static final String KEY_HEADER_BASEURL = "X-Baseurl";
    /** ????Cell?. */
    private static final int CELL_COUNT = 3;
    /** ????Cell. */
    private static Cell[] testCells = new Cell[CELL_COUNT];
    /** ????Box. */
    private static Box[] testBoxs = new Box[CELL_COUNT];
    /** ????ServiceCollection. */
    static ServiceCollection testSvcCol;
    /** ??Accessor. */
    private static Accessor testAs = null;
    /** Cell??. */
    static String cellName = "enginetest";
    /** Box. */
    static String boxName = "boxname";
    /** Box. */
    private static String boxSchema = "box";
    /** Account. */
    private static String accountName = "user001";
    /** . */
    private static String engineAccountName = "engine";
    /** Account password. */
    private static String accountPassword = "pass001";
    /** ServiceCollection??. */
    private static String serviceCollectionName = "svccol";
    /** ??. */
    private static String serviceName = "test";
    /** ??. */
    private static String serviceScriptPath = "test.js";
    /** Http. */
    HttpClient httpClient = HttpClientFactory.create("insecure", 0);
    /** . */
    private static String masterToken = PersoniumEngineConfig.getMasterToken();
    /** . */
    static String token = "";
    /** DC. */
    private static PersoniumContext personiumCtx;

    /**
     * .
     */
    public ScriptTestBase() {
        super();
    }

    /**
     * .
     * @param testContainerFactory .
     */
    public ScriptTestBase(TestContainerFactory testContainerFactory) {
        super(testContainerFactory);
    }

    /**
     * .
     * @param ad .
     */
    public ScriptTestBase(AppDescriptor ad) {
        super(ad);
    }

    /**
     * .
     * @param packages .
     */
    public ScriptTestBase(String... packages) {
        super(packages);
    }

    /**
     * ????.
     * @throws DaoException DAO
     */
    @BeforeClass
    public static final void beforeClass() throws DaoException {
        // ?
        personiumCtx = new PersoniumContext(baseUrl, cellName, boxSchema, boxSchema);
        String version = getVersion();
        if (version != null && !(version.equals(""))) {
            personiumCtx.setPersoniumVersion(version);
        }

        // ?
        if ("".equals(unitUserCell) || "".equals(unitUserAccount) || "".equals(unitUserPassword)) {
            // ??????????
            token = masterToken;
            personiumCtx.setDefaultHeader("X-Personium-Unit-User", "https://example.com/test#UnitUser");
        } else {
            // ???????????
            Accessor as = personiumCtx.asAccount(unitUserCell, unitUserAccount, unitUserPassword);
            token = as.cell(baseUrl).getAccessToken();
        }
        // CLIENT?????????
        personiumCtx.setClientToken(token);

        // ??Accessor?
        testAs = personiumCtx.withToken(token);

        // ??????????????????
        destroyResources();

        // ????
        makeResources();
    }

    /**
     * ???.
     */
    @AfterClass
    public static final void afterClass() {
        destroyResources();
    }

    /**
     * ????.
     */
    @SuppressWarnings("unchecked")
    static void makeResources() {
        // Account??JSON
        JSONObject accountJson = new JSONObject();
        accountJson.put("Name", accountName);

        // ??JSON
        JSONObject engineAccountJson = new JSONObject();
        engineAccountJson.put("Name", engineAccountName);

        // Box??JSON
        JSONObject boxJson = new JSONObject();
        boxJson.remove("Name");
        boxJson.put("Name", boxName);

        // Cell??JSON
        JSONObject json = new JSONObject();
        json.put("Name", cellName);

        for (int i = 0; i < testCells.length; i++) {
            try {
                testCells[i] = testAs.asCellOwner().unit.cell.create(json);
            } catch (DaoException e) {
                // CONFLICT(409)????????Cell?
                if (Integer.parseInt(e.getCode()) != HttpStatus.SC_CONFLICT) {
                    fail(e.getMessage());
                }
            }
            // Account?
            try {
                testCells[i].account.create(accountJson, accountPassword);
                // ??
                testCells[i].account.create(engineAccountJson, null);
            } catch (DaoException e) {
                // CONFLICT(409)????????Cell?
                if (Integer.parseInt(e.getCode()) != HttpStatus.SC_CONFLICT) {
                    fail(e.getMessage());
                }
            }
            // Box?
            try {
                testBoxs[i] = testCells[i].box.create(boxJson);
            } catch (DaoException e) {
                if (Integer.parseInt(e.getCode()) != HttpStatus.SC_CONFLICT) {
                    fail(e.getMessage());
                }
            }
            json.remove("Name");
            json.put("Name", cellName + (i + 1));
        }
        try {
            if (isServiceTest) {
                // ?? serviceCollectionName
                testBoxs[0].mkService(serviceCollectionName);
                testSvcCol = testBoxs[0].service(serviceCollectionName);
                // ? PROPPATCH
                testSvcCol.configure(serviceName, serviceScriptPath, engineAccountName);
                // ? Dav?put
                putScript("testCommon.js", "testCommon.js");
            }
        } catch (DaoException e) {
            if (Integer.parseInt(e.getCode()) != HttpStatus.SC_CONFLICT) {
                fail(e.getMessage());
            }
        }
    }

    /**
     * ?.
     */
    static void destroyResources() {
        String name = cellName;
        for (int i = 0; i < testCells.length; i++) {
            removeCell(name);
            name = cellName + (i + 1);
        }
    }

    /**
     * Cell??Cell???.
     * @param name ?Cell??
     */
    static void removeCell(String name) {
        Cell cell = null;
        Box box = null;
        ServiceCollection svc = null;
        try {
            if (!testAs.asCellOwner().unit.cell.exists(name)) {
                return;
            }
            cell = testAs.cell(name);
            box = cell.box(boxName);
            svc = cell.box(boxName).service(serviceCollectionName);
        } catch (DaoException e) {
            fail(e.getMessage());
        }

        try {
            if (isServiceTest) {
                // ? Dav?delete
                svc.del("testCommon.js");
                // ?
                box.del(serviceCollectionName);
            }
        } catch (DaoException e) {
            if (Integer.parseInt(e.getCode()) != HttpStatus.SC_NOT_FOUND) {
                fail(e.getMessage());
            }
        }

        // Box
        try {
            cell.box.del(boxName);
        } catch (DaoException e) {
            if (Integer.parseInt(e.getCode()) != HttpStatus.SC_NOT_FOUND) {
                fail(e.getMessage());
            }
        }

        // Account
        try {
            cell.account.del(accountName);
            // ?
            cell.account.del(engineAccountName);
        } catch (DaoException e) {
            if (Integer.parseInt(e.getCode()) != HttpStatus.SC_NOT_FOUND) {
                fail(e.getMessage());
            }
        }

        // Cell
        try {
            testAs.asCellOwner().unit.cell.del(name);
        } catch (DaoException e) {
            if (Integer.parseInt(e.getCode()) != HttpStatus.SC_NOT_FOUND) {
                fail(e.getMessage());
            }
        }
    }

    /**
     * ???.
     */
    protected static class IllegalResponseFixture {
        String responseMessage;
        String requestJson;

        IllegalResponseFixture(String responseMessage, String requestJson) {
            this.responseMessage = responseMessage;
            this.requestJson = requestJson;
        }
    }

    /**
     * ?.
     * @param resourceName ??
     * @param fileName ??
     */
    protected static void putScript(final String resourceName, final String fileName) {
        // ? Dav?put
        String testFilename = ScriptTest.class.getResource("/service/" + resourceName).getFile();

        // DAV
        // dc.setChunked(false);
        try {
            FileInputStream fis = new FileInputStream(testFilename);
            testSvcCol.put(fileName, "text/plain", fis, "*");
        } catch (DaoException e) {
            fail(e.getMessage());
        } catch (FileNotFoundException e) {
            fail(e.getMessage());
        }
    }

    /**
     * .
     * @param name ??
     */
    protected void callService(final String name) {
        String url;
        if (isServiceTest) {
            // ? Dav?put
            putScript(name, "test.js");
            url = requestUrl();
        } else {
            url = requestUrl(name);
        }
        // ?
        callServiceTest(url);
        if (isServiceTest) {
            // ?Dav?del
            try {
                testSvcCol.del("test.js");
            } catch (DaoException e) {
                fail(e.getMessage());
            }
        }
    }

    /**
     * .
     * @param url url
     */
    private void callServiceTest(final String url) {
        try {
            HttpUriRequest req = new PersoniumRequestBuilder().url(url).method("GET").token(token).build();
            req.setHeader(KEY_HEADER_BASEURL, baseUrl);
            String version = getVersion();
            if (version != null && !(version.equals(""))) {
                req.setHeader("X-Personium-Version", version);
            }
            PersoniumResponse res = request(req);
            assertEquals(HttpStatus.SC_OK, res.getStatusCode());
            assertEquals("OK", res.bodyAsString());
        } catch (DaoException e) {
            fail(e.getMessage());
        }
    }

    /**
     * ?URL??.
     * @return ???URL
     */
    protected String requestUrl() {
        return String.format("%s/%s/%s/%s/test?cell=%s", baseUrl, cellName, boxName, serviceCollectionName,
                cellName);
    }

    /**
     * ?URL??.
     * @param name ???
     * @return ???URL
     */
    protected String requestUrl(final String name) {
        return String.format("%s/%s/%s/test/%s?cell=%s", LOCAL_TEST_SERVICE_URL, cellName, boxName, name, cellName);
    }

    /**
     * Reponse????HTTP?.
     * @param httpReq HTTP
     * @return DC?
     * @throws DaoException DAO
     */
    protected PersoniumResponse request(final HttpUriRequest httpReq) throws DaoException {
        try {
            HttpResponse objResponse = httpClient.execute(httpReq);
            PersoniumResponse dcRes = new PersoniumResponse(objResponse);
            int statusCode = objResponse.getStatusLine().getStatusCode();
            if (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) {
                throw DaoException.create("{\"io exception\" : " + dcRes.bodyAsString() + "}", statusCode);
            }
            return dcRes;
        } catch (IOException ioe) {
            throw DaoException.create("{\"io exception\" : " + ioe.getMessage() + "}", 0);
        }
    }

    /**
     * ????.
     * @return ??
     */
    protected static String getVersion() {
        return PersoniumEngineTestConfig.getVersion();
    }

}