From e085b1ad3039b3c8685a7ed101822ad763eb77cb Mon Sep 17 00:00:00 2001 From: Wataru Sawami Date: Thu, 8 Jun 2017 15:08:48 +0900 Subject: [PATCH] V1.5.1 --- CHANGELOG.md | 6 + pom.xml | 6 +- .../core/PersoniumCoreException.java | 19 +- .../personium/core/PersoniumUnitConfig.java | 13 + .../java/io/personium/core/model/DavCmp.java | 5 + .../io/personium/core/model/ctl/Common.java | 21 +- .../core/model/ctl/ReceivedMessage.java | 10 +- .../model/file/StreamingOutputForDavFile.java | 24 +- .../StreamingOutputForDavFileWithRange.java | 8 +- .../core/model/impl/es/CellEsImpl.java | 3 +- .../core/model/impl/es/DavCmpEsImpl.java | 1516 ------------- .../personium/core/model/impl/es/EsModel.java | 12 +- .../accessor/AbstractEntitySetAccessor.java | 29 - .../model/impl/es/accessor/CellAccessor.java | 122 - .../impl/es/accessor/CellDeleteAccessor.java | 119 - .../impl/es/accessor/DataSourceAccessor.java | 200 +- .../impl/es/accessor/DavMoveAccessor.java | 370 --- .../impl/es/accessor/DavNodeAccessor.java | 285 --- .../impl/es/accessor/ODataEntityAccessor.java | 107 - .../impl/es/accessor/ODataLinkAccessor.java | 123 - .../personium/core/model/impl/es/ads/Ads.java | 320 --- .../impl/es/ads/AdsConnectionException.java | 38 - .../core/model/impl/es/ads/AdsException.java | 38 - .../core/model/impl/es/ads/JdbcAds.java | 1673 -------------- .../core/model/impl/es/ads/package-info.java | 20 - .../impl/es/odata/CellCtlODataProducer.java | 393 ++-- .../model/impl/es/repair/AdsAccessor.java | 217 -- .../core/model/impl/es/repair/EsAccessor.java | 105 - .../repair/PersoniumRepairAdsException.java | 46 - .../core/model/impl/es/repair/RepairAds.java | 567 ----- .../impl/es/repair/RepairAdsException.java | 46 - .../model/impl/es/repair/package-info.java | 21 - .../core/model/impl/fs/DavCmpFsImpl.java | 113 +- .../core/model/impl/fs/DavMetadataFile.java | 36 +- .../core/rs/PersoniumCoreApplication.java | 4 +- .../PersoniumEngineSvcCollectionResource.java | 10 +- .../core/rs/cell/MessageODataResource.java | 53 +- .../core/rs/odata/AbstractODataResource.java | 4 +- .../listener/RepairServiceLauncher.java | 130 -- .../WebContainerListenerForAdsRepair.java | 41 - .../webcontainer/listener/package-info.java | 17 - .../resources/personium-messages.properties | 10 +- .../personium-unit-config-default.properties | 2 +- src/main/webapp/WEB-INF/web.xml | 4 - .../model/file/BinaryDataAccessorTest.java | 231 -- .../core/model/impl/es/EsModelTest.java | 9 - .../core/model/impl/es/accessor/AllTests.java | 4 +- .../impl/es/accessor/CellAccessorTest.java | 510 ++--- .../impl/es/accessor/DavNodeAccessorTest.java | 761 ------- .../es/accessor/ODataEntityAccessorTest.java | 504 ++--- .../es/accessor/ODataLinkAccessorTest.java | 308 --- .../core/model/impl/es/ads/AllTests.java | 31 - .../core/model/impl/es/ads/JdbcAdsTest.java | 240 -- .../es/odata/CellCtlODataProducerTest.java | 1982 ++++++++++++----- .../core/model/impl/fs/DavCmpFsImplTest.java | 622 +++++- .../rs/cell/MessageODataResourceTest.java | 746 +++++++ .../rs/odata/AbstractODataResourceTest.java | 112 +- .../core/webcontainer/listener/AllTests.java | 31 - .../listener/RepairServiceLauncherTest.java | 137 -- .../io/personium/test/IntegrationTests.java | 4 +- .../io/personium/test/PerformanceTests.java | 4 +- .../io/personium/test/RegressionTests.java | 4 +- .../java/io/personium/test/UnitTests.java | 4 +- .../test/jersey/PersoniumIntegTestRunner.java | 2 + .../test/jersey/box/CollectionTest.java | 23 +- .../test/jersey/box/acl/AclTest.java | 59 +- .../box/dav/file/DavFileEncryptTest.java | 56 + .../personium/test/jersey/cell/AclTest.java | 64 +- .../test/jersey/cell/DeleteTest.java | 12 +- .../test/jersey/cell/MessageApproveTest.java | 1332 +++++++++-- .../test/jersey/cell/MessageReceivedTest.java | 183 +- .../test/jersey/cell/MessageSentTest.java | 1259 +++++++++-- .../jersey/cell/UnitUserCellCRUDTest.java | 6 +- .../cell/auth/AuthAccountUpdateTest.java | 11 +- .../test/jersey/cell/auth/AuthBasicTest.java | 9 +- .../test/jersey/cell/auth/AuthCheckTest.java | 102 +- .../test/jersey/cell/auth/AuthCookieTest.java | 23 +- .../test/jersey/cell/auth/AuthTest.java | 7 +- .../cell/auth/BasicAuthCellLevelTest.java | 12 +- .../jersey/cell/ctl/AccountRoleLinkTest.java | 4 +- .../test/jersey/cell/ctl/AccountTest.java | 6 +- .../jersey/cell/ctl/AccountViaNPTest.java | 8 +- .../test/jersey/cell/ctl/BoxRoleLinkTest.java | 53 +- .../jersey/cell/ctl/BoxRoleViaNPTest.java | 11 +- .../jersey/cell/ctl/ExtCellDeleteTest.java | 4 +- .../jersey/cell/ctl/ExtRoleDeleteTest.java | 4 +- .../jersey/cell/ctl/RelationDeleteTest.java | 4 +- .../test/jersey/cell/ctl/RoleCreateTest.java | 4 +- .../test/jersey/cell/ctl/RoleViaNPTest.java | 4 +- .../io/personium/test/unit/core/UrlUtils.java | 20 + .../unit/core/bar/BarFileContentsTest.java | 1092 +++++---- .../model/impl/es/repair/AdsAcessorTest.java | 332 --- .../core/model/impl/es/repair/AllTests.java | 35 - .../model/impl/es/repair/EsAcessorTest.java | 108 - .../impl/es/repair/RepairAdsCompleteTest.java | 685 ------ .../es/repair/RepairAdsIntegrationTest.java | 376 ---- .../model/impl/es/repair/RepairAdsTest.java | 488 ---- .../model/impl/es/repair/package-info.java | 21 - .../validate/ReceivedMessageValidateTest.java | 81 - .../validate/SentMessageValidateTest.java | 97 - .../io/personium/test/utils/RoleUtils.java | 32 +- src/test/resources/davFile/decrypt01.txt | 4 + src/test/resources/davFile/encrypt01.txt | 1 + src/test/resources/davFile/file01.txt | 2 + src/test/resources/davFile/range01.txt | 2 + 105 files changed, 6902 insertions(+), 12886 deletions(-) delete mode 100644 src/main/java/io/personium/core/model/impl/es/DavCmpEsImpl.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/accessor/CellDeleteAccessor.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/accessor/DavMoveAccessor.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/accessor/DavNodeAccessor.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/ads/Ads.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/ads/AdsConnectionException.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/ads/AdsException.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/ads/JdbcAds.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/ads/package-info.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/repair/AdsAccessor.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/repair/EsAccessor.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/repair/PersoniumRepairAdsException.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/repair/RepairAds.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/repair/RepairAdsException.java delete mode 100644 src/main/java/io/personium/core/model/impl/es/repair/package-info.java delete mode 100644 src/main/java/io/personium/core/webcontainer/listener/RepairServiceLauncher.java delete mode 100644 src/main/java/io/personium/core/webcontainer/listener/WebContainerListenerForAdsRepair.java delete mode 100644 src/main/java/io/personium/core/webcontainer/listener/package-info.java delete mode 100644 src/test/java/io/personium/core/model/impl/es/accessor/DavNodeAccessorTest.java delete mode 100644 src/test/java/io/personium/core/model/impl/es/accessor/ODataLinkAccessorTest.java delete mode 100644 src/test/java/io/personium/core/model/impl/es/ads/AllTests.java delete mode 100644 src/test/java/io/personium/core/model/impl/es/ads/JdbcAdsTest.java delete mode 100644 src/test/java/io/personium/core/webcontainer/listener/AllTests.java delete mode 100644 src/test/java/io/personium/core/webcontainer/listener/RepairServiceLauncherTest.java create mode 100644 src/test/java/io/personium/test/jersey/box/dav/file/DavFileEncryptTest.java delete mode 100644 src/test/java/io/personium/test/unit/core/model/impl/es/repair/AdsAcessorTest.java delete mode 100644 src/test/java/io/personium/test/unit/core/model/impl/es/repair/AllTests.java delete mode 100644 src/test/java/io/personium/test/unit/core/model/impl/es/repair/EsAcessorTest.java delete mode 100644 src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsCompleteTest.java delete mode 100644 src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsIntegrationTest.java delete mode 100644 src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsTest.java delete mode 100644 src/test/java/io/personium/test/unit/core/model/impl/es/repair/package-info.java create mode 100644 src/test/resources/davFile/decrypt01.txt create mode 100644 src/test/resources/davFile/encrypt01.txt create mode 100644 src/test/resources/davFile/file01.txt create mode 100644 src/test/resources/davFile/range01.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index d5d7c49d0..b09428ee7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## 1.5.1 +IMPROVEMENTS: +* Make relationship registration possible by role. ([#24](https://github.com/personium/personium-core/issues/24)) +* If ads: none, unnecessary logs are output.([#25](https://github.com/personium/personium-core/issues/25)) +* WebDAV file encryption.([#27](https://github.com/personium/personium-core/issues/27)) + ## 1.5.0 BUG FIXES: * Unavailability of TLS 1.2. diff --git a/pom.xml b/pom.xml index b0476d1c9..ba273ce81 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ io.personium personium-core war - 1.5.0 + 1.5.1 personium-core Maven Webapp http://maven.apache.org @@ -31,7 +31,7 @@ io.personium personium-lib-common - 1.4.2 + 1.4.3 io.personium @@ -46,7 +46,7 @@ io.personium personium-client-java - 1.4.3 + 1.4.4 test diff --git a/src/main/java/io/personium/core/PersoniumCoreException.java b/src/main/java/io/personium/core/PersoniumCoreException.java index 43d3f1bef..7bbd56fc6 100644 --- a/src/main/java/io/personium/core/PersoniumCoreException.java +++ b/src/main/java/io/personium/core/PersoniumCoreException.java @@ -577,20 +577,23 @@ public static class ReceivedMessage { * {0}:RelationClassURL */ public static final PersoniumCoreException BOX_THAT_MATCHES_RELATION_CLASS_URL_NOT_EXISTS = create("PR400-RM-0003"); // CHECKSTYLE IGNORE - To maintain readability - /** - * メッセージのRequestRelationのパースに失敗. - */ - public static final PersoniumCoreException REQUEST_RELATION_PARSE_ERROR = create("PR409-RM-0001"); + +// unnecessary. +// /** +// * メッセージのRequestRelationのパースに失敗. +// */ +// public static final PersoniumCoreException REQUEST_RELATION_PARSE_ERROR = create("PR409-RM-0001"); /** * 関係削除対象のRelationが存在しない. */ public static final PersoniumCoreException REQUEST_RELATION_DOES_NOT_EXISTS = create("PR409-RM-0002"); - /** - * メッセージのRequestRelationTargetのパースに失敗. - */ - public static final PersoniumCoreException REQUEST_RELATION_TARGET_PARSE_ERROR = create("PR409-RM-0003"); +// unnecessary. +// /** +// * メッセージのRequestRelationTargetのパースに失敗. +// */ +// public static final PersoniumCoreException REQUEST_RELATION_TARGET_PARSE_ERROR = create("PR409-RM-0003"); /** * 関係削除対象のExtCellが存在しない. diff --git a/src/main/java/io/personium/core/PersoniumUnitConfig.java b/src/main/java/io/personium/core/PersoniumUnitConfig.java index 7dda36dcc..3f2bb08c1 100644 --- a/src/main/java/io/personium/core/PersoniumUnitConfig.java +++ b/src/main/java/io/personium/core/PersoniumUnitConfig.java @@ -207,6 +207,11 @@ public static final class Security { * トークンを暗号化する際に利用している秘密鍵. */ public static final String AUTH_PASSWORD_SALT = KEY_ROOT + "security.auth.password.salt"; + + /** + * Encrypt the DAV file (true: enabled false: disabled (default)). + */ + public static final String DAV_ENCRYPT_ENABLED = KEY_ROOT + "security.dav.encrypt.enabled"; } /** @@ -1507,6 +1512,14 @@ public static String getAuthPasswordSalt() { return get(Security.AUTH_PASSWORD_SALT); } + /** + * Encrypt the DAV file. + * @return true: enabled false: disabled + */ + public static boolean isDavEncryptEnabled() { + return Boolean.parseBoolean(get(Security.DAV_ENCRYPT_ENABLED)); + } + /** * Repair処理が最初に起動するまでの遅延時間. * @return Repair処理が最初に起動するまでの遅延時間. diff --git a/src/main/java/io/personium/core/model/DavCmp.java b/src/main/java/io/personium/core/model/DavCmp.java index 96cd78638..28e75648f 100644 --- a/src/main/java/io/personium/core/model/DavCmp.java +++ b/src/main/java/io/personium/core/model/DavCmp.java @@ -127,6 +127,11 @@ public interface DavCmp { */ String getContentType(); + /** + * @return Encryption type + */ + String getEncryptionType(); + /** * @return true if Cell Level */ diff --git a/src/main/java/io/personium/core/model/ctl/Common.java b/src/main/java/io/personium/core/model/ctl/Common.java index c84fe19f8..66da39ac1 100644 --- a/src/main/java/io/personium/core/model/ctl/Common.java +++ b/src/main/java/io/personium/core/model/ctl/Common.java @@ -35,6 +35,11 @@ public class Common { private Common() { } + /** Regular expression in generic name. */ + private static final String REGEX_NAME = "[a-zA-Z0-9][a-zA-Z0-9-_]{0,127}"; + /** Regular expression in relation name. */ + private static final String REGEX_RELATION_NAME = "[a-zA-Z0-9-\\+][a-zA-Z0-9-_\\+:]{0,127}"; + /** * UnitCtlの名前空間名. */ @@ -78,26 +83,32 @@ private Common() { /** 拡張スキーマFormat定義.1つ以上のスペース区切り英数字. */ public static final String P_FORMAT_PATTERN_USUSST = "unordered-set-of-unique-space-separated-tokens"; /** 先頭が-,_以外で始まる半角英数大小文字,-,_が1文字から128文字. */ - public static final String PATTERN_NAME = "^[a-zA-Z0-9][a-zA-Z0-9-_]{0,127}$"; + public static final String PATTERN_NAME = "^" + REGEX_NAME + "$"; /** 先頭が半角記号以外で始まる半角英数大小文字,半角記号(-_!#$%*+/=^`{|}~.@)が1文字から128文字. */ public static final String PATTERN_NAME_WITH_SIGN = "^[a-zA-Z0-9][a-zA-Z0-9-_!$*=^`{|}~.@]{0,127}$"; /** 先頭が_,:以外で始まる半角英数大小文字,-,_,+,:が1文字から128文字. */ - public static final String PATTERN_RELATION_NAME = "^[a-zA-Z0-9-\\+][a-zA-Z0-9-_\\+:]{0,127}$"; + public static final String PATTERN_RELATION_NAME = "^" + REGEX_RELATION_NAME + "$"; /** String containing "/__relation/__/".
* Explanation of applicable group.
* $1:BaseURL * $2:CellName * $3:RelationName */ - public static final String PATTERN_RELATION_CLASS_URL = "(^.+)/([^/]+)/__relation/__/([^/]+)/?"; + public static final String PATTERN_RELATION_CLASS_URL = "(^.+)/([^/]+)/__relation/__/(" + REGEX_RELATION_NAME + ")/?$"; // CHECKSTYLE IGNORE - To maintain readability + /** String containing "/__role/__/".
+ * Explanation of applicable group.
+ * $1:BaseURL + * $2:CellName + * $3:RoleName */ + public static final String PATTERN_ROLE_CLASS_URL = "(^.+)/([^/]+)/__role/__/(" + REGEX_NAME + ")/?$"; /** multiplicityのFormat定義. */ public static final String PATTERN_MULTIPLICITY = "0\\.\\.1|1|\\*"; /** 先頭が-,_以外で始まる半角英数大小文字,-,_が1文字から200文字. */ public static final String PATTERN_ID = "^[a-zA-Z0-9][a-zA-Z0-9-_:]{0,199}$"; /** InReplyTo32文字. */ public static final String PATTERN_IN_REPLY_TO = "^.{32}$"; - /** メッセージタイプ_messageまたはreq.relation.buildまたはreq.relation.break. */ + /** MessageType message or req.relation.build or req.relation.break or req.role.grant or req.role.revoke. */ public static final String PATTERN_MESSAGE_TYPE = - "^(message)|(req\\.relation\\.build)|(req\\.relation\\.break)$"; + "^(message)|(req\\.relation\\.build)|(req\\.relation\\.break)|(req\\.role\\.grant)|(req\\.role\\.revoke)$"; /** メッセージタイトル0文字から256文字文字. */ public static final String PATTERN_MESSAGE_TITLE = "^.{0,256}$"; /** メッセージプライオリティ 1から5. */ diff --git a/src/main/java/io/personium/core/model/ctl/ReceivedMessage.java b/src/main/java/io/personium/core/model/ctl/ReceivedMessage.java index ecfd7c49c..3214c92ac 100644 --- a/src/main/java/io/personium/core/model/ctl/ReceivedMessage.java +++ b/src/main/java/io/personium/core/model/ctl/ReceivedMessage.java @@ -41,12 +41,16 @@ protected ReceivedMessage() { */ public static final String EDM_NPNAME_FOR_ACCOUNT = "_AccountRead"; - /** タイプ メッセージ. */ + /** Type message. */ public static final String TYPE_MESSAGE = "message"; - /** タイプ 関係登録. */ + /** Type register relation. */ public static final String TYPE_REQ_RELATION_BUILD = "req.relation.build"; - /** タイプ 関係削除. */ + /** Type delete relation. */ public static final String TYPE_REQ_RELATION_BREAK = "req.relation.break"; + /** Type register relation role. */ + public static final String TYPE_REQ_ROLE_GRANT = "req.role.grant"; + /** Type delete relation role. */ + public static final String TYPE_REQ_ROLE_REVOKE = "req.role.revoke"; /** ステータス 未読. */ public static final String STATUS_UNREAD = "unread"; diff --git a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java index 4f085a630..6c26f1511 100644 --- a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java +++ b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java @@ -62,11 +62,14 @@ public class StreamingOutputForDavFile implements StreamingOutput { InputStream hardLinkInput = null; /** - * コンストラクタ. - * @param fileFullPath 読み込むファイルのフルパス - * @throws BinaryDataNotFoundException ファイルが存在しない場合. + * Constructor. + * @param fileFullPath Full path of the file to be read + * @param cellId Cell ID + * @param encryptionType encryption type + * @throws BinaryDataNotFoundException Error when file does not exist. */ - public StreamingOutputForDavFile(String fileFullPath) throws BinaryDataNotFoundException { + public StreamingOutputForDavFile(String fileFullPath, String cellId, String encryptionType) + throws BinaryDataNotFoundException { if (!Files.exists(Paths.get(fileFullPath))) { throw new BinaryDataNotFoundException(fileFullPath); } @@ -81,7 +84,15 @@ public StreamingOutputForDavFile(String fileFullPath) throws BinaryDataNotFoundE hardLinkPath = Files.createLink(Paths.get(hardLinkName), Paths.get(fileFullPath)); } // ハードリンクからの入力ストリームを取得 - hardLinkInput = new BufferedInputStream(new FileInputStream(hardLinkPath.toFile())); + InputStream inputStream; + if (DataCryptor.ENCRYPTION_TYPE_AES.equals(encryptionType)) { + // Perform decryption. + DataCryptor cryptor = new DataCryptor(cellId); + inputStream = cryptor.decode(new FileInputStream(hardLinkPath.toFile())); + } else { + inputStream = new FileInputStream(hardLinkPath.toFile()); + } + hardLinkInput = new BufferedInputStream(inputStream); // 成功したら終了 return; } catch (IOException e) { @@ -98,6 +109,9 @@ public StreamingOutputForDavFile(String fileFullPath) throws BinaryDataNotFoundE throw new BinaryDataNotFoundException("Unable to create hard link for DAV file: " + hardLinkName); } + /** + * {@inheritDoc} + */ @Override public void write(OutputStream output) throws IOException, WebApplicationException { if (null == hardLinkInput) { diff --git a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java index 129d49332..4ddce1d98 100644 --- a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java +++ b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java @@ -43,12 +43,16 @@ public class StreamingOutputForDavFileWithRange extends StreamingOutputForDavFil * @param fileFullPath 読み込むファイルのフルパス * @param fileSize 読み込むファイルのサイズ * @param range RangeHeader + * @param cellId Cell ID + * @param encryptionType encryption type * @throws BinaryDataNotFoundException ファイルが存在しない場合. */ public StreamingOutputForDavFileWithRange(final String fileFullPath, final long fileSize, - final RangeHeaderHandler range) throws BinaryDataNotFoundException { - super(fileFullPath); + final RangeHeaderHandler range, + String cellId, + String encryptionType) throws BinaryDataNotFoundException { + super(fileFullPath, cellId, encryptionType); this.range = range; this.fileSize = fileSize; } diff --git a/src/main/java/io/personium/core/model/impl/es/CellEsImpl.java b/src/main/java/io/personium/core/model/impl/es/CellEsImpl.java index 7370bee48..0badb9be8 100644 --- a/src/main/java/io/personium/core/model/impl/es/CellEsImpl.java +++ b/src/main/java/io/personium/core/model/impl/es/CellEsImpl.java @@ -78,6 +78,7 @@ import io.personium.core.model.impl.es.doc.CellDocHandler; import io.personium.core.model.impl.es.doc.OEntityDocHandler; import io.personium.core.model.impl.es.odata.CellCtlODataProducer; +import io.personium.core.model.impl.fs.DavCmpFsImpl; import io.personium.core.model.lock.CellLockManager; import io.personium.core.odata.OEntityWrapper; import io.personium.core.utils.UriUtils; @@ -699,7 +700,7 @@ private void addRole(String uuid, List roles) { String boxName = null; if (boxId != null) { // Boxの検索 - Map boxsrc = DavCmpEsImpl.searchBox(this, boxId); + Map boxsrc = DavCmpFsImpl.searchBox(this, boxId); Map boxs = (Map) boxsrc.get("s"); boxName = (String) boxs.get(KEY_NAME); } diff --git a/src/main/java/io/personium/core/model/impl/es/DavCmpEsImpl.java b/src/main/java/io/personium/core/model/impl/es/DavCmpEsImpl.java deleted file mode 100644 index 69457f625..000000000 --- a/src/main/java/io/personium/core/model/impl/es/DavCmpEsImpl.java +++ /dev/null @@ -1,1516 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.Reader; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.StreamingOutput; -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.apache.commons.codec.CharEncoding; -import org.apache.http.HttpStatus; -import org.apache.wink.webdav.model.Multistatus; -import org.apache.wink.webdav.model.ObjectFactory; -import org.apache.wink.webdav.model.Prop; -import org.apache.wink.webdav.model.Propertyupdate; -import org.apache.wink.webdav.model.Response; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.odata4j.producer.CountResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -import io.personium.common.auth.token.Role; -import io.personium.common.es.response.PersoniumActionResponse; -import io.personium.common.es.response.PersoniumBulkItemResponse; -import io.personium.common.es.response.PersoniumBulkResponse; -import io.personium.common.es.response.PersoniumGetResponse; -import io.personium.common.es.response.PersoniumIndexResponse; -import io.personium.common.es.response.PersoniumSearchHit; -import io.personium.common.es.response.PersoniumSearchHits; -import io.personium.common.es.response.PersoniumSearchResponse; -import io.personium.common.es.util.PersoniumUUID; -import io.personium.common.es.util.IndexNameEncoder; -import io.personium.common.utils.PersoniumCoreUtils; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.PersoniumCoreException; -import io.personium.core.PersoniumCoreLog; -import io.personium.core.auth.AccessContext; -import io.personium.core.auth.BoxPrivilege; -import io.personium.core.auth.OAuth2Helper.Key; -import io.personium.core.http.header.ByteRangeSpec; -import io.personium.core.http.header.RangeHeaderHandler; -import io.personium.core.model.Box; -import io.personium.core.model.Cell; -import io.personium.core.model.DavCmp; -import io.personium.core.model.DavDestination; -import io.personium.core.model.ModelFactory; -import io.personium.core.model.ctl.ComplexType; -import io.personium.core.model.ctl.EntityType; -import io.personium.core.model.file.BinaryDataAccessException; -import io.personium.core.model.file.BinaryDataAccessor; -import io.personium.core.model.file.BinaryDataNotFoundException; -import io.personium.core.model.file.StreamingOutputForDavFile; -import io.personium.core.model.file.StreamingOutputForDavFileWithRange; -import io.personium.core.model.impl.es.accessor.DavMoveAccessor; -import io.personium.core.model.impl.es.accessor.DavNodeAccessor; -import io.personium.core.model.impl.es.accessor.EntitySetAccessor; -import io.personium.core.model.impl.es.doc.EsDocHandler; -import io.personium.core.model.impl.es.odata.UserSchemaODataProducer; -import io.personium.core.model.jaxb.Acl; -import io.personium.core.model.jaxb.ObjectIo; -import io.personium.core.model.lock.Lock; -import io.personium.core.model.lock.LockKeyComposer; -import io.personium.core.model.lock.LockManager; -import io.personium.core.odata.PersoniumODataProducer; - -/** - * DavCmpのElastic Search実装. - */ -public class DavCmpEsImpl implements DavCmp, EsDocHandler { - String nodeId; - Box box; - Cell cell; - DavNode davNode; - Long version; - ObjectFactory of; - String name; - Acl acl; - DavCmpEsImpl parent; - String confidentialLevel; - List ownerRepresentativeAccounts = new ArrayList(); - - /** - * Esの検索結果出力上限. - */ - private static final int TOP_NUM = PersoniumUnitConfig.getEsTopNum(); - - /** - * ログ. - */ - static Logger log = LoggerFactory.getLogger(DavCmpEsImpl.class); - - DavCmpEsImpl() { - } - - /** - * Boxをロックする. - * @return 自ノードのロック - */ - public Lock lock() { - log.debug("lock:" + LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_DAV, null, this.box.getId(), null)); - return LockManager.getLock(Lock.CATEGORY_DAV, null, this.box.getId(), null); - } - - /** - * @return ETag文字列. - */ - @Override - public String getEtag() { - StringBuilder sb = new StringBuilder("\""); - sb.append(this.version); - sb.append("-"); - sb.append(this.davNode.getUpdated()); - sb.append("\""); - return sb.toString(); - } - - /** - * コンストラクタ. - * @param name 担当パスコンポーネント名 - * @param parent 親部品 - * @param cell Cell - * @param box Box - * @param nodeId ノードID - * @param davNode DavNode情報 - */ - public DavCmpEsImpl(final String name, - final DavCmpEsImpl parent, - final Cell cell, - final Box box, - final String nodeId, - final DavNode davNode) { - this.cell = cell; - this.box = box; - this.name = name; - this.parent = parent; - this.nodeId = nodeId; - this.of = new ObjectFactory(); - this.davNode = davNode; - setMetadata(davNode.getSource()); - } - - /** - * コンストラクタ. - * @param name 担当パスコンポーネント名 - * @param parent 親部品 - * @param cell Cell - * @param box Box - * @param nodeId ノードID - */ - public DavCmpEsImpl(final String name, - final DavCmpEsImpl parent, - final Cell cell, - final Box box, - final String nodeId) { - this.cell = cell; - this.box = box; - this.name = name; - this.parent = parent; - this.nodeId = nodeId; - this.of = new ObjectFactory(); - if (this.nodeId != null) { - this.load(); - } - } - - @Override - public boolean isEmpty() { - - String type = this.getType(); - if (DavCmp.TYPE_COL_WEBDAV.equals(type)) { - return !(this.getChildrenCount() > 0); - } else if (DavCmp.TYPE_COL_BOX.equals(type)) { - return !(this.getChildrenCount() > 0); - } else if (DavCmp.TYPE_COL_ODATA.equals(type)) { - // Collectionに紐づくEntityTypeの一覧を取得する - // EntityTypeに紐づくリソース(AsssociationEndなど)はEntityTypeが必ず親となる関係であるため - // EntityTypeのみ検索すれば、EntityTypeに紐づくリソースまでチェックする必要はない - UserSchemaODataProducer producer = new UserSchemaODataProducer(this.cell, this); - CountResponse cr = producer.getEntitiesCount(EntityType.EDM_TYPE_NAME, null); - if (cr.getCount() > 0) { - return false; - } - // Collectionに紐づくComplexTypeの一覧を取得する - // ComplexTypeに紐づくリソース(ComplexTypeProperty)はComplexTypeが必ず親となる関係であるため - // ComplexTypeのみ検索すれば、ComplexTypeに紐づくリソースまでチェックする必要はない - cr = producer.getEntitiesCount(ComplexType.EDM_TYPE_NAME, null); - return cr.getCount() < 1; - } else if (DavCmp.TYPE_COL_SVC.equals(type)) { - DavCmp svcSourceCol = this.getChild(SERVICE_SRC_COLLECTION); - if (!svcSourceCol.exists()) { - // クリティカルなタイミングでServiceコレクションが削除された場合 - // ServiceSourceコレクションが存在しないため空とみなす - return true; - } - return !(svcSourceCol.getChildrenCount() > 0); - } - PersoniumCoreLog.Misc.UNREACHABLE_CODE_ERROR.writeLog(); - throw PersoniumCoreException.Server.UNKNOWN_ERROR; - } - - @Override - public void makeEmpty() { - // TODO 実装 - } - - /** - * ACLのgetter. - * @return acl - */ - public Acl getAcl() { - return this.acl; - } - - /** - * スキーマ認証のレベルを返す. - * @return スキーマ認証レベル - */ - public String getConfidentialLevel() { - return this.confidentialLevel; - } - - /** - * ユニット昇格許可ユーザ設定を返す. - * @return ユニット昇格許可ユーザ設定 - */ - public List getOwnerRepresentativeAccounts() { - return this.ownerRepresentativeAccounts; - } - - /** - * Cellレベルかのチェックをする. - * @return Cellレベルの場合はtrueを返却 - */ - @Override - public boolean isCellLevel() { - if (this.box != null) { - return false; - } - return true; - } - - /** - * DavNodeがDB上に存在するかどうか.
- * 本メソッドを使用する際は、事前にload()を呼出し情報を最新にすること - * @return 存在する場合はtrue - */ - public final boolean exists() { - return !(this.davNode == null); - } - - /** - * Davの管理データ情報を最新化する. - */ - public final void load() { - PersoniumGetResponse res = getNode(); - if (res == null) { - this.davNode = null; - return; - } - this.version = res.version(); - this.davNode = DavNode.createFromJsonString(res.getId(), res.sourceAsString()); - if (this.davNode == null) { - return; - } - try { - String jsonStr = res.sourceAsString(); - JSONParser parser = new JSONParser(); - JSONObject source = (JSONObject) parser.parse(jsonStr); - setMetadata(source); - } catch (ParseException e) { - // ESのJSONが壊れている状態。 - throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(e); - } - } - - /** - * JSONオブジェクトを解析し、ACLなどのメタデータをセットする. - * @param source 解析対象のJSONオブジェクト - */ - @SuppressWarnings("unchecked") - private void setMetadata(JSONObject source) { - JSONObject aclObj = (JSONObject) source.get(DavNode.KEY_ACL); - if (aclObj != null) { - log.debug(aclObj.toJSONString()); - // principalのhref の値を ロールID(__id)からロールリソースURLに変換する。 - // base:xml値の設定 - String baseUrlStr = createBaseUrlStr(); - roleIdToName(aclObj.get(KEY_ACE), baseUrlStr); - - // ConfidentialLevelの取り出し - this.confidentialLevel = (String) aclObj.get(KEY_REQUIRE_SCHEMA_AUTHZ); - - this.acl = Acl.fromJson(aclObj.toJSONString()); - this.acl.setBase(baseUrlStr); - log.debug(this.acl.toJSON()); - } - - Map props = (Map) source.get(DavNode.KEY_PROPS); - if (props != null) { - for (Map.Entry entry : props.entrySet()) { - String key = entry.getKey(); - String val = entry.getValue(); - int idx = key.indexOf("@"); - String elementName = key.substring(0, idx); - String namespace = key.substring(idx + 1); - QName keyQName = new QName(namespace, elementName); - - Element element = parseProp(val); - String elementNameSpace = element.getNamespaceURI(); - // ownerRepresentativeAccountsの取り出し - if (Key.PROP_KEY_OWNER_REPRESENTIVE_ACCOUNTS.equals(keyQName)) { - NodeList accountNodeList = element.getElementsByTagNameNS(elementNameSpace, - Key.PROP_KEY_OWNER_REPRESENTIVE_ACCOUNT.getLocalPart()); - for (int i = 0; i < accountNodeList.getLength(); i++) { - this.ownerRepresentativeAccounts.add(accountNodeList.item(i).getTextContent().trim()); - } - } - } - } - } - - /** - * Davの管理データ情報を最新化する.
- * 管理データが存在しない場合はエラーとする. - */ - public final void loadAndCheckDavInconsistency() { - load(); - if (this.davNode == null) { - // Boxから辿ってidで検索して、Davデータに不整合があった場合 - throw PersoniumCoreException.Dav.DAV_INCONSISTENCY_FOUND; - } - } - - /** - * Nodeのデータを取得する. - * @return Node取得結果 - */ - public PersoniumGetResponse getNode() { - PersoniumGetResponse res = this.getEsColType().get(this.nodeId); - return res; - } - - private Element parseProp(String value) { - // valをDOMでElement化 - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - DocumentBuilder builder = null; - Document doc = null; - try { - builder = factory.newDocumentBuilder(); - ByteArrayInputStream is = new ByteArrayInputStream(value.getBytes(CharEncoding.UTF_8)); - doc = builder.parse(is); - } catch (Exception e1) { - throw PersoniumCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1); - } - Element e = doc.getDocumentElement(); - return e; - } - - /** - * バックエンド操作に用いるEsTypeオブジェクトを取得します. - * @return EsTypeオブジェクト - */ - public DavNodeAccessor getEsColType() { - return this.parent.getEsColType(); - } - - /** - * 子リソースの情報を取得する. - * @return 子リソースの検索結果 - */ - public PersoniumSearchResponse getChildResource() { - // 子リソースの情報を取得する。 - Map source = new HashMap(); - - // 暗黙フィルタを指定して、検索対象を検索条件の先頭に設定する(絞りこみ) - List> implicitFilters = - QueryMapFactory.getImplicitFilters( - this.cell.getId(), this.box.getId(), null, null, this.getEsColType().getType()); - implicitFilters.add(0, QueryMapFactory.termQuery(DavNode.KEY_PARENT, this.nodeId)); - Map query = QueryMapFactory.mustQuery(implicitFilters); - Map filteredQuery = QueryMapFactory.filteredQuery(null, query); - source.put("query", filteredQuery); - // 検索結果件数設定 - // Davの子要素には上限値があるため、設定ファイルから読み込んだ値を設定しておく - // TODO 上限値を元の値より小さい値に変更する場合、このクエリでは取得できない情報が出てしまうが、 - // 検索性能の問題もあるため、対応方針を決めて修正する必要がある - source.put("size", TOP_NUM); - - PersoniumSearchResponse resp = this.getEsColType().search(source); - return resp; - } - - /* - * proppatch メソッドへの対応. 保存の方式 key = namespaceUri + "@" + localName Value = inner XML String - */ - @Override - @SuppressWarnings("unchecked") - public Multistatus proppatch(final Propertyupdate propUpdate, final String url) { - long now = new Date().getTime(); - String reqUri = url; - Multistatus ms = this.of.createMultistatus(); - Response res = this.of.createResponse(); - res.getHref().add(reqUri); - - // ロック - Lock lock = this.lock(); - // 更新処理 - try { - this.load(); // ロック後の最新情報取得 - - if (!this.exists()) { - // クリティカルなタイミング(初回ロード~ロック取得)で削除された場合は404エラーとする - throw getNotFoundException().params(this.getUrl()); - } - - Map propsJson = (Map) this.davNode.getProperties(); - - List propsToSet = propUpdate.getPropsToSet(); - - for (Prop prop : propsToSet) { - if (null == prop) { - throw PersoniumCoreException.Dav.XML_CONTENT_ERROR; - } - List lpe = prop.getAny(); - for (Element elem : lpe) { - res.setProperty(elem, HttpStatus.SC_OK); - String key = elem.getLocalName() + "@" + elem.getNamespaceURI(); - String value = PersoniumCoreUtils.nodeToString(elem); - log.debug("key: " + key); - log.debug("val: " + value); - propsJson.put(key, value); - } - } - - List propsToRemove = propUpdate.getPropsToRemove(); - for (Prop prop : propsToRemove) { - if (null == prop) { - throw PersoniumCoreException.Dav.XML_CONTENT_ERROR; - } - List lpe = prop.getAny(); - for (Element elem : lpe) { - - String key = elem.getLocalName() + "@" + elem.getNamespaceURI(); - String v = (String) propsJson.get(key); - log.debug("Removing key: " + key); - if (v == null) { - res.setProperty(elem, HttpStatus.SC_NOT_FOUND); - } else { - propsJson.remove(key); - res.setProperty(elem, HttpStatus.SC_OK); - } - } - } - // 変更日付を更新。 - this.davNode.setUpdated(now); - // 変更後JSONを書き出し。 - setPropToJson(propsJson); - PersoniumIndexResponse resp = updateNodeWithVersion(); - // ETAG生成用にVersionを反映 - this.version = resp.version(); - } finally { - // ロック開放 - lock.release(); - } - ms.getResponse().add(res); - return ms; - } - - /** - * jsonにProp情報を設定する. - * @param propsJson Prop - */ - protected void setPropToJson(Map propsJson) { - } - - /** - * バージョン指定でNodeの情報を更新する. - * @return 更新結果. - */ - public PersoniumIndexResponse updateNodeWithVersion() { - PersoniumIndexResponse resp; - resp = this.getEsColType().update(this.nodeId, this.davNode, this.version); - return resp; - } - - /** - * バージョン指定でNodeファイルの情報を更新する. - * @return 更新結果. - */ - public PersoniumIndexResponse updateNodeWithVersionForFile() { - PersoniumIndexResponse resp; - resp = this.getEsColType().updateForFile(this.nodeId, this.davNode, this.version); - return resp; - } - - @Override - @SuppressWarnings("unchecked") - public final ResponseBuilder acl(final Reader reader) { - // リクエストが空でない場合、パースして適切な拡張を行う。 - Acl aclToSet = null; - try { - aclToSet = ObjectIo.unmarshal(reader, Acl.class); - } catch (Exception e1) { - throw PersoniumCoreException.Dav.XML_CONTENT_ERROR.reason(e1); - } - if (!aclToSet.validateAcl(isCellLevel())) { - throw PersoniumCoreException.Dav.XML_VALIDATE_ERROR; - } - JSONParser parser = new JSONParser(); - JSONObject aclJson = null; - try { - aclJson = (JSONObject) parser.parse(aclToSet.toJSON()); - } catch (ParseException e) { - throw PersoniumCoreException.Dav.XML_ERROR.reason(e); - } - // ロック - Lock lock = this.lock(); - try { - // リソースのリロード - this.load(); - if (!this.exists()) { - throw getNotFoundException().params(this.getUrl()); - } - - // ACLのxml:baseの値を取得する - Object objAclBase = aclJson.get(KEY_ACL_BASE); - String aclBase = null; - if (objAclBase != null) { - aclBase = (String) objAclBase; - } - - // principalのhref の値を ロール名(Name) を ロールID(__id) に変換する。 - Object jsonObj = aclJson.get(KEY_ACE); - JSONArray array = new JSONArray(); - if (jsonObj instanceof JSONObject) { - array.add(jsonObj); - } else { - array = (JSONArray) jsonObj; - } - if (array != null) { - for (Object ace : (JSONArray) array) { - JSONObject aceJson = (JSONObject) ace; - JSONObject principal = (JSONObject) aceJson.get(KEY_ACL_PRINCIPAL); - if (principal.get(KEY_ACL_HREF) != null) { - principal.put(KEY_ACL_HREF, roleResourceUrlToId((String) principal.get(KEY_ACL_HREF), aclBase)); - } else if (principal.get(KEY_ACL_ALL) != null) { - principal.put(KEY_ACL_ALL, null); - } - - } - } - // ESへxm:baseの値を登録しない - aclJson.remove(KEY_ACL_BASE); - setAclToJson(aclJson); - // このノードの更新を保存 - PersoniumIndexResponse resp = updateNode(); - this.version = resp.getVersion(); - this.acl = aclToSet; - // レスポンス - return javax.ws.rs.core.Response.status(HttpStatus.SC_OK).header(HttpHeaders.ETAG, this.getEtag()); - } finally { - lock.release(); - } - } - - /** - * jsonにACL情報を設定する. - * @param aclJson ACL - */ - protected void setAclToJson(JSONObject aclJson) { - this.davNode.setAcl(aclJson); - } - - /** - * Nodeの情報を更新する. - * @return 更新結果. - */ - public PersoniumIndexResponse updateNode() { - PersoniumIndexResponse resp; - resp = this.getEsColType().update(this.nodeId, this.davNode); - return resp; - } - - @Override - public final ResponseBuilder putForCreate(final String contentType, final InputStream inputStream) { - // ロック - Lock lock = this.lock(); - try { - // 新規作成時には、作成対象のDavNodeは存在しないため、親DavNodeをリロードして存在確認する。 - // 親DavNodeが存在しない場合:他のリクエストによって削除されたたため、404を返却 - // 親DavNodeが存在するが、作成対象のDavNodeが存在する場合:他のリクエストによって作成されたたtめ、更新処理を実行 - this.parent.load(); - if (!this.parent.exists()) { - throw PersoniumCoreException.Dav.HAS_NOT_PARENT.params(this.parent.getUrl()); - } - - this.nodeId = this.parent.davNode.getChildren().get(this.name); - if (this.nodeId != null) { - this.load(); - // 作成対象のDavNodeが存在する場合は更新処理 - if (this.davNode != null) { - return this.doPutForUpdate(contentType, inputStream, null); - } - } - // 作成対象のDavNodeが存在しない場合は新規作成処理 - return this.doPutForCreate(contentType, inputStream); - } finally { - // ★UNLOCK - lock.release(); - log.debug("unlock1"); - } - } - - /** - * Node情報を作成する. - * @return 作成結果 - */ - public PersoniumActionResponse createNode() { - PersoniumIndexResponse res = null; - String id = PersoniumUUID.randomUUID(); - res = this.getEsColType().create(id, this.davNode); - return res; - } - - /** - * IDを指定してNode情報を作成する. - * @param id ID - * @return 作成結果 - */ - public PersoniumActionResponse createNodeWithId(String id) { - PersoniumActionResponse res; - res = this.getEsColType().createForFile(id, this.davNode); - return res; - } - - @Override - public final ResponseBuilder putForUpdate(final String contentType, final InputStream inputStream, String etag) { - // ロック - Lock lock = this.lock(); - try { - // 更新には、更新対象のDavNodeが存在するため、更新対象のDavNodeをリロードして存在確認する。 - // 更新対象のDavNodeが存在しない場合: - // ・更新対象の親DavNodeが存在しない場合:親ごと消えているため404を返却 - // ・更新対象の親DavNodeが存在する場合:他のリクエストによって削除されたたため、作成処理を実行 - // 更新対象のDavNodeが存在する場合:更新処理を実行 - this.load(); - if (this.davNode == null) { - this.parent.load(); - if (this.parent.davNode == null) { - throw getNotFoundException().params(this.parent.getUrl()); - } - return this.doPutForCreate(contentType, inputStream); - } - return this.doPutForUpdate(contentType, inputStream, etag); - } finally { - // ロックを開放する - lock.release(); - log.debug("unlock2"); - } - } - - final ResponseBuilder doPutForCreate(final String contentType, final InputStream inputStream) { - long now = new Date().getTime(); - // creating node Document - DavNode fileNode = new DavNode(this.cell.getId(), this.box.getId(), DavCmp.TYPE_DAV_FILE); - fileNode.setParentId(this.parent.nodeId); - - // ファイルの情報 - Map data = new HashMap(); - fileNode.setFile(data); - data.put(KEY_CONTENT_TYPE, contentType); - - BufferedInputStream bufferedInput = new BufferedInputStream(inputStream); - - // 親コレクション内のコレクション・ファイル数のチェック - checkChildResourceCount(); - - String newId = PersoniumUUID.randomUUID(); - try { - BinaryDataAccessor accessor = getBinaryDataAccessor(); - long writtenBytes = accessor.create(bufferedInput, newId); - data.put(KEY_CONTENT_LENGTH, writtenBytes); - } catch (BinaryDataNotFoundException nex) { - throw PersoniumCoreException.Dav.RESOURCE_NOT_FOUND.reason(nex); - } catch (BinaryDataAccessException ex) { - throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(ex); - } - - // メタデータの保存処理. - this.davNode = fileNode; - PersoniumActionResponse res = createNodeWithId(newId); - if (res instanceof PersoniumIndexResponse) { - this.nodeId = ((PersoniumIndexResponse) res).getId(); - this.version = ((PersoniumIndexResponse) res).version(); - } else if (res instanceof PersoniumGetResponse) { - this.nodeId = ((PersoniumGetResponse) res).getId(); - this.version = ((PersoniumGetResponse) res).version(); - } - - // adding newNode to this nodeDocument; - this.parent.linkChild(this.name, this.nodeId, now); - return javax.ws.rs.core.Response.ok().status(HttpStatus.SC_CREATED).header(HttpHeaders.ETAG, this.getEtag()); - } - - final ResponseBuilder doPutForUpdate(final String contentType, final InputStream inputStream, String etag) { - // 現在時刻を取得 - long now = new Date().getTime(); - // 最新ノード情報をロード - // TODO 全体として2回ロードしてしまうので、遅延ロードの仕組みを検討 - this.load(); - // クリティカルなタイミング(ロック~ロードまでの間)でWebDavの管理データが削除された場合の対応 - // WebDavの管理データがこの時点で存在しない場合は404エラーとする - if (!this.exists()) { - throw getNotFoundException().params(this.getUrl()); - } - - // 指定etagがあり、かつそれが*ではなく内部データから導出されるものと異なるときはエラー - if (etag != null && !"*".equals(etag) && !this.getEtag().equals(etag)) { - throw PersoniumCoreException.Dav.ETAG_NOT_MATCH; - } - - // 内容の更新をする - this.davNode.setUpdated(now); - Map data = new HashMap(); - - data.put(KEY_CONTENT_TYPE, contentType); - - BufferedInputStream bufferedInput = new BufferedInputStream(inputStream); - - try { - BinaryDataAccessor accessor = getBinaryDataAccessor(); - long writtenBytes = accessor.update(bufferedInput, this.nodeId); - data.put(KEY_CONTENT_LENGTH, writtenBytes); - } catch (BinaryDataNotFoundException nex) { - throw PersoniumCoreException.Dav.RESOURCE_NOT_FOUND.reason(nex); - } catch (BinaryDataAccessException ex) { - throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(ex); - } - - this.davNode.setFile(data); - // 更新内容を書きだす - PersoniumIndexResponse res = updateNodeWithVersionForFile(); - this.version = res.getVersion(); - return javax.ws.rs.core.Response.ok().status(HttpStatus.SC_NO_CONTENT).header(HttpHeaders.ETAG, this.getEtag()); - - } - - @Override - public final ResponseBuilder get(final String rangeHeaderField) { - String contentType = this.getContentType(); - - BinaryDataAccessor accessor = getBinaryDataAccessor(); - ResponseBuilder res = null; - final long fileSize = accessor.getSize(this.nodeId); - - // Rangeヘッダ解析処理 - final RangeHeaderHandler range = RangeHeaderHandler.parse(rangeHeaderField, fileSize); - - try { - String fileFullPath = accessor.getFilePath(this.nodeId); - - // Rangeヘッダ指定の時とで処理の切り分け - if (!range.isValid()) { - // ファイル全体返却 - StreamingOutput sout = new StreamingOutputForDavFile(fileFullPath); - res = davFileResponse(sout, fileSize, contentType); - } else { - // Range対応部分レスポンス - - // Rangeヘッダの範囲チェック - if (!range.isSatisfiable()) { - PersoniumCoreLog.Dav.REQUESTED_RANGE_NOT_SATISFIABLE.params(range.getRangeHeaderField()).writeLog(); - throw PersoniumCoreException.Dav.REQUESTED_RANGE_NOT_SATISFIABLE; - } - - if (range.getByteRangeSpecCount() > 1) { - // MultiPartレスポンスには未対応 - throw PersoniumCoreException.Misc.NOT_IMPLEMENTED.params("Range-MultiPart"); - } else { - StreamingOutput sout = new StreamingOutputForDavFileWithRange(fileFullPath, fileSize, range); - res = davFileResponseForRange(sout, fileSize, contentType, range); - } - } - return res.header(HttpHeaders.ETAG, this.getEtag()) - .header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); - - } catch (BinaryDataNotFoundException nex) { - this.load(); - if (!this.exists()) { - throw getNotFoundException().params(this.getUrl()); - } - throw PersoniumCoreException.Dav.DAV_UNAVAILABLE.reason(nex); - } - } - - /** - * ファイルレスポンス処理. - * @param sout StreamingOuputオブジェクト - * @param fileSize ファイルサイズ - * @param contentType コンテントタイプ - * @return レスポンス - */ - public ResponseBuilder davFileResponse(final StreamingOutput sout, long fileSize, String contentType) { - return javax.ws.rs.core.Response.ok(sout).header(HttpHeaders.CONTENT_LENGTH, fileSize) - .header(HttpHeaders.CONTENT_TYPE, contentType); - } - - /** - * ファイルレスポンス処理. - * @param sout StreamingOuputオブジェクト - * @param fileSize ファイルサイズ - * @param contentType コンテントタイプ - * @param range RangeHeaderHandler - * @return レスポンス - */ - public ResponseBuilder davFileResponseForRange( - final StreamingOutput sout, - long fileSize, String contentType, final RangeHeaderHandler range) { - // MultiPartには対応しないため1個目のbyte-renge-setだけ処理する。 - int rangeIndex = 0; - List brss = range.getByteRangeSpecList(); - final ByteRangeSpec brs = brss.get(rangeIndex); - - // iPadのsafariにおいてChunkedのRangeレスポンスを処理できなかったので明にContent-Lengthを返却している。 - return javax.ws.rs.core.Response.status(HttpStatus.SC_PARTIAL_CONTENT).entity(sout) - .header(PersoniumCoreUtils.HttpHeaders.CONTENT_RANGE, brs.makeContentRangeHeaderField()) - .header(HttpHeaders.CONTENT_LENGTH, brs.getContentLength()) - .header(HttpHeaders.CONTENT_TYPE, contentType); - } - - @Override - public final String getName() { - return this.name; - } - - @Override - public final DavCmp getChild(final String childName) { - if (this.davNode == null || this.davNode.getChildren() == null) { - return new DavCmpEsImpl(childName, this, this.cell, this.box, null); - } - String childNodeId = this.davNode.getChildren().get(childName); - if (childNodeId == null) { - return new DavCmpEsImpl(childName, this, this.cell, this.box, null); - } - return new DavCmpEsImpl(childName, this, this.cell, this.box, childNodeId); - } - - @Override - public final String getType() { - if (this.davNode == null) { - return DavCmp.TYPE_NULL; - } - return (String) this.davNode.getNodeType(); - } - - @Override - public final ResponseBuilder mkcol(final String type) { - // 新しいノードを作成 - this.davNode = new DavNode(this.cell.getId(), this.box.getId(), type); - this.davNode.setParentId(this.parent.nodeId); - - // ロック - Lock lock = this.lock(); - try { - // ここで改めて存在確認が必要。 - // 親をロードしなおして、自身へのパスがないことの確認 - this.parent.load(); - if (!this.parent.exists()) { - // クリティカルなタイミングで先に親を削除されてしまい、 - // 親が存在しないので409エラーとする - throw PersoniumCoreException.Dav.HAS_NOT_PARENT.params(this.parent.getUrl()); - } - if (this.parent.davNode.getChildren().get(this.name) != null) { - // クリティカルなタイミングで先にコレクションを作られてしまい、 - // すでに存在するのでEXCEPTION - throw PersoniumCoreException.Dav.METHOD_NOT_ALLOWED; - } - - // コレクションの階層数のチェック - DavCmpEsImpl current = this; - int depth = 0; - int maxDepth = PersoniumUnitConfig.getMaxCollectionDepth(); - while (null != current.parent) { - current = current.parent; - depth++; - } - if (depth > maxDepth) { - // コレクション数の制限を超えたため、400エラーとする - throw PersoniumCoreException.Dav.COLLECTION_DEPTH_ERROR; - } - - // 親コレクション内のコレクション・ファイル数のチェック - checkChildResourceCount(); - - // 新しいノードを保存 - PersoniumActionResponse resp = createNode(); - if (resp instanceof PersoniumIndexResponse) { - this.nodeId = ((PersoniumIndexResponse) resp).getId(); - this.version = ((PersoniumIndexResponse) resp).version(); - } else if (resp instanceof PersoniumGetResponse) { - this.nodeId = ((PersoniumGetResponse) resp).getId(); - this.version = ((PersoniumGetResponse) resp).version(); - } - - // 親ノードにポインタを追加 - this.parent.linkChild(this.name, this.nodeId, this.davNode.getPublished()); - } finally { - // ★UNLOCK - lock.release(); - log.debug("unlock"); - } - - // レスポンス - return javax.ws.rs.core.Response.status(HttpStatus.SC_CREATED).header(HttpHeaders.ETAG, this.getEtag()); - } - - /** - * MOVE処理を行う. - * @param etag ETag値 - * @param overwrite 移動先のリソースを上書きするかどうか - * @param davDestination 移動先の階層情報 - * @return ResponseBuilder レスポンス - */ - @Override - public ResponseBuilder move(String etag, String overwrite, DavDestination davDestination) { - // ロック - Lock lock = this.lock(); - try { - // 移動元リソースの存在チェック - this.load(); - if (!this.exists()) { - // クリティカルなタイミング(初回ロード~ロック取得)で移動元を削除された場合。 - // 移動元が存在しないため404エラーとする - throw getNotFoundException().params(this.getUrl()); - } - // 指定etagがあり、かつそれが*ではなく内部データから導出されるものと異なるときはエラー - if (etag != null && !"*".equals(etag) && !this.getEtag().equals(etag)) { - throw PersoniumCoreException.Dav.ETAG_NOT_MATCH; - } - - // 移動元のDavNodeをリロードしたことにより親DavNodeが別のリソースに切り替わっている可能性があるため、リロードする。 - // この際、親DavNodeが削除されている可能性もあるため、存在チェックを実施する。 - this.parent.nodeId = this.davNode.getParentId(); - this.parent.load(); - if (this.parent.davNode == null) { - throw getNotFoundException().params(this.parent.getUrl()); - } - - // 移動先のロード - davDestination.loadDestinationHierarchy(); - // 移動先のバリデート - davDestination.validateDestinationResource(overwrite, this); - - // MOVEメソッドでは移動元と移動先のBoxが同じであるため、移動先のアクセスコンテキストを取得しても、 - // 移動元のアクセスコンテキストを取得しても同じObjectが取得できる - // このため、移動先のアクセスコンテキストを用いている - AccessContext ac = davDestination.getDestinationRsCmp().getAccessContext(); - // 移動先に対するアクセス制御 - // 以下の理由により、ロック後に移動先に対するアクセス制御を行うこととした。 - // 1.アクセス制御ではESへのアクセスは発生しないため、ロック中に実施してもロック期間の長さに与える影響は少ない。 - // 2.ロック前に移動先のアクセス制御を行う場合、移動先の情報を取得する必要があり、ESへのリクエストが発生するため。 - davDestination.getDestinationRsCmp().getParent().checkAccessContext(ac, BoxPrivilege.WRITE); - - DavNode srcParentNode = ((DavCmpEsImpl) this.getParent()).getDavNode(); - - DavNode dstParentNode = ((DavCmpEsImpl) davDestination.getDestinationCmp().getParent()).getDavNode(); - DavNode srcNode = this.getDavNode(); - DavMoveAccessor accessor = new DavMoveAccessor(this.getEsColType().getIndex(), this.getType(), - this.getCell().getId()); - accessor.setSourceParentNodeForRollback(srcParentNode); - - DavCmp dstCmp = davDestination.getDestinationCmp(); - DavNode dstNode = ((DavCmpEsImpl) dstCmp).getDavNode(); - - accessor.setMoveRequest(this.name, dstCmp.getName(), srcNode, dstNode, srcParentNode, dstParentNode); - PersoniumBulkResponse bulkResponse = accessor.move(); - - // バルクレスポンスの解析 - for (PersoniumBulkItemResponse item : bulkResponse.items()) { - if (srcNode.getId().equals(item.getId())) { - // Etag返却用に、ソースのノードを更新した時のElaticsearchのバージョンを付与しておく - this.version = item.version(); - } - } - } finally { - // ★UNLOCK - lock.release(); - log.debug("unlock"); - } - - ResponseBuilder res = null; - if (null == ((DavCmpEsImpl) davDestination.getDestinationCmp()).getDavNode()) { - res = javax.ws.rs.core.Response.status(HttpStatus.SC_CREATED); - } else { - res = javax.ws.rs.core.Response.status(HttpStatus.SC_NO_CONTENT); - } - res.header(HttpHeaders.LOCATION, davDestination.getDestinationUri()); - res.header(HttpHeaders.ETAG, this.getEtag()); - return res; - } - - private void checkChildResourceCount() { - // 親コレクション内のコレクション・ファイル数のチェック - int maxChildResource = PersoniumUnitConfig.getMaxChildResourceCount(); - if (this.parent.getChildrenCount() >= maxChildResource) { - // コレクション内に作成可能なコレクション・ファイル数の制限を超えたため、400エラーとする - throw PersoniumCoreException.Dav.COLLECTION_CHILDRESOURCE_ERROR; - } - } - - @Override - public final ResponseBuilder linkChild(final String childName, final String childNodeId, final Long asof) { - this.davNode.getChildren().put(childName, childNodeId); - this.davNode.setUpdated(asof); - // このノードの更新を保存 - updateNode(); - return null; - } - - @Override - public final ResponseBuilder unlinkChild(final String childName, final Long asof) { - this.davNode.getChildren().remove(childName); - this.davNode.setUpdated(asof); - - // このノードの更新を保存 - updateNode(); - return null; - } - - /** - * リソースを削除する. - * @param ifMatch ifMatchヘッダ - * @param recursive bool - * @return JaxRS応答オブジェクトビルダ - */ - @Override - public final ResponseBuilder delete(final String ifMatch, boolean recursive) { - // 指定etagがあり、かつそれが*ではなく内部データから導出されるものと異なるときはエラー - if (ifMatch != null && !"*".equals(ifMatch) && !this.getEtag().equals(ifMatch)) { - throw PersoniumCoreException.Dav.ETAG_NOT_MATCH; - } - long now = new Date().getTime(); - // ロック - Lock lock = this.lock(); - try { - // リロード - this.load(); - if (this.davNode == null) { - throw getNotFoundException().params(this.getUrl()); - } - // WebDAVコレクションであって子孫リソースがあったら、エラーとする - if (TYPE_COL_WEBDAV.equals(this.getType()) && this.davNode.getChildren().size() > 0) { - throw PersoniumCoreException.Dav.HAS_CHILDREN; - } - - if (this.parent != null) { - // ここで改めて存在確認が必要。 - // 親をロードしなおして、自身へのパスがないことの確認 - this.parent.load(); - if (!this.parent.exists() || this.parent.davNode.getChildren().get(this.name) == null) { - // クリティカルなタイミングで先に削除がかかってしまい、 - // すでに親または自身が存在しない場合はEXCEPTION - throw getNotFoundException().params(this.parent.getUrl()); - } - // Serviceコレクションのときは__srcの削除を行う - // → 取得した子供が DavCmp ではない場合はデータ不整合として500エラーを返す(ありえない) - if (TYPE_COL_SVC.equals(this.getType())) { - DavCmp srcCmp = this.getChild(DavCmp.SERVICE_SRC_COLLECTION); - if (srcCmp.exists() && srcCmp instanceof DavCmpEsImpl) { - ((DavCmpEsImpl) srcCmp).deleteNode(); - } else { - throw PersoniumCoreException.Dav.DAV_INCONSISTENCY_FOUND; - } - } - this.parent.unlinkChild(this.name, now); - } - deleteNode(); - } finally { - // ★LOCK - log.debug("unlcok"); - lock.release(); - } - return javax.ws.rs.core.Response.ok().status(HttpStatus.SC_NO_CONTENT); - } - - /** - * Nodeを削除する. - */ - public void deleteNode() { - deleteNode(this.nodeId); - } - - /** - * Nodeid指定でNodeを削除する. - * @param deleteNodeId 削除対象NodeId - */ - public void deleteNode(final String deleteNodeId) { - this.getEsColType().delete(this.davNode); - - BinaryDataAccessor accessor = getBinaryDataAccessor(); - try { - accessor.delete(deleteNodeId); - } catch (BinaryDataAccessException e) { - throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(e); - } - } - - /** - * バイナリデータのアクセサのインスタンスを生成して返す. - * @return アクセサのインスタンス - */ - protected BinaryDataAccessor getBinaryDataAccessor() { - String owner = cell.getOwner(); - String unitUserName = null; - if (owner == null) { - unitUserName = AccessContext.TYPE_ANONYMOUS; - } else { - unitUserName = IndexNameEncoder.encodeEsIndexName(owner); - } - - return new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), unitUserName, - PersoniumUnitConfig.getPhysicalDeleteMode(), PersoniumUnitConfig.getFsyncEnabled()); - } - - @Override - public final DavCmp getParent() { - return this.parent; - } - - - - /** - * nodeIdを取得する. - * @return nodeId - */ - public final String getNodeId() { - return this.nodeId; - } - - @Override - public final PersoniumODataProducer getODataProducer() { - return ModelFactory.ODataCtl.userData(this.cell, this); - } - - @Override - public final PersoniumODataProducer getSchemaODataProducer(Cell cellObject) { - return ModelFactory.ODataCtl.userSchema(cellObject, this); - } - - @Override - public final int getChildrenCount() { - return this.davNode.getChildren().keySet().size(); - } - @Override - public Map getChildren() { - Map ret = new HashMap<>(); - for (String childName : this.davNode.getChildren().keySet()) { - ret.put(childName, this.getChild(childName)); - } - return ret; - } - - private String roleResourceUrlToId(String roleUrl, String baseUrl) { - EntitySetAccessor roleType = EsModel.cellCtl(this.cell, Role.EDM_TYPE_NAME); - - // roleNameがURLの対応 - URL url = null; - try { - // xml:baseの対応 - if (baseUrl != null && !"".equals(baseUrl)) { - // URLの相対パス対応 - url = new URL(new URL(baseUrl), roleUrl); - } else { - url = new URL(roleUrl); - } - } catch (MalformedURLException e) { - throw PersoniumCoreException.Dav.ROLE_NOT_FOUND.reason(e); - } - - Role role = null; - try { - role = new Role(url); - } catch (MalformedURLException e) { - log.info("Role URL:" + url.toString()); - throw PersoniumCoreException.Dav.ROLE_NOT_FOUND; - } - - // ロールリソースのセルURL部分はACL設定対象のセルURLと異なるものを指定することは許さない - if (!(this.cell.getUrl().equals(role.getBaseUrl()))) { - PersoniumCoreLog.Dav.ROLE_NOT_FOUND.params("Cell different").writeLog(); - throw PersoniumCoreException.Dav.ROLE_NOT_FOUND; - } - // Roleの検索 - List> queries = new ArrayList>(); - queries.add(QueryMapFactory.termQuery("c", this.cell.getId())); - queries.add(QueryMapFactory.termQuery("s." + KEY_NAME + ".untouched", role.getName())); - - Map query = QueryMapFactory.filteredQuery(null, QueryMapFactory.mustQuery(queries)); - - List> filters = new ArrayList>(); - if (!(Box.DEFAULT_BOX_NAME.equals(role.getBoxName()))) { - // Roleがボックスと紐付く場合に、検索クエリを追加 - Box targetBox = this.cell.getBoxForName(role.getBoxName()); - if (targetBox == null) { - throw PersoniumCoreException.Dav.BOX_LINKED_BY_ROLE_NOT_FOUND.params(baseUrl); - } - String boxId = targetBox.getId(); - filters.add(QueryMapFactory.termQuery(KEY_LINK + "." + Box.EDM_TYPE_NAME, boxId)); - } else { - // Roleがボックスと紐付かない場合にもnull検索クエリを追加 - filters.add(QueryMapFactory.missingFilter(KEY_LINK + "." + Box.EDM_TYPE_NAME)); - } - - Map source = new HashMap(); - if (!filters.isEmpty()) { - source.put("filter", QueryMapFactory.andFilter(filters)); - } - source.put("query", query); - PersoniumSearchHits hits = roleType.search(source).getHits(); - - // 対象のRoleが存在しない場合はNull - if (hits == null || hits.getCount() == 0) { - PersoniumCoreLog.Dav.ROLE_NOT_FOUND.params("Not Hit").writeLog(); - throw PersoniumCoreException.Dav.ROLE_NOT_FOUND; - } - // 対象のRoleが複数件取得された場合は内部エラーとする - if (hits.getAllPages() > 1) { - PersoniumCoreLog.OData.FOUND_MULTIPLE_RECORDS.params(hits.getAllPages()).writeLog(); - throw PersoniumCoreException.OData.DETECTED_INTERNAL_DATA_CONFLICT; - } - - PersoniumSearchHit hit = hits.getHits()[0]; - return hit.getId(); - } - - /** - * ロールIDからロールリソースURLを取得. jsonObjのロールIDをロールリソースURLに置換する - * @param jsonObj ID置換後のJSON - * @param baseUrlStr xml:base値 - */ - @SuppressWarnings("unchecked") - private void roleIdToName(Object jsonObj, String baseUrlStr) { - - JSONArray array = new JSONArray(); - if (jsonObj instanceof JSONObject) { - array.add(jsonObj); - } else { - array = (JSONArray) jsonObj; - } - if (array != null) { - // xml:base対応 - for (int i = 0; i < array.size(); i++) { - JSONObject aceJson = (JSONObject) array.get(i); - JSONObject principal = (JSONObject) aceJson.get(KEY_ACL_PRINCIPAL); - if (principal.get(KEY_ACL_HREF) != null) { - // ロールIDに該当するロール名が無かった場合はロールが削除済みと判断し、無視する。 - String roloResourceUrl = roleIdToRoleResourceUrl((String) principal.get(KEY_ACL_HREF)); - if (roloResourceUrl == null) { - // ロールIDに該当するロール名が無かった場合はロールが削除済みと判断し、ACEタグごと削除する。 - array.remove(i); - --i; - // すべてのロールIDが削除済みの場合、空のACEタグに変更する - if (array.isEmpty() && jsonObj instanceof JSONObject) { - JSONObject objJson = (JSONObject) jsonObj; - objJson.clear(); - } - continue; - } - // base:xml値からロールリソースURLの編集 - roloResourceUrl = baseUrlToRoleResourceUrl(baseUrlStr, roloResourceUrl); - principal.put(KEY_ACL_HREF, roloResourceUrl); - } else if (principal.get(KEY_ACL_ALL) != null) { - principal.put(KEY_ACL_ALL, null); - } - } - } - } - - /** - * ロールIDからロール名を取得. - * @param roleId ロールID - * @return ロール名 - */ - @SuppressWarnings("unchecked") - private String roleIdToRoleResourceUrl(String roleId) { - String boxName = null; - String schema = null; - - EntitySetAccessor roleType = EsModel.cellCtl(this.cell, Role.EDM_TYPE_NAME); - PersoniumGetResponse hit = roleType.get(roleId); - - if (hit == null || !hit.isExists()) { - // ロールが存在しない場合、nullを返す。 - return null; - } - Map role = hit.getSource(); - Map s = (Map) role.get(DavNode.KEY_PARENT); - Map l = (Map) role.get(KEY_LINK); - String roleName = (String) s.get(KEY_NAME); - String boxId = (String) l.get(Box.EDM_TYPE_NAME); - if (boxId != null) { - // Boxの検索 - Map boxsrc = searchBox(this.cell, boxId); - Map boxs = (Map) boxsrc.get("s"); - boxName = (String) boxs.get(KEY_NAME); - schema = (String) boxs.get(KEY_SCHEMA); - } - Role roleObj = new Role(roleName, boxName, schema, this.cell.getUrl()); - return roleObj.createUrl(); - } - - /** - * PROPFINDのACL内のxml:base値を生成します. - * @return - */ - private String createBaseUrlStr() { - String result = null; - if (this.box != null) { - // Boxレベル以下のACLの場合、BoxリソースのURL - // セルURLは連結でスラッシュつけてるので、URLの最後がスラッシュだったら消す。 - result = String.format(Role.ROLE_RESOURCE_FORMAT, this.cell.getUrl().replaceFirst("/$", ""), - this.box.getName(), ""); - } else { - // Cellレベル以下のACLの場合、デフォルトBoxのリソースURL - // セルURLは連結でスラッシュつけてるので、URLの最後がスラッシュだったら消す。 - result = String.format(Role.ROLE_RESOURCE_FORMAT, this.cell.getUrl().replaceFirst("/$", ""), - Box.DEFAULT_BOX_NAME, ""); - } - return result; - } - - /** - * xml:baseに従ってRoleResorceUrlの整形. - * @param baseUrlStr xml:baseの値 - * @param roloResourceUrl ロールリソースURL - * @return - */ - private String baseUrlToRoleResourceUrl(String baseUrlStr, String roloResourceUrlStr) { - String result = null; - Role baseUrl = null; - Role roloResourceUrl = null; - try { - // base:xmlはロールリソースURLではないため、ダミーで「__」を追加 - baseUrl = new Role(new URL(baseUrlStr + "__")); - roloResourceUrl = new Role(new URL(roloResourceUrlStr)); - } catch (MalformedURLException e) { - throw PersoniumCoreException.Dav.ROLE_NOT_FOUND.reason(e); - } - if (baseUrl.getBoxName().equals(roloResourceUrl.getBoxName())) { - // base:xmlのBOXとロールリソースURLのBOXが同じ場合 - result = roloResourceUrl.getName(); - } else { - // base:xmlのBOXとロールリソースURLのBOXが異なる場合 - result = String.format(ACL_RELATIVE_PATH_FORMAT, roloResourceUrl.getBoxName(), roloResourceUrl.getName()); - } - return result; - } - - static final String KEY_LINK = "l"; - static final String KEY_CONTENT_TYPE = "ct"; - static final String KEY_CONTENT_LENGTH = "length"; - static final String KEY_BASE64 = "b64"; - static final String KEY_NAME = "Name"; - static final String KEY_SCHEMA = "Schema"; - static final String KEY_ACL_PRINCIPAL = "D.principal"; - static final String KEY_ACE = "D.ace"; - static final String KEY_ACL_HREF = "D.href"; - static final String KEY_ACL_ALL = "D.all"; - static final String KEY_ACL_BASE = "@base"; - static final String KEY_REQUIRE_SCHEMA_AUTHZ = "@requireSchemaAuthz"; - static final String ACL_RELATIVE_PATH_FORMAT = "../%s/%s"; - - @Override - public String getId() { - return this.nodeId; - } - - /** - * IDのセッター. - * @param paramNodeId ノードID - */ - public void setId(String paramNodeId) { - this.nodeId = paramNodeId; - } - - /** - * DavNodeのゲッター. - * @return DavNode - */ - public DavNode getDavNode() { - return this.davNode; - } - - @Override - public Long getVersion() { - return this.version; - } - - @SuppressWarnings("unchecked") - @Override - public Map getSource() { - return this.davNode.getSource(); - } - - /** - * このDavNodeリソースのURLを返します. - * @return URL文字列 - */ - public String getUrl() { - // 再帰的に最上位のDavCmpEsImplまでいって、BoxCmpEsImplではここをオーバーライドしてルートURLを与えている。 - return this.parent.getUrl() + "/" + this.name; - } - - /** - * BoxIdでEsを検索する. - * @param cellObj Cell - * @param boxId ボックスId - * @return 検索結果 - */ - public static Map searchBox(final Cell cellObj, final String boxId) { - - EntitySetAccessor boxType = EsModel.box(cellObj); - PersoniumGetResponse getRes = boxType.get(boxId); - if (getRes == null || !getRes.isExists()) { - PersoniumCoreLog.Dav.ROLE_NOT_FOUND.params("Box Id Not Hit").writeLog(); - - throw PersoniumCoreException.Dav.ROLE_NOT_FOUND; - } - return getRes.getSource(); - } - - /** - * リソースに合わせてNotFoundの例外を返却する.
- * リソースによってメッセージがことなるため、各リソースのクラスはこのメソッドをオーバーライドしてメッセージを定義すること。
- * メッセージの付加情報は、ここでは設定せずに呼び出し元で設定すること。 - * @return NotFound例外 - */ - public PersoniumCoreException getNotFoundException() { - return PersoniumCoreException.Dav.RESOURCE_NOT_FOUND; - } - @Override - public Cell getCell() { - return this.cell; - } - - @Override - public Box getBox() { - return this.box; - } - - @Override - public Long getUpdated() { - return (Long) this.getSource().get(DavNode.KEY_UPDATED); - } - - @Override - public Long getPublished() { - return (Long) this.getSource().get(DavNode.KEY_PUBLISHED); - } - - @Override - public Long getContentLength() { - @SuppressWarnings("unchecked") - Map data = (Map) this.getSource().get(DavNode.KEY_FILE); - return (Long) data.get(KEY_CONTENT_LENGTH); - } - - @Override - public String getContentType() { - @SuppressWarnings("unchecked") - Map data = (Map) this.getSource().get(DavNode.KEY_FILE); - return (String) data.get(KEY_CONTENT_TYPE); - } - - @Override - @SuppressWarnings("unchecked") - public Map getProperties() { - return this.davNode.getProperties(); - } - -} diff --git a/src/main/java/io/personium/core/model/impl/es/EsModel.java b/src/main/java/io/personium/core/model/impl/es/EsModel.java index 827758e4b..25414fab4 100644 --- a/src/main/java/io/personium/core/model/impl/es/EsModel.java +++ b/src/main/java/io/personium/core/model/impl/es/EsModel.java @@ -23,13 +23,12 @@ import io.personium.common.es.EsIndex; import io.personium.common.es.EsRequestLogInfo; import io.personium.common.es.EsType; -import io.personium.core.PersoniumUnitConfig; import io.personium.core.PersoniumCoreLog; +import io.personium.core.PersoniumUnitConfig; import io.personium.core.model.Box; import io.personium.core.model.Cell; import io.personium.core.model.impl.es.accessor.CellAccessor; import io.personium.core.model.impl.es.accessor.DataSourceAccessor; -import io.personium.core.model.impl.es.accessor.DavNodeAccessor; import io.personium.core.model.impl.es.accessor.EntitySetAccessor; import io.personium.core.model.impl.es.accessor.ODataEntityAccessor; import io.personium.core.model.impl.es.accessor.ODataLinkAccessor; @@ -221,15 +220,6 @@ public static ODataLinkAccessor cellCtlLink(final Cell cell) { */ public static final String TYPE_CTL_LINK = "link"; - /** - * 指定Cell, BoxのDavノード情報Typeの操作オブジェクトを返します. - * @param cell Cell - * @return Typeオブジェクト - */ - public static DavNodeAccessor col(final Cell cell) { - return new DavNodeAccessor(idxUser(cell.getOwner()), "dav", cell.getId()); - } - /** * Cell用のBulkDataAccessorを返します. * @return Typeオブジェクト diff --git a/src/main/java/io/personium/core/model/impl/es/accessor/AbstractEntitySetAccessor.java b/src/main/java/io/personium/core/model/impl/es/accessor/AbstractEntitySetAccessor.java index ec36b6502..075a35d92 100644 --- a/src/main/java/io/personium/core/model/impl/es/accessor/AbstractEntitySetAccessor.java +++ b/src/main/java/io/personium/core/model/impl/es/accessor/AbstractEntitySetAccessor.java @@ -42,26 +42,6 @@ protected AbstractEntitySetAccessor(EsIndex index, String name, String routingId super(index, name, routingId); } - /** - * マスターデータを登録する. - * @param docHandler 登録データ - */ - protected abstract void createAds(EntitySetDocHandler docHandler); - - /** - * マスターデータを更新する. - * @param docHandler 登録データ - * @param version Elasticsearchに登録されたドキュメントのバージョン - */ - protected abstract void updateAds(EntitySetDocHandler docHandler, long version); - - /** - * マスタデータを削除する. - * @param docHandler 削除データ - * @param version 削除したデータのバージョン - */ - protected abstract void deleteAds(EntitySetDocHandler docHandler, long version); - /** * UUIDでODataEntityのデータ登録を行う. * @param docHandler 登録データ @@ -80,11 +60,8 @@ public PersoniumIndexResponse create(final EntitySetDocHandler docHandler) { * @return 登録結果 */ public PersoniumIndexResponse create(String id, EntitySetDocHandler docHandler) { - // マスタ書き込みでエラーが発生したためES更新を不可能とする - prepareDataUpdate(getIndex().getName()); docHandler.setId(id); PersoniumIndexResponse response = create(id, docHandler.getSource(), docHandler); - createAds(docHandler); return response; } @@ -107,10 +84,7 @@ public PersoniumIndexResponse update(String id, EntitySetDocHandler docHandler) * @return 更新結果 */ public PersoniumIndexResponse update(String id, EntitySetDocHandler docHandler, long version) { - // マスタ書き込みでエラーが発生したためES更新を不可能とする - prepareDataUpdate(getIndex().getName()); PersoniumIndexResponse response = update(id, docHandler.getSource(), version); - updateAds(docHandler, response.getVersion()); return response; } @@ -134,10 +108,7 @@ public PersoniumDeleteResponse delete(final EntitySetDocHandler docHandler) { public PersoniumDeleteResponse delete(EntitySetDocHandler docHandler, long version) { String id = docHandler.getId(); - // マスタ書き込みでエラーが発生したためES更新を不可能とする - super.prepareDataUpdate(getIndex().getName()); PersoniumDeleteResponse response = super.delete(id, version); - deleteAds(docHandler, response.getVersion()); return response; } } diff --git a/src/main/java/io/personium/core/model/impl/es/accessor/CellAccessor.java b/src/main/java/io/personium/core/model/impl/es/accessor/CellAccessor.java index ed7457711..43bb42bd4 100644 --- a/src/main/java/io/personium/core/model/impl/es/accessor/CellAccessor.java +++ b/src/main/java/io/personium/core/model/impl/es/accessor/CellAccessor.java @@ -16,27 +16,20 @@ */ package io.personium.core.model.impl.es.accessor; -import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import io.personium.common.ads.AdsWriteFailureLogInfo; import io.personium.common.es.EsIndex; import io.personium.common.es.query.PersoniumQueryBuilder; import io.personium.common.es.query.PersoniumQueryBuilders; import io.personium.common.es.response.EsClientException; import io.personium.common.es.response.PersoniumSearchHit; import io.personium.common.es.response.PersoniumSearchResponse; -import io.personium.core.PersoniumCoreLog; import io.personium.core.model.DavCmp; import io.personium.core.model.impl.es.EsModel; import io.personium.core.model.impl.es.QueryMapFactory; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.doc.EntitySetDocHandler; -import io.personium.core.model.lock.Lock; -import io.personium.core.model.lock.LockKeyComposer; /** * Cellのアクセス処理を実装したクラス. @@ -122,9 +115,6 @@ private Map getDavFileFilterQuery(String cellId) { * @param unitUserName ユニットユーザ名 */ public void cellBulkDeletion(String cellId, String unitUserName) { - // AdsのCell配下のエンティティはバッチにて削除するので - // Cell削除管理テーブルに削除対象のDB名とセルIDを追加する - insertCellDeleteRecord(unitUserName, cellId); DataSourceAccessor accessor = EsModel.dsa(unitUserName); // セルIDを指定してelasticsearchからセル関連エンティティを一括削除する @@ -138,117 +128,5 @@ public void cellBulkDeletion(String cellId, String unitUserName) { cellId, unitUserName), e); } } - private void insertCellDeleteRecord(String unitUserName, String cellId) { - CellDeleteAccessor accessor = new CellDeleteAccessor(); - if (!accessor.isValid()) { - log.warn(String.format("Insert CELL_DELETE Record To Ads Failed. db_name:[%s], cell_id:[%s]", - unitUserName, cellId)); - return; - } - accessor.createManagementDatabase(); - accessor.insertCellDeleteRecord(unitUserName, cellId); - } - - /** - * マスターデータを登録する. - * @param docHandler 登録データ - */ - @Override - protected void createAds(EntitySetDocHandler docHandler) { - // 登録に成功した場合、マスタデータを書き込む - if (getAds() != null) { - String unitUserName = docHandler.getUnitUserName(); - try { - getAds().createCell(unitUserName, docHandler); - } catch (AdsException e) { - // Indexが存在しない場合はインデックスを作成する。 - if (e.getCause() instanceof SQLException - && MYSQL_BAD_TABLE_ERROR.equals(((SQLException) e.getCause()).getSQLState())) { - PersoniumCoreLog.Server.ES_INDEX_NOT_EXIST.params(unitUserName).writeLog(); - createAdsIndex(unitUserName); - try { - getAds().createCell(unitUserName, docHandler); - } catch (AdsException e1) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_CREATE_FAIL.params( - e1.getMessage()).reason(e1).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, null); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - docHandler.getUnitUserName(), docHandler.getType(), lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.CREATE, 1, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } else { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_CREATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, null); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - docHandler.getUnitUserName(), docHandler.getType(), lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.CREATE, 1, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } - } - - /** - * マスターデータを更新する. - * @param docHandler 登録データ - * @param version Elasticsearchに登録されたドキュメントのバージョン - */ - @Override - protected void updateAds(EntitySetDocHandler docHandler, long version) { - // 更新に成功した場合、マスタデータを更新する - if (getAds() != null) { - try { - getAds().updateCell(docHandler.getUnitUserName(), docHandler); - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_UPDATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, null); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - docHandler.getUnitUserName(), docHandler.getType(), lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.UPDATE, version, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } - /** - * マスタデータを削除する. - * @param docHandler 削除データ - * @param version 削除したデータのバージョン - */ - @Override - protected void deleteAds(EntitySetDocHandler docHandler, long version) { - String id = docHandler.getId(); - String unitUserName = docHandler.getUnitUserName(); - - // 削除に成功した場合、マスタデータを削除する - if (getAds() != null) { - try { - getAds().deleteCell(unitUserName, id); - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_DELETE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, null); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - docHandler.getUnitUserName(), docHandler.getType(), lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.DELETE, version, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } } diff --git a/src/main/java/io/personium/core/model/impl/es/accessor/CellDeleteAccessor.java b/src/main/java/io/personium/core/model/impl/es/accessor/CellDeleteAccessor.java deleted file mode 100644 index b6a863098..000000000 --- a/src/main/java/io/personium/core/model/impl/es/accessor/CellDeleteAccessor.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.accessor; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.ads.AdsWriteFailureLogException; -import io.personium.common.ads.AdsWriteFailureLogInfo; -import io.personium.common.ads.AdsWriteFailureLogWriter; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.PersoniumCoreException; -import io.personium.core.PersoniumCoreLog; -import io.personium.core.model.impl.es.ads.Ads; -import io.personium.core.model.impl.es.ads.AdsConnectionException; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.ads.JdbcAds; - -/** - * Cell削除管理テーブルのアクセス処理を実装したクラス. - */ -public class CellDeleteAccessor { - - static Logger log = LoggerFactory.getLogger(CellDeleteAccessor.class); - - Ads ads; - - /** - * コンストラクタ. - */ - public CellDeleteAccessor() { - try { - if (PersoniumUnitConfig.getEsAdsType().equals(PersoniumUnitConfig.ES.ADS.TYPE_JDBC)) { - ads = new JdbcAds(); - } else { - ads = null; - } - } catch (AdsConnectionException e) { - // 接続エラー時は接続エラーのログを出力する. - PersoniumCoreLog.Server.ADS_CONNECTION_ERROR.params(e.getMessage()).reason(e).writeLog(); - throw PersoniumCoreException.Server.ADS_CONNECTION_ERROR; - } - } - - /** - * 使用可能な状態かを確認する. - * @return true:使用可能 false:使用不可 - */ - public boolean isValid() { - return ads != null; - } - - /** - * 管理用DBの作成する. - */ - public void createManagementDatabase() { - if (!isValid()) { - return; - } - try { - ads.createManagementDatabase(); - } catch (AdsException e) { - // 管理用DBの作成に失敗した場合はログを出力して処理を続行する - log.warn("Create pcs_management Database to Ads Failed.", e); - } - } - - /** - * 削除対象のDB名とセルIDを追加する. - * @param dbName DB名 - * @param cellId セルID - */ - public void insertCellDeleteRecord(String dbName, String cellId) { - if (!isValid()) { - return; - } - try { - ads.insertCellDeleteRecord(dbName, cellId); - log.info("Ads Deletion Success."); - } catch (AdsException e) { - // 削除対象のDB名とセルIDの追加に失敗した場合はログを出力して処理を続行する - log.info(String.format("Insert CELL_DELETE Record To Ads Failed. db_name:[%s], cell_id:[%s]", - dbName, cellId), e); - - // Adsの登録に失敗した場合は、専用のログに書込む - // Cell再帰削除のときは、DB名、Cell IDのみログに書込む - // ※Cell再帰削除時にAdsに登録する情報としては、他にTable名があるが、ここでは意識しない - AdsWriteFailureLogWriter adsWriteFailureLogWriter = AdsWriteFailureLogWriter.getInstance( - PersoniumUnitConfig.getAdsWriteFailureLogDir(), - PersoniumUnitConfig.getCoreVersion(), - PersoniumUnitConfig.getAdsWriteFailureLogPhysicalDelete()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - dbName, null, null, null, cellId, - AdsWriteFailureLogInfo.OperationKind.PCS_MANAGEMENT_INSERT, 0, 0); - try { - adsWriteFailureLogWriter.writeActiveFile(loginfo); - } catch (AdsWriteFailureLogException e2) { - PersoniumCoreLog.Server.WRITE_ADS_FAILURE_LOG_ERROR.reason(e2).writeLog(); - PersoniumCoreLog.Server.WRITE_ADS_FAILURE_LOG_INFO.params(loginfo.toString()); - } - - } - } - -} diff --git a/src/main/java/io/personium/core/model/impl/es/accessor/DataSourceAccessor.java b/src/main/java/io/personium/core/model/impl/es/accessor/DataSourceAccessor.java index f761fcdcc..a007bbf03 100644 --- a/src/main/java/io/personium/core/model/impl/es/accessor/DataSourceAccessor.java +++ b/src/main/java/io/personium/core/model/impl/es/accessor/DataSourceAccessor.java @@ -23,34 +23,25 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.personium.common.ads.AdsWriteFailureLogException; -import io.personium.common.ads.AdsWriteFailureLogInfo; -import io.personium.common.ads.AdsWriteFailureLogWriter; import io.personium.common.es.EsBulkRequest; import io.personium.common.es.EsIndex; import io.personium.common.es.EsType; import io.personium.common.es.query.PersoniumQueryBuilder; +import io.personium.common.es.response.EsClientException; import io.personium.common.es.response.PersoniumActionResponse; -import io.personium.common.es.response.PersoniumBulkItemResponse; import io.personium.common.es.response.PersoniumBulkResponse; import io.personium.common.es.response.PersoniumDeleteResponse; import io.personium.common.es.response.PersoniumGetResponse; import io.personium.common.es.response.PersoniumIndexResponse; import io.personium.common.es.response.PersoniumMultiSearchResponse; import io.personium.common.es.response.PersoniumSearchResponse; -import io.personium.common.es.response.EsClientException; import io.personium.common.es.util.PersoniumUUID; -import io.personium.core.PersoniumUnitConfig; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; +import io.personium.core.PersoniumUnitConfig; import io.personium.core.model.impl.es.EsModel; -import io.personium.core.model.impl.es.ads.AdsConnectionException; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.ads.JdbcAds; import io.personium.core.model.impl.es.doc.EntitySetDocHandler; import io.personium.core.model.impl.es.doc.LinkDocHandler; -import io.personium.core.model.lock.Lock; -import io.personium.core.model.lock.LockKeyComposer; /** * データストア層の基本処理を実装した基底クラス. @@ -58,7 +49,6 @@ public class DataSourceAccessor { private EsIndex index; private EsType type; - private JdbcAds ads; private String routingid; /** ログ用オブジェクト. */ @@ -70,17 +60,6 @@ public class DataSourceAccessor { */ public DataSourceAccessor(EsIndex index) { this.index = index; - try { - if (PersoniumUnitConfig.getEsAdsType().equals(PersoniumUnitConfig.ES.ADS.TYPE_JDBC)) { - ads = new JdbcAds(); - } else { - ads = null; - } - } catch (AdsConnectionException ex) { - // 初回接続エラー時は接続エラーのログを出力する. - PersoniumCoreLog.Server.ADS_CONNECTION_ERROR.params(ex.getMessage()).reason(ex).writeLog(); - throw PersoniumCoreException.Server.ADS_CONNECTION_ERROR; - } } /** @@ -95,33 +74,6 @@ protected DataSourceAccessor(EsIndex index, String name, String routingId) { int interval = Integer.valueOf(PersoniumUnitConfig.getESRetryInterval()); this.type = EsModel.type(index.getName(), name, routingId, times, interval); this.routingid = routingId; - try { - if (PersoniumUnitConfig.getEsAdsType().equals(PersoniumUnitConfig.ES.ADS.TYPE_JDBC)) { - ads = new JdbcAds(); - } else { - ads = null; - } - } catch (AdsConnectionException ex) { - // 初回接続エラー時は接続エラーのログを出力する. - PersoniumCoreLog.Server.ADS_CONNECTION_ERROR.params(ex.getMessage()).reason(ex).writeLog(); - throw PersoniumCoreException.Server.ADS_CONNECTION_ERROR; - } - } - - /** - * Adsのゲッター. - * @return JdbcAds - */ - protected JdbcAds getAds() { - return this.ads; - } - - /** - * Adsのセッター. - * @param ads JdbcAds - */ - protected void setAds(JdbcAds ads) { - this.ads = ads; } /** @@ -200,7 +152,6 @@ public PersoniumIndexResponse create(final String id, final Map data) { PersoniumCoreLog.Server.ES_INDEX_NOT_EXIST.params(this.index.getName()).writeLog(); try { this.index.create(); - createAdsIndex(null); return this.type.create(id, data); } catch (EsClientException.EsNoResponseException esRetry) { throw PersoniumCoreException.Server.ES_RETRY_OVER.params(esRetry.getMessage()); @@ -227,7 +178,6 @@ public PersoniumIndexResponse create(final String id, final Map data, final Enti PersoniumCoreLog.Server.ES_INDEX_NOT_EXIST.params(this.index.getName()).writeLog(); try { this.index.create(); - createAdsIndex(docHandler.getUnitUserName()); return this.type.create(id, data); } catch (EsClientException.EsNoResponseException esRetry) { throw PersoniumCoreException.Server.ES_RETRY_OVER.params(esRetry.getMessage()); @@ -254,7 +204,6 @@ public PersoniumIndexResponse update(final String id, final Map data, final long PersoniumCoreLog.Server.ES_INDEX_NOT_EXIST.params(this.index.getName()).writeLog(); try { this.index.create(); - createAdsIndex(null); return this.type.update(id, data, version); } catch (EsClientException.EsNoResponseException esRetry) { throw PersoniumCoreException.Server.ES_RETRY_OVER.params(esRetry.getMessage()); @@ -385,8 +334,6 @@ public PersoniumDeleteResponse delete(final String docId, final long version) { public PersoniumBulkResponse bulkCreate(List esBulkRequest, List adsBulkRequest, String routingId) { - // マスタ書き込みでエラーが発生したためES更新を不可能とする - prepareDataUpdate(this.index.getName()); PersoniumBulkResponse response = null; try { @@ -394,24 +341,6 @@ public PersoniumBulkResponse bulkCreate(List esBulkRequest, } catch (EsClientException.EsNoResponseException e) { throw PersoniumCoreException.Server.ES_RETRY_OVER.params(e.getMessage()); } - if (this.ads != null) { - try { - this.ads.bulkEntity(this.index.getName(), adsBulkRequest); - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_BULK_CREATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - for (EntitySetDocHandler docHandler : adsBulkRequest) { - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, docHandler.getNodeId()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), docHandler.getType(), lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.CREATE, 1, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } return response; } @@ -428,8 +357,6 @@ public PersoniumBulkResponse bulkUpdateLink(List esBulkRequest, List adsBulkEntityRequest, List adsBulkLinkRequest, String routingId) { - // マスタ書き込みでエラーが発生したためES更新を不可能とする - prepareDataUpdate(this.index.getName()); PersoniumBulkResponse response = null; try { @@ -437,57 +364,6 @@ public PersoniumBulkResponse bulkUpdateLink(List esBulkRequest, } catch (EsClientException.EsNoResponseException e) { throw PersoniumCoreException.Server.ES_RETRY_OVER.params(e.getMessage()); } - if (this.ads != null) { - try { - // Entityテーブル更新 - if (adsBulkEntityRequest.size() > 0) { - this.ads.bulkUpdateEntity(this.index.getName(), adsBulkEntityRequest); - } - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_BULK_CREATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - // ESでのバージョン情報を取得するためにesBulkRequestをループさせている - PersoniumBulkItemResponse[] responseItems = response.items(); - int responseIndex = 0; - int adsBulkEntityRequestIndex = 0; - for (EsBulkRequest request : esBulkRequest) { - if (request.getType().equals(EsModel.TYPE_CTL_LINK)) { - responseIndex++; - continue; - } - PersoniumBulkItemResponse itemResponse = responseItems[responseIndex++]; - EntitySetDocHandler docHandler = adsBulkEntityRequest.get(adsBulkEntityRequestIndex++); - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, docHandler.getNodeId()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), docHandler.getType(), lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.UPDATE, itemResponse.version(), - docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - try { - // Linkテーブル追加 - if (adsBulkLinkRequest.size() > 0) { - this.ads.bulkCreateLink(this.index.getName(), adsBulkLinkRequest); - } - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_BULK_CREATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - for (LinkDocHandler docHandler : adsBulkLinkRequest) { - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, docHandler.getNodeId()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), EsModel.TYPE_CTL_LINK, lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.CREATE, 1, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } return response; } @@ -500,18 +376,6 @@ protected void deleteByQuery(String routingId, PersoniumQueryBuilder deleteQuery this.index.deleteByQuery(routingId, deleteQuery); } - /** - * 指定されたIDのセルのリソースを削除する. - * @param cellId 削除対象のセルID - * @param unitUserName ユニットユーザ名 - * @throws AdsException 削除に失敗 - */ - protected void cellBulkDeletionAds(String cellId, String unitUserName) throws AdsException { - this.ads.deleteCellResourceFromEntity(unitUserName, cellId); - this.ads.deleteCellResourceFromDavNode(unitUserName, cellId); - this.ads.deleteCellResourceFromLink(unitUserName, cellId); - } - /** * インデックスに対して検索リクエストを実行する. * @param routingId routingId @@ -550,64 +414,4 @@ public PersoniumMultiSearchResponse multiSearchForIndex(String routingId, List esBulkRequest = new ArrayList(); - // ADS用バルク更新ドキュメントリスト - List adsBulkRequest = new ArrayList(); - - /** - * コンストラクタ. - * @param index インデックス - * @param name タイプ名 - * @param routingId routingID - */ - public DavMoveAccessor(EsIndex index, String name, String routingId) { - super(index, name, routingId); - } - - /** - * 移動元の親DavNodeをロールバック用に格納する.
- * 値が設定されていない場合はロールバック対象とはしない。 - * @param davNode DavNode - */ - public void setSourceParentNodeForRollback(DavNode davNode) { - this.srcParentNodeForRollback = cloneDavNode(davNode); - } - - /** - * 移動先の親DavNodeをロールバック用に格納する.
- * 値が設定されていない場合はロールバック対象とはしない。 - * @param davNode DavNode - */ - public void setDestinationParentNodeForRollback(DavNode davNode) { - this.dstParentNodeForRollback = cloneDavNode(davNode); - } - - /** - * 移動対象のDavNodeをロールバック用に格納する.
- * 値が設定されていない場合はロールバック対象とはしない。 - * @param davNode DavNode - */ - public void setSourceNodeForRollback(DavNode davNode) { - this.srcNodeForRollback = cloneDavNode(davNode); - } - - /** - * 移動先のDavNodeをロールバック用に格納する.
- * 値が設定されていない場合はロールバック対象とはしない。 - * @param davNode DavNode - */ - public void setDestinationNodeForRollback(DavNode davNode) { - this.dstNoeForRollback = cloneDavNode(davNode); - } - - /** - * DavNodeの複製を作成する. - * @param davNode - * @return 複製したDavNode - */ - private DavNode cloneDavNode(DavNode davNode) { - if (null == davNode) { - return null; - } - String jsonString = davNode.getSource().toJSONString(); - return DavNode.createFromJsonString(davNode.getId(), jsonString); - } - - /** - * DavNodeの移動用リクエストをAccessorに設定する. - * @param srcName 移動対象DavNodeの名前 - * @param dstName 移動対象DavNodeの名前 - * @param srcNode 移動対象DavNode - * @param dstNode 移動先のDavNodeの階層情報 - * @param srcParentNode 移動対象DavNodeの親DavNode - * @param dstParentNode 移動先DavNodeの親DavNode - */ - public void setMoveRequest( - String srcName, - String dstName, - DavNode srcNode, - DavNode dstNode, - DavNode srcParentNode, - DavNode dstParentNode) { - - long now = new Date().getTime(); - - // MOVEのパターンによって更新内容を作成し分ける - if (srcNode.getParentId().equals(dstParentNode.getId())) { - // 移動せず変名のみの場合 - // 親ノードのchildren情報から、移動対象のリソース情報を削除する - Map srcChildren = srcParentNode.getChildren(); - srcChildren.remove(srcName); - - // 親ノードのchildren情報に、移動対象のリソース情報を追加する - srcChildren.put(dstName, srcNode.getId()); - srcParentNode.setChildren(srcChildren); - srcParentNode.setUpdated(now); - - adsBulkRequest.add(srcParentNode); - esBulkRequest.add(srcParentNode); - } else { - // 異なるコレクションに移動する場合 - // 移動前の親ノードのchildren情報から、移動対象のリソース情報を削除する - Map srcChildren = srcParentNode.getChildren(); - srcChildren.remove(srcName); - srcParentNode.setChildren(srcChildren); - srcParentNode.setUpdated(now); - - adsBulkRequest.add(srcParentNode); - esBulkRequest.add(srcParentNode); - - setDestinationParentNodeForRollback(dstParentNode); - // 移動先の親ノードのchildren情報に、移動対象のリソース情報を追加する - Map dstChildren = dstParentNode.getChildren(); - dstChildren.put(dstName, srcNode.getId()); - dstParentNode.setChildren(dstChildren); - dstParentNode.setUpdated(now); - - adsBulkRequest.add(dstParentNode); - esBulkRequest.add(dstParentNode); - - setSourceNodeForRollback(srcNode); - // 移動対象のリソースの親リソース情報を移動先のものに変更する - srcNode.setParentId(dstParentNode.getId()); - srcNode.setUpdated(now); - - adsBulkRequest.add(srcNode); - esBulkRequest.add(srcNode); - } - // 移動先のDavNodeが存在する場合は、そのDavNodeを削除する(ファイル実体は含まない)。 - if (null != dstNode) { - dstNode.setRequestType(EsBulkRequest.BulkRequestType.DELETE); - adsBulkRequest.add(dstNode); - esBulkRequest.add(dstNode); - setDestinationNodeForRollback(dstNode); - } - } - - /** - * Move用の更新/削除リクエストをバルクで行う.
- * 全リクエストの情報をログに出力しているため、大量のリクエストを行う際には要注意.
- * ES用のバルク登録ドキュメント数とADS用のバルク登録ドキュメント数は、同じにすること - * @return バルクレスポンス - */ - public PersoniumBulkResponse move() { - PersoniumBulkResponse response = esMove(this.esBulkRequest); - // ESへのバルクリクエストでエラーが発生した場合はロールバックするためバイナリファイルの削除とADSの更新は行わない - if (response.hasFailures()) { - rollback(); - throw PersoniumCoreException.Server.DATA_STORE_UPDATE_ERROR_ROLLBACKED; - } - - adsMove(response); - - deleteDavFile(this.dstNoeForRollback); - - return response; - } - - private PersoniumBulkResponse adsMove(PersoniumBulkResponse response) { - // ADSへの書込みは、連続した登録/更新のリクエストをバルクで実行する - // 削除リクエストはリクエストを単体で実行する - // 例)登録→更新→削除→削除→登録→更新→登録→削除 の順で実行した場合 - // 1. 登録→更新 をバルクで実行 - // 2. 削除を実行 - // 3. 削除を実行 - // 4. 登録→更新→登録 をバルクで実行 - // 5. 削除を実行 - // TODO 削除リクエストを複数実行する際は、バルク化する - if (getAds() != null) { - List adsUpdateBulkRequest = new ArrayList(); - int i; - for (i = 0; i < esBulkRequest.size(); i++) { - EsBulkRequest esReq = esBulkRequest.get(i); - if (BulkRequestType.DELETE != esReq.getRequestType()) { - adsUpdateBulkRequest.add(adsBulkRequest.get(i)); - } else { - // Davテーブル一括更新 - bulkUpdateAds(adsUpdateBulkRequest, response, i); - adsUpdateBulkRequest.clear(); - - // Davテーブル削除 - deleteAds(adsBulkRequest.get(i), -1); - } - } - // Davテーブル一括更新 - bulkUpdateAds(adsUpdateBulkRequest, response, i); - } - return response; - } - - /** - * moveメソッドでのElasticsearchへのデータの更新を行う.
- * ロールバックでもこのメソッドを使用するため、リクエスト情報はパラメータとして受け取る。 - * @param esRequest ES用バルク登録ドキュメントリスト - * @return バルクレスポンス - */ - public PersoniumBulkResponse esMove(List esRequest) { - // マスタ書き込みでエラーが発生したためES更新を不可能とする - prepareDataUpdate(getIndex().getName()); - - PersoniumBulkResponse response = null; - try { - response = getIndex().bulkRequest(getRoutingId(), esRequest, true); - } catch (EsClientException.EsNoResponseException e) { - throw PersoniumCoreException.Server.ES_RETRY_OVER.params(e.getMessage()); - } - return response; - } - - /** - * マスターデータを一括更新する. - * @param metaFile 更新データ - * @param response Elasticsearchのバルク更新レスポンス(Ads書込み失敗ログ出力用) - * @param responseIndex Elasticsearchのバルク更新レスポンスのインデックス - */ - private void bulkUpdateAds(List adsRequest, PersoniumBulkResponse response, int responseIndex) { - try { - // Davテーブルを一括更新 - if (adsRequest.size() > 0) { - getAds().bulkUpdateDav(getIndex().getName(), adsRequest); - } - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_BULK_CREATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - // ESでのバージョン情報を取得するためにesBulkRequestをループさせている - PersoniumBulkItemResponse[] responseItems = response.items(); - - for (DavNode docHandler : adsRequest) { - // Adsの登録に失敗した場合は、専用のログに書込む - PersoniumBulkItemResponse itemResponse = responseItems[responseIndex++]; - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_DAV, - null, docHandler.getBoxId(), null); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), "dav", lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.UPDATE, itemResponse.version(), - docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } - - /** - * ESへのバルクリクエスト失敗時に、元の状態に戻すためのリクエストを実行する. - */ - private void rollback() { - log.info("Failed to update data store, then rollback start"); - // バルクリクエスト作成 - List adsRequest = new ArrayList(); - List esRequest = new ArrayList(); - - adsRequest.add(this.srcParentNodeForRollback); - esRequest.add(this.srcParentNodeForRollback); - - if (null != this.dstParentNodeForRollback) { - adsRequest.add(this.dstParentNodeForRollback); - esRequest.add(this.dstParentNodeForRollback); - } - - if (null != this.srcNodeForRollback) { - adsRequest.add(this.srcNodeForRollback); - esRequest.add(this.srcNodeForRollback); - } - - if (null != this.dstNoeForRollback) { - adsRequest.add(this.dstNoeForRollback); - esRequest.add(this.dstNoeForRollback); - } - - // ロールバックではElasticsearchのデータのみを戻す - PersoniumBulkResponse bulkResponse = esMove(esRequest); - if (bulkResponse.hasFailures()) { - // ロールバック失敗時はロールバックしようとしたデータの内容を出力する - log.info("rollback was abnormally end."); - outputRollbackRequest("srcParent ", srcParentNodeForRollback); - outputRollbackRequest("dstParent", dstParentNodeForRollback); - outputRollbackRequest("source", srcNodeForRollback); - outputRollbackRequest("destination", dstNoeForRollback); - // ロールバックに失敗 - throw PersoniumCoreException.Server.DATA_STORE_UPDATE_ROLLBACK_ERROR; - } - // ロールバックに成功 - log.info("rollback was successfully end."); - } - - /** - * ロールバック失敗時にデータ補正用のDavNodeデータを出力する. - * @param prefix データ項目名 - * @param davNode DavNode - */ - private void outputRollbackRequest(String prefix, DavNode davNode) { - if (null != davNode) { - log.info(String.format("%-11s: %s", prefix, davNode.getSource().toJSONString())); - } - } - - /** - * DavNodeのIDをもとにファイルを削除する. - * @param davCmp Davコンポーネント - */ - private void deleteDavFile(DavNode davNode) { - if (null != davNode) { - BinaryDataAccessor accessor = getBinaryDataAccessor(); - try { - accessor.delete(davNode.getId()); - } catch (BinaryDataAccessException e) { - PersoniumCoreLog.Dav.FILE_DELETE_FAIL.params(davNode.getId()).writeLog(); - } - } - } - - /** - * バイナリデータのアクセサのインスタンスを生成して返す. - * @return アクセサのインスタンス - */ - protected BinaryDataAccessor getBinaryDataAccessor() { - String unitUserName = getIndex().getName().replace(PersoniumUnitConfig.getEsUnitPrefix() + "_", ""); - return new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), unitUserName, - PersoniumUnitConfig.getPhysicalDeleteMode(), PersoniumUnitConfig.getFsyncEnabled()); - } -} diff --git a/src/main/java/io/personium/core/model/impl/es/accessor/DavNodeAccessor.java b/src/main/java/io/personium/core/model/impl/es/accessor/DavNodeAccessor.java deleted file mode 100644 index bce78160b..000000000 --- a/src/main/java/io/personium/core/model/impl/es/accessor/DavNodeAccessor.java +++ /dev/null @@ -1,285 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.accessor; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.ads.AdsWriteFailureLogInfo; -import io.personium.common.es.EsIndex; -import io.personium.common.es.response.PersoniumActionResponse; -import io.personium.common.es.response.PersoniumDeleteResponse; -import io.personium.common.es.response.PersoniumIndexResponse; -import io.personium.common.es.util.PersoniumUUID; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.PersoniumCoreException; -import io.personium.core.PersoniumCoreLog; -import io.personium.core.model.file.BinaryDataAccessException; -import io.personium.core.model.file.BinaryDataAccessor; -import io.personium.core.model.impl.es.DavNode; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.lock.Lock; -import io.personium.core.model.lock.LockKeyComposer; - -/** - * DavNode情報のアクセス処理を実装したクラス. - */ -public class DavNodeAccessor extends DataSourceAccessor { - - /** - * ログ. - */ - static Logger log = LoggerFactory.getLogger(DavNodeAccessor.class); - - /** - * コンストラクタ. - * @param index インデックス - * @param name タイプ名 - * @param routingId routingID - */ - public DavNodeAccessor(EsIndex index, String name, String routingId) { - super(index, name, routingId); - } - - /** - * UUIDでDavNodeのデータ登録を行う. - * @param davNode Davコンポーネント - * @return 登録結果 - */ - public PersoniumIndexResponse create(final DavNode davNode) { - String id = PersoniumUUID.randomUUID(); - return this.create(id, davNode); - } - - /** - * DavNodeのデータ登録を行う. - * @param id 登録データのID - * @param davNode Davコンポーネント - * @return 登録結果 - */ - public PersoniumIndexResponse create(String id, DavNode davNode) { - // マスタ書き込みでエラーが発生したためES更新を不可能とする - super.prepareDataUpdate(getIndex().getName()); - davNode.setId(id); - PersoniumIndexResponse response = super.create(id, davNode.getSource()); - createAds(davNode); - return response; - } - - /** - * DavNodeファイルのデータ登録を行う. - * @param id 登録データのID - * @param davNode Davコンポーネント - * @return 登録結果 - */ - public PersoniumActionResponse createForFile(String id, DavNode davNode) { - // マスタ書き込みでエラーが発生したためES更新を不可能とする - prepareDataUpdate(getIndex().getName()); - davNode.setId(id); - PersoniumActionResponse response = null; - try { - // ElasticSearch更新 - response = createForDavNodeFile(id, davNode.getSource()); - - // 一時ファイルコピー - String unitUserName = getIndex().getName().replace(PersoniumUnitConfig.getEsUnitPrefix() + "_", ""); - BinaryDataAccessor binaryDataAccessor = new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), - unitUserName, PersoniumUnitConfig.getFsyncEnabled()); - binaryDataAccessor.copyFile(id); - - // MySQL更新 - createAds(davNode); - } catch (BinaryDataAccessException ex) { - // 一時ファイルコピー失敗 - throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(ex); - } finally { - // 一時ファイル削除 - deleteTmpFile(id); - } - - return response; - } - - private void deleteTmpFile(String id) { - String unitUserName = getIndex().getName().replace(PersoniumUnitConfig.getEsUnitPrefix() + "_", ""); - BinaryDataAccessor binaryDataAccessor = new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), - unitUserName, PersoniumUnitConfig.getFsyncEnabled()); - try { - // 一時ファイル物理削除 - binaryDataAccessor.deletePhysicalFile(id + ".tmp"); - } catch (BinaryDataAccessException e1) { - log.info(e1.getMessage()); - } - } - - /** - * マスターデータを登録する. - * @param davNode 登録データ - */ - protected void createAds(DavNode davNode) { - // 登録に成功した場合、マスタデータを書き込む - if (getAds() != null) { - try { - getAds().createDavNode(getIndex().getName(), davNode); - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_CREATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_DAV, null, - davNode.getBoxId(), null); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), "dav", lockKey, davNode.getCellId(), davNode.getId(), - AdsWriteFailureLogInfo.OperationKind.CREATE, 1, davNode.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } - - /** - * DavNodeのデータ削除を行う. - * @param davNode 削除データ - * @return 削除結果 - */ - public PersoniumDeleteResponse delete(DavNode davNode) { - return this.delete(davNode, -1); - } - - /** - * DavNodeのデータ削除を行う. - * @param version バージョン情報 - * @param davNode 削除データ - * @return 削除結果 - */ - public PersoniumDeleteResponse delete(DavNode davNode, long version) { - String id = davNode.getId(); - - // マスタ書き込みでエラーが発生したためES更新を不可能とする - super.prepareDataUpdate(getIndex().getName()); - PersoniumDeleteResponse response = super.delete(id, version); - deleteAds(davNode, response.getVersion()); - return response; - } - - /** - * マスターデータを削除する. - * @param davNode 削除データ - * @param version 削除したデータのバージョン - */ - protected void deleteAds(DavNode davNode, long version) { - String id = davNode.getId(); - - // 削除に成功した場合、マスタデータを書き込む - if (getAds() != null) { - try { - getAds().deleteDavNode(getIndex().getName(), id); - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_DELETE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_DAV, null, - davNode.getBoxId(), null); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), "dav", lockKey, davNode.getCellId(), davNode.getId(), - AdsWriteFailureLogInfo.OperationKind.DELETE, version, davNode.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } - - /** - * DavNodeのデータ更新を行う. - * @param id 更新データのID - * @param davNode Davコンポーネント - * @return 更新結果 - */ - public PersoniumIndexResponse update(String id, DavNode davNode) { - return this.update(id, davNode, -1); - } - - /** - * バージョン指定ありでDavNodeのデータ更新を行う. - * @param id 更新データのID - * @param davNode Davコンポーネント - * @param version バージョン情報 - * @return 更新結果 - */ - public PersoniumIndexResponse update(String id, DavNode davNode, long version) { - // マスタ書き込みでエラーが発生したためES更新を不可能とする - super.prepareDataUpdate(getIndex().getName()); - PersoniumIndexResponse response = super.update(id, davNode.getSource(), version); - updateAds(davNode, response.getVersion()); - return response; - } - - /** - * バージョン指定ありでDavNodeファイルのデータ更新を行う. - * @param id 更新データのID - * @param davNode Davコンポーネント - * @param version バージョン情報 - * @return 更新結果 - */ - public PersoniumIndexResponse updateForFile(String id, DavNode davNode, long version) { - // マスタ書き込みでエラーが発生したためES更新を不可能とする - super.prepareDataUpdate(getIndex().getName()); - PersoniumIndexResponse response = null; - try { - // ElasticSearch更新 - response = super.update(id, davNode.getSource(), version); - - // 一時ファイルコピー - String unitUserName = getIndex().getName().replace(PersoniumUnitConfig.getEsUnitPrefix() + "_", ""); - BinaryDataAccessor binaryDataAccessor = new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), - unitUserName, PersoniumUnitConfig.getFsyncEnabled()); - binaryDataAccessor.copyFile(id); - - // MySQL更新 - updateAds(davNode, response.getVersion()); - } catch (BinaryDataAccessException ex) { - // 一時ファイルコピー失敗 - throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(ex); - } finally { - // 一時ファイル削除 - deleteTmpFile(id); - } - - return response; - } - - /** - * マスターデータを更新する. - * @param davNode 更新データ - * @param version Elasticsearchに登録されたドキュメントのバージョン - */ - protected void updateAds(DavNode davNode, long version) { - // 更新に成功した場合、マスタデータを書き込む - if (getAds() != null) { - try { - getAds().updateDavNode(getIndex().getName(), davNode); - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_UPDATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_DAV, null, - davNode.getBoxId(), null); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), "dav", lockKey, davNode.getCellId(), davNode.getId(), - AdsWriteFailureLogInfo.OperationKind.UPDATE, version, davNode.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } -} diff --git a/src/main/java/io/personium/core/model/impl/es/accessor/ODataEntityAccessor.java b/src/main/java/io/personium/core/model/impl/es/accessor/ODataEntityAccessor.java index 1570fe62a..ba5baab46 100644 --- a/src/main/java/io/personium/core/model/impl/es/accessor/ODataEntityAccessor.java +++ b/src/main/java/io/personium/core/model/impl/es/accessor/ODataEntityAccessor.java @@ -16,15 +16,7 @@ */ package io.personium.core.model.impl.es.accessor; -import java.sql.SQLException; - -import io.personium.common.ads.AdsWriteFailureLogInfo; import io.personium.common.es.EsIndex; -import io.personium.core.PersoniumCoreLog; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.doc.EntitySetDocHandler; -import io.personium.core.model.lock.Lock; -import io.personium.core.model.lock.LockKeyComposer; /** * ODataEntityのアクセス処理を実装したクラス. @@ -41,103 +33,4 @@ public ODataEntityAccessor(EsIndex index, String name, String routingId) { super(index, name, routingId); } - /** - * マスターデータを登録する. - * @param docHandler 登録データ - */ - protected void createAds(EntitySetDocHandler docHandler) { - // 登録に成功した場合、マスタデータを書き込む - if (getAds() != null) { - String indexName = getIndex().getName(); - try { - getAds().createEntity(indexName, docHandler); - } catch (AdsException e) { - // Indexが存在しない場合はインデックスを作成する。 - if (e.getCause() instanceof SQLException - && MYSQL_BAD_TABLE_ERROR.equals(((SQLException) e.getCause()).getSQLState())) { - PersoniumCoreLog.Server.ES_INDEX_NOT_EXIST.params(indexName).writeLog(); - createAdsIndex(indexName); - try { - getAds().createEntity(indexName, docHandler); - } catch (AdsException e1) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_CREATE_FAIL.params( - e1.getMessage()).reason(e1).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, docHandler.getNodeId()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), docHandler.getType(), lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.CREATE, 1, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } else { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_CREATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, docHandler.getNodeId()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), docHandler.getType(), lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.CREATE, 1, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } - } - - /** - * マスターデータを更新する. - * @param docHandler 登録データ - * @param version Elasticsearchに登録されたドキュメントのバージョン - */ - protected void updateAds(EntitySetDocHandler docHandler, long version) { - // 更新に成功した場合、マスタデータを更新する - if (getAds() != null) { - try { - getAds().updateEntity(getIndex().getName(), docHandler); - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_UPDATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, docHandler.getNodeId()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), docHandler.getType(), lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.UPDATE, version, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } - - /** - * マスタデータを削除する. - * @param docHandler 削除データ - * @param version 削除したデータのバージョン - */ - @Override - protected void deleteAds(EntitySetDocHandler docHandler, long version) { - String id = docHandler.getId(); - - // 削除に成功した場合、マスタデータを削除する - if (getAds() != null) { - try { - getAds().deleteEntity(getIndex().getName(), id); - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_DELETE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, docHandler.getNodeId()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), docHandler.getType(), lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.DELETE, version, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } } diff --git a/src/main/java/io/personium/core/model/impl/es/accessor/ODataLinkAccessor.java b/src/main/java/io/personium/core/model/impl/es/accessor/ODataLinkAccessor.java index 095b5d060..4a025300e 100644 --- a/src/main/java/io/personium/core/model/impl/es/accessor/ODataLinkAccessor.java +++ b/src/main/java/io/personium/core/model/impl/es/accessor/ODataLinkAccessor.java @@ -16,17 +16,10 @@ */ package io.personium.core.model.impl.es.accessor; -import io.personium.common.ads.AdsWriteFailureLogInfo; import io.personium.common.es.EsIndex; import io.personium.common.es.response.PersoniumDeleteResponse; import io.personium.common.es.response.PersoniumIndexResponse; -import io.personium.common.es.util.PersoniumUUID; -import io.personium.core.PersoniumCoreLog; -import io.personium.core.model.impl.es.EsModel; -import io.personium.core.model.impl.es.ads.AdsException; import io.personium.core.model.impl.es.doc.LinkDocHandler; -import io.personium.core.model.lock.Lock; -import io.personium.core.model.lock.LockKeyComposer; /** * ODataLink情報のアクセス処理を実装したクラス. @@ -43,16 +36,6 @@ public ODataLinkAccessor(EsIndex index, String name, String routingId) { super(index, name, routingId); } - /** - * UUIDでODataLinkのデータ登録を行う. - * @param docHandler 登録データ - * @return 登録結果 - */ - public PersoniumIndexResponse create(final LinkDocHandler docHandler) { - String id = PersoniumUUID.randomUUID(); - return this.create(id, docHandler); - } - /** * ODataLinkのデータ登録を行う. * @param id 登録データのID @@ -60,88 +43,11 @@ public PersoniumIndexResponse create(final LinkDocHandler docHandler) { * @return 登録結果 */ public PersoniumIndexResponse create(String id, LinkDocHandler docHandler) { - // マスタ書き込みでエラーが発生したためES更新を不可能とする - super.prepareDataUpdate(getIndex().getName()); docHandler.setId(id); PersoniumIndexResponse response = super.create(id, docHandler.createLinkDoc()); - createAds(docHandler); - return response; - } - - /** - * マスターデータを登録する. - * @param docHandler 登録データ - */ - protected void createAds(LinkDocHandler docHandler) { - // 登録に成功した場合、マスタデータを書き込む - if (getAds() != null) { - try { - getAds().createLink(getIndex().getName(), docHandler); - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_CREATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, docHandler.getNodeId()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), EsModel.TYPE_CTL_LINK, lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.CREATE, 1, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } - - /** - * ODataLinkのデータ更新を行う. - * @param id 更新データのID - * @param docHandler 登録データ - * @return 更新結果 - */ - public PersoniumIndexResponse update(String id, LinkDocHandler docHandler) { - return this.update(id, docHandler, -1); - } - - /** - * バージョン指定ありでODataLinkのデータ更新を行う. - * @param id 更新データのID - * @param docHandler 登録データ - * @param version バージョン情報 - * @return 更新結果 - */ - public PersoniumIndexResponse update(String id, LinkDocHandler docHandler, long version) { - // マスタ書き込みでエラーが発生したためES更新を不可能とする - super.prepareDataUpdate(getIndex().getName()); - PersoniumIndexResponse response = super.update(id, docHandler.createLinkDoc(), version); - updateAds(docHandler, response.getVersion()); return response; } - /** - * マスターデータを更新する. - * @param docHandler 更新データ - * @param version Elasticsearchに登録されたドキュメントのバージョン - */ - protected void updateAds(LinkDocHandler docHandler, long version) { - // 更新に成功した場合、マスタデータを書き込む - if (getAds() != null) { - try { - getAds().updateLink(getIndex().getName(), docHandler); - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_UPDATE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, docHandler.getNodeId()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), EsModel.TYPE_CTL_LINK, lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.UPDATE, version, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } - /** * Delete a document. * @param docHandler 削除データ @@ -160,37 +66,8 @@ public PersoniumDeleteResponse delete(final LinkDocHandler docHandler) { public PersoniumDeleteResponse delete(final LinkDocHandler docHandler, long version) { String id = docHandler.getId(); - // マスタ書き込みでエラーが発生したためES更新を不可能とする - super.prepareDataUpdate(getIndex().getName()); PersoniumDeleteResponse response = super.delete(id, version); - deleteAds(docHandler, response.getVersion()); return response; } - /** - * マスターデータを削除する. - * @param docHandler 削除データ - * @param version 削除したデータのバージョン - */ - protected void deleteAds(LinkDocHandler docHandler, long version) { - String id = docHandler.getId(); - - // 削除に成功した場合、マスタデータを書き込む - if (getAds() != null) { - try { - getAds().deleteLink(getIndex().getName(), id); - } catch (AdsException e) { - PersoniumCoreLog.Server.DATA_STORE_ENTITY_DELETE_FAIL.params(e.getMessage()).reason(e).writeLog(); - - // Adsの登録に失敗した場合は、専用のログに書込む - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - docHandler.getCellId(), null, docHandler.getNodeId()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - this.getIndex().getName(), EsModel.TYPE_CTL_LINK, lockKey, - docHandler.getCellId(), docHandler.getId(), - AdsWriteFailureLogInfo.OperationKind.DELETE, version, docHandler.getUpdated()); - recordAdsWriteFailureLog(loginfo); - } - } - } } diff --git a/src/main/java/io/personium/core/model/impl/es/ads/Ads.java b/src/main/java/io/personium/core/model/impl/es/ads/Ads.java deleted file mode 100644 index b37814b75..000000000 --- a/src/main/java/io/personium/core/model/impl/es/ads/Ads.java +++ /dev/null @@ -1,320 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.ads; - -import java.util.List; - -import org.json.simple.JSONObject; - -import io.personium.core.model.impl.es.DavNode; -import io.personium.core.model.impl.es.doc.EntitySetDocHandler; -import io.personium.core.model.impl.es.doc.LinkDocHandler; - -/** - * ES のADS ( Authentic Data Store ) のインターフェース. - * ひとつのIndexに対して、一つのADSが対応する。 - */ -public interface Ads { - /** - * Entity Document生成に伴い、Adsの対応レコード生成を行う. - * @param index index - * @param oedh OEntityDocHandler - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void createEntity(String index, EntitySetDocHandler oedh) throws AdsException; - - /** - * Entity Document更新に伴い、Adsの対応レコード更新を行う. - * @param index index - * @param oedh OEntityDocHandler - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void updateEntity(String index, EntitySetDocHandler oedh) throws AdsException; - - /** - * Entity Document削除に伴い、Adsの対応レコード削除を行う. - * @param index index - * @param id id - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void deleteEntity(String index, String id) throws AdsException; - - /** - * リカバリ用に、ADS内の特定indexに対応するEntity件数を取得する。 - * @param index index - * @return 件数 - * @throws AdsException 取得失敗時 - */ - long countEntity(String index) throws AdsException; - - /** - * Entity Document一括生成に伴い、Adsの対応レコード一括生成を行う. - * @param index index - * @param bulkRequestList 一括生成データ - * @throws AdsException 処理失敗時発生 - */ - void bulkEntity(String index, List bulkRequestList) throws AdsException; - - /** - * Entity Document一括更新に伴い、Adsの対応レコード一括更新を行う. - * @param index index - * @param bulkRequestList 一括更新データ - * @throws AdsException 処理失敗時発生 - */ - void bulkUpdateEntity(String index, List bulkRequestList) throws AdsException; - - /** - * Dav Document一括更新に伴い、Adsの対応レコード一括更新を行う. - * @param index index - * @param bulkRequestList 一括更新データ - * @throws AdsException 処理失敗時発生 - */ - void bulkUpdateDav(String index, List bulkRequestList) throws AdsException; - - /** - * リカバリ用に、ADS内の特定indexに対応するEntityのリストを取得する。 - * @param index index - * @param offset 取得開始レコード(最初から取るときは0) - * @param size 取得件数 - * @return JSONObjectのリスト. - * @throws AdsException 取得失敗時 - */ - List getEntityList(String index, long offset, long size) throws AdsException; - - /** - * 引数で渡されたuuidをもとに、ADS内の特定indexに対応するデータを検索する。 - * @param index DataBundle名 - * @param idList 検索対象のuuidリスト - * @return JSONObjectのリスト. - * @throws AdsException 取得失敗時 - */ - List searchEntityList(String index, List idList) throws AdsException; - - /** - * Cell Document生成に伴い、Adsの対応レコード生成を行う. - * @param index index - * @param docHandler CellDocHandler - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void createCell(String index, EntitySetDocHandler docHandler) throws AdsException; - - /** - * Cell Document更新に伴い、Adsの対応レコード更新を行う. - * @param index index - * @param docHandler CellDocHandler - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void updateCell(String index, EntitySetDocHandler docHandler) throws AdsException; - - /** - * Cell Document削除に伴い、Adsの対応レコード削除を行う. - * @param index index - * @param id id - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void deleteCell(String index, String id) throws AdsException; - - /** - * リカバリ用に、ADS内の特定indexに対応するCell件数を取得する。 - * @param index index - * @return 件数 - * @throws AdsException 取得失敗時 - */ - long countCell(String index) throws AdsException; - - /** - * リカバリ用に、ADS内の特定indexに対応するCellのリストを取得する。 - * @param index index - * @param offset 取得開始レコード(最初から取るときは0) - * @param size 取得件数 - * @return JSONObjectのリスト. - * @throws AdsException 取得失敗時 - */ - List getCellList(String index, long offset, long size) throws AdsException; - - /** - * 引数で渡されたuuidをもとに、ADS内の特定indexに対応するデータを検索する。 - * @param index DataBundle名 - * @param idList 検索対象のuuidリスト - * @return JSONObjectのリスト. - * @throws AdsException 取得失敗時 - */ - List searchCellList(String index, List idList) throws AdsException; - - /** - * Link Document生成に伴い、Adsの対応レコード生成を行う. - * @param index index - * @param ldh LinkDocHandler - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void createLink(String index, LinkDocHandler ldh) throws AdsException; - - /** - * Link Document生成に伴い、Adsの一括登録用のレコード生成を行う. - * @param index index - * @param bulkRequestList 一括登録するLinkDocHandlerのリスト - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void bulkCreateLink(String index, List bulkRequestList) throws AdsException; - - /** - * Link Document更新に伴い、Adsの対応レコード更新を行う. - * @param index index - * @param ldh LinkDocHandler - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void updateLink(String index, LinkDocHandler ldh) throws AdsException; - - /** - * Link Document削除に伴い、Adsの対応レコード削除を行う. - * @param index index - * @param id id - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void deleteLink(String index, String id) throws AdsException; - - /** - * リカバリ用に、ADS内の特定indexに対応するLink件数を取得する。 - * @param index index - * @return 件数 - * @throws AdsException 取得失敗時 - */ - long countLink(String index) throws AdsException; - - /** - * リカバリ用に、ADS内の特定indexに対応するLinkのリストを取得する。 - * @param index index - * @param offset 取得開始レコード(最初から取るときは0) - * @param size 取得件数 - * @return JSONObjectのリスト. - * @throws AdsException 取得失敗時 - */ - List getLinkList(String index, long offset, long size) throws AdsException; - - /** - * 引数で渡されたuuidをもとに、ADS内の特定indexに対応するデータを検索する。 - * @param index DataBundle名 - * @param idList 検索対象のuuidリスト - * @return JSONObjectのリスト. - * @throws AdsException 取得失敗時 - */ - List searchLinkList(String index, List idList) throws AdsException; - - /** - * DavNode生成に伴い、Adsの対応レコード生成を行う. - * @param index index - * @param davNode DavNode - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void createDavNode(String index, DavNode davNode) throws AdsException; - - /** - * DavNode更新に伴い、Adsの対応レコード更新を行う. - * @param index index - * @param davNode DavNode - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void updateDavNode(String index, DavNode davNode) throws AdsException; - - /** - * DavNode削除に伴い、Adsの対応レコード削除を行う. - * @param index index - * @param id id - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void deleteDavNode(String index, String id) throws AdsException; - - /** - * リカバリ用に、ADS内の特定indexに対応するDavNode件数を取得する。 - * @param index index - * @return 件数 - * @throws AdsException 取得失敗時 - */ - long countDavNode(String index) throws AdsException; - - /** - * リカバリ用に、ADS内の特定indexに対応するDavNodeのリストを取得する。 - * @param index index - * @param offset 取得開始レコード(最初から取るときは0) - * @param size 取得件数 - * @return JSONObjectのリスト. - * @throws AdsException 取得失敗時 - */ - List getDavNodeList(String index, long offset, long size) throws AdsException; - - /** - * 引数で渡されたuuidをもとに、ADS内の特定indexに対応するデータを検索する。 - * @param index DataBundle名 - * @param idList 検索対象のuuidリスト - * @return JSONObjectのリスト. - * @throws AdsException 取得失敗時 - */ - List searchDavNodeList(String index, List idList) throws AdsException; - - /** - * 指定されたIDのCellのリソースをENTITYテーブルから削除する. - * @param index 対象インデックス - * @param cellId 対象セルID - * @throws AdsException 削除失敗時 - */ - void deleteCellResourceFromEntity(String index, String cellId) throws AdsException; - - /** - * 指定されたIDのCellのリソースをDAV_NODEテーブルから削除する. - * @param index 対象インデックス - * @param cellId 対象セルID - * @throws AdsException 削除失敗時 - */ - void deleteCellResourceFromDavNode(String index, String cellId) throws AdsException; - - /** - * 指定されたIDのCellのリソースをLINKテーブルから削除する. - * @param index 対象インデックス - * @param cellId 対象セルID - * @throws AdsException 削除失敗時 - */ - void deleteCellResourceFromLink(String index, String cellId) throws AdsException; - - /** - * Es Index生成に伴い、Adsの対応空間を生成する. - * @param index index - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void createIndex(String index) throws AdsException; - - /** - * PCS管理用DBを作成する. - * @throws AdsException 管理用DBの作成に失敗 - */ - void createManagementDatabase() throws AdsException; - - /** - * Es Index削除に伴い、Adsの対応空間を削除する. - * @param index index - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - void deleteIndex(String index) throws AdsException; - - /** - * セル削除用管理テーブルに削除するセル情報を登録する. - * @param dbName セル削除対象のDB名 - * @param cellId セル削除対象のセルID - * @throws AdsException 登録失敗時 - */ - void insertCellDeleteRecord(String dbName, String cellId) throws AdsException; - -} diff --git a/src/main/java/io/personium/core/model/impl/es/ads/AdsConnectionException.java b/src/main/java/io/personium/core/model/impl/es/ads/AdsConnectionException.java deleted file mode 100644 index 3a4b8f751..000000000 --- a/src/main/java/io/personium/core/model/impl/es/ads/AdsConnectionException.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.ads; - -/** - * ADSの更新処理失敗時に投げられるException. - */ -@SuppressWarnings("serial") -public class AdsConnectionException extends AdsException { - /** - * コンストラクタ. - * @param t 原因Throwable - */ - public AdsConnectionException(Throwable t) { - super(t); - } - /** - * コンストラクタ. - * @param msg メッセージ - */ - public AdsConnectionException(String msg) { - super(msg); - } -} diff --git a/src/main/java/io/personium/core/model/impl/es/ads/AdsException.java b/src/main/java/io/personium/core/model/impl/es/ads/AdsException.java deleted file mode 100644 index 30d2cfc43..000000000 --- a/src/main/java/io/personium/core/model/impl/es/ads/AdsException.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.ads; - -/** - * ADSの更新処理失敗時に投げられるException. - */ -@SuppressWarnings("serial") -public class AdsException extends Exception { - /** - * コンストラクタ. - * @param t 原因Throwable - */ - public AdsException(Throwable t) { - super(t); - } - /** - * コンストラクタ. - * @param msg メッセージ - */ - public AdsException(String msg) { - super(msg); - } -} diff --git a/src/main/java/io/personium/core/model/impl/es/ads/JdbcAds.java b/src/main/java/io/personium/core/model/impl/es/ads/JdbcAds.java deleted file mode 100644 index 470f5ce89..000000000 --- a/src/main/java/io/personium/core/model/impl/es/ads/JdbcAds.java +++ /dev/null @@ -1,1673 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.ads; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.sql.DataSource; - -import org.apache.commons.dbcp.BasicDataSourceFactory; -import org.apache.commons.dbcp.DelegatingPreparedStatement; -import org.apache.commons.lang.CharEncoding; -import org.json.simple.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.utils.PersoniumCoreUtils; -import io.personium.core.PersoniumCoreLog; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.impl.es.DavNode; -import io.personium.core.model.impl.es.doc.CellDocHandler; -import io.personium.core.model.impl.es.doc.EntitySetDocHandler; -import io.personium.core.model.impl.es.doc.LinkDocHandler; -import io.personium.core.model.impl.es.doc.OEntityDocHandler; -import io.personium.core.model.impl.es.odata.UserDataODataProducer; - -/** - * JDBCタイプのADS ( Authentic Data Store ). - */ -public class JdbcAds implements Ads { - private static DataSource ds; - Map peersMap = new HashMap(); - - static Logger log = LoggerFactory.getLogger(JdbcAds.class); - static final String SCHEMA_NAME_REPLACING_KEY = "##schema##"; - static final boolean AUTO_COMMIT = true; - - static final String MANAGEMENT_DB_NAME = "pcs_management"; - - /** - * コンストラクタ. - * @throws AdsConnectionException ADS接続失敗 - */ - public JdbcAds() throws AdsConnectionException { - - try { - if (ds == null) { - Properties p = PersoniumUnitConfig.getEsAdsDbcpProps(); - ds = BasicDataSourceFactory.createDataSource(p); - } - } catch (Exception e) { - log.info("Failed to create instance of Ads."); - throw new AdsConnectionException(e); - } - } - - /** - * Adsの接続確認を行う. - * @throws AdsException 処理失敗時発生 - */ - public void checkConnection() throws AdsException { - try { - // 接続確認を行う - ds.getConnection().close(); - } catch (SQLException e) { - // 接続失敗時は例外を出力する - log.info("Failed to connect Ads."); - throw new AdsException(e); - } - } - - @Override - public void createEntity(String index, EntitySetDocHandler edh) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.createEntity(edh); - } - - @Override - public void updateEntity(String index, EntitySetDocHandler edh) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.updateEntity(edh); - } - - @Override - public void deleteEntity(String index, String id) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.deleteEntity(id); - } - - /** - * Entity Document一括生成に伴い、Adsの対応レコード一括生成を行う. - * @param index index - * @param bulkRequestList 一括生成データ - * @throws AdsException 処理失敗時発生 - */ - @Override - public void bulkEntity(String index, List bulkRequestList) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.bulkEntity(bulkRequestList); - } - - /** - * Entity Document一括更新に伴い、Adsの対応レコード一括更新を行う. - * @param index index - * @param bulkRequestList 一括更新データ - * @throws AdsException 処理失敗時発生 - */ - @Override - public void bulkUpdateEntity(String index, List bulkRequestList) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.bulkUpdateEntityLink(bulkRequestList); - } - - /** - * Dav Document一括更新に伴い、Adsの対応レコード一括更新を行う. - * @param index index - * @param bulkRequestList 一括更新データ - * @throws AdsException 処理失敗時発生 - */ - @Override - public void bulkUpdateDav(String index, List bulkRequestList) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.bulkUpdateDav(bulkRequestList); - } - - @Override - public void createCell(String index, EntitySetDocHandler docHandler) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.createCell(docHandler); - } - - @Override - public void updateCell(String index, EntitySetDocHandler docHandler) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.updateCell(docHandler); - } - - @Override - public void deleteCell(String index, String id) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.deleteCell(id); - } - - @Override - public void createLink(String index, LinkDocHandler ldh) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.createLink(ldh); - } - - @Override - public void updateLink(String index, LinkDocHandler ldh) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.updateLink(ldh); - } - - @Override - public void deleteLink(String index, String id) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.deleteLink(id); - } - - @Override - public void createDavNode(String index, DavNode davNode) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.createDavNode(davNode); - } - - @Override - public void updateDavNode(String index, DavNode davNode) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.updateDavNode(davNode); - } - - @Override - public void deleteDavNode(String index, String id) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.deleteDavNode(id); - } - - @Override - public long countEntity(String index) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.countEntity(); - } - - @Override - public List getEntityList(String index, long offset, long size) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.getEntityList(offset, size); - } - - @Override - public long countCell(String index) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.countCell(); - } - - @Override - public List getCellList(String index, long offset, long size) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.getCellList(offset, size); - } - - @Override - public long countLink(String index) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.countLink(); - } - - @Override - public List searchEntityList(String index, List idList) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.searchEntityList(idList); - } - - @Override - public List searchCellList(String index, List idList) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.searchCellList(idList); - } - - @Override - public List searchLinkList(String index, List idList) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.searchLinkList(idList); - } - - @Override - public List searchDavNodeList(String index, List idList) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.searchDavNodeList(idList); - } - - /** - * Link Document生成に伴い、Adsの一括登録用のレコード生成を行う. - * @param index index - * @param bulkRequestList 一括登録するLinkDocHandlerのリスト - * @throws AdsException 同期失敗時発生。(処理結果が1件でない場合にも発生する) - */ - @Override - public void bulkCreateLink(String index, List bulkRequestList) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.bulkCreateLink(bulkRequestList); - } - - @Override - public List getLinkList(String index, long offset, long size) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.getLinkList(offset, size); - } - - @Override - public long countDavNode(String index) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.countDavNode(); - } - - @Override - public List getDavNodeList(String index, long offset, long size) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - return ip.getDavNodeList(offset, size); - } - - @Override - public void deleteCellResourceFromEntity(String index, String cellId) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.deleteCellResourceFromEntity(cellId); - } - - @Override - public void deleteCellResourceFromDavNode(String index, String cellId) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.deleteCellResourceFromDavNode(cellId); - } - - @Override - public void deleteCellResourceFromLink(String index, String cellId) throws AdsException { - IndexPeer ip = this.getIndexPeer(index); - ip.deleteCellResourceFromLink(cellId); - } - - @Override - public void insertCellDeleteRecord(String dbName, String cellId) throws AdsException { - IndexPeer ip = this.getIndexPeer(MANAGEMENT_DB_NAME); - ip.insertCellDeleteRecord(dbName, cellId); - } - - @Override - public void createIndex(String index) throws AdsException { - Connection con = null; - Statement stmt = null; - try { - con = ds.getConnection(); - stmt = con.createStatement(); - int res = stmt.executeUpdate(Sql.createSchema.replace(SCHEMA_NAME_REPLACING_KEY, index)); - log.debug("create schema:" + res); - res = stmt.executeUpdate(Sql.createTableEntity.replace(SCHEMA_NAME_REPLACING_KEY, index)); - log.debug("create table entity:" + res); - res = stmt.executeUpdate(Sql.createTableLink.replace(SCHEMA_NAME_REPLACING_KEY, index)); - log.debug("create table Link:" + res); - res = stmt.executeUpdate(Sql.createTableDavNode.replace(SCHEMA_NAME_REPLACING_KEY, index)); - log.debug("create table DavNode:" + res); - res = stmt.executeUpdate(Sql.createTableCell.replace(SCHEMA_NAME_REPLACING_KEY, index)); - log.debug("create table cell:" + res); - } catch (SQLException e) { - throw new AdsException(e); - } finally { - try { - if (stmt != null) { - stmt.close(); - } - if (con != null) { - con.close(); - } - } catch (SQLException e) { - throw new AdsException(e); - } - } - } - - /** - * 管理用DBを作成する. - * @throws AdsException 管理用DB作成に失敗 - */ - public void createManagementDatabase() throws AdsException { - Connection con = null; - Statement stmt = null; - try { - con = ds.getConnection(); - stmt = con.createStatement(); - stmt.executeUpdate(Sql.createSchema.replace(SCHEMA_NAME_REPLACING_KEY, MANAGEMENT_DB_NAME)); - stmt.executeUpdate( - Sql.createManagementTableCellDelete.replace(SCHEMA_NAME_REPLACING_KEY, MANAGEMENT_DB_NAME)); - } catch (SQLException e) { - throw new AdsException(e); - } finally { - try { - if (stmt != null) { - stmt.close(); - } - if (con != null) { - con.close(); - } - } catch (SQLException e) { - throw new AdsException(e); - } - } - } - - @Override - public void deleteIndex(String index) throws AdsException { - Connection con = null; - Statement stmt = null; - try { - con = ds.getConnection(); - stmt = con.createStatement(); - int res = stmt.executeUpdate(Sql.dropSchema.replace(SCHEMA_NAME_REPLACING_KEY, index)); - log.debug("delete schema:" + res); - stmt.close(); - con.close(); - } catch (SQLException e) { - throw new AdsException(e); - } finally { - try { - if (stmt != null) { - stmt.close(); - } - if (con != null) { - con.close(); - } - } catch (SQLException e) { - throw new AdsException(e); - } - } - } - - IndexPeer getIndexPeer(final String index) { - IndexPeer ip = this.peersMap.get(index); - if (ip != null) { - return ip; - } - ip = new IndexPeer(ds, index); - this.peersMap.put(index, ip); - return ip; - } - - /** - * Indexに対応するオブジェクト. - */ - static class IndexPeer { - DataSource ds; - String index; - String sqlEntityInsert; - String sqlEntityUpdate; - String sqlEntityDelete; - String sqlEntityBulkInsert; - String sqlCellInsert; - String sqlCellUpdate; - String sqlCellDelete; - String sqlLinkInsert; - String sqlLinkUpdate; - String sqlLinkDelete; - String sqlDavNodeInsert; - String sqlDavNodeUpdate; - String sqlDavNodeDelete; - String sqlDavBulkInsert; - String sqlDeleteCellResourceFromEntity; - String sqlDeleteCellResourceFromDavNode; - String sqlDeleteCellResourceFromLink; - String sqlCountCellResourceFromEntity; - String sqlCountCellResourceFromDavNode; - String sqlCountCellResourceFromLink; - String sqlEntitySelect; - String sqlEntityCount; - String sqlCellSelect; - String sqlCellCount; - String sqlLinkSelect; - String sqlLinkCount; - String sqlLinkBulkInsert; - String sqlDavNodeSelect; - String sqlDavNodeCount; - String sqlEntitySearch; - String sqlCellSearch; - String sqlLinkSearch; - String sqlDavNodeSearch; - - // 管理DB用SQL群 - String sqlCellDeleteInsert; - - static final StatementHandler NOP_STATEMENT_HANDLER = new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - writeLog(stmt); - } - }; - static final QueryResultHandler QUERY_RESULT_HANDLER_FOR_COUNT = new QueryResultHandler() { - @Override - public Object handle(ResultSet resultSet) throws AdsException { - try { - if (!resultSet.next()) { - throw new AdsException("No row was returened while 1 row is expected to be returned."); - } - return resultSet.getLong(1); - } catch (SQLException e) { - throw new AdsException(e); - } - } - - @Override - public Object handleQueryIsEmpty() throws AdsException { - throw new AdsException("No row was returened while 1 row is expected to be returned."); - } - }; - - IndexPeer(DataSource ds, String index) { - this.ds = ds; - this.index = index; - this.sqlEntityInsert = Sql.insertEntity.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlEntityUpdate = Sql.updateEntity.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlEntityDelete = Sql.deleteEntity.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlEntityBulkInsert = Sql.bulkInsertEntity.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlCellInsert = Sql.insertCell.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlCellUpdate = Sql.updateCell.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlCellDelete = Sql.deleteCell.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlLinkInsert = Sql.insertLink.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlLinkBulkInsert = Sql.bulkInsertLink.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlLinkUpdate = Sql.updateLink.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlLinkDelete = Sql.deleteLink.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlDavNodeInsert = Sql.insertDavNode.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlDavNodeUpdate = Sql.updateDavNode.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlDavNodeDelete = Sql.deleteDavNode.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlDavBulkInsert = Sql.bulkInsertDav.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlDeleteCellResourceFromEntity = Sql.deleteCellResourceFromEntity - .replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlDeleteCellResourceFromDavNode = Sql.deleteCellResourceFromDavNode - .replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlDeleteCellResourceFromLink = Sql.deleteCellResourceFromLink - .replace(SCHEMA_NAME_REPLACING_KEY, this.index); - - this.sqlCountCellResourceFromEntity = Sql.countCellResourceFromEntity - .replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlCountCellResourceFromDavNode = Sql.countCellResourceFromDavNode - .replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlCountCellResourceFromLink = Sql.countCellResourceFromLink - .replace(SCHEMA_NAME_REPLACING_KEY, this.index); - - this.sqlEntitySelect = Sql.selectEntity.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlEntityCount = Sql.countEntity.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlCellSelect = Sql.selectCell.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlCellCount = Sql.countCell.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlLinkSelect = Sql.selectLink.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlLinkCount = Sql.countLink.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlDavNodeSelect = Sql.selectDav.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlDavNodeCount = Sql.countDav.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - - this.sqlEntitySearch = Sql.searchEntity.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlCellSearch = Sql.searchCell.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlLinkSearch = Sql.searchLink.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - this.sqlDavNodeSearch = Sql.searchDav.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - - // 管理DB用SQL群 - this.sqlCellDeleteInsert = Sql.insertCellDelete.replace(SCHEMA_NAME_REPLACING_KEY, this.index); - } - - void createEntity(final EntitySetDocHandler oedh) throws AdsException { - this.executeUpdateSql(this.sqlEntityInsert, new StatementHandlerForEntity(oedh)); - } - - void updateEntity(final EntitySetDocHandler oedh) throws AdsException { - this.executeUpdateSql(this.sqlEntityUpdate, new StatementHandlerForEntity(oedh)); - } - - void deleteEntity(final String id) throws AdsException { - this.executeUpdateSql(this.sqlEntityDelete, new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(1, id); - writeLog(stmt); - } - }); - } - - void bulkEntity(final List bulkRequestList) throws AdsException { - // 一括登録のSQLを生成する - StringBuilder sql = new StringBuilder(this.sqlEntityBulkInsert); - for (int i = 0; i < bulkRequestList.size(); i++) { - sql.append("(?,?,?,?,?,?,?,?,?,?,?,?)"); - if (i != bulkRequestList.size() - 1) { - sql.append(","); - } - } - this.executeUpdateSql(sql.toString(), new StatementHandlerForBulkEntity(bulkRequestList), - bulkRequestList.size()); - - } - - void bulkUpdateEntityLink(final List bulkRequestList) throws AdsException { - // 一括更新のSQLを生成する - StringBuilder sql = new StringBuilder(this.sqlEntityBulkInsert); - for (int i = 0; i < bulkRequestList.size(); i++) { - sql.append("(?,?,?,?,?,?,?,?,?,?,?,?)"); - if (i != bulkRequestList.size() - 1) { - sql.append(","); - } - } - - sql.append(" on duplicate key update "); - sql.append("links=values(links)"); - - int expectedUpdateCount = bulkRequestList.size() * 2; - this.executeUpdateSql(sql.toString(), new StatementHandlerForBulkEntity(bulkRequestList), - expectedUpdateCount); - - } - - void bulkUpdateDav(List bulkRequestList) throws AdsException { - // 一括更新のSQLを生成する - StringBuilder sql = new StringBuilder(this.sqlDavBulkInsert); - for (int i = 0; i < bulkRequestList.size(); i++) { - sql.append("(?,?,?,?,?,?,?,?,?,?,?)"); - if (i != bulkRequestList.size() - 1) { - sql.append(","); - } - } - - sql.append(" on duplicate key update "); - sql.append("cell_id=values(cell_id)"); - sql.append(",box_id=values(box_id)"); - sql.append(",parent_id=values(parent_id)"); - sql.append(",children=values(children)"); - sql.append(",node_type=values(node_type)"); - sql.append(",acl=values(acl)"); - sql.append(",properties=values(properties)"); - sql.append(",file=values(file)"); - sql.append(",published=values(published)"); - sql.append(",updated=values(updated)"); - sql.append(",id=values(id)"); - - int expectedUpdateCount = bulkRequestList.size() * 2; - this.executeUpdateSql(sql.toString(), new StatementHandlerForBulkDav(bulkRequestList), - expectedUpdateCount); - - } - - void bulkCreateLink(final List bulkRequestList) throws AdsException { - // 一括登録のSQLを生成する - StringBuilder sql = new StringBuilder(this.sqlLinkBulkInsert); - for (int i = 0; i < bulkRequestList.size(); i++) { - sql.append("(?,?,?,?,?,?,?,?,?,?)"); - if (i != bulkRequestList.size() - 1) { - sql.append(","); - } - } - this.executeUpdateSql(sql.toString(), new StatementHandlerForBulkLink(bulkRequestList), - bulkRequestList.size()); - - } - - void createCell(final EntitySetDocHandler docHandler) throws AdsException { - this.executeUpdateSql(this.sqlCellInsert, new StatementHandlerForCell(docHandler)); - } - - void updateCell(final EntitySetDocHandler docHandler) throws AdsException { - this.executeUpdateSql(this.sqlCellUpdate, new StatementHandlerForCell(docHandler)); - } - - void deleteCell(final String id) throws AdsException { - this.executeUpdateSql(this.sqlCellDelete, new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(1, id); - writeLog(stmt); - } - }); - } - - void createLink(final LinkDocHandler ldh) throws AdsException { - this.executeUpdateSql(this.sqlLinkInsert, new StatementHandlerForLink(ldh)); - } - - void updateLink(final LinkDocHandler ldh) throws AdsException { - this.executeUpdateSql(this.sqlLinkUpdate, new StatementHandlerForLink(ldh)); - } - - void deleteLink(final String id) throws AdsException { - this.executeUpdateSql(this.sqlLinkDelete, new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(1, id); - writeLog(stmt); - } - }); - } - - void createDavNode(final DavNode davNode) throws AdsException { - this.executeUpdateSql(this.sqlDavNodeInsert, new StatementHandlerForDavNode(davNode)); - } - - void updateDavNode(final DavNode davNode) throws AdsException { - this.executeUpdateSql(this.sqlDavNodeUpdate, new StatementHandlerForDavNode(davNode)); - } - - void deleteDavNode(final String id) throws AdsException { - this.executeUpdateSql(this.sqlDavNodeDelete, new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(1, id); - writeLog(stmt); - } - }); - } - - void deleteCellResourceFromEntity(final String cellId) throws AdsException { - this.executeDeleteByQuerySql(this.sqlDeleteCellResourceFromEntity, - this.sqlCountCellResourceFromEntity, new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(1, cellId); - writeLog(stmt); - } - }); - } - - void deleteCellResourceFromDavNode(final String cellId) throws AdsException { - this.executeDeleteByQuerySql(this.sqlDeleteCellResourceFromDavNode, - this.sqlCountCellResourceFromDavNode, new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(1, cellId); - writeLog(stmt); - } - }); - } - - void deleteCellResourceFromLink(final String cellId) throws AdsException { - this.executeDeleteByQuerySql(this.sqlDeleteCellResourceFromLink, - this.sqlCountCellResourceFromLink, new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(1, cellId); - writeLog(stmt); - } - }); - } - - void insertCellDeleteRecord(String dbName, String cellId) throws AdsException { - String[] tableNames = {"ENTITY", "LINK", "DAV_NODE" }; - for (String tableName : tableNames) { - this.executeUpdateSql(this.sqlCellDeleteInsert, - new StatementHandlerForCellDelete(dbName, tableName, cellId)); - } - } - - Long countEntity() throws AdsException { - Object ret = this.executeQuerySql( - this.sqlEntityCount, - NOP_STATEMENT_HANDLER, - QUERY_RESULT_HANDLER_FOR_COUNT); - return (Long) ret; - } - - Long countCell() throws AdsException { - Object ret = this.executeQuerySql( - this.sqlCellCount, - NOP_STATEMENT_HANDLER, - QUERY_RESULT_HANDLER_FOR_COUNT); - return (Long) ret; - } - - Long countLink() throws AdsException { - Object ret = this.executeQuerySql( - this.sqlLinkCount, - NOP_STATEMENT_HANDLER, - QUERY_RESULT_HANDLER_FOR_COUNT); - return (Long) ret; - } - - Long countDavNode() throws AdsException { - Object ret = this.executeQuerySql( - this.sqlDavNodeCount, - NOP_STATEMENT_HANDLER, - QUERY_RESULT_HANDLER_FOR_COUNT); - return (Long) ret; - } - - @SuppressWarnings("unchecked") - List getEntityList(final long offset, final long size) throws AdsException { - Object ret = this.executeQuerySql( - this.sqlEntitySelect, - new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setLong(1, offset); - stmt.setLong(2, size); - } - }, - createEntityQueryResultHandler()); - return (List) ret; - } - - private QueryResultHandler createEntityQueryResultHandler() { - return new QueryResultHandler() { - @Override - public Object handle(ResultSet resultSet) throws AdsException { - try { - List ret = new ArrayList(); - while (resultSet.next()) { - ret.add(getEntityJsonObject(resultSet)); - } - return ret; - } catch (SQLException e) { - throw new AdsException(e); - } - } - - @Override - public Object handleQueryIsEmpty() throws AdsException { - return new ArrayList(); - } - }; - } - - @SuppressWarnings("unchecked") - private JSONObject getEntityJsonObject(ResultSet resultSet) - throws SQLException { - JSONObject json = new JSONObject(); - json.put("type", resultSet.getString(Sql.IDX_ENTITY_TYPE)); - json.put("id", resultSet.getString(Sql.NUMCOLS_ENTITY)); - JSONObject source = new JSONObject(); - json.put("source", source); - source.put(OEntityDocHandler.KEY_CELL_ID, - resultSet.getString(Sql.IDX_ENTITY_CELL_ID)); - source.put(OEntityDocHandler.KEY_BOX_ID, - resultSet.getString(Sql.IDX_ENTITY_BOX_ID)); - source.put(OEntityDocHandler.KEY_NODE_ID, - resultSet.getString(Sql.IDX_ENTITY_NODE_ID)); - source.put(OEntityDocHandler.KEY_ENTITY_ID, - resultSet.getString(Sql.IDX_ENTITY_ENTITY_ID)); - source.put(OEntityDocHandler.KEY_STATIC_FIELDS, - resultSet.getString(Sql.IDX_ENTITY_DECLARED_PROPS)); - source.put(OEntityDocHandler.KEY_DYNAMIC_FIELDS, - resultSet.getString(Sql.IDX_ENTITY_DYNAMIC_PROPS)); - source.put(OEntityDocHandler.KEY_HIDDEN_FIELDS, - resultSet.getString(Sql.IDX_ENTITY_HIDDEN_FIELDS)); - source.put(OEntityDocHandler.KEY_LINK, - resultSet.getString(Sql.IDX_ENTITY_LINKS)); - source.put(OEntityDocHandler.KEY_PUBLISHED, - resultSet.getString(Sql.IDX_ENTITY_PUBLISHED)); - source.put(OEntityDocHandler.KEY_UPDATED, - resultSet.getString(Sql.IDX_ENTITY_UPDATED)); - return json; - } - - @SuppressWarnings("unchecked") - List getCellList(final long offset, final long size) throws AdsException { - Object ret = this.executeQuerySql( - this.sqlCellSelect, - new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setLong(1, offset); - stmt.setLong(2, size); - } - }, - createCellQueryResultHandler()); - return (List) ret; - } - - private QueryResultHandler createCellQueryResultHandler() { - return new QueryResultHandler() { - @Override - public Object handle(ResultSet resultSet) throws AdsException { - try { - List ret = new ArrayList(); - while (resultSet.next()) { - ret.add(getCellJsonObject(resultSet)); - } - return ret; - } catch (SQLException e) { - throw new AdsException(e); - } - } - - @Override - public Object handleQueryIsEmpty() throws AdsException { - return new ArrayList(); - } - }; - } - - @SuppressWarnings("unchecked") - private JSONObject getCellJsonObject(ResultSet resultSet) throws SQLException { - JSONObject json = new JSONObject(); - json.put("type", resultSet.getString(Sql.IDX_CELL_TYPE)); - json.put("id", resultSet.getString(Sql.NUMCOLS_CELL)); - JSONObject source = new JSONObject(); - json.put("source", source); - source.put(CellDocHandler.KEY_CELL_ID, - resultSet.getString(Sql.IDX_CELL_CELL_ID)); - source.put(CellDocHandler.KEY_BOX_ID, - resultSet.getString(Sql.IDX_CELL_BOX_ID)); - source.put(CellDocHandler.KEY_NODE_ID, - resultSet.getString(Sql.IDX_CELL_NODE_ID)); - source.put(CellDocHandler.KEY_STATIC_FIELDS, - resultSet.getString(Sql.IDX_CELL_DECLARED_PROPS)); - source.put(CellDocHandler.KEY_DYNAMIC_FIELDS, - resultSet.getString(Sql.IDX_CELL_DYNAMIC_PROPS)); - source.put(CellDocHandler.KEY_HIDDEN_FIELDS, - resultSet.getString(Sql.IDX_CELL_HIDDEN_FIELDS)); - source.put(CellDocHandler.KEY_LINK, - resultSet.getString(Sql.IDX_CELL_LINKS)); - source.put(CellDocHandler.KEY_ACL_FIELDS, - resultSet.getString(Sql.IDX_CELL_ACL_FIELDS)); - source.put(CellDocHandler.KEY_PUBLISHED, - resultSet.getString(Sql.IDX_CELL_PUBLISHED)); - source.put(CellDocHandler.KEY_UPDATED, - resultSet.getString(Sql.IDX_CELL_UPDATED)); - return json; - } - - @SuppressWarnings("unchecked") - List getLinkList(final long offset, final long size) throws AdsException { - Object ret = this.executeQuerySql( - this.sqlLinkSelect, - new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setLong(1, offset); - stmt.setLong(2, size); - writeLog(stmt); - } - }, - createLinkQueryResultHandler()); - return (List) ret; - } - - private QueryResultHandler createLinkQueryResultHandler() { - return new QueryResultHandler() { - @Override - public Object handle(ResultSet resultSet) throws AdsException { - try { - List ret = new ArrayList(); - while (resultSet.next()) { - ret.add(getLinkJsonObject(resultSet)); - } - return ret; - } catch (SQLException e) { - throw new AdsException(e); - } - } - - @Override - public Object handleQueryIsEmpty() throws AdsException { - return new ArrayList(); - } - }; - } - - @SuppressWarnings("unchecked") - private JSONObject getLinkJsonObject(ResultSet resultSet) throws SQLException { - JSONObject json = new JSONObject(); - json.put("type", "link"); - json.put("id", resultSet.getString(Sql.NUMCOLS_LINK)); - JSONObject source = new JSONObject(); - json.put("source", source); - // // LINK 操作 SQLの 項目数 - // static final int NUMCOLS_LINK = 10; - // // 各項目の順序 - // static final int IDX_LINK_CELL_ID = 1; - // static final int IDX_LINK_BOX_ID = 2; - // static final int IDX_LINK_NODE_ID = 3; - // static final int IDX_LINK_ENT1_TYPE = 4; - // static final int IDX_LINK_ENT1_ID = 5; - // static final int IDX_LINK_ENT2_TYPE = 6; - // static final int IDX_LINK_ENT2_ID = 7; - // static final int IDX_LINK_PUBLISHED = 8; - // static final int IDX_LINK_UPDATED = 9; - // - source.put(LinkDocHandler.KEY_CELL_ID, - resultSet.getString(Sql.IDX_LINK_CELL_ID)); - source.put(LinkDocHandler.KEY_BOX_ID, - resultSet.getString(Sql.IDX_LINK_BOX_ID)); - source.put(LinkDocHandler.KEY_NODE_ID, - resultSet.getString(Sql.IDX_LINK_NODE_ID)); - source.put(LinkDocHandler.KEY_ENT1_TYPE, - resultSet.getString(Sql.IDX_LINK_ENT1_TYPE)); - source.put(LinkDocHandler.KEY_ENT1_ID, - resultSet.getString(Sql.IDX_LINK_ENT1_ID)); - source.put(LinkDocHandler.KEY_ENT2_TYPE, - resultSet.getString(Sql.IDX_LINK_ENT2_TYPE)); - source.put(LinkDocHandler.KEY_ENT2_ID, - resultSet.getString(Sql.IDX_LINK_ENT2_ID)); - source.put(OEntityDocHandler.KEY_PUBLISHED, - resultSet.getString(Sql.IDX_LINK_PUBLISHED)); - source.put(OEntityDocHandler.KEY_UPDATED, - resultSet.getString(Sql.IDX_LINK_UPDATED)); - return json; - } - - @SuppressWarnings("unchecked") - List getDavNodeList(final long offset, final long size) throws AdsException { - Object ret = this.executeQuerySql( - this.sqlDavNodeSelect, - new StatementHandler() { - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setLong(1, offset); - stmt.setLong(2, size); - writeLog(stmt); - } - }, - createDavNodeQueryResultHandler() - ); - return (List) ret; - } - - private QueryResultHandler createDavNodeQueryResultHandler() { - return new QueryResultHandler() { - @Override - public Object handle(ResultSet resultSet) throws AdsException { - try { - List ret = new ArrayList(); - while (resultSet.next()) { - ret.add(getDavNodeJsonObject(resultSet)); - } - return ret; - } catch (SQLException e) { - throw new AdsException(e); - } - } - - @Override - public Object handleQueryIsEmpty() throws AdsException { - return new ArrayList(); - } - }; - } - - @SuppressWarnings("unchecked") - private JSONObject getDavNodeJsonObject(ResultSet resultSet) - throws SQLException { - JSONObject json = new JSONObject(); - json.put("type", "dav"); - json.put("id", resultSet.getString(Sql.NUMCOLS_DAVNODE)); - JSONObject source = new JSONObject(); - json.put("source", source); - - // // DAV_NODE 操作 SQLの 項目数 - // static final int NUMCOLS_DAVNODE = 10; - // // 各項目の順序 - // static final int IDX_DAVNODE_CELL_ID = 1; - // static final int IDX_DAVNODE_BOX_ID = 2; - // static final int IDX_DAVNODE_PARENT = 3; - // static final int IDX_DAVNODE_CHILDREN = 4; - // static final int IDX_DAVNODE_NODE_TYPE = 5; - // static final int IDX_DAVNODE_ACL = 6; - // static final int IDX_DAVNODE_PROPERTIES = 7; - // static final int IDX_DAVNODE_PUBLISHED = 8; - // static final int IDX_DAVNODE_UPDATED = 9; - source.put(DavNode.KEY_CELL_ID, - resultSet.getString(Sql.IDX_DAVNODE_CELL_ID)); - source.put(DavNode.KEY_BOX_ID, - resultSet.getString(Sql.IDX_DAVNODE_BOX_ID)); - source.put(DavNode.KEY_PARENT, - resultSet.getString(Sql.IDX_DAVNODE_PARENT)); - source.put(DavNode.KEY_CHILDREN, - resultSet.getString(Sql.IDX_DAVNODE_CHILDREN)); - source.put(DavNode.KEY_NODE_TYPE, - resultSet.getString(Sql.IDX_DAVNODE_NODE_TYPE)); - source.put(DavNode.KEY_ACL, - resultSet.getString(Sql.IDX_DAVNODE_ACL)); - source.put(DavNode.KEY_PROPS, - resultSet.getString(Sql.IDX_DAVNODE_PROPERTIES)); - source.put(DavNode.KEY_FILE, - resultSet.getString(Sql.IDX_DAVNODE_FILE)); - source.put(DavNode.KEY_PUBLISHED, - resultSet.getString(Sql.IDX_DAVNODE_PUBLISHED)); - source.put(DavNode.KEY_UPDATED, - resultSet.getString(Sql.IDX_DAVNODE_UPDATED)); - return json; - } - - private String createSearchSqlQueryString(final String sql, final List idList) { - // uuidリストを使用した検索用SQLを作成する。 - StringBuilder sqlbuf = new StringBuilder(sql + "("); - for (int i = 0; i < idList.size(); i++) { - sqlbuf.append("?"); - if (i != idList.size() - 1) { - sqlbuf.append(","); - } - } - sqlbuf.append(")"); - return sqlbuf.toString(); - } - - @SuppressWarnings("unchecked") - List searchEntityList(final List idList) throws AdsException { - String sql = createSearchSqlQueryString(this.sqlEntitySearch, idList); - Object ret = this.executeQuerySql(sql, new StatementHandlerForSearch(idList), - createEntityQueryResultHandler()); - return (List) ret; - } - - @SuppressWarnings("unchecked") - List searchCellList(final List idList) throws AdsException { - String sql = createSearchSqlQueryString(this.sqlCellSearch, idList); - Object ret = this.executeQuerySql(sql, new StatementHandlerForSearch(idList), - createCellQueryResultHandler()); - return (List) ret; - } - - @SuppressWarnings("unchecked") - List searchLinkList(final List idList) throws AdsException { - String sql = createSearchSqlQueryString(this.sqlLinkSearch, idList); - Object ret = this.executeQuerySql(sql, new StatementHandlerForSearch(idList), - new QueryResultHandler() { - @Override - public Object handle(ResultSet resultSet) throws AdsException { - try { - List ret = new ArrayList(); - while (resultSet.next()) { - ret.add(getLinkJsonObject(resultSet)); - } - return ret; - } catch (SQLException e) { - throw new AdsException(e); - } - } - - @Override - public Object handleQueryIsEmpty() throws AdsException { - return new ArrayList(); - } - }); - return (List) ret; - } - - @SuppressWarnings("unchecked") - List searchDavNodeList(final List idList) throws AdsException { - String sql = createSearchSqlQueryString(this.sqlDavNodeSearch, idList); - Object ret = this.executeQuerySql(sql, new StatementHandlerForSearch(idList), - createDavNodeQueryResultHandler()); - return (List) ret; - } - - Connection getConnection() throws AdsException { - try { - // 接続する。 - Connection con = ds.getConnection(); - // DBCP経由だと以下のようなデータベースの切り替えは うまくいかない模様。 - // con.setSchema(index); - // なのでDBの選択は個別のSQLに埋め込む設計としている。 - return con; - } catch (SQLException e) { - PersoniumCoreLog.Server.RDB_CONNECT_FAIL.params(e.getMessage()).reason(e).writeLog(); - throw new AdsException(e); - } - } - - Object executeQuerySql(String sql, StatementHandler sp, - QueryResultHandler queryResultHandler) throws AdsException { - log.debug(sql); - Connection con = this.getConnection(); - PreparedStatement stmt = null; - try { - stmt = con.prepareStatement(sql); - sp.handle(stmt); - ResultSet rs = stmt.executeQuery(); - if (!rs.next()) { - return queryResultHandler.handleQueryIsEmpty(); - } - rs.beforeFirst(); - return queryResultHandler.handle(rs); - } catch (SQLException e) { - PersoniumCoreLog.Server.EXECUTE_QUERY_SQL_FAIL.params(e.getMessage()).reason(e).writeLog(); - throw new AdsException(e); - } finally { - try { - stmt.close(); - con.close(); - } catch (SQLException e) { - PersoniumCoreLog.Server.RDB_DISCONNECT_FAIL.params(e.getMessage()).reason(e).writeLog(); - throw new AdsException(e); - } - } - } - - void executeDeleteByQuerySql(String deleteSql, - String countSql, - StatementHandler sp) throws AdsException { - Connection con = this.getConnection(); - PreparedStatement stmt = null; - try { - stmt = con.prepareStatement(deleteSql); - sp.handle(stmt); - PersoniumCoreLog.Server.JDBC_EXEC_SQL.params( - ((DelegatingPreparedStatement) stmt).getDelegate().toString()).writeLog(); - stmt.executeUpdate(); - if (!AUTO_COMMIT) { - con.commit(); - } - } catch (SQLException e) { - throw new AdsException(e); - } finally { - try { - stmt.close(); - } catch (SQLException e) { - PersoniumCoreLog.Server.RDB_DISCONNECT_FAIL.params(e.getMessage()).reason(e).writeLog(); - throw new AdsException(e); - } - } - - try { - // 件数の確認 - stmt = con.prepareStatement(countSql); - sp.handle(stmt); - ResultSet resultSet = stmt.executeQuery(); // NOPMD - PMDのバグのためチェックから除外 - long count = 0; - if (resultSet.next()) { - count = resultSet.getLong(1); - } else { - throw new AdsException("No row was returened while 1 row is expected to be returned."); - } - if (count != 0) { - throw new AdsException(String.format( - "[%d] rows have been affected while 0 row is expected to be affected.", count)); - } - } catch (SQLException e) { - throw new AdsException(e); - } finally { - try { - stmt.close(); - con.close(); - } catch (SQLException e) { - PersoniumCoreLog.Server.RDB_DISCONNECT_FAIL.params(e.getMessage()).reason(e).writeLog(); - throw new AdsException(e); - } - } - } - - void executeUpdateSql(String sql, StatementHandler sp) throws AdsException { - executeUpdateSql(sql, sp, 1); - } - - void executeUpdateSql(String sql, StatementHandler sp, int expectedCount) throws AdsException { - Connection con = this.getConnection(); - PreparedStatement stmt = null; - try { - stmt = con.prepareStatement(sql); - sp.handle(stmt); - int count = stmt.executeUpdate(); - if (!AUTO_COMMIT) { - con.commit(); - } - if (count != expectedCount) { - throw new AdsException("[" - + count + "] rows have been affected while " + expectedCount - + " row is expected to be affected."); - } - } catch (SQLException e) { - PersoniumCoreLog.Server.JDBC_EXEC_SQL.params( - ((DelegatingPreparedStatement) stmt).getDelegate().toString()).writeLog(); - throw new AdsException(e); - } finally { - try { - stmt.close(); - con.close(); - } catch (SQLException e) { - PersoniumCoreLog.Server.RDB_DISCONNECT_FAIL.params(e.getMessage()).reason(e).writeLog(); - throw new AdsException(e); - } - } - } - - /** - * SQLのPreparedStatementを受け取ってプレースホルダに値を埋め込むHandler. - */ - abstract static class StatementHandler { - abstract void handle(PreparedStatement stmt) throws SQLException; - - void writeLog(PreparedStatement stmt) { - PersoniumCoreLog.Server.JDBC_EXEC_SQL.params( - ((DelegatingPreparedStatement) stmt).getDelegate().toString()).writeLog(); - } - } - - /** - * Entityを扱うためのStatementHandler. - */ - static class StatementHandlerForEntity extends StatementHandler { - EntitySetDocHandler oedh; - - StatementHandlerForEntity(EntitySetDocHandler oedh) { - this.oedh = oedh; - } - - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(Sql.IDX_ENTITY_TYPE, oedh.getType()); - stmt.setString(Sql.IDX_ENTITY_CELL_ID, oedh.getCellId()); - stmt.setString(Sql.IDX_ENTITY_BOX_ID, oedh.getBoxId()); - stmt.setString(Sql.IDX_ENTITY_NODE_ID, oedh.getNodeId()); - stmt.setString(Sql.IDX_ENTITY_ENTITY_ID, oedh.getEntityTypeId()); - stmt.setString(Sql.IDX_ENTITY_DECLARED_PROPS, this.oedh.getStaticFieldsString()); - stmt.setString(Sql.IDX_ENTITY_DYNAMIC_PROPS, this.oedh.getDynamicFieldsString()); - stmt.setString(Sql.IDX_ENTITY_HIDDEN_FIELDS, this.oedh.getHiddenFieldsString()); - stmt.setString(Sql.IDX_ENTITY_LINKS, this.oedh.getManyToOnelinkIdString()); - stmt.setLong(Sql.IDX_ENTITY_PUBLISHED, oedh.getPublished()); - stmt.setLong(Sql.IDX_ENTITY_UPDATED, oedh.getUpdated()); - stmt.setString(Sql.NUMCOLS_ENTITY, oedh.getId()); - if (UserDataODataProducer.USER_ODATA_NAMESPACE.equals(oedh.getType())) { - PersoniumCoreLog.Server.JDBC_USER_ODATA_SQL.params(oedh.getUnitUserName(), "ENTITY", oedh.getId(), - oedh.getType(), oedh.getCellId(), oedh.getBoxId(), oedh.getNodeId(), - oedh.getEntityTypeId()).writeLog(); - } else { - writeLog(stmt); - } - } - } - - /** - * BulkEntityを扱うためのStatementHandler. - */ - static class StatementHandlerForBulkEntity extends StatementHandler { - List bulkRequestList; - - StatementHandlerForBulkEntity(List bulkRequestList) { - this.bulkRequestList = bulkRequestList; - } - - @Override - public void handle(PreparedStatement stmt) throws SQLException { - int index = 1; - for (EntitySetDocHandler docHandler : bulkRequestList) { - stmt.setString(index++, docHandler.getType()); - stmt.setString(index++, docHandler.getCellId()); - stmt.setString(index++, docHandler.getBoxId()); - stmt.setString(index++, docHandler.getNodeId()); - stmt.setString(index++, docHandler.getEntityTypeId()); - stmt.setString(index++, docHandler.getStaticFieldsString()); - stmt.setString(index++, docHandler.getDynamicFieldsString()); - stmt.setString(index++, docHandler.getHiddenFieldsString()); - stmt.setString(index++, docHandler.getManyToOnelinkIdString()); - stmt.setLong(index++, docHandler.getPublished()); - stmt.setLong(index++, docHandler.getUpdated()); - stmt.setString(index++, docHandler.getId()); - } - } - } - - /** - * BulkLinkを扱うためのStatementHandler. - */ - static class StatementHandlerForBulkLink extends StatementHandler { - List bulkRequestList; - - StatementHandlerForBulkLink(List bulkRequestList) { - this.bulkRequestList = bulkRequestList; - } - - @Override - public void handle(PreparedStatement stmt) throws SQLException { - int index = 1; - for (LinkDocHandler docHandler : bulkRequestList) { - stmt.setString(index++, docHandler.getCellId()); - stmt.setString(index++, docHandler.getBoxId()); - stmt.setString(index++, docHandler.getNodeId()); - stmt.setString(index++, docHandler.getEnt1Type()); - stmt.setString(index++, docHandler.getEnt1Key()); - stmt.setString(index++, docHandler.getEnt2Type()); - stmt.setString(index++, docHandler.getEnt2Key()); - stmt.setLong(index++, docHandler.getPublished()); - stmt.setLong(index++, docHandler.getUpdated()); - stmt.setString(index++, docHandler.getId()); - } - } - } - - /** - * CellEntityを扱うためのStatementHandler. - */ - static class StatementHandlerForCell extends StatementHandler { - EntitySetDocHandler docHandler; - - StatementHandlerForCell(EntitySetDocHandler docHandler) { - this.docHandler = docHandler; - } - - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(Sql.IDX_CELL_TYPE, docHandler.getType()); - stmt.setString(Sql.IDX_CELL_CELL_ID, docHandler.getCellId()); - stmt.setString(Sql.IDX_CELL_BOX_ID, docHandler.getBoxId()); - stmt.setString(Sql.IDX_CELL_NODE_ID, docHandler.getNodeId()); - stmt.setString(Sql.IDX_CELL_DECLARED_PROPS, docHandler.getStaticFieldsString()); - stmt.setString(Sql.IDX_CELL_DYNAMIC_PROPS, docHandler.getDynamicFieldsString()); - stmt.setString(Sql.IDX_CELL_HIDDEN_FIELDS, docHandler.getHiddenFieldsString()); - stmt.setString(Sql.IDX_CELL_LINKS, docHandler.getManyToOnelinkIdString()); - stmt.setString(Sql.IDX_CELL_ACL_FIELDS, JSONObject.toJSONString(docHandler.getAclFields())); - stmt.setLong(Sql.IDX_CELL_PUBLISHED, docHandler.getPublished()); - stmt.setLong(Sql.IDX_CELL_UPDATED, docHandler.getUpdated()); - stmt.setString(Sql.NUMCOLS_CELL, docHandler.getId()); - writeLog(stmt); - } - } - - /** - * Linkを扱うためのStatementHandler. - */ - static class StatementHandlerForLink extends StatementHandler { - LinkDocHandler ldh; - - StatementHandlerForLink(LinkDocHandler ldh) { - this.ldh = ldh; - } - - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(Sql.IDX_LINK_CELL_ID, ldh.getCellId()); - stmt.setString(Sql.IDX_LINK_BOX_ID, ldh.getBoxId()); - stmt.setString(Sql.IDX_LINK_NODE_ID, ldh.getNodeId()); - stmt.setString(Sql.IDX_LINK_ENT1_TYPE, ldh.getEnt1Type()); - stmt.setString(Sql.IDX_LINK_ENT1_ID, ldh.getEnt1Key()); - stmt.setString(Sql.IDX_LINK_ENT2_TYPE, ldh.getEnt2Type()); - stmt.setString(Sql.IDX_LINK_ENT2_ID, ldh.getEnt2Key()); - stmt.setLong(Sql.IDX_LINK_PUBLISHED, ldh.getPublished()); - stmt.setLong(Sql.IDX_LINK_UPDATED, ldh.getUpdated()); - stmt.setString(Sql.NUMCOLS_LINK, ldh.getId()); - writeLog(stmt); - } - } - - /** - * DavNodeを扱うためのStatementHandler. - */ - static class StatementHandlerForDavNode extends StatementHandler { - DavNode davNode; - - StatementHandlerForDavNode(DavNode davNode) { - this.davNode = davNode; - } - - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(Sql.IDX_DAVNODE_CELL_ID, davNode.getCellId()); - stmt.setString(Sql.IDX_DAVNODE_BOX_ID, davNode.getBoxId()); - stmt.setString(Sql.IDX_DAVNODE_PARENT, davNode.getParentId()); - stmt.setString(Sql.IDX_DAVNODE_CHILDREN, JSONObject.toJSONString(davNode.getChildren())); - stmt.setString(Sql.IDX_DAVNODE_NODE_TYPE, davNode.getNodeType()); - stmt.setString(Sql.IDX_DAVNODE_ACL, JSONObject.toJSONString(davNode.getAcl())); - stmt.setString(Sql.IDX_DAVNODE_PROPERTIES, JSONObject.toJSONString(davNode.getProperties())); - String file = null; - if (davNode.getFile() != null) { - file = JSONObject.toJSONString(davNode.getFile()); - } - stmt.setString(Sql.IDX_DAVNODE_FILE, file); - stmt.setLong(Sql.IDX_DAVNODE_PUBLISHED, davNode.getPublished()); - stmt.setLong(Sql.IDX_DAVNODE_UPDATED, davNode.getUpdated()); - stmt.setString(Sql.NUMCOLS_DAVNODE, davNode.getId()); - writeLog(stmt); - } - } - - /** - * BulkDavを扱うためのStatementHandler. - */ - static class StatementHandlerForBulkDav extends StatementHandler { - List bulkRequestList; - - StatementHandlerForBulkDav(List bulkRequestList) { - this.bulkRequestList = bulkRequestList; - } - - @Override - public void handle(PreparedStatement stmt) throws SQLException { - int index = 1; - for (DavNode docHandler : bulkRequestList) { - stmt.setString(index++, docHandler.getCellId()); - stmt.setString(index++, docHandler.getBoxId()); - stmt.setString(index++, docHandler.getParentId()); - stmt.setString(index++, JSONObject.toJSONString(docHandler.getChildren())); - stmt.setString(index++, docHandler.getNodeType()); - stmt.setString(index++, JSONObject.toJSONString(docHandler.getAcl())); - stmt.setString(index++, JSONObject.toJSONString(docHandler.getProperties())); - String file = null; - if (docHandler.getFile() != null) { - file = JSONObject.toJSONString(docHandler.getFile()); - } - stmt.setString(index++, file); - stmt.setLong(index++, docHandler.getPublished()); - stmt.setLong(index++, docHandler.getUpdated()); - stmt.setString(index++, docHandler.getId()); - } - } - } - - /** - * セル削除管理を扱うためのStatementHandler. - */ - static class StatementHandlerForCellDelete extends StatementHandler { - String dbName; - String tableName; - String cellId; - - StatementHandlerForCellDelete(String dbName, String tableName, String cellId) { - this.dbName = dbName; - this.tableName = tableName; - this.cellId = cellId; - } - - @Override - public void handle(PreparedStatement stmt) throws SQLException { - stmt.setString(Sql.IDX_CELL_DELETE_DB_NAME, dbName); - stmt.setString(Sql.IDX_CELL_DELETE_TABLE_NAME, tableName); - stmt.setString(Sql.IDX_CELL_DELETE_CELL_ID, cellId); - writeLog(stmt); - } - } - - /** - * Entityテーブルを検索するためのStatementHandler. - */ - static class StatementHandlerForSearch extends StatementHandler { - List idList; - - StatementHandlerForSearch(List idList) { - this.idList = idList; - } - - @Override - public void handle(PreparedStatement stmt) throws SQLException { - int index = 1; - for (String uuid : idList) { - stmt.setString(index++, uuid); - } - } - } - - /** - * PreStatementに. - */ - interface QueryResultHandler { - Object handleQueryIsEmpty() throws AdsException; - - Object handle(ResultSet resultSet) throws AdsException; - } - } - - /** - * 使用するSQLのテンプレートをStaticで保持しておくクラス. - */ - static class Sql { - static String createSchema = - PersoniumCoreUtils.readStringResource("es/ads/ddl-createschema.sql", CharEncoding.UTF_8); - static String dropSchema = - PersoniumCoreUtils.readStringResource("es/ads/ddl-dropschema.sql", CharEncoding.UTF_8); - static String createTableEntity = - PersoniumCoreUtils.readStringResource("es/ads/ddl-createtable-entity.sql", CharEncoding.UTF_8); - static String createTableLink = - PersoniumCoreUtils.readStringResource("es/ads/ddl-createtable-link.sql", CharEncoding.UTF_8); - static String createTableDavNode = - PersoniumCoreUtils.readStringResource("es/ads/ddl-createtable-davnode.sql", CharEncoding.UTF_8); - static String createTableCell = - PersoniumCoreUtils.readStringResource("es/ads/ddl-createtable-cell.sql", CharEncoding.UTF_8); - static String createManagementTableCellDelete = - PersoniumCoreUtils.readStringResource("es/ads/ddl-create-management-table-cell-delete.sql", - CharEncoding.UTF_8); - - static String insertEntity = - PersoniumCoreUtils.readStringResource("es/ads/entity-insert.sql", CharEncoding.UTF_8); - static String updateEntity = - PersoniumCoreUtils.readStringResource("es/ads/entity-update.sql", CharEncoding.UTF_8); - static String deleteEntity = - PersoniumCoreUtils.readStringResource("es/ads/entity-delete.sql", CharEncoding.UTF_8); - static String bulkInsertEntity = - PersoniumCoreUtils.readStringResource("es/ads/entity-bulk-insert.sql", CharEncoding.UTF_8); - - static String insertCell = - PersoniumCoreUtils.readStringResource("es/ads/cell-insert.sql", CharEncoding.UTF_8); - static String updateCell = - PersoniumCoreUtils.readStringResource("es/ads/cell-update.sql", CharEncoding.UTF_8); - static String deleteCell = - PersoniumCoreUtils.readStringResource("es/ads/cell-delete.sql", CharEncoding.UTF_8); - - static String insertLink = - PersoniumCoreUtils.readStringResource("es/ads/link-insert.sql", CharEncoding.UTF_8); - static String updateLink = - PersoniumCoreUtils.readStringResource("es/ads/link-update.sql", CharEncoding.UTF_8); - static String deleteLink = - PersoniumCoreUtils.readStringResource("es/ads/link-delete.sql", CharEncoding.UTF_8); - static String bulkInsertLink = - PersoniumCoreUtils.readStringResource("es/ads/link-bulk-insert.sql", CharEncoding.UTF_8); - - static String insertDavNode = - PersoniumCoreUtils.readStringResource("es/ads/dav-insert.sql", CharEncoding.UTF_8); - static String updateDavNode = - PersoniumCoreUtils.readStringResource("es/ads/dav-update.sql", CharEncoding.UTF_8); - static String deleteDavNode = - PersoniumCoreUtils.readStringResource("es/ads/dav-delete.sql", CharEncoding.UTF_8); - static String bulkInsertDav = - PersoniumCoreUtils.readStringResource("es/ads/dav-bulk-insert.sql", CharEncoding.UTF_8); - - static String deleteCellResourceFromEntity = - PersoniumCoreUtils.readStringResource("es/ads/delete-cellresource-from-entity.sql", CharEncoding.UTF_8); - static String deleteCellResourceFromDavNode = - PersoniumCoreUtils.readStringResource("es/ads/delete-cellresource-from-davnode.sql", - CharEncoding.UTF_8); - static String deleteCellResourceFromLink = - PersoniumCoreUtils.readStringResource("es/ads/delete-cellresource-from-link.sql", CharEncoding.UTF_8); - - static String countCellResourceFromEntity = - PersoniumCoreUtils.readStringResource("es/ads/count-cellresource-from-entity.sql", CharEncoding.UTF_8); - static String countCellResourceFromDavNode = - PersoniumCoreUtils.readStringResource("es/ads/count-cellresource-from-davnode.sql", CharEncoding.UTF_8); - static String countCellResourceFromLink = - PersoniumCoreUtils.readStringResource("es/ads/count-cellresource-from-link.sql", CharEncoding.UTF_8); - - static String selectEntity = - PersoniumCoreUtils.readStringResource("es/ads/entity-select.sql", CharEncoding.UTF_8); - static String countEntity = - PersoniumCoreUtils.readStringResource("es/ads/entity-count.sql", CharEncoding.UTF_8); - static String selectCell = - PersoniumCoreUtils.readStringResource("es/ads/cell-select.sql", CharEncoding.UTF_8); - static String countCell = - PersoniumCoreUtils.readStringResource("es/ads/cell-count.sql", CharEncoding.UTF_8); - static String selectLink = - PersoniumCoreUtils.readStringResource("es/ads/link-select.sql", CharEncoding.UTF_8); - static String countLink = - PersoniumCoreUtils.readStringResource("es/ads/link-count.sql", CharEncoding.UTF_8); - static String selectDav = - PersoniumCoreUtils.readStringResource("es/ads/dav-select.sql", CharEncoding.UTF_8); - static String countDav = - PersoniumCoreUtils.readStringResource("es/ads/dav-count.sql", CharEncoding.UTF_8); - - static String searchEntity = - PersoniumCoreUtils.readStringResource("es/ads/entity-search.sql", CharEncoding.UTF_8); - static String searchCell = - PersoniumCoreUtils.readStringResource("es/ads/cell-search.sql", CharEncoding.UTF_8); - static String searchLink = - PersoniumCoreUtils.readStringResource("es/ads/link-search.sql", CharEncoding.UTF_8); - static String searchDav = - PersoniumCoreUtils.readStringResource("es/ads/dav-search.sql", CharEncoding.UTF_8); - - // Cell管理用SQL群 - static String insertCellDelete = - PersoniumCoreUtils.readStringResource("es/ads/celldelete-insert.sql", CharEncoding.UTF_8); - - // ENTITY 操作 SQLの 項目数 - static final int NUMCOLS_ENTITY = 12; - // 各項目の順序 - static final int IDX_ENTITY_TYPE = 1; - static final int IDX_ENTITY_CELL_ID = 2; - static final int IDX_ENTITY_BOX_ID = 3; - static final int IDX_ENTITY_NODE_ID = 4; - static final int IDX_ENTITY_ENTITY_ID = 5; - static final int IDX_ENTITY_DECLARED_PROPS = 6; - static final int IDX_ENTITY_DYNAMIC_PROPS = 7; - static final int IDX_ENTITY_HIDDEN_FIELDS = 8; - static final int IDX_ENTITY_LINKS = 9; - static final int IDX_ENTITY_PUBLISHED = 10; - static final int IDX_ENTITY_UPDATED = 11; - - // LINK 操作 SQLの 項目数 - static final int NUMCOLS_LINK = 10; - // 各項目の順序 - static final int IDX_LINK_CELL_ID = 1; - static final int IDX_LINK_BOX_ID = 2; - static final int IDX_LINK_NODE_ID = 3; - static final int IDX_LINK_ENT1_TYPE = 4; - static final int IDX_LINK_ENT1_ID = 5; - static final int IDX_LINK_ENT2_TYPE = 6; - static final int IDX_LINK_ENT2_ID = 7; - static final int IDX_LINK_PUBLISHED = 8; - static final int IDX_LINK_UPDATED = 9; - - // DAV_NODE 操作 SQLの 項目数 - static final int NUMCOLS_DAVNODE = 11; - // 各項目の順序 - static final int IDX_DAVNODE_CELL_ID = 1; - static final int IDX_DAVNODE_BOX_ID = 2; - static final int IDX_DAVNODE_PARENT = 3; - static final int IDX_DAVNODE_CHILDREN = 4; - static final int IDX_DAVNODE_NODE_TYPE = 5; - static final int IDX_DAVNODE_ACL = 6; - static final int IDX_DAVNODE_PROPERTIES = 7; - static final int IDX_DAVNODE_FILE = 8; - static final int IDX_DAVNODE_PUBLISHED = 9; - static final int IDX_DAVNODE_UPDATED = 10; - - // ENTITY 操作 SQLの 項目数 - static final int NUMCOLS_CELL = 12; - // 各項目の順序 - static final int IDX_CELL_TYPE = 1; - static final int IDX_CELL_CELL_ID = 2; - static final int IDX_CELL_BOX_ID = 3; - static final int IDX_CELL_NODE_ID = 4; - static final int IDX_CELL_DECLARED_PROPS = 5; - static final int IDX_CELL_DYNAMIC_PROPS = 6; - static final int IDX_CELL_HIDDEN_FIELDS = 7; - static final int IDX_CELL_LINKS = 8; - static final int IDX_CELL_ACL_FIELDS = 9; - static final int IDX_CELL_PUBLISHED = 10; - static final int IDX_CELL_UPDATED = 11; - - // CELL_DELETE 操作 SQLの 項目 - static final int IDX_CELL_DELETE_DB_NAME = 1; - static final int IDX_CELL_DELETE_TABLE_NAME = 2; - static final int IDX_CELL_DELETE_CELL_ID = 3; - } - -} diff --git a/src/main/java/io/personium/core/model/impl/es/ads/package-info.java b/src/main/java/io/personium/core/model/impl/es/ads/package-info.java deleted file mode 100644 index 8202dfae8..000000000 --- a/src/main/java/io/personium/core/model/impl/es/ads/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * 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. - */ -/** - * ESのデータ保全信頼性を補うための正本データ保管機構(Authentic Data Storage)を実装するパッケージ. - */ -package io.personium.core.model.impl.es.ads; diff --git a/src/main/java/io/personium/core/model/impl/es/odata/CellCtlODataProducer.java b/src/main/java/io/personium/core/model/impl/es/odata/CellCtlODataProducer.java index 32494a9e0..f4d475cfe 100644 --- a/src/main/java/io/personium/core/model/impl/es/odata/CellCtlODataProducer.java +++ b/src/main/java/io/personium/core/model/impl/es/odata/CellCtlODataProducer.java @@ -47,6 +47,7 @@ import io.personium.core.model.ctl.ExtCell; import io.personium.core.model.ctl.ReceivedMessage; import io.personium.core.model.ctl.Relation; +import io.personium.core.model.ctl.Role; import io.personium.core.model.ctl.SentMessage; import io.personium.core.model.impl.es.EsModel; import io.personium.core.model.impl.es.accessor.DataSourceAccessor; @@ -263,175 +264,212 @@ protected Map convertNtkpValueToFields( } /** - * 関係登録/削除を行う. - * @param entitySetDocHandler 受信メッセージ - * @param status 変更するStatus + * Perform relationship registration / deletion. + * @param entitySetDocHandler Received message + * @param status Change Status */ private void updateRelation(EntitySetDocHandler entitySetDocHandler, String status) { - String type = (String) entitySetDocHandler.getStaticFields().get(ReceivedMessage.P_TYPE.getName()); if (ReceivedMessage.STATUS_APPROVED.equals(status)) { - // approvedの場合、Relation/ExtCellの登録/削除を行う + // Do register / delete Entity / ExtCell + String type = (String) entitySetDocHandler.getStaticFields().get(ReceivedMessage.P_TYPE.getName()); + + // Get name to be registered + String requestRelation = (String) entitySetDocHandler.getStaticFields().get( + ReceivedMessage.P_REQUEST_RELATION.getName()); + String name = getNameFromRequestRelation(requestRelation, type); + // Get box name + String boxName = getBoxNameFromRequestRelation(requestRelation, type); + if (boxName == null) { + // If box can not be found from RequestRelation (RequestRelation is Name only), + // get BoxName from _ Box.Name + boxName = (String) entitySetDocHandler.getStaticFields().get(ReceivedMessage.P_BOX_NAME.getName()); + } + // Get cell URL to link + String extCellUrl = (String) entitySetDocHandler.getStaticFields().get( + ReceivedMessage.P_REQUEST_RELATION_TARGET.getName()); + if (!extCellUrl.endsWith("/")) { + extCellUrl += "/"; + } + Map entityKeyMap = getEntityKeyMapFromType(name, boxName, type); + + Map extCellKeyMap = new HashMap<>(); + extCellKeyMap.put(ExtCell.P_URL.getName(), extCellUrl); + + // registration / deletion if (ReceivedMessage.TYPE_REQ_RELATION_BUILD.equals(type)) { - buildRelation(entitySetDocHandler); + registerRelation(Relation.EDM_TYPE_NAME, entityKeyMap, extCellKeyMap); } else if (ReceivedMessage.TYPE_REQ_RELATION_BREAK.equals(type)) { - breakRelation(entitySetDocHandler); + deleteRelation(Relation.EDM_TYPE_NAME, entityKeyMap, extCellKeyMap); + } else if (ReceivedMessage.TYPE_REQ_ROLE_GRANT.equals(type)) { + registerRelation(Role.EDM_TYPE_NAME, entityKeyMap, extCellKeyMap); + } else if (ReceivedMessage.TYPE_REQ_ROLE_REVOKE.equals(type)) { + deleteRelation(Role.EDM_TYPE_NAME, entityKeyMap, extCellKeyMap); } } } /** - * 関係登録を行う.
- * 現状はRequestRelationで指定されたURLのRelation名のみ取得して、対象の受信メッセージのCellに
- * Boxと紐付かないRelationを登録する. - * @param entitySetDocHandler 受信メッセージ + * Get Name from RequestRelation. + * @param requestRelation RequestRelation + * @param type message type + * @return RelationName */ - private void buildRelation(EntitySetDocHandler entitySetDocHandler) { - - // 登録対象のRelation名取得 - String requestRelation = (String) entitySetDocHandler.getStaticFields().get( - ReceivedMessage.P_REQUEST_RELATION.getName()); - String relationName = getRelationNameFromRequestRelation(requestRelation); - // Get box name - String boxName = getBoxNameFromRequestRelation(requestRelation); - if (boxName == null) { - // If box can not be found from RequestRelation (RequestRelation is RelationName only), - // get BoxName from _ Box.Name - boxName = (String) entitySetDocHandler.getStaticFields().get(ReceivedMessage.P_BOX_NAME.getName()); - } - - EntitySetDocHandler relation = getRelation(relationName, boxName); - if (relation == null) { - // データが存在しない場合はRelationを新規に登録 - createRelationEntity(relationName, boxName); - } + protected String getNameFromRequestRelation(String requestRelation, String type) { + String name = null; + log.debug(String.format("RequestRelation = [%s]", requestRelation)); - // 関係を結ぶセルURL取得 - String requestExtCell = (String) entitySetDocHandler.getStaticFields().get( - ReceivedMessage.P_REQUEST_RELATION_TARGET.getName()); - if (!requestExtCell.endsWith("/")) { - requestExtCell += "/"; - } - - if (getExtCell(requestExtCell) == null) { - // データが存在しない場合はExtCellを新規に登録 - createExtCellEntity(requestExtCell); + // convert localunitUrl to unitUrl + String convertedRequestRelation = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), requestRelation); + Pattern pattern = Pattern.compile(getRegexFromType(type)); + Matcher m = pattern.matcher(convertedRequestRelation); + if (m.matches()) { + name = m.replaceAll("$3"); + } else { + name = convertedRequestRelation; } - - // RelationとExtCellの$linksを作成 - createRelationExtCellLinks(relationName, boxName, requestExtCell); + return name; } /** - * RelationとExtCellの$links作成. - * @param relationName Relation name - * @param boxName Box name linked to relation - * @param requestExtCell ExtCell name + * Get BoxName from RequestRelation. + * If RequestRelation is only Name, return null. + * @param requestRelation RequestRelation + * @param type message type + * @return BoxName + * @throws PersoniumCoreException Box corresponding to the ClassURL can not be found */ - private void createRelationExtCellLinks(String relationName, String boxName, String requestExtCell) { - try { - OEntityKey relationOEntityKey = createRelationOEntityKey(relationName, boxName); - OEntityId relationEntityId = OEntityIds.create(Relation.EDM_TYPE_NAME, relationOEntityKey); - OEntityKey extCellOEntityKey = createExtCellOEntityKey(requestExtCell); - OEntityId extCellEntityId = OEntityIds.create(ExtCell.EDM_TYPE_NAME, extCellOEntityKey); + protected String getBoxNameFromRequestRelation(String requestRelation, String type) + throws PersoniumCoreException { + String boxName = null; + log.debug(String.format("RequestRelation = [%s]", requestRelation)); - // n:nの場合 - createLinks(relationEntityId, extCellEntityId); - } catch (PersoniumCoreException e) { - if (PersoniumCoreException.OData.CONFLICT_LINKS.getCode().equals(e.getCode())) { - // $linksが既に存在する場合 - throw PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_EXISTS_ERROR; + // convert localunitUrl to unitUrl + String convertedRequestRelation = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), requestRelation); + Pattern pattern = Pattern.compile(getRegexFromType(type)); + Matcher matcher = pattern.matcher(convertedRequestRelation); + if (matcher.matches()) { + String schema = matcher.replaceAll("$1" + "/" + "$2" + "/"); + Box box = this.cell.getBoxForSchema(schema); + if (box != null) { + boxName = box.getName(); + } else { + throw PersoniumCoreException.ReceivedMessage + .BOX_THAT_MATCHES_RELATION_CLASS_URL_NOT_EXISTS.params(convertedRequestRelation); } - throw e; } + return boxName; } - private OEntityKey createExtCellOEntityKey(String requestExtCell) { - OEntityKey extCellOEntityKey; - try { - extCellOEntityKey = OEntityKey.parse("('" + requestExtCell + "')"); - } catch (IllegalArgumentException e) { - throw PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_TARGET_PARSE_ERROR.reason(e); + /** + * Get regex from message type. + * @param type message type + * @return regex + */ + private String getRegexFromType(String type) { + if (ReceivedMessage.TYPE_REQ_RELATION_BUILD.equals(type) + || ReceivedMessage.TYPE_REQ_RELATION_BREAK.equals(type)) { + return Common.PATTERN_RELATION_CLASS_URL; + } else if (ReceivedMessage.TYPE_REQ_ROLE_GRANT.equals(type) + || ReceivedMessage.TYPE_REQ_ROLE_REVOKE.equals(type)) { + return Common.PATTERN_ROLE_CLASS_URL; } - return extCellOEntityKey; + // There is usually no root for else. + // Return empty for the time being. + return ""; } /** - * Create relation key. - * @param relationName relation name + * Get entity key map from message type. + * @param name name * @param boxName box name - * @return relation key + * @param type message type + * @return key map */ - private OEntityKey createRelationOEntityKey(String relationName, String boxName) { - OEntityKey relationOEntityKey; - String parseString; + private Map getEntityKeyMapFromType(String name, String boxName, String type) { + Map entityKeyMap = new HashMap<>(); if (boxName != null) { - parseString = "(" + Relation.P_NAME.getName() + "='" + relationName + "'," - + Common.P_BOX_NAME.getName() + "='" + boxName + "')"; - } else { - parseString = "('" + relationName + "')"; + entityKeyMap.put(Common.P_BOX_NAME.getName(), boxName); } - try { - relationOEntityKey = OEntityKey.parse(parseString); - } catch (IllegalArgumentException e) { - throw PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_PARSE_ERROR.reason(e); + if (ReceivedMessage.TYPE_REQ_RELATION_BUILD.equals(type) + || ReceivedMessage.TYPE_REQ_RELATION_BREAK.equals(type)) { + entityKeyMap.put(Relation.P_NAME.getName(), name); + } else if (ReceivedMessage.TYPE_REQ_ROLE_GRANT.equals(type) + || ReceivedMessage.TYPE_REQ_ROLE_REVOKE.equals(type)) { + entityKeyMap.put(Role.P_NAME.getName(), name); } - return relationOEntityKey; + return entityKeyMap; } /** - * Relationを取得する. - * @param relationName Relation name - * @param boxName Box name - * @return EntitySetDocHandler + * Register relationship. + * @param edmType Entity EDM Type + * @param entityKeyMap Entity key map to be registered + * @param extCellKeyMap ExtCell key map to link */ - protected EntitySetDocHandler getRelation(String relationName, String boxName) { - EdmEntitySet edmEntitySet = getMetadata().getEdmEntitySet(Relation.EDM_TYPE_NAME); - OEntityKey oEntityKey = createRelationOEntityKey(relationName, boxName); + private void registerRelation(String edmType, Map entityKeyMap, Map extCellKeyMap) { + if (getEntitySetDocHandler(edmType, entityKeyMap) == null) { + // If data does not exist, register newly + createOEntity(edmType, entityKeyMap); + } - return retrieveWithKey(edmEntitySet, oEntityKey); + if (getEntitySetDocHandler(ExtCell.EDM_TYPE_NAME, extCellKeyMap) == null) { + // If data does not exist, register newly + createOEntity(ExtCell.EDM_TYPE_NAME, extCellKeyMap); + } + + // Create relationship between Entity and ExtCell + createExtCellLinks(edmType, entityKeyMap, extCellKeyMap); } /** - * ExtCellを取得する. - * @param key キー - * @return EntitySetDocHandler + * Delete relationship. + * @param edmType Entity EDM Type + * @param entityKeyMap Entity key map to be delete + * @param extCellKeyMap ExtCell key map to unlink */ - protected EntitySetDocHandler getExtCell(String key) { - EdmEntitySet edmEntitySet = getMetadata().getEdmEntitySet(ExtCell.EDM_TYPE_NAME); - OEntityKey oEntityKey = createExtCellOEntityKey(key); + private void deleteRelation(String edmType, Map entityKeyMap, Map extCellKeyMap) { + // Confirm that target Entity exists + EntitySetDocHandler entity = getEntitySetDocHandler(edmType, entityKeyMap); + if (entity == null) { + log.debug(String.format("RequestRelation does not exists. Type [%s]. Keys [%s]", + edmType, entityKeyMap.toString())); + throw PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_DOES_NOT_EXISTS.params( + edmType, entityKeyMap.toString()); + } - return retrieveWithKey(edmEntitySet, oEntityKey); - } + // Confirm that target ExtCell exists + EntitySetDocHandler extCell = getEntitySetDocHandler(ExtCell.EDM_TYPE_NAME, extCellKeyMap); + if (extCell == null) { + log.debug(String.format("RequestRelationTarget does not exists. Type [%s]. Keys [%s].", + ExtCell.EDM_TYPE_NAME, extCellKeyMap.toString())); + throw PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_TARGET_DOES_NOT_EXISTS.params( + ExtCell.EDM_TYPE_NAME, extCellKeyMap.toString()); + } - /** - * RelationをESに保存. - * @param relationName Relation name - * @param boxName Link target box name - */ - private void createRelationEntity(String relationName, String boxName) { - // staticFields - Map staticFields = new HashMap(); - staticFields.put(Relation.P_NAME.getName(), relationName); - if (boxName != null) { - staticFields.put(Common.P_BOX_NAME.getName(), boxName); + // Delete relationship between Entity and ExtCell + if (!deleteLinkEntity(entity, extCell)) { + log.debug(String.format("RequestRelation and RequestRelationTarget does not related. " + + "[Type [{%s}]. Keys[{%s}]] - [Type {%s}. Keys[{%s}]]", + edmType, entityKeyMap.toString(), ExtCell.EDM_TYPE_NAME, extCellKeyMap.toString())); + throw PersoniumCoreException.ReceivedMessage.LINK_DOES_NOT_EXISTS.params( + edmType, entityKeyMap.toString(), ExtCell.EDM_TYPE_NAME, extCellKeyMap.toString()); } - createEntity(Relation.EDM_TYPE_NAME, staticFields); } /** - * ExtCellをESに保存. - * @param key ExtCellのUrlの値 + * Get EntitySetDocHandler. + * @param edmType edm type + * @param entityKeyMap entity key map + * @return EntitySetDocHandler */ - private void createExtCellEntity(String key) { - - // staticFields - Map staticFields = new HashMap(); - staticFields.put(ExtCell.P_URL.getName(), key); + protected EntitySetDocHandler getEntitySetDocHandler(String edmType, Map entityKeyMap) { + EdmEntitySet edmEntitySet = getMetadata().getEdmEntitySet(edmType); + OEntityKey oEntityKey = OEntityKey.create(entityKeyMap); - createEntity(ExtCell.EDM_TYPE_NAME, staticFields); + return retrieveWithKey(edmEntitySet, oEntityKey); } /** @@ -439,7 +477,7 @@ private void createExtCellEntity(String key) { * @param typeName 登録するデータのType名 * @param staticFields 登録するstaticFieldsの値 */ - private void createEntity(String typeName, Map staticFields) { + private void createOEntity(String typeName, Map staticFields) { EntitySetAccessor esType = this.getAccessorForEntitySet(typeName); // EntitySetDocHandlerの作成 @@ -448,7 +486,7 @@ private void createEntity(String typeName, Map staticFields) { oedh.setId(PersoniumUUID.randomUUID()); // staticFields - oedh.setStaticFields(staticFields); + oedh.setStaticFields(new HashMap(staticFields)); // Cell, Box, Nodeの紐付 oedh.setCellId(this.getCellId()); @@ -497,95 +535,28 @@ private void setLinksFromOEntityKey(OEntityKey key, String typeName, EntitySetDo } /** - * 関係削除を行う. - * @param entitySetDocHandler 受信メッセージ + * Create $link with ExtCell. + * @param edmType Entity EDM Type + * @param entityKeyMap Entity key map + * @param extCellKeyMap ExtCell key map */ - protected void breakRelation(EntitySetDocHandler entitySetDocHandler) { - log.debug("breakRelation start."); - // RequestRelationからRelation名を取得する - String reqRelation = entitySetDocHandler.getStaticFields() - .get(ReceivedMessage.P_REQUEST_RELATION.getName()).toString(); - String relationName = getRelationNameFromRequestRelation(reqRelation); - // Get box name - String boxName = getBoxNameFromRequestRelation(reqRelation); - if (boxName == null) { - // If box can not be found from RequestRelation (RequestRelation is RelationName only), - // get BoxName from _ Box.Name - boxName = (String) entitySetDocHandler.getStaticFields().get(ReceivedMessage.P_BOX_NAME.getName()); - } - - // 対象のRelationが存在することを確認 - EntitySetDocHandler relation = getRelation(relationName, boxName); - if (relation == null) { - log.debug(String.format("RequestRelation does not exists. [%s]", relationName)); - throw PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_DOES_NOT_EXISTS.params(relationName); - } - - // 対象のExtCell(RequestRelationTarget)が存在することを確認 - String extCellUrl = entitySetDocHandler.getStaticFields() - .get(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName()).toString(); - EntitySetDocHandler extCell = getExtCell(extCellUrl); - if (extCell == null) { - log.debug(String.format("RequestRelationTarget does not exists. [%s]", extCellUrl)); - throw PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_TARGET_DOES_NOT_EXISTS.params(extCellUrl); - } - - // RelationとExtCellの関連を削除する - if (!deleteLinkEntity(relation, extCell)) { - log.debug(String.format("RequestRelation and RequestRelationTarget does not related. [%s] - [%s]", - relationName, extCellUrl)); - throw PersoniumCoreException.ReceivedMessage.LINK_DOES_NOT_EXISTS.params(relationName, extCellUrl); - } - log.debug("breakRelation success."); - } - - /** - * Get BoxName from RequestRelation. - * If RequestRelation is only RelationName, return null. - * @param requestRelation RequestRelation - * @return BoxName - * @throws PersoniumCoreException Box corresponding to the RelationClassURL can not be found - */ - protected String getBoxNameFromRequestRelation(String requestRelation) throws PersoniumCoreException { - String boxName = null; - log.debug(String.format("RequestRelation URI = [%s]", requestRelation)); + private void createExtCellLinks(String edmType, + Map entityKeyMap, Map extCellKeyMap) { + try { + OEntityKey oEntityKey = OEntityKey.create(entityKeyMap); + OEntityId entityId = OEntityIds.create(edmType, oEntityKey); + OEntityKey extCellOEntityKey = OEntityKey.create(extCellKeyMap); + OEntityId extCellEntityId = OEntityIds.create(ExtCell.EDM_TYPE_NAME, extCellOEntityKey); - // convert localunitUrl to unitUrl - String convertedRequestRelation = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), requestRelation); - Pattern pattern = Pattern.compile(Common.PATTERN_RELATION_CLASS_URL); - Matcher matcher = pattern.matcher(convertedRequestRelation); - if (matcher.matches()) { - String schema = matcher.replaceAll("$1" + "/" + "$2" + "/"); - Box box = this.cell.getBoxForSchema(schema); - if (box != null) { - boxName = box.getName(); - } else { - throw PersoniumCoreException.ReceivedMessage - .BOX_THAT_MATCHES_RELATION_CLASS_URL_NOT_EXISTS.params(convertedRequestRelation); + // n:nの場合 + createLinks(entityId, extCellEntityId); + } catch (PersoniumCoreException e) { + if (PersoniumCoreException.OData.CONFLICT_LINKS.getCode().equals(e.getCode())) { + // $linksが既に存在する場合 + throw PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_EXISTS_ERROR; } + throw e; } - return boxName; - } - - /** - * Get RelationName from RequestRelation. - * @param requestRelation RequestRelation - * @return RelationName - */ - protected String getRelationNameFromRequestRelation(String requestRelation) { - String relationName = null; - log.debug(String.format("RequestRelation URI = [%s]", requestRelation)); - - // convert localunitUrl to unitUrl - String convertedRequestRelation = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), requestRelation); - Pattern pattern = Pattern.compile(Common.PATTERN_RELATION_CLASS_URL); - Matcher m = pattern.matcher(convertedRequestRelation); - if (m.matches()) { - relationName = m.replaceAll("$3"); - } else { - relationName = convertedRequestRelation; - } - return relationName; } /** @@ -610,9 +581,11 @@ protected boolean isValidMessageStatus(String type, String status) { * @return boolean */ protected boolean isValidRelationStatus(String type, String status) { - // build or breakの場合のみバリデートをして、approved / rejectedであればtrueを返却する + // Validate only for relation registration / deletion, and return true if approved / rejected if (type.equals(ReceivedMessage.TYPE_REQ_RELATION_BUILD) - || type.equals(ReceivedMessage.TYPE_REQ_RELATION_BREAK)) { + || type.equals(ReceivedMessage.TYPE_REQ_RELATION_BREAK) + || type.equals(ReceivedMessage.TYPE_REQ_ROLE_GRANT) + || type.equals(ReceivedMessage.TYPE_REQ_ROLE_REVOKE)) { return ReceivedMessage.STATUS_APPROVED.equals(status) || ReceivedMessage.STATUS_REJECTED.equals(status); } @@ -626,9 +599,11 @@ protected boolean isValidRelationStatus(String type, String status) { * @return boolean */ protected boolean isValidCurrentStatus(String type, String status) { - // build or breakの場合のみバリデートをして、none であればtrueを返却する + // Validate only for relation registration / deletion, and return true if none if (type.equals(ReceivedMessage.TYPE_REQ_RELATION_BUILD) - || type.equals(ReceivedMessage.TYPE_REQ_RELATION_BREAK)) { + || type.equals(ReceivedMessage.TYPE_REQ_RELATION_BREAK) + || type.equals(ReceivedMessage.TYPE_REQ_ROLE_GRANT) + || type.equals(ReceivedMessage.TYPE_REQ_ROLE_REVOKE)) { return ReceivedMessage.STATUS_NONE.equals(status); } return true; diff --git a/src/main/java/io/personium/core/model/impl/es/repair/AdsAccessor.java b/src/main/java/io/personium/core/model/impl/es/repair/AdsAccessor.java deleted file mode 100644 index c36674da2..000000000 --- a/src/main/java/io/personium/core/model/impl/es/repair/AdsAccessor.java +++ /dev/null @@ -1,217 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.repair; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import org.json.simple.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.ads.AdsWriteFailureLogInfo; -import io.personium.common.es.response.PersoniumSearchHit; -import io.personium.common.es.response.PersoniumSearchResponse; -import io.personium.core.PersoniumCoreException; -import io.personium.core.model.Cell; -import io.personium.core.model.impl.es.DavNode; -import io.personium.core.model.impl.es.ads.Ads; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.ads.JdbcAds; -import io.personium.core.model.impl.es.doc.CellDocHandler; -import io.personium.core.model.impl.es.doc.EntitySetDocHandler; -import io.personium.core.model.impl.es.doc.LinkDocHandler; -import io.personium.core.model.impl.es.doc.OEntityDocHandler; -import io.personium.core.model.impl.es.doc.UserDataDocHandler; -import io.personium.core.model.impl.es.odata.UserDataODataProducer; - -/** - * データストア層(ADS)への操作処理を実装したクラス. - */ -public class AdsAccessor { - - /** ログ用オブジェクト. */ - static Logger logger = LoggerFactory.getLogger(AdsAccessor.class); - - private static Ads ads; - - /** - * デフォルトコンストラクタ(使用不可). - */ - private AdsAccessor() { - } - - /** - * ADSを初期化する. - * この際、接続チェックも行う。 - * @return 初期化に成功した場合は trueを、それ以外は falseを返す。 - */ - public static boolean initializedAds() { - try { - ads = new JdbcAds(); - ((JdbcAds) ads).checkConnection(); - } catch (AdsException e) { - logger.error("Ads connection failed.", e); - return false; - } - return true; - } - - /** - * ADSからリペア対象のデータが存在するか検索をする. - * @param logInfo ログから読み込んだADS書き込み失敗情報 - * @return リペア対象のデータの検索結果 - * @throws AdsException AdsException - */ - public static List getIdListOnAds(AdsWriteFailureLogInfo logInfo) throws AdsException { - List idList = new ArrayList(); - idList.add(logInfo.getUuid()); - - String indexName = logInfo.getIndexName(); - String type = logInfo.getType(); - if (Cell.EDM_TYPE_NAME.equals(type)) { - return ads.searchCellList(indexName, idList); - } else if ("link".equals(type)) { - return ads.searchLinkList(indexName, idList); - } else if ("dav".equals(type)) { - return ads.searchDavNodeList(indexName, idList); - } else { - return ads.searchEntityList(indexName, idList); - } - } - - /** - * リペア対象のデータをADSに登録する. - * @param indexName リペア対象インデックス名 - * @param type リペア対象のESのタイプ名 - * @param esResponse ESから取得したリペア対象のデータ情報 - * @throws AdsException AdsException - */ - public static void createAds(String indexName, String type, - PersoniumSearchResponse esResponse) throws AdsException { - // MySQLへデータ登録処理 - PersoniumSearchHit[] personiumSearchHit = esResponse.getHits().getHits(); - try { - if (Cell.EDM_TYPE_NAME.equals(type)) { - // CELLテーブルに登録 - EntitySetDocHandler oedh = new CellDocHandler(personiumSearchHit[0]); - ads.createCell(indexName, oedh); - } else if ("link".equals(type)) { - // LINKテーブルに登録 - LinkDocHandler ldh = new LinkDocHandler(personiumSearchHit[0]); - ads.createLink(indexName, ldh); - } else if ("dav".equals(type)) { - // DAV_NODEテーブルに登録 - DavNode davNode = DavNode.createFromJsonString(personiumSearchHit[0].getId(), - personiumSearchHit[0].sourceAsString()); - ads.createDavNode(indexName, davNode); - } else { - // ENTITYテーブルに登録 - EntitySetDocHandler oedh; - if (type.equals(UserDataODataProducer.USER_ODATA_NAMESPACE)) { - oedh = new UserDataDocHandler(personiumSearchHit[0]); - } else { - oedh = new OEntityDocHandler(personiumSearchHit[0]); - } - - if (oedh.getDynamicFields() == null) { - // リペア対象のデータのDynamicFieldsが空の場合にAdsのデータがnullになってしまうので空オブジェクトを挿入 - // DocHandlerでの修正も検討したが、既存のcore側の処理に影響を与えないようここで修正 - oedh.setDynamicFields(new HashMap()); - } - - ads.createEntity(indexName, oedh); - } - } catch (PersoniumCoreException e) { - throw new AdsException(e); - } - } - - /** - * リペア対象のデータをADSに更新する. - * @param indexName リペア対象インデックス名 - * @param type リペア対象タイプ名 - * @param esResponse ESから取得したリペア対象のデータ情報 - * @throws AdsException AdsException - */ - public static void updateAds(String indexName, String type, - PersoniumSearchResponse esResponse) throws AdsException { - try { - // MySQLへデータ更新処理 - PersoniumSearchHit[] personiumSearchHit = esResponse.getHits().getHits(); - if (Cell.EDM_TYPE_NAME.equals(type)) { - // CELLテーブルに更新 - EntitySetDocHandler oedh = new CellDocHandler(personiumSearchHit[0]); - ads.updateCell(indexName, oedh); - } else if ("link".equals(type)) { - // LINKテーブルに更新 - LinkDocHandler ldh = new LinkDocHandler(personiumSearchHit[0]); - ads.updateLink(indexName, ldh); - } else if ("dav".equals(type)) { - // DAV_NODEテーブルに更新 - DavNode davNode = DavNode.createFromJsonString(personiumSearchHit[0].getId(), - personiumSearchHit[0].sourceAsString()); - ads.updateDavNode(indexName, davNode); - } else { - // ENTITYテーブルに更新 - EntitySetDocHandler oedh; - if (type.equals(UserDataODataProducer.USER_ODATA_NAMESPACE)) { - oedh = new UserDataDocHandler(personiumSearchHit[0]); - } else { - oedh = new OEntityDocHandler(personiumSearchHit[0]); - } - - if (oedh.getDynamicFields() == null) { - // リペア対象のデータのDynamicFieldsが空の場合にAdsのデータがnullになってしまうので空オブジェクトを挿入 - // DocHandlerでの修正も検討したが、既存のcore側の処理に影響を与えないようここで修正 - oedh.setDynamicFields(new HashMap()); - } - - ads.updateEntity(indexName, oedh); - } - } catch (PersoniumCoreException e) { - throw new AdsException(e); - } - - } - - /** - * リペア対象のデータをADSに削除する. - * @param indexName リペア対象インデックス名 - * @param type リペア対象タイプ名 - * @param idList リペア対象のuuid - * @throws AdsException AdsException - */ - public static void deleteAds(String indexName, String type, - String idList) throws AdsException { - // MySQLへデータ削除処理 - if (Cell.EDM_TYPE_NAME.equals(type)) { - // CELLテーブルに削除 - ads.deleteCell(indexName, idList); - } else if ("link".equals(type)) { - // LINKテーブルに削除 - ads.deleteLink(indexName, idList); - } else if ("dav".equals(type)) { - // DAV_NODEテーブルに削除 - ads.deleteDavNode(indexName, idList); - } else { - // ENTITYテーブルに削除 - ads.deleteEntity(indexName, idList); - } - } -} diff --git a/src/main/java/io/personium/core/model/impl/es/repair/EsAccessor.java b/src/main/java/io/personium/core/model/impl/es/repair/EsAccessor.java deleted file mode 100644 index 6456dc96e..000000000 --- a/src/main/java/io/personium/core/model/impl/es/repair/EsAccessor.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.repair; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.es.EsIndex; -import io.personium.common.es.response.PersoniumSearchResponse; -import io.personium.common.es.response.EsClientException; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.impl.es.EsModel; -import io.personium.core.model.impl.es.QueryMapFactory; - -/** - * データストア層(Elasticsearch)への操作処理を実装したクラス. - */ -public class EsAccessor { - - /** ログ用オブジェクト. */ - static Logger log = LoggerFactory.getLogger(EsAccessor.class); - - /** - * デフォルトコンストラクタ(使用不可). - */ - private EsAccessor() { - } - - /** - * ドキュメントを検索. - * @param indexName 検索対象のインデックス名 - * @param routingId 検索時のルーティングID - * @param idList 検索対象のuuidリスト - * @param type タイプ名 - * @return 検索結果 - * @throws EsClientException ESへの検索に失敗した場合 - */ - public static PersoniumSearchResponse search(final String indexName, - final String routingId, - final List idList, - final String type) - throws EsClientException { - - // TODO クエリを作成する箇所とESへリクエストする箇所を別のメソッドにする。 - // IDとTypeで検索する。 - Map query = new HashMap(); - List> queries = new ArrayList>(); - Map ids = new HashMap(); - Map idValues = new HashMap(); - Map typeFilter = new HashMap(); - Map typeValue = new HashMap(); - - query.put("filter", QueryMapFactory.mustQuery(queries)); - // ids - queries.add(ids); - ids.put("ids", idValues); - idValues.put("values", idList); - // typeFilter - queries.add(typeFilter); - typeFilter.put("type", typeValue); - typeValue.put("value", type); - // version - query.put("version", true); - // size - query.put("size", idList.size()); - // リペアツールでは、アクセス先が特定のインデックスに限らないため、その都度EsIndexを生成する。 - // TODO コスト的に問題がないのかを確認する必要あり。 - EsIndex index = getEsIndex(indexName); - return index.search(routingId, query); - } - - /** - * インデックス名に応じたEsIndex インスタンスを取得する. - * @param indexName インデックス名(unit prefix付き) - * @return 生成した EsIndex インスタンス - */ - private static EsIndex getEsIndex(final String indexName) { - final String cellIndexName = EsIndex.CATEGORY_AD; - String unitUserName = indexName.replace(PersoniumUnitConfig.getEsUnitPrefix() + "_", ""); - if (cellIndexName.equals(unitUserName)) { - return EsModel.idxAdmin(); - } else { - return EsModel.idxUser(unitUserName); - } - } -} diff --git a/src/main/java/io/personium/core/model/impl/es/repair/PersoniumRepairAdsException.java b/src/main/java/io/personium/core/model/impl/es/repair/PersoniumRepairAdsException.java deleted file mode 100644 index 4e7bbbcef..000000000 --- a/src/main/java/io/personium/core/model/impl/es/repair/PersoniumRepairAdsException.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.repair; - -/** - * ADSへのデータ補正時にスローする例外. - */ -public class PersoniumRepairAdsException extends Exception { - - /** - * デフォルトシリアルバージョンID. - */ - private static final long serialVersionUID = 1L; - - /** - * コンストラクタ. - * @param msg メッセージ - * @param cause 原因となったThrowable - */ - public PersoniumRepairAdsException(String msg, Throwable cause) { - super(msg, cause); - } - - /** - * コンストラクタ. - * @param msg メッセージ - */ - public PersoniumRepairAdsException(String msg) { - super(msg); - } - -} diff --git a/src/main/java/io/personium/core/model/impl/es/repair/RepairAds.java b/src/main/java/io/personium/core/model/impl/es/repair/RepairAds.java deleted file mode 100644 index c0274612b..000000000 --- a/src/main/java/io/personium/core/model/impl/es/repair/RepairAds.java +++ /dev/null @@ -1,567 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.repair; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.json.simple.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.ads.AbstractAdsWriteFailureLog; -import io.personium.common.ads.AdsWriteFailureLogException; -import io.personium.common.ads.AdsWriteFailureLogFilter; -import io.personium.common.ads.AdsWriteFailureLogInfo; -import io.personium.common.ads.AdsWriteFailureLogWriter; -import io.personium.common.ads.RollingAdsWriteFailureLog; -import io.personium.common.es.EsIndex; -import io.personium.common.es.response.EsClientException; -import io.personium.common.es.response.PersoniumSearchHits; -import io.personium.common.es.response.PersoniumSearchResponse; -import io.personium.core.PersoniumCoreException; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.Cell; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.lock.Lock; -import io.personium.core.model.lock.LockManager; - -/** - * ADSへのデータ補正処理を実装したクラス. - *

- * 本クラスでは、ADS書き込み失敗ログを読み込み、Elasticsearch上のデータを基準としてADSへのデータ補正を実施する。 データ補正処理は singletonとし、personium-coreの - * ScheduleExecutorServiceにて一定間隔で実行する。 なお、本処理の内容は、PCSのAPIとは異なるため、別ファイルとしてログを出力する。 - *

- */ -public class RepairAds { - - static Logger logger = LoggerFactory.getLogger(RepairAds.class); - - private static RepairAds singleton; - static { - singleton = new RepairAds(); - } - private String pcsVersion; - private String adsLogBaseDirPath; - private File adsLogBaseDir; - private boolean physicalDelete; - private int logCountPerIteration; - // 処理中のADS書き込み失敗ログのファイル名に付加されているタイムスタンプ - // TODO AdsWriteFailureLogWriterクラスから取得するように見直す。 - private long createTime; - - /** - * デフォルトコンストラクタ(使用不可). - */ - private RepairAds() { - super(); - } - - /** - * インスタンスの取得. - * @return singletonインスタンス - */ - public static RepairAds getInstance() { - if (null == singleton) { - singleton = new RepairAds(); - } - return singleton; - } - - /** - * ADSへのデータ補正を実施するメイン処理. - * TODO OutOfMemoryErrorが発生した場合、ここで対処しておく必要があるか? - * (singletonのオブジェクトをクリアするなどの対処) - * TODO 全般的にエラーが連続して発生する場合のログ出力抑止を検討すること。 - */ - public void repairAds() { - - try { - logger.info("Ads repair process started."); - - // プロパティ情報の読み込み - readProperties(); - - if (!AdsAccessor.initializedAds()) { - // MySQLへの初回接続に失敗したため、リペアツールを異常終了させる - throw new RepairAdsException("Failed to connect MySQL master."); - } - - // ADS書き込み失敗ログファイルの一覧取得とファイルのソート(created timestamp) - Map logFilesMap = collectAdsWriteFailureLogFiles(); - if (logFilesMap.isEmpty()) { - logger.info("AdsWriteFailureLog does not exist. Terminate the repair process."); - return; - } - - // リペア処理本体 - // - ADS書き込み失敗ログファイルの読み込み(一定量での読み込み) - // - リペア有無判定とリペア方法選別 - // - ADSへのリペア(Memcachedへのロックを含む) - for (Map.Entry map : logFilesMap.entrySet()) { - File logFile = map.getValue(); - this.createTime = map.getKey(); - logger.info("Starting repair. Repairlog file: " + logFile.toString()); - readAdsWriteFialureLog(logFile); - logger.info("Finished repair. Repairlog file: " + logFile.toString()); - } - - if (isRepairCompleted()) { - // INFOログに出力されるとログ情報が膨大なため調査困難と監視が検知できない場合が発生する。このためリペア完了メッセージはERRORレベルで対応する - logger.error("All ads repair process is completed on " + pcsVersion + "."); - } else { - logger.info("Ads repair process is completed. Remained target files will be processed later."); - } - } catch (Throwable e) { - // TODO 同じエラーは抑止しておきたい。 - // - 最後にまとめて失敗したログファイルを出す? - // - 前回からのエラーも検出したいので、static変数でログ出力可否を判定する? - logger.error("An error is detected in ads repair process.", e); - } finally { - rotateRetryAndErrorLog(); - } - } - - /** - * リペア処理中に出力されたリトライ用/エラー用のADS書き込み失敗ログをローテートする. - */ - private void rotateRetryAndErrorLog() { - AdsWriteFailureLogWriter errorlog = AdsWriteFailureLogWriter.getInstanceforError( - adsLogBaseDir.getAbsolutePath(), pcsVersion, PersoniumUnitConfig.getAdsWriteFailureLogPhysicalDelete()); - AdsWriteFailureLogWriter retrylog = AdsWriteFailureLogWriter.getInstanceforRetry( - adsLogBaseDir.getAbsolutePath(), pcsVersion, PersoniumUnitConfig.getAdsWriteFailureLogPhysicalDelete()); - // エラー用ADS書き込み失敗ログをローテートする - try { - if (errorlog.isExistsAdsWriteFailureLogs()) { - errorlog.rotateActiveFile(); - } - } catch (AdsWriteFailureLogException e1) { - logger.warn("Failed to rotate errorAdsWriteFailureLog.", e1); - } - // リトライ用ADS書き込み失敗ログをローテートする - try { - if (retrylog.isExistsAdsWriteFailureLogs()) { - retrylog.rotateActiveFile(); - } - } catch (AdsWriteFailureLogException e1) { - logger.warn("Failed to rotate retryAdsWriteFailureLog.", e1); - } - } - - /** - * プロパティ情報を読み込む. - */ - private void readProperties() { - pcsVersion = PersoniumUnitConfig.getCoreVersion(); - adsLogBaseDirPath = PersoniumUnitConfig.getAdsWriteFailureLogDir(); - adsLogBaseDir = new File(adsLogBaseDirPath); - physicalDelete = PersoniumUnitConfig.getAdsWriteFailureLogPhysicalDelete(); - logCountPerIteration = PersoniumUnitConfig.getAdsWriteFailureLogCountPerIteration(); - } - - /** - * ファイル作成時刻でソートしたADS書き込み失敗ログのファイル一覧を取得する. - * @return ADS書き込み失敗ログのファイル一覧 - * @throws RepairAdsException 実行環境に問題が発生した場合 - */ - private Map collectAdsWriteFailureLogFiles() throws RepairAdsException { - // TreeMapを使い、ファイル名のsuffixについた作成時刻をキーにして自動的にソートされるようにしておく。 - Map logFilesMap = new TreeMap(); - - if (!adsLogBaseDir.isDirectory()) { - String message = String.format("Configuration is wrong, invalid adsWriteFailureLog directory [%s]", - adsLogBaseDir.getAbsolutePath()); - throw new RepairAdsException(message); - } - - File[] logFiles = adsLogBaseDir.listFiles(new AdsWriteFailureLogFilter(pcsVersion)); - for (File logFile : logFiles) { - // この時点でファイル名フォーマットは正しいのでsuffixからファイルの作成時刻を抽出しMapに格納する。 - String fileNamePrefix = String.format("adsWriteFailure_%s.log.", pcsVersion); - String createdTimeStr = logFile.getName().replace(fileNamePrefix, ""); - // リトライ用ADS失敗ログの場合はファイル名の最後に「.retry」が付加されているので、削除してファイルの作成時刻だけにする - createdTimeStr = createdTimeStr.replace(AbstractAdsWriteFailureLog.RETRY_LOGNAME_SUFFIX, ""); - long createdTime = Long.parseLong(createdTimeStr); - logFilesMap.put(createdTime, logFile); - } - return logFilesMap; - } - - /** - * エラー用ADS書き込み失敗ログのファイルが存在するかどうかを返却する. - * @return true baseDir配下にエラー用ADS書き込み失敗ファイルが存在する - * false baseDir配下にエラー用ADS書き込み失敗ファイルが存在しない - * @throws RepairAdsException 実行環境に問題が発生した場合 - */ - private boolean existsErrorLog() throws RepairAdsException { - if (!adsLogBaseDir.isDirectory()) { - String message = String.format("Configuration is wrong, invalid adsWriteFailureLog directory [%s]", - adsLogBaseDir.getAbsolutePath()); - throw new RepairAdsException(message); - } - - File[] logFiles = adsLogBaseDir.listFiles(); - for (File logFile : logFiles) { - if (logFile.getName().endsWith(AbstractAdsWriteFailureLog.ERROR_LOGNAME_SUFFIX)) { - return true; - } - } - return false; - } - - /** - * アクティブログが存在するかを返却する. - * @return true baseDir配下アクティブのADS書き込み失敗ファイルが存在する - * false baseDir配下にアクティブのADS書き込み失敗ファイルが存在しない - * @throws RepairAdsException 実行環境に問題が発生した場合 - */ - private boolean existsActiveLog() throws RepairAdsException { - if (!adsLogBaseDir.isDirectory()) { - String message = String.format("Configuration is wrong, invalid adsWriteFailureLog directory [%s]", - adsLogBaseDir.getAbsolutePath()); - throw new RepairAdsException(message); - } - - File[] logFiles = adsLogBaseDir.listFiles(); - for (File logFile : logFiles) { - String regex = "adsWriteFailure_" + pcsVersion + "_\\d{13}.log"; - Pattern p = Pattern.compile(regex); - Matcher m = p.matcher(logFile.getName()); - if (m.find()) { - return true; - } - } - return false; - } - - /** - * ADS書き込み失敗ログを1ファイルずつ読み込み、ADSへデータ補正する. - * @param logFile ローテートされたADS書き込み失敗ログ - */ - private void readAdsWriteFialureLog(File logFile) throws RepairAdsException { - RollingAdsWriteFailureLog adsLog = new RollingAdsWriteFailureLog( - logFile, adsLogBaseDirPath, pcsVersion, physicalDelete); - try { - while (true) { - // ADS書き込み失敗ログを読み込み、ログ出力情報を作成する。 - List logRecords = adsLog.readAdsFailureLog(logCountPerIteration); - if (null == logRecords || logRecords.size() == 0) { - break; - } - List rowsData = new ArrayList(logRecords.size()); - - for (int i = 0; i < logRecords.size(); i++) { - try { - // 各行のフォーマットチェック - AdsWriteFailureLogInfo logInfo = AdsWriteFailureLogInfo.parse(logRecords.get(i)); - // セル再帰的削除のリペアは未サポートのため退避ログに出力しスキップ - if (AdsWriteFailureLogInfo.OperationKind.PCS_MANAGEMENT_INSERT - == AdsWriteFailureLogInfo.OperationKind.fromValue(logInfo.getOperation())) { - writeAdsErrorLog(logInfo.toString()); - logger.warn("CellBulkDeletion is not supported by Master Repair."); - continue; - } - rowsData.add(logInfo); - } catch (AdsWriteFailureLogException e) { - // ADS書き込み失敗ログの内容のフォーマットが不正 - // 該当行はエラーとし、次の行を読み込む - writeAdsErrorLog(logRecords.get(i)); - logger.error("Failed to parse adsWriteFailureLog.", e); - } - } - Map> mapOfOdataLock = - new HashMap>(); - // データ書き込み時のOData空間キーごとにADS書き込み失敗ログから読み込んだログ出力情報を集約する。 - // 同じデータに対するログが複数存在する場合は、後勝ちとする。 - for (AdsWriteFailureLogInfo logInfo : rowsData) { - String key = logInfo.getIndexName() + "_" + logInfo.getLockKey(); - updateAdsWriteFailureLogMap(mapOfOdataLock, logInfo, key); - } - for (Entry> sourceLogInfo : mapOfOdataLock.entrySet()) { - executeRepairAds(sourceLogInfo.getValue()); - } - } - } catch (AdsWriteFailureLogException e) { - // ここでエラーとなった場合は、呼び出し元に戻り、次のADS書き込み失敗ログの処理に移行する。 - String message = String.format("Failed to read rotated adsWriteFailureLog. [%s]", - logFile.getAbsoluteFile()); - logger.error(message, e); - // エラー発生のため、ADS出力失敗ログは削除せず、クローズのみとしておく - adsLog.closeRotatedFile(); - return; - } - try { - // 正常終了のため、ADS出力失敗ログのクローズおよび削除を行う - adsLog.deleteRotatedLog(); - } catch (AdsWriteFailureLogException e) { - logger.error("Faild to delete adsWriteFailureLog.", e); - } - } - - /** - * OData空間ごとに管理しているリペア情報を新たに読み込んだ情報で更新する. - * @param map OData空間ごとに管理しているリペア情報のマップ - * @param logInfo ログから読み込んだADS書き込み失敗情報 - * @param key mapへアクセスするためのキー - */ - private void updateAdsWriteFailureLogMap(Map> map, - AdsWriteFailureLogInfo logInfo, String key) { - List list = map.get(key); - if (null == list) { - list = new ArrayList(); - list.add(logInfo); - map.put(key, list); - } else { - // OData空間が存在する場合は、リストの中身をUUIDで検索し、検索結果をもとに追加 or 更新する。 - String uuid = logInfo.getUuid(); - int index = 0; - for (; index < list.size(); index++) { - AdsWriteFailureLogInfo item = list.get(index); - if (uuid.equals(item.getUuid())) { - break; - } - } - if (index == list.size()) { - list.add(logInfo); - } else { - list.remove(index); - list.add(logInfo); - } - } - } - - private void executeRepairAds(List logInfos) throws RepairAdsException { - // 1件ごとに処理を行う。 - // TODO 性能的な問題が発生した場合は、n件ごとに処理を行うように修正すること。 - for (AdsWriteFailureLogInfo logInfo : logInfos) { - logger.info("Starting repair. Repair record: " + logInfo.toString()); - String indexName = logInfo.getIndexName(); - String routingId = logInfo.getRoutingId(); - if ("".equals(routingId)) { - routingId = EsIndex.CELL_ROUTING_KEY_NAME; - } - - Lock lock = null; - String lockKey = logInfo.getLockKey(); - try { - // lockKeyが空(Cell再帰的削除の場合)であれば、ロックしない - if (null != lockKey && !lockKey.isEmpty()) { - try { - lock = lock(lockKey); - } catch (PersoniumCoreException e) { - if (e.getCode().equals(PersoniumCoreException.Server.GET_LOCK_STATE_ERROR.getCode()) - || e.getCode().equals( - PersoniumCoreException.Server.DATA_STORE_UNKNOWN_ERROR.getCode())) { - // 全体を異常終了させる - throw e; - } else { - // lockが他のプロセスに取得されており、取得できなかったため、異常終了にはせず、次の行に移行する - writeAdsRetryLog(logInfo.toString()); - logger.info("Other process has a lockObject."); - continue; - } - } - if (null == lock) { - // 該当行を不正ログファイルに退避する - writeAdsErrorLog(logInfo.toString()); - String message = String.format("Faild to get lock. lockKey= [%s]", lockKey); - logger.error(message); - continue; - } - } - - List idList = new ArrayList(); - idList.add(logInfo.getUuid()); - try { - // TypeがCellである場合は、Elasticsearchのインデックス名を「{UnitPrefix}_ad」に変更する - if (Cell.EDM_TYPE_NAME.equals(logInfo.getType())) { - indexName = PersoniumUnitConfig.getEsUnitPrefix() + "_" + EsIndex.CATEGORY_AD; - } - // ES/ADSへの検索は、一括検索ができるようなAPIを使用しているが、今のところは1件ずつ処理することを前提としている。 - PersoniumSearchResponse esResponse = EsAccessor.search( - indexName, routingId, idList, logInfo.getType()); - List adsResponse = AdsAccessor.getIdListOnAds(logInfo); - repairToAds(logInfo, esResponse, adsResponse); - } catch (EsClientException e) { - String message = String.format("Failed to get response from Elasticsearch. [%s]", - logInfo.toString()); - // Elasticsearchへの検索に失敗したため、ツール全体を異常終了させる - throw new RepairAdsException(message, e); - } catch (AdsException e) { - String message = String.format("Failed to get response from Ads. [%s]", logInfo.toString()); - // MySQLへの検索に失敗したため、ツール全体を異常終了させる - throw new RepairAdsException(message, e); - } - } finally { - if (null != lock) { - logger.debug("unlock"); - lock.release(); - } - } - } - - } - - /** - * ロックオブジェクトを取得する. - * @param lockKey ロックオブジェクトのキー(カテゴリ-UUID) - * @return ロックオブジェクト or null(ロックのカテゴリが不正である場合) - */ - private Lock lock(String lockKey) { - Lock lock = null; - if (lockKey.startsWith(Lock.CATEGORY_DAV + "-")) { - // Boxレベルのロックを取得 - String boxId = lockKey.substring((Lock.CATEGORY_DAV + "-").length()); - lock = LockManager.getLock(Lock.CATEGORY_DAV, null, boxId, null); - } else if (lockKey.startsWith(Lock.CATEGORY_ODATA + "-")) { - // ODataレベルのロックを取得 - String nodeId = lockKey.substring((Lock.CATEGORY_ODATA + "-").length()); - lock = LockManager.getLock(Lock.CATEGORY_ODATA, null, null, nodeId); - } else { - // ロックのカテゴリが不正なため、ロックを取得しない - String message = String.format("lockKey is wrong. [%s]", lockKey); - logger.info(message); - } - return lock; - } - - /** - * リペア対象のデータをADSにリクエストする. - * @param logInfo ログから読み込んだADS書き込み失敗情報 - * @param esResponse Elasticsearchにリペア対象のデータを検索した結果 - * @param adsResponse ADSにリペア対象のデータを検索した結果 - * @throws RepairAdsException RepairAdsException - */ - public void repairToAds( - AdsWriteFailureLogInfo logInfo, - PersoniumSearchResponse esResponse, - List adsResponse) throws RepairAdsException { - - // 検索結果として、2件以上がヒットした場合は異常事態とみなし、エラーとする。 - // (現状は、1件ずつ処理しているため、このチェックがある。n件ずつ処理する場合は、n件ヒットで確認する) - // TODO 件数の数値は、フィールドに追い出す。 - PersoniumSearchHits hits = esResponse.getHits(); - if (hits.getAllPages() > 1) { - String message = - String.format("Unexpected number of data returned from Elasticsearch. [%d]", hits.getAllPages()); - // 2件以上帰ってきた場合は、ツール全体を異常終了させる - throw new RepairAdsException(message); - } else if (adsResponse.size() > 1) { - String message = String.format("Unexpected number of data returned from ads. [id=%s, hits=%d]", - logInfo.getUuid(), adsResponse.size()); - // 2件以上帰ってきた場合は、ツール全体を異常終了させる - throw new RepairAdsException(message); - } - - try { - // リペアの判断 - String repairId = logInfo.getUuid(); - String indexName = logInfo.getIndexName(); - String type = logInfo.getType(); - - if (hits.getCount() == 1 && adsResponse.size() == 0) { - // Elasticsearchに存在し、MySQLにデータが存在しない場合 - // MySQLにデータを登録する(Create) - AdsAccessor.createAds(indexName, type, esResponse); - logger.info("New recored is inserted into ads. : " + hits.getAt(0).getSource()); - } else if (hits.getCount() == 1 && adsResponse.size() == 1 - && logInfo.getEsVersion() == hits.getAt(0).getVersion()) { - // Elasticsearchにデータが存在し、データのバージョンがJournalログのバージョンと同じである場合 - // MySQLにデータを更新する(Update) - AdsAccessor.updateAds(indexName, type, esResponse); - logger.info("Ads record is updated : " + hits.getAt(0).getSource()); - } else if (hits.getCount() == 0 && adsResponse.size() == 1) { - // ES上にデータが存在せず、MySQLにデータが存在する場合 - // MySQLにデータを削除する(Delete) - AdsAccessor.deleteAds(indexName, type, repairId); - logger.info("Ads record is deleted from ads. : " + repairId); - } else { - // ここに来た場合は、MySQLのデータ更新は無視されたことになる。 - logger.info("No operation performed for repair log recordID : " + repairId); - } - } catch (AdsException e) { - if (e.getCause() instanceof PersoniumCoreException) { - // 該当行を不正ログファイルに退避する - // MySQLへのリペア用データの作成に失敗した場合(Elasticsearchから取得したデータのパースに失敗) - writeAdsErrorLog(logInfo.toString()); - logger.error("Failed to repair record to MySQL. Invalid data is detected in Elasticsearch.", e); - } else { - writeAdsRetryLog(logInfo.toString()); - logger.error("Failed to repair record to MySQL.", e); - } - } - } - - /** - * リペア完了を判定する. - * リペア完了の判定条件は以下のとおり - * ADS書き込み失敗ログと出力中のADS書き込み失敗ログが存在しない場合 - * @return リペアが完了していればtrue、完了していない場合はfalse - * @throws RepairAdsException ベースディレクトリがディレクトリではない場合 - */ - private boolean isRepairCompleted() throws RepairAdsException { - AdsWriteFailureLogWriter writer = AdsWriteFailureLogWriter.getInstance( - this.adsLogBaseDir.getAbsolutePath(), - this.pcsVersion, - PersoniumUnitConfig.getAdsWriteFailureLogPhysicalDelete()); - Map logFilesMap = collectAdsWriteFailureLogFiles(); - if (logFilesMap.isEmpty() && !writer.isExistsAdsWriteFailureLogs() - && !existsErrorLog() && !existsActiveLog()) { - return true; - } - return false; - } - - /** - * リトライログにログを出力する. - * @param logInfo ログ情報 - */ - private void writeAdsRetryLog(String logInfo) { - AdsWriteFailureLogWriter retryLog = AdsWriteFailureLogWriter.getInstanceforRetry( - adsLogBaseDir.getPath(), pcsVersion, - PersoniumUnitConfig.getAdsWriteFailureLogPhysicalDelete()); - try { - retryLog.openActiveFile(createTime); - retryLog.writeActiveFile(logInfo); - } catch (AdsWriteFailureLogException e) { - logger.error("Faild to write retry information.", e); - } - } - - /** - * 退避ログにログを出力する. - * @param logInfo ログ情報 - */ - private void writeAdsErrorLog(String logInfo) { - AdsWriteFailureLogWriter errorLog = AdsWriteFailureLogWriter.getInstanceforError( - adsLogBaseDir.getPath(), pcsVersion, - PersoniumUnitConfig.getAdsWriteFailureLogPhysicalDelete()); - try { - errorLog.openActiveFile(createTime); - errorLog.writeActiveFile(logInfo); - } catch (AdsWriteFailureLogException e) { - logger.error("Failed to write error information.", e); - } - } -} diff --git a/src/main/java/io/personium/core/model/impl/es/repair/RepairAdsException.java b/src/main/java/io/personium/core/model/impl/es/repair/RepairAdsException.java deleted file mode 100644 index c41e440b0..000000000 --- a/src/main/java/io/personium/core/model/impl/es/repair/RepairAdsException.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.repair; - -/** - * ADSへのデータ補正時にスローする例外. - */ -public class RepairAdsException extends Exception { - - /** - * デフォルトシリアルバージョンID. - */ - private static final long serialVersionUID = 1L; - - /** - * コンストラクタ. - * @param msg メッセージ - * @param cause 原因となったThrowable - */ - public RepairAdsException(String msg, Throwable cause) { - super(msg, cause); - } - - /** - * コンストラクタ. - * @param msg メッセージ - */ - public RepairAdsException(String msg) { - super(msg); - } - -} diff --git a/src/main/java/io/personium/core/model/impl/es/repair/package-info.java b/src/main/java/io/personium/core/model/impl/es/repair/package-info.java deleted file mode 100644 index 5a6b6f1e4..000000000 --- a/src/main/java/io/personium/core/model/impl/es/repair/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * 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. - */ -/** - * ADSへのデータ補正処理を実装したクラス群. - */ -package io.personium.core.model.impl.es.repair; - diff --git a/src/main/java/io/personium/core/model/impl/fs/DavCmpFsImpl.java b/src/main/java/io/personium/core/model/impl/fs/DavCmpFsImpl.java index c8abba829..b9053cb5b 100644 --- a/src/main/java/io/personium/core/model/impl/fs/DavCmpFsImpl.java +++ b/src/main/java/io/personium/core/model/impl/fs/DavCmpFsImpl.java @@ -60,6 +60,7 @@ import org.w3c.dom.NodeList; import io.personium.common.auth.token.Role; +import io.personium.common.es.response.PersoniumGetResponse; import io.personium.common.es.util.IndexNameEncoder; import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreException; @@ -79,8 +80,12 @@ import io.personium.core.model.ctl.EntityType; import io.personium.core.model.file.BinaryDataAccessor; import io.personium.core.model.file.BinaryDataNotFoundException; +import io.personium.core.model.file.CipherInputStream; +import io.personium.core.model.file.DataCryptor; import io.personium.core.model.file.StreamingOutputForDavFile; import io.personium.core.model.file.StreamingOutputForDavFileWithRange; +import io.personium.core.model.impl.es.EsModel; +import io.personium.core.model.impl.es.accessor.EntitySetAccessor; import io.personium.core.model.impl.es.odata.UserSchemaODataProducer; import io.personium.core.model.jaxb.Ace; import io.personium.core.model.jaxb.Acl; @@ -552,34 +557,57 @@ public final ResponseBuilder putForUpdate(final String contentType, final InputS } } - /* - * newly create the resource + /** + * Newly create the resource. + * @param contentType ContentType of the generated file + * @param inputStream Stream of generated file + * @return ResponseBuilder */ - final ResponseBuilder doPutForCreate(final String contentType, final InputStream inputStream) { + private ResponseBuilder doPutForCreate(final String contentType, final InputStream inputStream) { // check the resource count checkChildResourceCount(); - BufferedInputStream bufferedInput = new BufferedInputStream(inputStream); + InputStream input = inputStream; + if (PersoniumUnitConfig.isDavEncryptEnabled()) { + // Perform encryption. + DataCryptor cryptor = new DataCryptor(getCellId()); + input = cryptor.encode(inputStream); + } + + BufferedInputStream bufferedInput = new BufferedInputStream(input); try { // create new directory. - Files.createDirectory(Paths.get(this.fsPath)); + Files.createDirectories(Paths.get(this.fsPath)); // store the file content. - File newFile = new File(this.getContentFilePath()); + File newFile = new File(getContentFilePath()); Files.copy(bufferedInput, newFile.toPath()); long writtenBytes = newFile.length(); + String encryptionType = DataCryptor.ENCRYPTION_TYPE_NONE; + if (PersoniumUnitConfig.isDavEncryptEnabled()) { + writtenBytes = ((CipherInputStream) input).getReadLengthBeforEncryption(); + encryptionType = DataCryptor.ENCRYPTION_TYPE_AES; + } // create new metadata file. this.metaFile = DavMetadataFile.prepareNewFile(this, DavCmp.TYPE_DAV_FILE); this.metaFile.setContentType(contentType); this.metaFile.setContentLength(writtenBytes); + this.metaFile.setEncryptionType(encryptionType); this.metaFile.save(); } catch (IOException ex) { throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(ex); } this.isPhantom = false; - return javax.ws.rs.core.Response.ok().status(HttpStatus.SC_CREATED).header(HttpHeaders.ETAG, this.getEtag()); + return javax.ws.rs.core.Response.ok().status(HttpStatus.SC_CREATED).header(HttpHeaders.ETAG, getEtag()); } - final ResponseBuilder doPutForUpdate(final String contentType, final InputStream inputStream, String etag) { + /** + * Overwrite resources.. + * @param contentType ContentType of the update file + * @param inputStream Stream of update file + * @param etag Etag + * @return ResponseBuilder + */ + private ResponseBuilder doPutForUpdate(final String contentType, final InputStream inputStream, String etag) { // 現在時刻を取得 long now = new Date().getTime(); // 最新ノード情報をロード @@ -589,7 +617,7 @@ final ResponseBuilder doPutForUpdate(final String contentType, final InputStream // クリティカルなタイミング(ロック~ロードまでの間)でWebDavの管理データが削除された場合の対応 // WebDavの管理データがこの時点で存在しない場合は404エラーとする if (!this.exists()) { - throw getNotFoundException().params(this.getUrl()); + throw getNotFoundException().params(getUrl()); } // 指定etagがあり、かつそれが*ではなく内部データから導出されるものと異なるときはエラー @@ -599,35 +627,52 @@ final ResponseBuilder doPutForUpdate(final String contentType, final InputStream try { // Update Content - BufferedInputStream bufferedInput = new BufferedInputStream(inputStream); - File tmpFile = new File(this.getTempContentFilePath()); - File contentFile = new File(this.getContentFilePath()); + InputStream input = inputStream; + if (PersoniumUnitConfig.isDavEncryptEnabled()) { + // Perform encryption. + DataCryptor cryptor = new DataCryptor(getCellId()); + input = cryptor.encode(inputStream); + } + BufferedInputStream bufferedInput = new BufferedInputStream(input); + File tmpFile = new File(getTempContentFilePath()); + File contentFile = new File(getContentFilePath()); Files.copy(bufferedInput, tmpFile.toPath()); - Files.delete(contentFile.toPath()); Files.move(tmpFile.toPath(), contentFile.toPath()); + long writtenBytes = contentFile.length(); + String encryptionType = DataCryptor.ENCRYPTION_TYPE_NONE; + if (PersoniumUnitConfig.isDavEncryptEnabled()) { + writtenBytes = ((CipherInputStream) input).getReadLengthBeforEncryption(); + encryptionType = DataCryptor.ENCRYPTION_TYPE_AES; + } + // Update Metadata this.metaFile.setUpdated(now); this.metaFile.setContentType(contentType); - this.metaFile.setContentLength(contentFile.length()); + this.metaFile.setContentLength(writtenBytes); + this.metaFile.setEncryptionType(encryptionType); this.metaFile.save(); } catch (IOException ex) { throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(ex); } // response - return javax.ws.rs.core.Response.ok().status(HttpStatus.SC_NO_CONTENT).header(HttpHeaders.ETAG, this.getEtag()); + return javax.ws.rs.core.Response.ok().status(HttpStatus.SC_NO_CONTENT).header(HttpHeaders.ETAG, getEtag()); } + /** + * {@inheritDoc} + */ @Override public final ResponseBuilder get(final String rangeHeaderField) { - String contentType = this.getContentType(); + String contentType = getContentType(); ResponseBuilder res = null; String fileFullPath = this.fsPath + File.separator + CONTENT_FILE_NAME; - final long fileSize = this.getContentLength(); + long fileSize = getContentLength(); + String encryptionType = getEncryptionType(); // Rangeヘッダ解析処理 final RangeHeaderHandler range = RangeHeaderHandler.parse(rangeHeaderField, fileSize); @@ -637,7 +682,7 @@ public final ResponseBuilder get(final String rangeHeaderField) { // Rangeヘッダ指定の時とで処理の切り分け if (!range.isValid()) { // ファイル全体返却 - StreamingOutput sout = new StreamingOutputForDavFile(fileFullPath); + StreamingOutput sout = new StreamingOutputForDavFile(fileFullPath, getCellId(), encryptionType); res = davFileResponse(sout, fileSize, contentType); } else { // Range対応部分レスポンス @@ -652,17 +697,18 @@ public final ResponseBuilder get(final String rangeHeaderField) { // MultiPartレスポンスには未対応 throw PersoniumCoreException.Misc.NOT_IMPLEMENTED.params("Range-MultiPart"); } else { - StreamingOutput sout = new StreamingOutputForDavFileWithRange(fileFullPath, fileSize, range); + StreamingOutput sout = new StreamingOutputForDavFileWithRange( + fileFullPath, fileSize, range, getCellId(), encryptionType); res = davFileResponseForRange(sout, contentType, range); } } - return res.header(HttpHeaders.ETAG, this.getEtag()).header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, + return res.header(HttpHeaders.ETAG, getEtag()).header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); } catch (BinaryDataNotFoundException nex) { this.load(); - if (!this.exists()) { - throw getNotFoundException().params(this.getUrl()); + if (!exists()) { + throw getNotFoundException().params(getUrl()); } throw PersoniumCoreException.Dav.DAV_UNAVAILABLE.reason(nex); } @@ -1150,6 +1196,24 @@ public String getUrl() { return this.parent.getUrl() + "/" + this.name; } + /** + * BoxIdでEsを検索する. + * @param cellObj Cell + * @param boxId ボックスId + * @return 検索結果 + */ + public static Map searchBox(final Cell cellObj, final String boxId) { + + EntitySetAccessor boxType = EsModel.box(cellObj); + PersoniumGetResponse getRes = boxType.get(boxId); + if (getRes == null || !getRes.isExists()) { + PersoniumCoreLog.Dav.ROLE_NOT_FOUND.params("Box Id Not Hit").writeLog(); + + throw PersoniumCoreException.Dav.ROLE_NOT_FOUND; + } + return getRes.getSource(); + } + /** * retruns NotFoundException for this resource.
* messages should vary among resource type Cell, box, file, etc.. @@ -1191,6 +1255,11 @@ public String getContentType() { return this.metaFile.getContentType(); } + @Override + public String getEncryptionType() { + return this.metaFile.getEncryptionType(); + } + @Override public String getId() { return this.metaFile.getNodeId(); diff --git a/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java b/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java index 218f47d78..52d911b0e 100644 --- a/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java +++ b/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java @@ -41,31 +41,34 @@ public class DavMetadataFile { JSONObject json = new JSONObject(); - /* JSON Key for ID. */ + /** JSON Key for ID. */ private static final String KEY_ID = "i"; - /* JSON Key for Node Type. */ + /** JSON Key for Node Type. */ private static final String KEY_NODE_TYPE = "t"; - /* JSON Key for ACL. */ + /** JSON Key for ACL. */ private static final String KEY_ACL = "a"; - /* JSON Key for PROPSを保存するJSONキー. */ + /** JSON Key for PROPSを保存するJSONキー. */ private static final String KEY_PROPS = "d"; - /* JSON Key for published. */ + /** JSON Key for published. */ private static final String KEY_PUBLISHED = "p"; - /* JSON Key for updated. */ + /** JSON Key for updated. */ private static final String KEY_UPDATED = "u"; - /* JSON Key for ContentType. */ + /** JSON Key for ContentType. */ private static final String KEY_CONTENT_TYPE = "ct"; - /* JSON Key for Content Length. */ + /** JSON Key for Content Length. */ private static final String KEY_CONTENT_LENGTH = "cl"; - /* JSON Key for Version. */ + /** JSON Key for Encryption Type. */ + private static final String KEY_ENCRYPTION_TYPE = "et"; + + /** JSON Key for Version. */ private static final String KEY_VERSION = "v"; /** @@ -291,6 +294,21 @@ public void setContentLength(long contentLength) { this.json.put(KEY_CONTENT_LENGTH, contentLength); } + /** + * @return encryption type string. + */ + public String getEncryptionType() { + return (String) this.json.get(KEY_ENCRYPTION_TYPE); + } + + /** + * @param encryptionType encryption type string + */ + @SuppressWarnings("unchecked") + public void setEncryptionType(String encryptionType) { + this.json.put(KEY_ENCRYPTION_TYPE, encryptionType); + } + /** * @return long value of the resource version */ diff --git a/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java b/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java index ac1265a59..15ac8a695 100644 --- a/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java +++ b/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java @@ -24,8 +24,9 @@ import io.personium.common.auth.token.LocalToken; import io.personium.common.auth.token.TransCellAccessToken; import io.personium.core.PersoniumCoreLog; -import io.personium.core.plugin.PluginManager; import io.personium.core.PersoniumUnitConfig; +import io.personium.core.model.file.DataCryptor; +import io.personium.core.plugin.PluginManager; /** * Personium-coreの/_cell_/* 以下URLを担当するJAX-RSのApplication. @@ -38,6 +39,7 @@ public class PersoniumCoreApplication extends Application { TransCellAccessToken.configureX509(PersoniumUnitConfig.getX509PrivateKey(), PersoniumUnitConfig.getX509Certificate(), PersoniumUnitConfig.getX509RootCertificate()); LocalToken.setKeyString(PersoniumUnitConfig.getTokenSecretKey()); + DataCryptor.setKeyString(PersoniumUnitConfig.getTokenSecretKey()); pm = new PluginManager(); } catch (Exception e) { PersoniumCoreLog.Server.FAILED_TO_START_SERVER.reason(e).writeLog(); diff --git a/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java index 5639e5dcd..ce99c7915 100644 --- a/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java @@ -58,14 +58,13 @@ import org.slf4j.LoggerFactory; import io.personium.common.utils.PersoniumCoreUtils; -import io.personium.core.PersoniumUnitConfig; import io.personium.core.PersoniumCoreException; +import io.personium.core.PersoniumUnitConfig; import io.personium.core.annotations.ACL; import io.personium.core.auth.BoxPrivilege; import io.personium.core.model.DavCmp; import io.personium.core.model.DavMoveResource; import io.personium.core.model.DavRsCmp; -import io.personium.core.model.impl.es.DavCmpEsImpl; import io.personium.core.model.impl.fs.DavCmpFsImpl; /** @@ -305,12 +304,7 @@ public Response relaycommon( if (davCmp instanceof DavCmpFsImpl) { DavCmpFsImpl dcmp = (DavCmpFsImpl) davCmp; req.addHeader("X-Personium-Fs-Path", dcmp.getFsPath()); - } else if (davCmp instanceof DavCmpEsImpl) { - DavCmpEsImpl dcmp = (DavCmpEsImpl) davCmp; - req.addHeader("X-Personium-Es-Index", dcmp.getEsColType().getIndex().getName()); - req.addHeader("X-Personium-Es-Id", dcmp.getNodeId()); - req.addHeader("X-Personium-Es-Type", dcmp.getEsColType().getType()); - req.addHeader("X-Personium-Es-Routing-Id", this.davRsCmp.getCell().getId()); + req.addHeader("X-Personium-Fs-Routing-Id", dcmp.getCellId()); } req.addHeader("X-Personium-Box-Schema", this.davRsCmp.getBox().getSchema()); diff --git a/src/main/java/io/personium/core/rs/cell/MessageODataResource.java b/src/main/java/io/personium/core/rs/cell/MessageODataResource.java index 44a26518f..210c5d790 100644 --- a/src/main/java/io/personium/core/rs/cell/MessageODataResource.java +++ b/src/main/java/io/personium/core/rs/cell/MessageODataResource.java @@ -605,36 +605,34 @@ private JSONObject bodyAsJson(HttpResponse objResponse) { */ @Override public void validate(List> props) { - // メッセージ受信のときのチェック if (ReceivedMessage.EDM_TYPE_NAME.equals(this.getEntitySetName())) { + // メッセージ受信のときのチェック validateReceivedBoxBoundSchema(this.odataResource, propMap.get(ReceivedMessagePort.P_SCHEMA.getName())); - MessageODataResource.validateUriCsv(ReceivedMessage.P_MULTICAST_TO.getName(), + validateUriCsv(ReceivedMessage.P_MULTICAST_TO.getName(), propMap.get(ReceivedMessage.P_MULTICAST_TO.getName())); - MessageODataResource.validateBody(propMap.get(ReceivedMessage.P_BODY.getName()), + validateBody(propMap.get(ReceivedMessage.P_BODY.getName()), Common.MAX_MESSAGE_BODY_LENGTH); - MessageODataResource.validateStatus(propMap.get(ReceivedMessage.P_TYPE.getName()), + validateStatus(propMap.get(ReceivedMessage.P_TYPE.getName()), propMap.get(ReceivedMessage.P_STATUS.getName())); - MessageODataResource.validateReqRelation(propMap.get(ReceivedMessage.P_TYPE.getName()), + validateReqRelation(propMap.get(ReceivedMessage.P_TYPE.getName()), propMap.get(ReceivedMessage.P_REQUEST_RELATION.getName()), propMap.get(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName())); - } - // メッセージ送信のときのチェック - if (SentMessage.EDM_TYPE_NAME.equals(this.getEntitySetName())) { + } else if (SentMessage.EDM_TYPE_NAME.equals(this.getEntitySetName())) { + // メッセージ送信のときのチェック validateSentBoxBoundSchema(this.odataResource, Boolean.valueOf(propMap.get(SentMessagePort.P_BOX_BOUND.getName()))); - MessageODataResource.validateUriCsv(SentMessage.P_TO.getName(), propMap.get(SentMessage.P_TO.getName())); - MessageODataResource.validateBody(propMap.get(SentMessage.P_BODY.getName()), + validateUriCsv(SentMessage.P_TO.getName(), propMap.get(SentMessage.P_TO.getName())); + validateBody(propMap.get(SentMessage.P_BODY.getName()), Common.MAX_MESSAGE_BODY_LENGTH); - MessageODataResource.validateToAndToRelation( + validateToAndToRelation( propMap.get(SentMessage.P_TO.getName()), propMap.get(SentMessage.P_TO_RELATION.getName())); - MessageODataResource.validateToValue( + validateToValue( propMap.get(SentMessage.P_TO.getName()), this.odataResource.getAccessContext().getBaseUri()); - MessageODataResource.validateReqRelation(propMap.get(SentMessage.P_TYPE.getName()), + validateReqRelation(propMap.get(SentMessage.P_TYPE.getName()), propMap.get(SentMessage.P_REQUEST_RELATION.getName()), propMap.get(SentMessage.P_REQUEST_RELATION_TARGET.getName())); - } } @@ -762,11 +760,13 @@ public static void validateBody(String value, int maxLength) { * @param status ステータス */ public static void validateStatus(String type, String status) { - // Typeがmessageの場合unread:未読 - // Typeがreq.relation.build/req.relation.breakの場合 none:未決 + // Unread if Type is message + // None if Type is req.relation.build/req.relation.break/req.role.grant/req.role.revoke if (!(ReceivedMessage.TYPE_MESSAGE.equals(type) && ReceivedMessage.STATUS_UNREAD.equals(status)) && !((ReceivedMessage.TYPE_REQ_RELATION_BUILD.equals(type) - || ReceivedMessage.TYPE_REQ_RELATION_BREAK.equals(type)) + || ReceivedMessage.TYPE_REQ_RELATION_BREAK.equals(type) + || ReceivedMessage.TYPE_REQ_ROLE_GRANT.equals(type) + || ReceivedMessage.TYPE_REQ_ROLE_REVOKE.equals(type)) && ReceivedMessage.STATUS_NONE.equals(status))) { throw PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(ReceivedMessage.P_STATUS.getName()); } @@ -779,13 +779,30 @@ public static void validateStatus(String type, String status) { * @param requestRelationTarget 関係登録依頼CellURL */ public static void validateReqRelation(String type, String requestRelation, String requestRelationTarget) { + // Conditional required check if ((ReceivedMessage.TYPE_REQ_RELATION_BUILD.equals(type) - || ReceivedMessage.TYPE_REQ_RELATION_BREAK.equals(type)) + || ReceivedMessage.TYPE_REQ_RELATION_BREAK.equals(type) + || ReceivedMessage.TYPE_REQ_ROLE_GRANT.equals(type) + || ReceivedMessage.TYPE_REQ_ROLE_REVOKE.equals(type)) && (requestRelation == null || requestRelationTarget == null)) { String detail = ReceivedMessage.P_REQUEST_RELATION.getName() + "," + ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(); throw PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(detail); } + // Correlation format check + if ((ReceivedMessage.TYPE_REQ_RELATION_BUILD.equals(type) + || ReceivedMessage.TYPE_REQ_RELATION_BREAK.equals(type)) + && !ODataUtils.validateClassUrl(requestRelation, Common.PATTERN_RELATION_CLASS_URL) + && !ODataUtils.validateRegEx(requestRelation, Common.PATTERN_RELATION_NAME)) { + throw PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_REQUEST_RELATION.getName()); + } else if ((ReceivedMessage.TYPE_REQ_ROLE_GRANT.equals(type) + || ReceivedMessage.TYPE_REQ_ROLE_REVOKE.equals(type)) + && !ODataUtils.validateClassUrl(requestRelation, Common.PATTERN_ROLE_CLASS_URL) + && !ODataUtils.validateRegEx(requestRelation, Common.PATTERN_NAME)) { + throw PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_REQUEST_RELATION.getName()); + } } /** diff --git a/src/main/java/io/personium/core/rs/odata/AbstractODataResource.java b/src/main/java/io/personium/core/rs/odata/AbstractODataResource.java index f41de84cf..92fc565da 100644 --- a/src/main/java/io/personium/core/rs/odata/AbstractODataResource.java +++ b/src/main/java/io/personium/core/rs/odata/AbstractODataResource.java @@ -849,7 +849,9 @@ protected void validatePropertyUsusst(String propName, OProperty op, String p */ protected void validatePropertyMessageRequestRelation(String propName, OProperty op) { if (!ODataUtils.validateClassUrl(op.getValue().toString(), Common.PATTERN_RELATION_CLASS_URL) - && !ODataUtils.validateRegEx(op.getValue().toString(), Common.PATTERN_RELATION_NAME)) { + && !ODataUtils.validateRegEx(op.getValue().toString(), Common.PATTERN_RELATION_NAME) + && !ODataUtils.validateClassUrl(op.getValue().toString(), Common.PATTERN_ROLE_CLASS_URL) + && !ODataUtils.validateRegEx(op.getValue().toString(), Common.PATTERN_NAME)) { throw PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(propName); } } diff --git a/src/main/java/io/personium/core/webcontainer/listener/RepairServiceLauncher.java b/src/main/java/io/personium/core/webcontainer/listener/RepairServiceLauncher.java deleted file mode 100644 index 2e689e3ff..000000000 --- a/src/main/java/io/personium/core/webcontainer/listener/RepairServiceLauncher.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * 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 io.personium.core.webcontainer.listener; - -import java.io.File; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.ads.AdsWriteFailureLogException; -import io.personium.common.ads.AdsWriteFailureLogWriter; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.impl.es.repair.RepairAds; - -/** - * Ads書き込み失敗内容をリペアするServiceの定期実行を起動するユーティリティクラス. - */ -public class RepairServiceLauncher { - - private static Logger logger = LoggerFactory.getLogger(RepairServiceLauncher.class); - - /** - * Adsのリペア処理を行うクラス. - */ - public static class RepairAdsService implements Runnable { - - /** - * RepairAdsを起動するか否かを判定するファイルのパス. - */ - String invocationFlagFile = PersoniumUnitConfig.getRepairAdsInvocationFilePath(); - - @Override - public void run() { - try { - AdsWriteFailureLogWriter adsWriteFailureLogWriter = AdsWriteFailureLogWriter.getInstance( - PersoniumUnitConfig.getAdsWriteFailureLogDir(), - PersoniumUnitConfig.getCoreVersion(), - PersoniumUnitConfig.getAdsWriteFailureLogPhysicalDelete()); - - // 現在出力中のジャーナルログファイルのローテート。 - adsWriteFailureLogWriter.rotateActiveFile(); - } catch (AdsWriteFailureLogException e) { - logger.warn("Faield to rotate ads failure log file."); - return; - } - - // Adsリペア処理実行の有無チェック. - logger.debug("Checking invocation flag for RepairAds."); - if (shouldInvoke()) { - logger.debug("Invocation flag for RepairAds exists. Invoking RepairAds."); - // Adsリペア処理の実行. - try { - RepairAds.getInstance().repairAds(); - } catch (Throwable t) { - // 例外を飛ばすとそれ以降のスケジュールが無効になるため、外部には飛ばさない。 - // warnレベルでログを出力したいが、定期的にアラートメールが飛ぶのを防ぐため、infoレベルで出力. - logger.info("Ads repair process reported an error.", t); - } - } else { - logger.debug("No invocation flag for RepairAds. Invocation cancelled."); - } - } - - /** - * 特定ファイルの存在有無で、リペア処理の実行必要性の有無を判断する. - * @return true: 実行が指示されている false: 実行しないように指示されている - */ - public boolean shouldInvoke() { - File flagFile = new File(invocationFlagFile); - return flagFile.exists() && flagFile.isFile(); - } - } - - ScheduledThreadPoolExecutor executor; - - /** - * コンストラクタ. Webコンテナ起動時に呼ばれる。 - */ - public RepairServiceLauncher() { - // 同時起動はしないため、Threadは1つ. - executor = new ScheduledThreadPoolExecutor(1); - executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); - // リペアツールの実行をスケジュールする. - RepairAdsService service = new RepairAdsService(); - executor.scheduleWithFixedDelay(service, - PersoniumUnitConfig.getAdsRepairInitialDelayInSec(), - PersoniumUnitConfig.getAdsRepairIntervalInSec(), - TimeUnit.SECONDS); - logger.info(String.format("RepairAds scheduled with delay interval %d sec.", - PersoniumUnitConfig.getAdsRepairIntervalInSec())); - } - - /** - * Webコンテナ終了時に呼ばれるメソッド. - */ - public void shutdown() { - if (null != executor && !executor.isTerminated()) { - logger.info("Shutting down RepairAds scheduler."); - executor.shutdown(); - try { - long awaitShutdownInSec = PersoniumUnitConfig.getAdsRepairAwaitShutdownInSec(); - logger.info(String.format("Waiting RepairAds termination up to %d sec.", awaitShutdownInSec)); - if (executor.awaitTermination(awaitShutdownInSec, TimeUnit.SECONDS)) { - logger.info("Completed shutting down RepairAds scheduler."); - } else { - logger.warn("Shutting down timed out. RepairAds scheduler have not been terminated."); - executor.shutdownNow(); - } - } catch (InterruptedException e) { - executor.shutdownNow(); - } - } - } -} diff --git a/src/main/java/io/personium/core/webcontainer/listener/WebContainerListenerForAdsRepair.java b/src/main/java/io/personium/core/webcontainer/listener/WebContainerListenerForAdsRepair.java deleted file mode 100644 index 0fa6238a2..000000000 --- a/src/main/java/io/personium/core/webcontainer/listener/WebContainerListenerForAdsRepair.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 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 io.personium.core.webcontainer.listener; - -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - - -/** - * Webコンテナ起動/終了時に呼び出されるListenerクラス. - */ -public class WebContainerListenerForAdsRepair implements ServletContextListener { - - RepairServiceLauncher launcher = null; - - @Override - public void contextInitialized(ServletContextEvent arg0) { - launcher = new RepairServiceLauncher(); - } - - @Override - public void contextDestroyed(ServletContextEvent arg0) { - if (null != launcher) { - launcher.shutdown(); - } - } -} diff --git a/src/main/java/io/personium/core/webcontainer/listener/package-info.java b/src/main/java/io/personium/core/webcontainer/listener/package-info.java deleted file mode 100644 index 915a089db..000000000 --- a/src/main/java/io/personium/core/webcontainer/listener/package-info.java +++ /dev/null @@ -1,17 +0,0 @@ -/** - * 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 io.personium.core.webcontainer.listener; diff --git a/src/main/resources/personium-messages.properties b/src/main/resources/personium-messages.properties index 1e1672dd7..b296bf75b 100644 --- a/src/main/resources/personium-messages.properties +++ b/src/main/resources/personium-messages.properties @@ -164,11 +164,11 @@ io.personium.core.msg.PR500-SM-0002=Sent Message body parse error. io.personium.core.msg.PR400-RM-0001=Requested relation already exists. io.personium.core.msg.PR400-RM-0002=Box corresponding to the schema can not be found. Schema [{0}]. io.personium.core.msg.PR400-RM-0003=Box corresponding to the RelationClassURL can not be found. RelationClassURL [{0}]. -io.personium.core.msg.PR409-RM-0001=Requested relation URL parse error. -io.personium.core.msg.PR409-RM-0002=Requested relation [{0}] does not exists. -io.personium.core.msg.PR409-RM-0003=Requested relation target URL parse error. -io.personium.core.msg.PR409-RM-0004=Request relation target [{0}] does not exist. -io.personium.core.msg.PR409-RM-0005=RequestRelation and RequestRelationTarget is not related. [{0}] - [{1}]. +# io.personium.core.msg.PR409-RM-0001=Requested relation URL parse error. +io.personium.core.msg.PR409-RM-0002=Requested relation does not exists. Type [{0}]. Keys [{1}]. +# io.personium.core.msg.PR409-RM-0003=Requested relation target URL parse error. +io.personium.core.msg.PR409-RM-0004=Request relation target does not exist. Type [{0}]. Keys [{1}]. +io.personium.core.msg.PR409-RM-0005=RequestRelation and RequestRelationTarget is not related. [Type [{0}]. Keys[{1}]] - [Type {2}. Keys[{3}]]. ## Auth # PR400-AU diff --git a/src/main/resources/personium-unit-config-default.properties b/src/main/resources/personium-unit-config-default.properties index 5811e60bd..006a8ccc7 100644 --- a/src/main/resources/personium-unit-config-default.properties +++ b/src/main/resources/personium-unit-config-default.properties @@ -23,7 +23,7 @@ ################################################# # core version -io.personium.core.version=1.5.0 +io.personium.core.version=1.5.1 # general configurations io.personium.core.unitUser.issuers= diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml index a8c84b713..13caa871b 100644 --- a/src/main/webapp/WEB-INF/web.xml +++ b/src/main/webapp/WEB-INF/web.xml @@ -23,10 +23,6 @@ id="WebApp_ID" version="3.0"> personium-core - - io.personium.core.webcontainer.listener.WebContainerListenerForAdsRepair - - PersoniumCoreApp diff --git a/src/test/java/io/personium/core/model/file/BinaryDataAccessorTest.java b/src/test/java/io/personium/core/model/file/BinaryDataAccessorTest.java index c13709374..d6310b9c2 100644 --- a/src/test/java/io/personium/core/model/file/BinaryDataAccessorTest.java +++ b/src/test/java/io/personium/core/model/file/BinaryDataAccessorTest.java @@ -16,18 +16,10 @@ */ package io.personium.core.model.file; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.BufferedInputStream; import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileDescriptor; import java.io.FileOutputStream; -import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; @@ -36,7 +28,6 @@ import org.junit.runner.RunWith; import org.mockito.Mockito; -import io.personium.core.PersoniumUnitConfig; import io.personium.test.categories.Unit; import io.personium.test.jersey.PersoniumIntegTestRunner; @@ -47,228 +38,6 @@ @Category({Unit.class }) public class BinaryDataAccessorTest { - /** - * 既存ディレクトリにファイルの登録が可能な事を確認する. - * PersoniumUnitConfingを利用するため、coreにテストを記述する - */ - @Test - public void 既存ディレクトリにファイルの登録が可能な事を確認する() { - String filename1 = "PcsInnov1"; - String filename2 = "PcsInnov2"; - String filename3 = "Pcs3nnov3"; - BinaryDataAccessor binaryDataAccessor = new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), - PersoniumUnitConfig.getFsyncEnabled()); - try { - long dataSize = "testhoge".getBytes().length; - // ディレクトリを作成 - InputStream is = new ByteArrayInputStream("testhoge".getBytes()); - BufferedInputStream bufferedInput = new BufferedInputStream(is); - try { - long fileSize = binaryDataAccessor.create(bufferedInput, filename1); - assertEquals(dataSize, fileSize); - } catch (BinaryDataAccessException e) { - fail(e.getMessage()); - } - // 既存ディレクトリにファイル登録 - dataSize = "testhuga".getBytes().length; - InputStream is2 = new ByteArrayInputStream("testhuga".getBytes()); - BufferedInputStream bufferedInput2 = new BufferedInputStream(is2); - try { - long fileSize = binaryDataAccessor.create(bufferedInput2, filename2); - assertEquals(dataSize, fileSize); - } catch (BinaryDataAccessException e) { - fail(e.getMessage()); - } - // 親ディレクトリにファイル登録 - InputStream is3 = new ByteArrayInputStream("testhugahoge".getBytes()); - BufferedInputStream bufferedInput3 = new BufferedInputStream(is3); - dataSize = "testhugahoge".getBytes().length; - try { - long fileSize = binaryDataAccessor.create(bufferedInput3, filename3); - assertEquals(dataSize, fileSize); - } catch (BinaryDataAccessException e) { - fail(e.getMessage()); - } - } finally { - // ファイル削除の確認 - try { - binaryDataAccessor.delete(filename3 + ".tmp"); - binaryDataAccessor.delete(filename2 + ".tmp"); - binaryDataAccessor.delete(filename1 + ".tmp"); - } catch (BinaryDataAccessException e) { - fail(e.getMessage()); - } - } - - } - - /** - * ファイルを物理削除した場合ファイルが削除されていること. - * PersoniumUnitConfingを利用するため、coreにテストを記述する - * @throws BinaryDataAccessException バイナリアクセスに失敗 - */ - @Test - public void ファイルを物理削除した場合ファイルが削除されていること() throws BinaryDataAccessException { - String filename1 = "PcsInnovPhysicalDelete1"; - BinaryDataAccessor binaryDataAccessor = new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), - PersoniumUnitConfig.getFsyncEnabled()); - try { - // テンポラリファイルファイル作成 - long dataSize = "testhoge".getBytes().length; - InputStream is = new ByteArrayInputStream("testhoge".getBytes()); - BufferedInputStream bufferedInput = new BufferedInputStream(is); - long fileSize = binaryDataAccessor.create(bufferedInput, filename1); - assertEquals(dataSize, fileSize); - - // 「XXX.tmp」→「XXX」 - binaryDataAccessor.copyFile(filename1); - - // 物理削除 - binaryDataAccessor.deletePhysicalFile(filename1); - - // 削除確認 - boolean isExists = binaryDataAccessor.existsForFilename(filename1); - assertFalse(isExists); - } finally { - // ファイル削除 - binaryDataAccessor.deletePhysicalFile(filename1); - } - } - - /** - * ファイルの物理削除で存在しないファイルを指定した場合例外がスローされないこと. - * PersoniumUnitConfingを利用するため、coreにテストを記述する - * @throws BinaryDataAccessException バイナリアクセスに失敗 - */ - @Test - public void ファイルの物理削除で存在しないファイルを指定した場合例外がスローされないこと() throws BinaryDataAccessException { - String filename1 = "PcsInnovPhysicalDelete1"; - BinaryDataAccessor binaryDataAccessor = new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), - PersoniumUnitConfig.getFsyncEnabled()); - // 物理削除 - binaryDataAccessor.deletePhysicalFile(filename1); - - // 削除確認 - boolean isExists = binaryDataAccessor.existsForFilename(filename1); - assertFalse(isExists); - } - - /** - * 物理削除設定を指定していない場合ファイルが論理削除されていること. - * PersoniumUnitConfingを利用するため、coreにテストを記述する - * @throws BinaryDataAccessException バイナリアクセスに失敗 - */ - @Test - public void 物理削除設定を指定していない場合ファイルが論理削除されていること() throws BinaryDataAccessException { - String filename1 = "PcsInnovPhysicalDelete1"; - BinaryDataAccessor binaryDataAccessor = new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), - PersoniumUnitConfig.getFsyncEnabled()); - try { - // テンポラリファイルファイル作成 - long dataSize = "testhoge".getBytes().length; - InputStream is = new ByteArrayInputStream("testhoge".getBytes()); - BufferedInputStream bufferedInput = new BufferedInputStream(is); - long fileSize = binaryDataAccessor.create(bufferedInput, filename1); - assertEquals(dataSize, fileSize); - - // 「XXX.tmp」→「XXX」 - binaryDataAccessor.copyFile(filename1); - - // ファイル削除 - binaryDataAccessor.delete(filename1); - - // 削除確認 - boolean isExists = binaryDataAccessor.existsForFilename(filename1); - assertFalse(isExists); - // 論理削除ファイルが存在することの確認 - isExists = binaryDataAccessor.existsForFilename(filename1 + ".deleted"); - assertTrue(isExists); - - } finally { - // ファイル削除 - binaryDataAccessor.deletePhysicalFile(filename1); - binaryDataAccessor.deletePhysicalFile(filename1 + ".deleted"); - } - } - - /** - * 物理削除設定の場合ファイルの実体が削除されていること. - * PersoniumUnitConfingを利用するため、coreにテストを記述する - * @throws BinaryDataAccessException バイナリアクセスに失敗 - */ - @Test - public void 物理削除設定の場合ファイルの実体が削除されていること() throws BinaryDataAccessException { - String filename1 = "PcsInnovPhysicalDelete1"; - boolean isPhysicalDeleteMode = true; - BinaryDataAccessor binaryDataAccessor = new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), null, - isPhysicalDeleteMode, PersoniumUnitConfig.getFsyncEnabled()); - try { - // テンポラリファイルファイル作成 - long dataSize = "testhoge".getBytes().length; - InputStream is = new ByteArrayInputStream("testhoge".getBytes()); - BufferedInputStream bufferedInput = new BufferedInputStream(is); - long fileSize = binaryDataAccessor.create(bufferedInput, filename1); - assertEquals(dataSize, fileSize); - - // 「XXX.tmp」→「XXX」 - binaryDataAccessor.copyFile(filename1); - - // ファイル削除 - binaryDataAccessor.delete(filename1); - - // 削除確認 - boolean isExists = binaryDataAccessor.existsForFilename(filename1); - assertFalse(isExists); - // 論理削除ファイルが存在しないことの確認 - isExists = binaryDataAccessor.existsForFilename(filename1 + ".deleted"); - assertFalse(isExists); - - } finally { - // ファイル削除 - binaryDataAccessor.deletePhysicalFile(filename1); - binaryDataAccessor.deletePhysicalFile(filename1 + ".deleted"); - } - } - - /** - * 論理削除設定の場合ファイルが論理削除されていること. - * PersoniumUnitConfingを利用するため、coreにテストを記述する - * @throws BinaryDataAccessException バイナリアクセスに失敗 - */ - @Test - public void 論理削除設定の場合ファイルが論理削除されていること() throws BinaryDataAccessException { - String filename1 = "PcsInnovPhysicalDelete1"; - boolean isPhysicalDeleteMode = false; - BinaryDataAccessor binaryDataAccessor = new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), null, - isPhysicalDeleteMode, PersoniumUnitConfig.getFsyncEnabled()); - try { - // テンポラリファイルファイル作成 - long dataSize = "testhoge".getBytes().length; - InputStream is = new ByteArrayInputStream("testhoge".getBytes()); - BufferedInputStream bufferedInput = new BufferedInputStream(is); - long fileSize = binaryDataAccessor.create(bufferedInput, filename1); - assertEquals(dataSize, fileSize); - - // 「XXX.tmp」→「XXX」 - binaryDataAccessor.copyFile(filename1); - - // ファイル削除 - binaryDataAccessor.delete(filename1); - - // 削除確認 - boolean isExists = binaryDataAccessor.existsForFilename(filename1); - assertFalse(isExists); - // 論理削除ファイルが存在することの確認 - isExists = binaryDataAccessor.existsForFilename(filename1 + ".deleted"); - assertTrue(isExists); - - } finally { - // ファイル削除 - binaryDataAccessor.deletePhysicalFile(filename1); - binaryDataAccessor.deletePhysicalFile(filename1 + ".deleted"); - } - } - /** * fsync ON & FileInputStream. * FileDescriptor#sync() should be called. diff --git a/src/test/java/io/personium/core/model/impl/es/EsModelTest.java b/src/test/java/io/personium/core/model/impl/es/EsModelTest.java index 28835b7db..1bb637a6e 100644 --- a/src/test/java/io/personium/core/model/impl/es/EsModelTest.java +++ b/src/test/java/io/personium/core/model/impl/es/EsModelTest.java @@ -30,7 +30,6 @@ import org.junit.runner.RunWith; import io.personium.common.es.EsIndex; -import io.personium.core.model.impl.es.accessor.DavNodeAccessor; import io.personium.core.model.impl.es.accessor.EntitySetAccessor; import io.personium.core.model.impl.es.accessor.ODataLinkAccessor; import io.personium.test.categories.Unit; @@ -165,12 +164,4 @@ public void tearDown() throws Exception { assertNotNull(cellCtlLink); } - /** - * colメソッドでnullを指定した場合にNullPointerExceptionをスローする. - */ - @Test(expected = NullPointerException.class) - public void colメソッドでnullを指定した場合にNullPointerExceptionをスローする() { - DavNodeAccessor col = EsModel.col(null); - assertNotNull(col); - } } diff --git a/src/test/java/io/personium/core/model/impl/es/accessor/AllTests.java b/src/test/java/io/personium/core/model/impl/es/accessor/AllTests.java index 765830ae4..eb285a034 100644 --- a/src/test/java/io/personium/core/model/impl/es/accessor/AllTests.java +++ b/src/test/java/io/personium/core/model/impl/es/accessor/AllTests.java @@ -27,9 +27,7 @@ @SuiteClasses({ CellAccessorTest.class, DataSourceAccessorTest.class, - DavNodeAccessorTest.class, - ODataEntityAccessorTest.class, - ODataLinkAccessorTest.class + ODataEntityAccessorTest.class }) public class AllTests { } diff --git a/src/test/java/io/personium/core/model/impl/es/accessor/CellAccessorTest.java b/src/test/java/io/personium/core/model/impl/es/accessor/CellAccessorTest.java index ea3ae8492..218e40f04 100644 --- a/src/test/java/io/personium/core/model/impl/es/accessor/CellAccessorTest.java +++ b/src/test/java/io/personium/core/model/impl/es/accessor/CellAccessorTest.java @@ -1,329 +1,181 @@ -/** - * 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 io.personium.core.model.impl.es.accessor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.json.simple.JSONObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; - -import io.personium.common.es.EsClient; -import io.personium.common.es.EsIndex; -import io.personium.common.es.response.PersoniumIndexResponse; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.ads.JdbcAds; -import io.personium.core.model.impl.es.doc.CellDocHandler; -import io.personium.core.model.impl.es.doc.EntitySetDocHandler; -import io.personium.test.categories.Unit; -import io.personium.test.jersey.PersoniumIntegTestRunner; -import io.personium.test.unit.core.UrlUtils; - -/** - * CellAccessorTestの単体テストケース. - */ -@RunWith(PersoniumIntegTestRunner.class) -@Category({Unit.class }) -public class CellAccessorTest { - - private static final String INDEX_NAME = "index_for_test"; - private static final String TYPE_NAME = "TypeForTest"; - private static final String ROUTING_ID_NAME = "routing_id_for_test"; - - private EsClient esClient; - - /** - * 各テスト実行前の初期化処理. - * @throws Exception 異常が発生した場合の例外 - */ - @Before - public void setUp() throws Exception { - esClient = new EsClient(PersoniumUnitConfig.getEsClusterName(), PersoniumUnitConfig.getEsHosts()); - } - - /** - * 各テスト実行後のクリーンアップ処理. - * @throws Exception 異常が発生した場合の例外 - */ - @After - public void tearDown() throws Exception { - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix() + "_"; - EsIndex index = esClient.idxAdmin(esUnitPrefix + INDEX_NAME); - try { - index.delete(); - JdbcAds ads = new JdbcAds(); - ads.deleteIndex(esUnitPrefix + INDEX_NAME); - } catch (Exception ex) { - System.out.println(""); - } - } - - /** - * 例外用Mock. - * @author Administrator - */ - class JdbcAdsMock extends JdbcAds { - - JdbcAdsMock() throws Exception { - super(); - } - - @Override - public void createCell(String index, EntitySetDocHandler docHandler) throws AdsException { - throw new AdsException("MockErrorCreare"); - } - - @Override - public void updateCell(String index, EntitySetDocHandler docHandler) throws AdsException { - throw new AdsException("MockErrorUpdate"); - } - - @Override - public void deleteCell(String index, String id) throws AdsException { - throw new AdsException("MockErrorDelete"); - } - } - - /** - * create処理が正常に終了する. - */ - @Test - public void create処理が正常に終了する() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix() + "_"; - EsIndex index = esClient.idxAdmin(esUnitPrefix + INDEX_NAME); - assertNotNull(index); - CellAccessor cellAccessor = new CellAccessor(index, TYPE_NAME, ROUTING_ID_NAME); - CellDocHandler docHandler = createTestCellDocHandler(); - - // データ登録実行 - PersoniumIndexResponse response = cellAccessor.create(docHandler); - - // レスポンスのチェック - assertNotNull(response); - assertFalse(response.getId().equals("")); - - // マスタにデータが登録されていることを確認 - if (cellAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(1, ads.countCell(esUnitPrefix + INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - cellAccessor.delete(docHandler); - } - - /** - * create処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void create処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix() + "_"; - EsIndex index = esClient.idxAdmin(esUnitPrefix + INDEX_NAME); - assertNotNull(index); - CellAccessor cellAccessor = new CellAccessor(index, TYPE_NAME, ROUTING_ID_NAME); - CellDocHandler docHandler = createTestCellDocHandler(); - try { - cellAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データ登録実行 - PersoniumIndexResponse response = cellAccessor.create(docHandler); - - // レスポンスのチェック - assertNotNull(response); - assertFalse(response.getId().equals("")); - } - - /** - * update処理が正常に終了する. - */ - @Test - public void update処理が正常に終了する() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix() + "_"; - EsIndex index = esClient.idxAdmin(esUnitPrefix + INDEX_NAME); - assertNotNull(index); - CellAccessor cellAccessor = new CellAccessor(index, TYPE_NAME, ROUTING_ID_NAME); - CellDocHandler docHandler = createTestCellDocHandler(); - PersoniumIndexResponse createResponse = cellAccessor.create(docHandler); - assertNotNull(createResponse); - assertFalse(createResponse.getId().equals("")); - - // データ更新実行 - Map staticFields = new HashMap(); - staticFields.put("test", "testdata"); - docHandler.setStaticFields(staticFields); - - PersoniumIndexResponse updateResponse = cellAccessor.update(createResponse.getId(), docHandler); - - // レスポンスのチェック - assertNotNull(updateResponse); - assertEquals(createResponse.getId(), updateResponse.getId()); - - // マスタにデータが更新されていることを確認 - if (cellAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - List list = ads.getCellList(esUnitPrefix + INDEX_NAME, 0, 1); - assertEquals(1, list.size()); - assertEquals(JSONObject.toJSONString(staticFields), ((JSONObject) list.get(0).get("source")).get("s")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - cellAccessor.delete(docHandler); - } - - /** - * update処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void update処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix() + "_"; - EsIndex index = esClient.idxAdmin(esUnitPrefix + INDEX_NAME); - assertNotNull(index); - CellAccessor cellAccessor = new CellAccessor(index, TYPE_NAME, ROUTING_ID_NAME); - CellDocHandler docHandler = createTestCellDocHandler(); - PersoniumIndexResponse createResponse = cellAccessor.create(docHandler); - assertNotNull(createResponse); - assertFalse(createResponse.getId().equals("")); - - // データ更新実行 - try { - cellAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - Map staticFields = new HashMap(); - staticFields.put("test", "testdata"); - docHandler.setStaticFields(staticFields); - - PersoniumIndexResponse updateResponse = cellAccessor.update(createResponse.getId(), docHandler); - - // レスポンスのチェック - assertNotNull(updateResponse); - assertEquals(createResponse.getId(), updateResponse.getId()); - } - - /** - * delete処理が正常に終了する. - */ - @Test - public void delete処理が正常に終了する() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix() + "_"; - EsIndex index = esClient.idxAdmin(esUnitPrefix + INDEX_NAME); - assertNotNull(index); - CellAccessor cellAccessor = new CellAccessor(index, TYPE_NAME, ROUTING_ID_NAME); - CellDocHandler docHandler = createTestCellDocHandler(); - PersoniumIndexResponse response = cellAccessor.create(docHandler); - assertNotNull(response); - assertFalse(response.getId().equals("")); - - // データを削除する - cellAccessor.delete(docHandler); - - // データが削除されていることを確認する - if (cellAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(0, ads.countCell(esUnitPrefix + INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - } - - /** - * delete処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void delete処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix() + "_"; - EsIndex index = esClient.idxAdmin(esUnitPrefix + INDEX_NAME); - assertNotNull(index); - CellAccessor cellAccessor = new CellAccessor(index, TYPE_NAME, ROUTING_ID_NAME); - CellDocHandler docHandler = createTestCellDocHandler(); - PersoniumIndexResponse response = cellAccessor.create(docHandler); - assertNotNull(response); - assertFalse(response.getId().equals("")); - try { - cellAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データを削除する - cellAccessor.delete(docHandler); - } - - /** - * CellDocHandlerを生成する. - * @return - */ - private CellDocHandler createTestCellDocHandler() { - long dateTime = new Date().getTime(); - Map dynamicField = new HashMap(); - Map staticFields = new HashMap(); - Map hiddenFields = new HashMap(); - Map aclFields = new HashMap(); - Map link = new HashMap(); - CellDocHandler docHandler = new CellDocHandler(); - docHandler.setType("testType"); - docHandler.setCellId("testCellId"); - docHandler.setBoxId("testBoxId"); - docHandler.setNodeId("testNodeId"); - docHandler.setPublished(dateTime); - docHandler.setUpdated(dateTime); - docHandler.setDynamicFields(dynamicField); - docHandler.setStaticFields(staticFields); - docHandler.setHiddenFields(hiddenFields); - docHandler.setAclFields(aclFields); - docHandler.setManyToOnelinkId(link); - String url = UrlUtils.getBaseUrl() + "#" + INDEX_NAME; - hiddenFields.put("Owner", url); - docHandler.resolveUnitUserName(hiddenFields); - return docHandler; - } -} +/** + * 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 io.personium.core.model.impl.es.accessor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.json.simple.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; + +import io.personium.common.es.EsClient; +import io.personium.common.es.EsIndex; +import io.personium.common.es.response.PersoniumIndexResponse; +import io.personium.core.PersoniumUnitConfig; +import io.personium.core.model.impl.es.doc.CellDocHandler; +import io.personium.test.categories.Unit; +import io.personium.test.jersey.PersoniumIntegTestRunner; +import io.personium.test.unit.core.UrlUtils; + +/** + * CellAccessorTestの単体テストケース. + */ +@RunWith(PersoniumIntegTestRunner.class) +@Category({Unit.class }) +public class CellAccessorTest { + + private static final String INDEX_NAME = "index_for_test"; + private static final String TYPE_NAME = "TypeForTest"; + private static final String ROUTING_ID_NAME = "routing_id_for_test"; + + private EsClient esClient; + + /** + * 各テスト実行前の初期化処理. + * @throws Exception 異常が発生した場合の例外 + */ + @Before + public void setUp() throws Exception { + esClient = new EsClient(PersoniumUnitConfig.getEsClusterName(), PersoniumUnitConfig.getEsHosts()); + } + + /** + * 各テスト実行後のクリーンアップ処理. + * @throws Exception 異常が発生した場合の例外 + */ + @After + public void tearDown() throws Exception { + String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix() + "_"; + EsIndex index = esClient.idxAdmin(esUnitPrefix + INDEX_NAME); + try { + index.delete(); + } catch (Exception ex) { + System.out.println(""); + } + } + + /** + * create処理が正常に終了する. + */ + @Test + public void create処理が正常に終了する() { + // 事前準備 + String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix() + "_"; + EsIndex index = esClient.idxAdmin(esUnitPrefix + INDEX_NAME); + assertNotNull(index); + CellAccessor cellAccessor = new CellAccessor(index, TYPE_NAME, ROUTING_ID_NAME); + CellDocHandler docHandler = createTestCellDocHandler(); + + // データ登録実行 + PersoniumIndexResponse response = cellAccessor.create(docHandler); + + // レスポンスのチェック + assertNotNull(response); + assertFalse(response.getId().equals("")); + + // データを削除する + cellAccessor.delete(docHandler); + } + + /** + * update処理が正常に終了する. + */ + @Test + public void update処理が正常に終了する() { + // 事前準備 + String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix() + "_"; + EsIndex index = esClient.idxAdmin(esUnitPrefix + INDEX_NAME); + assertNotNull(index); + CellAccessor cellAccessor = new CellAccessor(index, TYPE_NAME, ROUTING_ID_NAME); + CellDocHandler docHandler = createTestCellDocHandler(); + PersoniumIndexResponse createResponse = cellAccessor.create(docHandler); + assertNotNull(createResponse); + assertFalse(createResponse.getId().equals("")); + + // データ更新実行 + Map staticFields = new HashMap(); + staticFields.put("test", "testdata"); + docHandler.setStaticFields(staticFields); + + PersoniumIndexResponse updateResponse = cellAccessor.update(createResponse.getId(), docHandler); + + // レスポンスのチェック + assertNotNull(updateResponse); + assertEquals(createResponse.getId(), updateResponse.getId()); + + // データを削除する + cellAccessor.delete(docHandler); + } + + /** + * delete処理が正常に終了する. + */ + @Test + public void delete処理が正常に終了する() { + // 事前準備 + String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix() + "_"; + EsIndex index = esClient.idxAdmin(esUnitPrefix + INDEX_NAME); + assertNotNull(index); + CellAccessor cellAccessor = new CellAccessor(index, TYPE_NAME, ROUTING_ID_NAME); + CellDocHandler docHandler = createTestCellDocHandler(); + PersoniumIndexResponse response = cellAccessor.create(docHandler); + assertNotNull(response); + assertFalse(response.getId().equals("")); + + // データを削除する + cellAccessor.delete(docHandler); + + } + + /** + * CellDocHandlerを生成する. + * @return + */ + private CellDocHandler createTestCellDocHandler() { + long dateTime = new Date().getTime(); + Map dynamicField = new HashMap(); + Map staticFields = new HashMap(); + Map hiddenFields = new HashMap(); + Map aclFields = new HashMap(); + Map link = new HashMap(); + CellDocHandler docHandler = new CellDocHandler(); + docHandler.setType("testType"); + docHandler.setCellId("testCellId"); + docHandler.setBoxId("testBoxId"); + docHandler.setNodeId("testNodeId"); + docHandler.setPublished(dateTime); + docHandler.setUpdated(dateTime); + docHandler.setDynamicFields(dynamicField); + docHandler.setStaticFields(staticFields); + docHandler.setHiddenFields(hiddenFields); + docHandler.setAclFields(aclFields); + docHandler.setManyToOnelinkId(link); + String url = UrlUtils.getBaseUrl() + "#" + INDEX_NAME; + hiddenFields.put("Owner", url); + docHandler.resolveUnitUserName(hiddenFields); + return docHandler; + } +} diff --git a/src/test/java/io/personium/core/model/impl/es/accessor/DavNodeAccessorTest.java b/src/test/java/io/personium/core/model/impl/es/accessor/DavNodeAccessorTest.java deleted file mode 100644 index a135a9832..000000000 --- a/src/test/java/io/personium/core/model/impl/es/accessor/DavNodeAccessorTest.java +++ /dev/null @@ -1,761 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.accessor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.util.Date; -import java.util.List; - -import org.json.simple.JSONObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; - -import io.personium.common.es.EsClient; -import io.personium.common.es.EsIndex; -import io.personium.common.es.response.PersoniumActionResponse; -import io.personium.common.es.response.PersoniumGetResponse; -import io.personium.common.es.response.PersoniumIndexResponse; -import io.personium.common.es.response.EsClientException; -import io.personium.common.es.util.PersoniumUUID; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.file.BinaryDataAccessException; -import io.personium.core.model.file.BinaryDataAccessor; -import io.personium.core.model.impl.es.DavNode; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.ads.JdbcAds; -import io.personium.test.categories.Unit; -import io.personium.test.jersey.PersoniumIntegTestRunner; - -/** - * DavNodeAccessorTestの単体テストケース. - */ -@RunWith(PersoniumIntegTestRunner.class) -@Category({Unit.class }) -public class DavNodeAccessorTest { - - private static final String UNIT_USER_NAME = "index_for_test"; - private static final String UNIT_PREFIX = PersoniumUnitConfig.getEsUnitPrefix(); - private static final String INDEX_NAME = UNIT_PREFIX + "_" + UNIT_USER_NAME; - private static final String TYPE_NAME = "TypeForTest"; - private static final String ROUTING_ID = "RoutingIdTest"; - - private BinaryDataAccessor binaryDataAccessor = new BinaryDataAccessor(PersoniumUnitConfig.getBlobStoreRoot(), - "index_for_test", PersoniumUnitConfig.getFsyncEnabled()); - private static EsClient esClient; - - /** - * 各テスト実行前の初期化処理. - * @throws Exception 異常が発生した場合の例外 - */ - @Before - public void setUp() throws Exception { - esClient = new EsClient(PersoniumUnitConfig.getEsClusterName(), PersoniumUnitConfig.getEsHosts()); - } - - /** - * 各テスト実行後のクリーンアップ処理. - * @throws Exception 異常が発生した場合の例外 - */ - @After - public void tearDown() throws Exception { - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - try { - index.delete(); - JdbcAds ads = new JdbcAds(); - ads.deleteIndex(INDEX_NAME); - } catch (Exception ex) { - System.out.println(""); - } - } - - /** - * 例外用Mock. - * @author Administrator - */ - class JdbcAdsMock extends JdbcAds { - - JdbcAdsMock() throws Exception { - super(); - } - - @Override - public void createDavNode(String index, DavNode davNode) throws AdsException { - throw new AdsException("MockErrorCreare"); - } - - @Override - public void updateDavNode(String index, DavNode davNode) throws AdsException { - throw new AdsException("MockErrorUpdate"); - } - - @Override - public void deleteDavNode(String index, String id) throws AdsException { - throw new AdsException("MockErrorDelete"); - } - } - - /** - * 例外用Mock. - * @author Administrator - */ - class JdbcAdsMockDavNodeAccessor extends DavNodeAccessor { - - JdbcAdsMockDavNodeAccessor(EsIndex index, String name, String routingId) throws Exception { - super(index, name, routingId); - } - - @Override - public PersoniumActionResponse createForFile(String id, DavNode davNode) { - throw new EsClientException(id); - } - } - - /** - * create処理が正常に終了する. - */ - @Test - public void create処理が正常に終了する() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(); - - // データ登録実行 - PersoniumIndexResponse response = davNodeAccessor.create(davNode); - - // レスポンスのチェック - assertNotNull(response); - assertFalse(response.getId().equals("")); - - // マスタにデータが登録されていることを確認 - if (davNodeAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(1, ads.countDavNode(INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - davNodeAccessor.delete(davNode); - } - - /** - * create処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void create処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(); - try { - davNodeAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データ登録実行 - PersoniumIndexResponse response = davNodeAccessor.create(davNode); - - // レスポンスのチェック - assertNotNull(response); - assertFalse(response.getId().equals("")); - } - - /** - * update処理が正常に終了する. - */ - @Test - public void update処理が正常に終了する() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(); - PersoniumIndexResponse createResponse = davNodeAccessor.create(davNode); - assertNotNull(createResponse); - assertFalse(createResponse.getId().equals("")); - - // データ更新実行 - long dateTime = new Date().getTime(); - davNode.setUpdated(dateTime); - - PersoniumIndexResponse updateResponse = davNodeAccessor.update(createResponse.getId(), davNode); - - // レスポンスのチェック - assertNotNull(updateResponse); - assertEquals(createResponse.getId(), updateResponse.getId()); - - // マスタにデータが更新されていることを確認 - if (davNodeAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - List list = ads.getDavNodeList(INDEX_NAME, 0, 1); - assertEquals(1, list.size()); - assertEquals(dateTime, Long.parseLong((String) ((JSONObject) list.get(0).get("source")).get("u"))); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - davNodeAccessor.delete(davNode); - } - - /** - * update処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void update処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(); - PersoniumIndexResponse createResponse = davNodeAccessor.create(davNode); - assertNotNull(createResponse); - assertFalse(createResponse.getId().equals("")); - try { - davNodeAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データ更新実行 - long dateTime = new Date().getTime(); - davNode.setUpdated(dateTime); - - PersoniumIndexResponse updateResponse = davNodeAccessor.update(createResponse.getId(), davNode); - - // レスポンスのチェック - assertNotNull(updateResponse); - assertEquals(createResponse.getId(), updateResponse.getId()); - } - - /** - * delete処理が正常に終了する. - */ - @Test - public void delete処理が正常に終了する() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(); - PersoniumIndexResponse response = davNodeAccessor.create(davNode); - assertNotNull(response); - assertFalse(response.getId().equals("")); - - // データを削除する - davNodeAccessor.delete(davNode); - - // データが削除されていることを確認する - if (davNodeAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(0, ads.countDavNode(INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - } - - /** - * delete処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void delete処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(); - PersoniumIndexResponse response = davNodeAccessor.create(davNode); - assertNotNull(response); - assertFalse(response.getId().equals("")); - try { - davNodeAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データを削除する - davNodeAccessor.delete(davNode); - } - - /** - * ファイルありcreate処理が正常に終了する. - */ - @Test - public void ファイルありcreate処理が正常に終了する() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - - String id = PersoniumUUID.randomUUID(); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(id); - - // データ登録実行 - PersoniumActionResponse response = davNodeAccessor.createForFile(id, davNode); - - // レスポンスのチェック - assertNotNull(response); - String resId = null; - if (response instanceof PersoniumIndexResponse) { - resId = ((PersoniumIndexResponse) response).getId(); - } else if (response instanceof PersoniumGetResponse) { - resId = ((PersoniumGetResponse) response).getId(); - } - assertEquals(id, resId); - - assertTrue(binaryDataAccessor.existsForFilename(id)); - assertFalse(binaryDataAccessor.existsForFilename(id + ".tmp")); - - // マスタにデータが登録されていることを確認 - if (davNodeAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(1, ads.countDavNode(INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - davNodeAccessor.delete(davNode); - deleteTestTmpFile(id); - } - - /** - * ファイルありcreate処理でESエラーが発生した場合ファイルが存在しないこと. - */ - @Test - public void ファイルありcreate処理でESエラーが発生した場合ファイルが存在しないこと() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - - String id = PersoniumUUID.randomUUID(); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(id); - - // データ登録実行 - PersoniumActionResponse response = davNodeAccessor.createForFile(id, davNode); - - // レスポンスのチェック - assertNotNull(response); - String resId = null; - if (response instanceof PersoniumIndexResponse) { - resId = ((PersoniumIndexResponse) response).getId(); - } else if (response instanceof PersoniumGetResponse) { - resId = ((PersoniumGetResponse) response).getId(); - } - assertEquals(id, resId); - assertTrue(binaryDataAccessor.existsForFilename(id)); - assertFalse(binaryDataAccessor.existsForFilename(id + ".tmp")); - - // マスタにデータが登録されていることを確認 - if (davNodeAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(1, ads.countDavNode(INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // テスト用にファイル削除 - deleteTestTmpFile(id); - - try { - // データ登録実行 - // Mockを使用してESClientExceptionを発生させる - new JdbcAdsMockDavNodeAccessor(index, TYPE_NAME, ROUTING_ID).createForFile(id, davNode); - } catch (Exception e) { - e.printStackTrace(); - } - assertFalse(binaryDataAccessor.existsForFilename(id)); - assertFalse(binaryDataAccessor.existsForFilename(id + ".tmp")); - - // データを削除する - davNodeAccessor.delete(davNode); - } - - /** - * ファイルありcreate処理でMySQLエラーが発生した場合ファイルが存在しないこと. - */ - @Test - public void ファイルありcreate処理でMySQLエラーが発生した場合ファイルが存在しないこと() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - - String id = PersoniumUUID.randomUUID(); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(id); - - DavNodeAccessor davNodeAccessorTest = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - try { - davNodeAccessorTest.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データ登録実行 - PersoniumActionResponse response = davNodeAccessorTest.createForFile(id, davNode); - - // レスポンスのチェック - assertNotNull(response); - String resId = null; - if (response instanceof PersoniumIndexResponse) { - resId = ((PersoniumIndexResponse) response).getId(); - } else if (response instanceof PersoniumGetResponse) { - resId = ((PersoniumGetResponse) response).getId(); - } - assertEquals(id, resId); - assertTrue(binaryDataAccessor.existsForFilename(id)); - assertFalse(binaryDataAccessor.existsForFilename(id + ".tmp")); - - // マスタにデータが登録されていないことを確認 - if (davNodeAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(0, ads.countDavNode(INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - davNodeAccessor.delete(davNode); - deleteTestTmpFile(id); - } - - /** - * ファイルありcreate処理で一時ファイルのコピーに失敗した場合ファイルが存在しないこと. - */ - @Test - public void ファイルありcreate処理で一時ファイルのコピーに失敗した場合ファイルが存在しないこと() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - - String id = PersoniumUUID.randomUUID(); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(); - - try { - // データ登録実行 - davNodeAccessor.createForFile(id, davNode); - } catch (Exception e) { - e.printStackTrace(); - } - - // レスポンスのチェック - assertFalse(binaryDataAccessor.existsForFilename(id)); - assertFalse(binaryDataAccessor.existsForFilename(id + ".tmp")); - - // マスタにデータが登録されていないことを確認 - if (davNodeAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(0, ads.countDavNode(INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - davNodeAccessor.delete(davNode); - } - - /** - * ファイルありupdate処理が正常に終了する. - */ - @Test - public void ファイルありupdate処理が正常に終了する() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - String id = PersoniumUUID.randomUUID(); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(id); - PersoniumActionResponse createResponse = davNodeAccessor.createForFile(id, davNode); - assertNotNull(createResponse); - String resId = null; - if (createResponse instanceof PersoniumIndexResponse) { - resId = ((PersoniumIndexResponse) createResponse).getId(); - } else if (createResponse instanceof PersoniumGetResponse) { - resId = ((PersoniumGetResponse) createResponse).getId(); - } - assertFalse(resId.equals("")); - - assertTrue(binaryDataAccessor.existsForFilename(id)); - assertFalse(binaryDataAccessor.existsForFilename(id + ".tmp")); - - // データ更新実行 - long dateTime = new Date().getTime(); - davNode.setUpdated(dateTime); - createTestTmpFile(id, "DavNodeAccessorTest Update!"); - - PersoniumIndexResponse updateResponse = davNodeAccessor.updateForFile(resId, davNode, -1); - - // レスポンスのチェック - assertNotNull(updateResponse); - assertEquals(resId, updateResponse.getId()); - assertTrue(binaryDataAccessor.existsForFilename(id)); - assertFalse(binaryDataAccessor.existsForFilename(id + ".tmp")); - assertEquals("DavNodeAccessorTest Update!", readFile(id)); - - // マスタにデータが更新されていることを確認 - if (davNodeAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - List list = ads.getDavNodeList(INDEX_NAME, 0, 1); - assertEquals(1, list.size()); - assertEquals(dateTime, Long.parseLong((String) ((JSONObject) list.get(0).get("source")).get("u"))); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - davNodeAccessor.delete(davNode); - deleteTestTmpFile(id); - } - - /** - * ファイルありupdate処理でMySQLエラーが発生した場合ファイルが更新されないこと. - */ - @Test - public void ファイルありupdate処理でMySQLエラーが発生した場合ファイルが更新されないこと() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - String id = PersoniumUUID.randomUUID(); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(id); - PersoniumActionResponse createResponse = davNodeAccessor.createForFile(id, davNode); - assertNotNull(createResponse); - String resId = null; - if (createResponse instanceof PersoniumIndexResponse) { - resId = ((PersoniumIndexResponse) createResponse).getId(); - } else if (createResponse instanceof PersoniumGetResponse) { - resId = ((PersoniumGetResponse) createResponse).getId(); - } - assertFalse(resId.equals("")); - assertTrue(binaryDataAccessor.existsForFilename(id)); - assertFalse(binaryDataAccessor.existsForFilename(id + ".tmp")); - - // データ更新実行 - long dateTime = new Date().getTime(); - davNode.setUpdated(dateTime); - createTestTmpFile(id, "DavNodeAccessorTest Update!"); - - DavNodeAccessor davNodeAccessorUp = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - try { - davNodeAccessorUp.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - PersoniumIndexResponse updateResponse = davNodeAccessorUp.updateForFile(resId, davNode, -1); - - // レスポンスのチェック - assertNotNull(updateResponse); - assertEquals(resId, updateResponse.getId()); - assertTrue(binaryDataAccessor.existsForFilename(id)); - assertFalse(binaryDataAccessor.existsForFilename(id + ".tmp")); - assertEquals("DavNodeAccessorTest Update!", readFile(id)); - - // マスタにデータが更新されていないことを確認 - if (davNodeAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - List list = ads.getDavNodeList(INDEX_NAME, 0, 1); - assertEquals(1, list.size()); - assertFalse(Long.toString(dateTime).equals((String) ((JSONObject) list.get(0).get("source")).get("u"))); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - davNodeAccessor.delete(davNode); - deleteTestTmpFile(id); - } - - /** - * ファイルありupdate処理で一時ファイルのコピーに失敗した場合ファイルが更新されないこと. - */ - @Test - public void ファイルありupdate処理で一時ファイルのコピーに失敗した場合ファイルが更新されないこと() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - String id = PersoniumUUID.randomUUID(); - DavNodeAccessor davNodeAccessor = new DavNodeAccessor(index, TYPE_NAME, ROUTING_ID); - DavNode davNode = createTestDavNode(id); - PersoniumActionResponse createResponse = davNodeAccessor.createForFile(id, davNode); - assertNotNull(createResponse); - String resId = null; - if (createResponse instanceof PersoniumIndexResponse) { - resId = ((PersoniumIndexResponse) createResponse).getId(); - } else if (createResponse instanceof PersoniumGetResponse) { - resId = ((PersoniumGetResponse) createResponse).getId(); - } - assertFalse(resId.equals("")); - assertTrue(binaryDataAccessor.existsForFilename(id)); - assertFalse(binaryDataAccessor.existsForFilename(id + ".tmp")); - - // データ更新実行 - long dateTime = new Date().getTime(); - davNode.setUpdated(dateTime); - - try { - davNodeAccessor.updateForFile(resId, davNode, -1); - } catch (Exception e) { - e.printStackTrace(); - } - - // レスポンスのチェック - assertTrue(binaryDataAccessor.existsForFilename(id)); - assertFalse(binaryDataAccessor.existsForFilename(id + ".tmp")); - assertEquals("DavNodeAccessorTest", readFile(id)); - - // マスタにデータが更新されていないことを確認 - if (davNodeAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - List list = ads.getDavNodeList(INDEX_NAME, 0, 1); - assertEquals(1, list.size()); - assertFalse(Long.toString(dateTime).equals((String) ((JSONObject) list.get(0).get("source")).get("u"))); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - davNodeAccessor.delete(davNode); - deleteTestTmpFile(id); - } - - /** - * DavCmpEsImplを生成する. - * @return DavCmpEsImpl - */ - private DavNode createTestDavNode() { - DavNode davNode = new DavNode(); - return davNode; - } - - /** - * DavCmpEsImplを生成する. - * @return DavCmpEsImpl - */ - private DavNode createTestDavNode(String id) { - DavNode davNode = new DavNode(); - // 一時ファイル作成 - createTestTmpFile(id); - return davNode; - } - - private void createTestTmpFile(String id) { - createTestTmpFile(id, "DavNodeAccessorTest"); - } - - private void createTestTmpFile(String id, String body) { - InputStream is = new ByteArrayInputStream(body.getBytes()); - BufferedInputStream bufferedInput = new BufferedInputStream(is); - - try { - binaryDataAccessor.create(bufferedInput, id); - } catch (BinaryDataAccessException e) { - fail(e.getMessage()); - } - } - - private void deleteTestTmpFile(String id) { - try { - binaryDataAccessor.deletePhysicalFile(id); - } catch (BinaryDataAccessException e) { - fail(e.getMessage()); - } - } - - private String readFile(String filename) { - FileReader f = null; - BufferedReader b = null; - StringBuffer sb = new StringBuffer(); - - String filepath = binaryDataAccessor.getFilePath(filename); - try { - f = new FileReader(filepath); - b = new BufferedReader(f); - String s; - while ((s = b.readLine()) != null) { - sb.append(s); - } - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - if (b != null) { - try { - b.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - if (f != null) { - try { - f.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - return sb.toString(); - } -} diff --git a/src/test/java/io/personium/core/model/impl/es/accessor/ODataEntityAccessorTest.java b/src/test/java/io/personium/core/model/impl/es/accessor/ODataEntityAccessorTest.java index 137a4c839..daf848a43 100644 --- a/src/test/java/io/personium/core/model/impl/es/accessor/ODataEntityAccessorTest.java +++ b/src/test/java/io/personium/core/model/impl/es/accessor/ODataEntityAccessorTest.java @@ -1,327 +1,177 @@ -/** - * 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 io.personium.core.model.impl.es.accessor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.json.simple.JSONObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; - -import io.personium.common.es.EsClient; -import io.personium.common.es.EsIndex; -import io.personium.common.es.response.PersoniumIndexResponse; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.ads.JdbcAds; -import io.personium.core.model.impl.es.doc.EntitySetDocHandler; -import io.personium.core.model.impl.es.doc.OEntityDocHandler; -import io.personium.test.categories.Unit; -import io.personium.test.jersey.PersoniumIntegTestRunner; -import io.personium.test.unit.core.UrlUtils; - -/** - * ODataEntityAccessorTestの単体テストケース. - */ -@RunWith(PersoniumIntegTestRunner.class) -@Category({Unit.class }) -public class ODataEntityAccessorTest { - - private static final String INDEX_NAME = "index_for_test"; - private static final String TYPE_NAME = "TypeForTest"; - private static final String ROUTING_ID = "RoutingIdTest"; - - private static EsClient esClient; - - /** - * 各テスト実行前の初期化処理. - * @throws Exception 異常が発生した場合の例外 - */ - @Before - public void setUp() throws Exception { - esClient = new EsClient(PersoniumUnitConfig.getEsClusterName(), PersoniumUnitConfig.getEsHosts()); - } - - /** - * 各テスト実行後のクリーンアップ処理. - * @throws Exception 異常が発生した場合の例外 - */ - @After - public void tearDown() throws Exception { - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); - EsIndex index = esClient.idxUser(esUnitPrefix, INDEX_NAME); - try { - index.delete(); - JdbcAds ads = new JdbcAds(); - ads.deleteIndex(esUnitPrefix + "_" + INDEX_NAME); - } catch (Exception ex) { - System.out.println(""); - } - } - - /** - * 例外用Mock. - * @author Administrator - */ - class JdbcAdsMock extends JdbcAds { - - JdbcAdsMock() throws Exception { - super(); - } - - @Override - public void createEntity(String index, EntitySetDocHandler docHandler) throws AdsException { - throw new AdsException("MockErrorCreare"); - } - - @Override - public void updateEntity(String index, EntitySetDocHandler docHandler) throws AdsException { - throw new AdsException("MockErrorUpdate"); - } - - @Override - public void deleteEntity(String index, String id) throws AdsException { - throw new AdsException("MockErrorDelete"); - } - } - - /** - * create処理が正常に終了する. - */ - @Test - public void create処理が正常に終了する() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); - EsIndex index = esClient.idxUser(esUnitPrefix, INDEX_NAME); - assertNotNull(index); - ODataEntityAccessor entityAccessor = new ODataEntityAccessor(index, TYPE_NAME, ROUTING_ID); - OEntityDocHandler docHandler = createTestOEntityDocHandler(); - - // データ登録実行 - PersoniumIndexResponse response = entityAccessor.create(docHandler); - - // レスポンスのチェック - assertNotNull(response); - assertFalse(response.getId().equals("")); - - // マスタにデータが登録されていることを確認 - if (entityAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(1, ads.countEntity(esUnitPrefix + "_" + INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - entityAccessor.delete(docHandler); - } - - /** - * create処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void create処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); - EsIndex index = esClient.idxUser(esUnitPrefix, INDEX_NAME); - assertNotNull(index); - ODataEntityAccessor entityAccessor = new ODataEntityAccessor(index, TYPE_NAME, ROUTING_ID); - OEntityDocHandler docHandler = createTestOEntityDocHandler(); - try { - entityAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データ登録実行 - PersoniumIndexResponse response = entityAccessor.create(docHandler); - - // レスポンスのチェック - assertNotNull(response); - assertFalse(response.getId().equals("")); - } - - /** - * update処理が正常に終了する. - */ - @Test - public void update処理が正常に終了する() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); - EsIndex index = esClient.idxUser(esUnitPrefix, INDEX_NAME); - assertNotNull(index); - ODataEntityAccessor entityAccessor = new ODataEntityAccessor(index, TYPE_NAME, ROUTING_ID); - OEntityDocHandler docHandler = createTestOEntityDocHandler(); - PersoniumIndexResponse createResponse = entityAccessor.create(docHandler); - assertNotNull(createResponse); - assertFalse(createResponse.getId().equals("")); - - // データ更新実行 - Map staticFields = new HashMap(); - staticFields.put("test", "testdata"); - docHandler.setStaticFields(staticFields); - - PersoniumIndexResponse updateResponse = entityAccessor.update(createResponse.getId(), docHandler); - - // レスポンスのチェック - assertNotNull(updateResponse); - assertEquals(createResponse.getId(), updateResponse.getId()); - - // マスタにデータが更新されていることを確認 - if (entityAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - List list = ads.getEntityList(esUnitPrefix + "_" + INDEX_NAME, 0, 1); - assertEquals(1, list.size()); - assertEquals(JSONObject.toJSONString(staticFields), ((JSONObject) list.get(0).get("source")).get("s")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - entityAccessor.delete(docHandler); - } - - /** - * update処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void update処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); - EsIndex index = esClient.idxUser(esUnitPrefix, INDEX_NAME); - assertNotNull(index); - ODataEntityAccessor entityAccessor = new ODataEntityAccessor(index, TYPE_NAME, ROUTING_ID); - OEntityDocHandler docHandler = createTestOEntityDocHandler(); - PersoniumIndexResponse createResponse = entityAccessor.create(docHandler); - assertNotNull(createResponse); - assertFalse(createResponse.getId().equals("")); - try { - entityAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データ更新実行 - Map staticFields = new HashMap(); - staticFields.put("test", "testdata"); - docHandler.setStaticFields(staticFields); - - PersoniumIndexResponse updateResponse = entityAccessor.update(createResponse.getId(), docHandler); - - // レスポンスのチェック - assertNotNull(updateResponse); - assertEquals(createResponse.getId(), updateResponse.getId()); - } - - /** - * delete処理が正常に終了する. - */ - @Test - public void delete処理が正常に終了する() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); - EsIndex index = esClient.idxUser(esUnitPrefix, INDEX_NAME); - assertNotNull(index); - ODataEntityAccessor entityAccessor = new ODataEntityAccessor(index, TYPE_NAME, ROUTING_ID); - OEntityDocHandler docHandler = createTestOEntityDocHandler(); - PersoniumIndexResponse response = entityAccessor.create(docHandler); - assertNotNull(response); - assertFalse(response.getId().equals("")); - - // データを削除する - entityAccessor.delete(docHandler); - - // データが削除されていることを確認する - if (entityAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(0, ads.countEntity(esUnitPrefix + "_" + INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - } - - /** - * delete処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void delete処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); - EsIndex index = esClient.idxUser(esUnitPrefix, INDEX_NAME); - assertNotNull(index); - ODataEntityAccessor entityAccessor = new ODataEntityAccessor(index, TYPE_NAME, ROUTING_ID); - OEntityDocHandler docHandler = createTestOEntityDocHandler(); - PersoniumIndexResponse response = entityAccessor.create(docHandler); - assertNotNull(response); - assertFalse(response.getId().equals("")); - try { - entityAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データを削除する - entityAccessor.delete(docHandler); - } - - /** - * OEntityDocHandlerを生成する. - * @return - */ - private OEntityDocHandler createTestOEntityDocHandler() { - long dateTime = new Date().getTime(); - Map dynamicField = new HashMap(); - Map staticFields = new HashMap(); - Map hiddenFields = new HashMap(); - Map link = new HashMap(); - OEntityDocHandler docHandler = new OEntityDocHandler(); - docHandler.setType("testType"); - docHandler.setCellId("testCellId"); - docHandler.setBoxId("testBoxId"); - docHandler.setNodeId("testNodeId"); - docHandler.setPublished(dateTime); - docHandler.setUpdated(dateTime); - docHandler.setDynamicFields(dynamicField); - docHandler.setStaticFields(staticFields); - docHandler.setHiddenFields(hiddenFields); - docHandler.setManyToOnelinkId(link); - String url = UrlUtils.getBaseUrl() + "#" + INDEX_NAME; - hiddenFields.put("Owner", url); - docHandler.resolveUnitUserName(hiddenFields); - return docHandler; - } -} +/** + * 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 io.personium.core.model.impl.es.accessor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; + +import io.personium.common.es.EsClient; +import io.personium.common.es.EsIndex; +import io.personium.common.es.response.PersoniumIndexResponse; +import io.personium.core.PersoniumUnitConfig; +import io.personium.core.model.impl.es.doc.OEntityDocHandler; +import io.personium.test.categories.Unit; +import io.personium.test.jersey.PersoniumIntegTestRunner; +import io.personium.test.unit.core.UrlUtils; + +/** + * ODataEntityAccessorTestの単体テストケース. + */ +@RunWith(PersoniumIntegTestRunner.class) +@Category({Unit.class }) +public class ODataEntityAccessorTest { + + private static final String INDEX_NAME = "index_for_test"; + private static final String TYPE_NAME = "TypeForTest"; + private static final String ROUTING_ID = "RoutingIdTest"; + + private static EsClient esClient; + + /** + * 各テスト実行前の初期化処理. + * @throws Exception 異常が発生した場合の例外 + */ + @Before + public void setUp() throws Exception { + esClient = new EsClient(PersoniumUnitConfig.getEsClusterName(), PersoniumUnitConfig.getEsHosts()); + } + + /** + * 各テスト実行後のクリーンアップ処理. + * @throws Exception 異常が発生した場合の例外 + */ + @After + public void tearDown() throws Exception { + String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); + EsIndex index = esClient.idxUser(esUnitPrefix, INDEX_NAME); + try { + index.delete(); + } catch (Exception ex) { + System.out.println(""); + } + } + + /** + * create処理が正常に終了する. + */ + @Test + public void create処理が正常に終了する() { + // 事前準備 + String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); + EsIndex index = esClient.idxUser(esUnitPrefix, INDEX_NAME); + assertNotNull(index); + ODataEntityAccessor entityAccessor = new ODataEntityAccessor(index, TYPE_NAME, ROUTING_ID); + OEntityDocHandler docHandler = createTestOEntityDocHandler(); + + // データ登録実行 + PersoniumIndexResponse response = entityAccessor.create(docHandler); + + // レスポンスのチェック + assertNotNull(response); + assertFalse(response.getId().equals("")); + + // データを削除する + entityAccessor.delete(docHandler); + } + + /** + * update処理が正常に終了する. + */ + @Test + public void update処理が正常に終了する() { + // 事前準備 + String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); + EsIndex index = esClient.idxUser(esUnitPrefix, INDEX_NAME); + assertNotNull(index); + ODataEntityAccessor entityAccessor = new ODataEntityAccessor(index, TYPE_NAME, ROUTING_ID); + OEntityDocHandler docHandler = createTestOEntityDocHandler(); + PersoniumIndexResponse createResponse = entityAccessor.create(docHandler); + assertNotNull(createResponse); + assertFalse(createResponse.getId().equals("")); + + // データ更新実行 + Map staticFields = new HashMap(); + staticFields.put("test", "testdata"); + docHandler.setStaticFields(staticFields); + + PersoniumIndexResponse updateResponse = entityAccessor.update(createResponse.getId(), docHandler); + + // レスポンスのチェック + assertNotNull(updateResponse); + assertEquals(createResponse.getId(), updateResponse.getId()); + + // データを削除する + entityAccessor.delete(docHandler); + } + + /** + * delete処理が正常に終了する. + */ + @Test + public void delete処理が正常に終了する() { + // 事前準備 + String esUnitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); + EsIndex index = esClient.idxUser(esUnitPrefix, INDEX_NAME); + assertNotNull(index); + ODataEntityAccessor entityAccessor = new ODataEntityAccessor(index, TYPE_NAME, ROUTING_ID); + OEntityDocHandler docHandler = createTestOEntityDocHandler(); + PersoniumIndexResponse response = entityAccessor.create(docHandler); + assertNotNull(response); + assertFalse(response.getId().equals("")); + + // データを削除する + entityAccessor.delete(docHandler); + } + + /** + * OEntityDocHandlerを生成する. + * @return + */ + private OEntityDocHandler createTestOEntityDocHandler() { + long dateTime = new Date().getTime(); + Map dynamicField = new HashMap(); + Map staticFields = new HashMap(); + Map hiddenFields = new HashMap(); + Map link = new HashMap(); + OEntityDocHandler docHandler = new OEntityDocHandler(); + docHandler.setType("testType"); + docHandler.setCellId("testCellId"); + docHandler.setBoxId("testBoxId"); + docHandler.setNodeId("testNodeId"); + docHandler.setPublished(dateTime); + docHandler.setUpdated(dateTime); + docHandler.setDynamicFields(dynamicField); + docHandler.setStaticFields(staticFields); + docHandler.setHiddenFields(hiddenFields); + docHandler.setManyToOnelinkId(link); + String url = UrlUtils.getBaseUrl() + "#" + INDEX_NAME; + hiddenFields.put("Owner", url); + docHandler.resolveUnitUserName(hiddenFields); + return docHandler; + } +} diff --git a/src/test/java/io/personium/core/model/impl/es/accessor/ODataLinkAccessorTest.java b/src/test/java/io/personium/core/model/impl/es/accessor/ODataLinkAccessorTest.java deleted file mode 100644 index ae29a154e..000000000 --- a/src/test/java/io/personium/core/model/impl/es/accessor/ODataLinkAccessorTest.java +++ /dev/null @@ -1,308 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.accessor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.util.Date; -import java.util.List; - -import org.json.simple.JSONObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; - -import io.personium.common.es.EsClient; -import io.personium.common.es.EsIndex; -import io.personium.common.es.response.PersoniumIndexResponse; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.ads.JdbcAds; -import io.personium.core.model.impl.es.doc.LinkDocHandler; -import io.personium.test.categories.Unit; -import io.personium.test.jersey.PersoniumIntegTestRunner; - -/** - * ODataLinkAccessorTestの単体テストケース. - */ -@RunWith(PersoniumIntegTestRunner.class) -@Category({Unit.class }) -public class ODataLinkAccessorTest { - - private static final String UNIT_PREFIX = PersoniumUnitConfig.getEsUnitPrefix(); - private static final String UNIT_USER_NAME = "index_for_test"; - private static final String INDEX_NAME = UNIT_PREFIX + "_" + UNIT_USER_NAME; - private static final String TYPE_NAME = "TypeForTest"; - private static final String ROUTING_ID = "RoutingIdTest"; - - private static EsClient esClient; - - /** - * 各テスト実行前の初期化処理. - * @throws Exception 異常が発生した場合の例外 - */ - @Before - public void setUp() throws Exception { - esClient = new EsClient(PersoniumUnitConfig.getEsClusterName(), PersoniumUnitConfig.getEsHosts()); - } - - /** - * 各テスト実行後のクリーンアップ処理. - * @throws Exception 異常が発生した場合の例外 - */ - @After - public void tearDown() throws Exception { - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - try { - index.delete(); - JdbcAds ads = new JdbcAds(); - ads.deleteIndex(INDEX_NAME); - } catch (Exception ex) { - System.out.println(""); - } - } - - /** - * 例外用Mock. - * @author Administrator - */ - class JdbcAdsMock extends JdbcAds { - - JdbcAdsMock() throws Exception { - super(); - } - - @Override - public void createLink(String index, LinkDocHandler docHandler) throws AdsException { - throw new AdsException("MockErrorCreare"); - } - - @Override - public void updateLink(String index, LinkDocHandler docHandler) throws AdsException { - throw new AdsException("MockErrorUpdate"); - } - - @Override - public void deleteLink(String index, String id) throws AdsException { - throw new AdsException("MockErrorDelete"); - } - } - - /** - * create処理が正常に終了する. - */ - @Test - public void create処理が正常に終了する() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - ODataLinkAccessor linkAccessor = new ODataLinkAccessor(index, TYPE_NAME, ROUTING_ID); - LinkDocHandler docHandler = createTestLinkDocHandler(); - - // データ登録実行 - PersoniumIndexResponse response = linkAccessor.create(docHandler); - - // レスポンスのチェック - assertNotNull(response); - assertFalse(response.getId().equals("")); - - // マスタにデータが登録されていることを確認 - if (linkAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(1, ads.countLink(INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - linkAccessor.delete(docHandler); - } - - /** - * create処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void create処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - ODataLinkAccessor linkAccessor = new ODataLinkAccessor(index, TYPE_NAME, ROUTING_ID); - LinkDocHandler docHandler = createTestLinkDocHandler(); - try { - linkAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データ登録実行 - PersoniumIndexResponse response = linkAccessor.create(docHandler); - - // レスポンスのチェック - assertNotNull(response); - assertFalse(response.getId().equals("")); - } - - /** - * update処理が正常に終了する. - */ - @Test - public void update処理が正常に終了する() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - ODataLinkAccessor linkAccessor = new ODataLinkAccessor(index, TYPE_NAME, ROUTING_ID); - LinkDocHandler docHandler = createTestLinkDocHandler(); - PersoniumIndexResponse createResponse = linkAccessor.create(docHandler); - assertNotNull(createResponse); - assertFalse(createResponse.getId().equals("")); - - // データ更新実行 - String updateString = "updatedEnt1Key"; - docHandler.setEnt1Key(updateString); - - PersoniumIndexResponse updateResponse = linkAccessor.update(createResponse.getId(), docHandler); - - // レスポンスのチェック - assertNotNull(updateResponse); - assertEquals(createResponse.getId(), updateResponse.getId()); - - // マスタにデータが更新されていることを確認 - if (linkAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - List list = ads.getLinkList(INDEX_NAME, 0, 1); - assertEquals(1, list.size()); - assertEquals(updateString, ((JSONObject) list.get(0).get("source")).get("k1")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - // データを削除する - linkAccessor.delete(docHandler); - } - - /** - * update処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void update処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - ODataLinkAccessor linkAccessor = new ODataLinkAccessor(index, TYPE_NAME, ROUTING_ID); - LinkDocHandler docHandler = createTestLinkDocHandler(); - PersoniumIndexResponse createResponse = linkAccessor.create(docHandler); - assertNotNull(createResponse); - assertFalse(createResponse.getId().equals("")); - try { - linkAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データ更新実行 - String updateString = "updatedEnt1Key"; - docHandler.setEnt1Key(updateString); - - PersoniumIndexResponse updateResponse = linkAccessor.update(createResponse.getId(), docHandler); - - // レスポンスのチェック - assertNotNull(updateResponse); - assertEquals(createResponse.getId(), updateResponse.getId()); - } - - /** - * delete処理が正常に終了する. - */ - @Test - public void delete処理が正常に終了する() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - ODataLinkAccessor linkAccessor = new ODataLinkAccessor(index, TYPE_NAME, ROUTING_ID); - LinkDocHandler docHandler = createTestLinkDocHandler(); - PersoniumIndexResponse response = linkAccessor.create(docHandler); - assertNotNull(response); - assertFalse(response.getId().equals("")); - - // データを削除する - linkAccessor.delete(docHandler); - - // データが削除されていることを確認する - if (linkAccessor.getAds() != null) { - JdbcAds ads = null; - try { - ads = new JdbcAds(); - assertEquals(0, ads.countLink(INDEX_NAME)); - } catch (Exception e) { - fail(e.getMessage()); - } - } - } - - /** - * delete処理にてAdsが例外を上げた場合でも正常に終了すること. - */ - @Test - public void delete処理にてAdsが例外を上げた場合でも正常に終了すること() { - // 事前準備 - EsIndex index = esClient.idxUser(UNIT_PREFIX, UNIT_USER_NAME); - assertNotNull(index); - ODataLinkAccessor linkAccessor = new ODataLinkAccessor(index, TYPE_NAME, ROUTING_ID); - LinkDocHandler docHandler = createTestLinkDocHandler(); - PersoniumIndexResponse response = linkAccessor.create(docHandler); - assertNotNull(response); - assertFalse(response.getId().equals("")); - try { - linkAccessor.setAds(new JdbcAdsMock()); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - - // データを削除する - linkAccessor.delete(docHandler); - } - - /** - * LinkDocHandlerを生成する. - * @return - */ - private LinkDocHandler createTestLinkDocHandler() { - long dateTime = new Date().getTime(); - LinkDocHandler docHandler = new LinkDocHandler(); - docHandler.setBoxId("testBoxId"); - docHandler.setCellId("testCellId"); - docHandler.setNodeId("testNodeId"); - docHandler.setPublished(dateTime); - docHandler.setUpdated(dateTime); - docHandler.setEnt1Key("ent1Key"); - docHandler.setEnt1Type("ent1Type"); - docHandler.setEnt2Key("ent2Key"); - docHandler.setEnt2Type("ent2Type"); - return docHandler; - } -} diff --git a/src/test/java/io/personium/core/model/impl/es/ads/AllTests.java b/src/test/java/io/personium/core/model/impl/es/ads/AllTests.java deleted file mode 100644 index 419d7b768..000000000 --- a/src/test/java/io/personium/core/model/impl/es/ads/AllTests.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.ads; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -/** - * パッケージ配下のテストケースを全て実行するためのテストスイート. - */ -@RunWith(Suite.class) -@SuiteClasses({ - JdbcAdsTest.class - }) -public class AllTests { -} diff --git a/src/test/java/io/personium/core/model/impl/es/ads/JdbcAdsTest.java b/src/test/java/io/personium/core/model/impl/es/ads/JdbcAdsTest.java deleted file mode 100644 index 62d01cc43..000000000 --- a/src/test/java/io/personium/core/model/impl/es/ads/JdbcAdsTest.java +++ /dev/null @@ -1,240 +0,0 @@ -/** - * 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 io.personium.core.model.impl.es.ads; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.json.simple.JSONObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.mockito.Mockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.es.util.PersoniumUUID; -import io.personium.core.model.Box; -import io.personium.core.model.Cell; -import io.personium.core.model.impl.es.DavNode; -import io.personium.core.model.impl.es.doc.LinkDocHandler; -import io.personium.core.model.impl.es.doc.OEntityDocHandler; -import io.personium.test.categories.Unit; - -/** - * JdbcAdsユニットテストクラス. - */ -@Category({ Unit.class }) -public class JdbcAdsTest { - static Logger log = LoggerFactory.getLogger(JdbcAdsTest.class); - - // 本テストで作成・削除するRDBのSchema(Database)名。 - // 本番データを消すような事件が起こらぬよう、万が一に備えて衝突しづらい名前にしておく. - static final String TEST_INDEX = "test_index_jipwoearewprie"; - - /** - * テストの前処理. - * Indexに対応する空間、すなわちJDBCではSchema(Database)の新規作成. - * @throws Exception Exception - */ - @Before - public void before() throws Exception { - JdbcAds ads = new JdbcAds(); - ads.createIndex(TEST_INDEX); - } - - /** - * テストの後処理 - * Indexに対応する空間、すなわちJDBCではSchema(Database)の削除. - * @throws Exception Exception - */ - @After - public void after() throws Exception { - JdbcAds ads = new JdbcAds(); - ads.deleteIndex(TEST_INDEX); - } - - /** - * CELLに対応するADSのCRUD. - * @throws Exception Exception - */ - @Test - public void CELLに対応するADSのCRUD() throws Exception { - JdbcAds ads = new JdbcAds(); - OEntityDocHandler oedh = new OEntityDocHandler(); - String testId = PersoniumUUID.randomUUID(); - oedh.setId(testId); - oedh.setType(Cell.EDM_TYPE_NAME); - oedh.setPublished(new Date().getTime()); - oedh.setUpdated(new Date().getTime()); - - // 作成 - ads.createCell(TEST_INDEX, oedh); - assertEquals(1, ads.countCell(TEST_INDEX)); - - List list = ads.getCellList(TEST_INDEX, 0, 10); - assertEquals(1, list.size()); - - // 更新 - oedh.setUpdated(new Date().getTime()); - ads.updateCell(TEST_INDEX, oedh); - assertEquals(1, ads.countCell(TEST_INDEX)); - - // ID検索 - List idList = new ArrayList(); - idList.add(oedh.getId()); - List res = ads.searchCellList(TEST_INDEX, idList); - assertEquals(1, res.size()); - - // 削除 - ads.deleteCell(TEST_INDEX, oedh.getId()); - assertEquals(0, ads.countCell(TEST_INDEX)); - } - - /** - * OEntityDocに対応するADSのCRUD. - * @throws Exception Exception - */ - @Test - public void OEntityDocに対応するADSのCRUD() throws Exception { - JdbcAds ads = new JdbcAds(); - OEntityDocHandler oedh = this.createTestOEntityDocHandler(); - // 作成 - ads.createEntity(TEST_INDEX, oedh); - assertEquals(1, ads.countEntity(TEST_INDEX)); - - List list = ads.getEntityList(TEST_INDEX, 0, 10); - assertEquals(1, list.size()); - - // 更新 - oedh.setUpdated(new Date().getTime()); - ads.updateEntity(TEST_INDEX, oedh); - assertEquals(1, ads.countEntity(TEST_INDEX)); - - // ID検索 - List idList = new ArrayList(); - idList.add(oedh.getId()); - List res = ads.searchEntityList(TEST_INDEX, idList); - assertEquals(1, res.size()); - String id = (String) res.get(0).get("id"); - assertEquals(oedh.getId(), id); - - // 削除 - ads.deleteEntity(TEST_INDEX, oedh.getId()); - assertEquals(0, ads.countEntity(TEST_INDEX)); - } - - OEntityDocHandler createTestOEntityDocHandler() { - OEntityDocHandler oedh = new OEntityDocHandler(); - String testId = PersoniumUUID.randomUUID(); - oedh.setId(testId); - oedh.setType(PersoniumUUID.randomUUID()); - oedh.setCellId("cellid"); - oedh.setBoxId("boxid"); - oedh.setPublished(new Date().getTime()); - oedh.setUpdated(new Date().getTime()); - return oedh; - } - - /** - * LinkDocに対応するADSのCRUD. - * @throws Exception Exception - */ - @Test - public void LinkDocに対応するADSのCRUD() throws Exception { - JdbcAds ads = new JdbcAds(); - OEntityDocHandler oedh1 = this.createTestOEntityDocHandler(); - OEntityDocHandler oedh2 = this.createTestOEntityDocHandler(); - - LinkDocHandler ldh = new LinkDocHandler(oedh1, oedh2); - ldh.setPublished(new Date().getTime()); - ldh.setUpdated(new Date().getTime()); - // 作成 - ads.createLink(TEST_INDEX, ldh); - assertEquals(1, ads.countLink(TEST_INDEX)); - List list = ads.getLinkList(TEST_INDEX, 0, 10); - assertEquals(1, list.size()); - log.debug(" Link Body:" + list.get(0).toJSONString()); - - // 更新 - ldh.setUpdated(new Date().getTime()); - ads.updateLink(TEST_INDEX, ldh); - assertEquals(1, ads.countLink(TEST_INDEX)); - - // ID検索 - List idList = new ArrayList(); - idList.add(ldh.getId()); - List res = ads.searchLinkList(TEST_INDEX, idList); - assertEquals(1, res.size()); - String id = (String) res.get(0).get("id"); - assertEquals(ldh.getId(), id); - - // 削除 - ads.deleteLink(TEST_INDEX, ldh.getId()); - assertEquals(0, ads.countLink(TEST_INDEX)); - } - - /** - * DavNodeに対応するADSのCRUD. - * @throws Exception Exception - */ - @Test - public void DavNodeに対応するADSのCRUD() throws Exception { - JdbcAds ads = new JdbcAds(); - // Mockの作成 - Cell cell = Mockito.mock(Cell.class); - Mockito.when(cell.getName()).thenReturn("dummyCell"); - Mockito.when(cell.getId()).thenReturn("cellid"); - Mockito.when(cell.getUrl()).thenReturn("http://example.com/dummyCell"); - Mockito.when(cell.getOwner()).thenReturn("dummy_cell_owner"); - - Box box = new Box(cell, null); - box.setId("dummyBoxId"); - box.setName("dummyBoxName"); - - // 作成 - DavNode davNode = new DavNode(); - davNode.setId(PersoniumUUID.randomUUID()); - ads.createDavNode(TEST_INDEX, davNode); - assertEquals(1, ads.countDavNode(TEST_INDEX)); - List list = ads.getDavNodeList(TEST_INDEX, 0, 10); - assertEquals(1, list.size()); - log.debug(" DavNode Body:" + list.get(0).toJSONString()); - - // 更新 - davNode.setUpdated(new Date().getTime()); - ads.updateDavNode(TEST_INDEX, davNode); - assertEquals(1, ads.countDavNode(TEST_INDEX)); - - // ID検索 - List idList = new ArrayList(); - idList.add(davNode.getId()); - List res = ads.searchDavNodeList(TEST_INDEX, idList); - assertEquals(1, res.size()); - String id = (String) res.get(0).get("id"); - assertEquals(davNode.getId(), id); - - // 削除 - ads.deleteDavNode(TEST_INDEX, davNode.getId()); - assertEquals(0, ads.countDavNode(TEST_INDEX)); - } - -} diff --git a/src/test/java/io/personium/core/model/impl/es/odata/CellCtlODataProducerTest.java b/src/test/java/io/personium/core/model/impl/es/odata/CellCtlODataProducerTest.java index d7bea5033..80b721560 100644 --- a/src/test/java/io/personium/core/model/impl/es/odata/CellCtlODataProducerTest.java +++ b/src/test/java/io/personium/core/model/impl/es/odata/CellCtlODataProducerTest.java @@ -18,12 +18,12 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.anyMap; +import static org.mockito.Matchers.anyMapOf; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doNothing; @@ -39,6 +39,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.junit.Before; @@ -47,6 +48,7 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.odata4j.core.OEntity; +import org.odata4j.core.OEntityId; import org.odata4j.core.OEntityKey; import org.odata4j.edm.EdmEntitySet; import org.powermock.api.mockito.PowerMockito; @@ -58,9 +60,11 @@ import io.personium.core.model.Box; import io.personium.core.model.Cell; import io.personium.core.model.ctl.Common; +import io.personium.core.model.ctl.ExtCell; import io.personium.core.model.ctl.ReceivedMessage; import io.personium.core.model.ctl.ReceivedMessagePort; import io.personium.core.model.ctl.Relation; +import io.personium.core.model.ctl.Role; import io.personium.core.model.ctl.SentMessage; import io.personium.core.model.impl.es.CellEsImpl; import io.personium.core.model.impl.es.accessor.EntitySetAccessor; @@ -310,32 +314,6 @@ public void befor() { ReceivedMessagePort.STATUS_REJECTED)); } - /** - * extCellの取得で存在する場合にEntitySetDocHandlerが返却されること. - */ - @Test - public void extCellの取得で存在する場合にEntitySetDocHandlerが返却されること() { - doReturn(new OEntityDocHandler()).when(cellCtlODataProducer).retrieveWithKey(anyObject(), anyObject()); - assertTrue(cellCtlODataProducer.getExtCell("https://example.com/test0110/") != null); - } - - /** - * リレーションクラスURLのフォーマットが不正な場合はnullが取得できること. - */ - @Test - public void extCellの存在確認でOEntityKeyのパースに失敗した場合はREQUEST_RELATION_TARGET_PARSE_ERRORが発生すること() { - try { - doReturn(new OEntityDocHandler()).when(cellCtlODataProducer).retrieveWithKey(anyObject(), anyObject()); - cellCtlODataProducer.getExtCell("https://example.com/'/"); - fail("PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_TARGET_PARSE_ERROR does not occurred."); - } catch (PersoniumCoreException e) { - PersoniumCoreException expected = - PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_TARGET_PARSE_ERROR; - assertEquals(expected.getCode(), e.getCode()); - assertEquals(expected.getMessage(), e.getMessage()); - } - } - /** * Test beforeCreate(). * EntitySet is ReceivedMessage. @@ -1004,38 +982,40 @@ protected void getNtkpValueMap(EdmEntitySet eSet, assertThat(captor.getValue(), is(entitySet)); } + /** - * Test buildRelation(). - * Relation and extcell is not exists. + * Test updateRelation(). + * boxName is null. * @throws Exception Unexpected error */ @Test - public void buildRelation_Normal_not_exists_relation_and_extcell() throws Exception { + public void updateRelation_Normal_boxName_is_null() throws Exception { cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- EntitySetDocHandler entitySetDocHandler = mock(EntitySetDocHandler.class); + String status = ReceivedMessage.STATUS_APPROVED; // -------------------- // Mock settings // -------------------- Map mockStaticFields = new HashMap(); + mockStaticFields.put(ReceivedMessage.P_TYPE.getName(), ReceivedMessage.TYPE_MESSAGE); mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION.getName(), "dummyRelation"); + mockStaticFields.put(ReceivedMessage.P_BOX_NAME.getName(), "dummyBox"); mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell/"); doReturn(mockStaticFields).when(entitySetDocHandler).getStaticFields(); - doReturn("dummyRelation").when(cellCtlODataProducer).getRelationNameFromRequestRelation("dummyRelation"); - doReturn("dummyBoxName").when(cellCtlODataProducer).getBoxNameFromRequestRelation("dummyRelation"); - - doReturn(null).when(cellCtlODataProducer).getRelation("dummyRelation", "dummyBoxName"); - PowerMockito.doNothing().when(cellCtlODataProducer, "createRelationEntity", "dummyRelation", "dummyBoxName"); + doReturn("dummyRelation").when(cellCtlODataProducer).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_MESSAGE); - doReturn(null).when(cellCtlODataProducer).getExtCell("http://personium/dummyExtCell/"); - PowerMockito.doNothing().when(cellCtlODataProducer, "createExtCellEntity", "http://personium/dummyExtCell/"); + doReturn(null).when(cellCtlODataProducer).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_MESSAGE); - PowerMockito.doNothing().when(cellCtlODataProducer, "createRelationExtCellLinks", "dummyRelation", - "dummyBoxName", "http://personium/dummyExtCell/"); + Map entityKeyMap = new HashMap(); + PowerMockito.doReturn(entityKeyMap).when(cellCtlODataProducer, "getEntityKeyMapFromType", + "dummyRelation", "dummyBox", ReceivedMessage.TYPE_MESSAGE); // -------------------- // Expected result @@ -1046,55 +1026,65 @@ public void buildRelation_Normal_not_exists_relation_and_extcell() throws Except // Run method // -------------------- // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("buildRelation", EntitySetDocHandler.class); + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "updateRelation", EntitySetDocHandler.class, String.class); method.setAccessible(true); // Run method - method.invoke(cellCtlODataProducer, entitySetDocHandler); + method.invoke(cellCtlODataProducer, entitySetDocHandler, status); // -------------------- // Confirm result // -------------------- // Confirm function call + verify(cellCtlODataProducer, times(1)).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_MESSAGE); + verify(cellCtlODataProducer, times(1)).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_MESSAGE); PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke( - "createRelationEntity", "dummyRelation", "dummyBoxName"); - PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke( - "createExtCellEntity", "http://personium/dummyExtCell/"); - PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke( - "createRelationExtCellLinks", "dummyRelation", "dummyBoxName", "http://personium/dummyExtCell/"); + "getEntityKeyMapFromType", "dummyRelation", "dummyBox", ReceivedMessage.TYPE_MESSAGE); + + PowerMockito.verifyPrivate(cellCtlODataProducer, never()).invoke( + "registerRelation", anyString(), anyObject(), anyObject()); + PowerMockito.verifyPrivate(cellCtlODataProducer, never()).invoke( + "deleteRelation", anyString(), anyObject(), anyObject()); } /** - * Test buildRelation(). - * Relation and extcell is exists. + * Test updateRelation(). + * extCellUrl is not trailing slash. * @throws Exception Unexpected error */ + @SuppressWarnings("rawtypes") @Test - public void buildRelation_Normal_exists_relation_and_extcell() throws Exception { + public void updateRelation_Normal_extCellUrl_is_not_trailing_slash() throws Exception { cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- EntitySetDocHandler entitySetDocHandler = mock(EntitySetDocHandler.class); + String status = ReceivedMessage.STATUS_APPROVED; // -------------------- // Mock settings // -------------------- Map mockStaticFields = new HashMap(); + mockStaticFields.put(ReceivedMessage.P_TYPE.getName(), ReceivedMessage.TYPE_REQ_RELATION_BUILD); mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION.getName(), "dummyRelation"); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell/"); + mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell"); doReturn(mockStaticFields).when(entitySetDocHandler).getStaticFields(); - doReturn("dummyRelation").when(cellCtlODataProducer).getRelationNameFromRequestRelation("dummyRelation"); - doReturn("dummyBoxName").when(cellCtlODataProducer).getBoxNameFromRequestRelation("dummyRelation"); + doReturn("dummyRelation").when(cellCtlODataProducer).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BUILD); - doReturn(new OEntityDocHandler()).when(cellCtlODataProducer).getRelation("dummyRelation", "dummyBoxName"); - PowerMockito.doNothing().when(cellCtlODataProducer, "createRelationEntity", "dummyRelation", "dummyBoxName"); + doReturn("dummyBox").when(cellCtlODataProducer).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BUILD); - doReturn(new OEntityDocHandler()).when(cellCtlODataProducer).getExtCell("http://personium/dummyExtCell/"); - PowerMockito.doNothing().when(cellCtlODataProducer, "createExtCellEntity", "http://personium/dummyExtCell/"); + Map entityKeyMap = new HashMap(); + entityKeyMap.put(Common.P_BOX_NAME.getName(), "dummyBox"); + PowerMockito.doReturn(entityKeyMap).when(cellCtlODataProducer, "getEntityKeyMapFromType", + "dummyRelation", "dummyBox", ReceivedMessage.TYPE_REQ_RELATION_BUILD); - PowerMockito.doNothing().when(cellCtlODataProducer, "createRelationExtCellLinks", "dummyRelation", - "dummyBoxName", "http://personium/dummyExtCell/"); + PowerMockito.doNothing().when(cellCtlODataProducer, "registerRelation", anyString(), anyObject(), anyObject()); // -------------------- // Expected result @@ -1105,55 +1095,72 @@ public void buildRelation_Normal_exists_relation_and_extcell() throws Exception // Run method // -------------------- // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("buildRelation", EntitySetDocHandler.class); + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "updateRelation", EntitySetDocHandler.class, String.class); method.setAccessible(true); // Run method - method.invoke(cellCtlODataProducer, entitySetDocHandler); + method.invoke(cellCtlODataProducer, entitySetDocHandler, status); // -------------------- // Confirm result // -------------------- // Confirm function call - PowerMockito.verifyPrivate(cellCtlODataProducer, never()).invoke( - "createRelationEntity", "dummyRelation", "dummyBoxName"); - PowerMockito.verifyPrivate(cellCtlODataProducer, never()).invoke( - "createExtCellEntity", "http://personium/dummyExtCell/"); + verify(cellCtlODataProducer, times(1)).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BUILD); + verify(cellCtlODataProducer, times(1)).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BUILD); PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke( - "createRelationExtCellLinks", "dummyRelation", "dummyBoxName", "http://personium/dummyExtCell/"); + "getEntityKeyMapFromType", "dummyRelation", "dummyBox", ReceivedMessage.TYPE_REQ_RELATION_BUILD); + + ArgumentCaptor edmTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor entityKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor extCellKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke("registerRelation", + edmTypeCaptor.capture(), entityKeyMapCaptor.capture(), extCellKeyMapCaptor.capture()); + PowerMockito.verifyPrivate(cellCtlODataProducer, never()).invoke("deleteRelation", + anyString(), anyObject(), anyObject()); + + assertThat(edmTypeCaptor.getValue(), is(Relation.EDM_TYPE_NAME)); + assertThat(entityKeyMapCaptor.getValue().get(Common.P_BOX_NAME.getName()), is("dummyBox")); + assertThat(extCellKeyMapCaptor.getValue().get(ExtCell.P_URL.getName()), is("http://personium/dummyExtCell/")); } /** - * Test buildRelation(). - * requestExtCell does not end with a slash. + * Test updateRelation(). + * Type is relationBuild. * @throws Exception Unexpected error */ + @SuppressWarnings("rawtypes") @Test - public void buildRelation_Normal_requestExtCell_does_not_endwith_slash() throws Exception { + public void updateRelation_Normal_type_is_relation_build() throws Exception { cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- EntitySetDocHandler entitySetDocHandler = mock(EntitySetDocHandler.class); + String status = ReceivedMessage.STATUS_APPROVED; // -------------------- // Mock settings // -------------------- Map mockStaticFields = new HashMap(); + mockStaticFields.put(ReceivedMessage.P_TYPE.getName(), ReceivedMessage.TYPE_REQ_RELATION_BUILD); mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION.getName(), "dummyRelation"); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell"); + mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell/"); doReturn(mockStaticFields).when(entitySetDocHandler).getStaticFields(); - doReturn("dummyRelation").when(cellCtlODataProducer).getRelationNameFromRequestRelation("dummyRelation"); - doReturn("dummyBoxName").when(cellCtlODataProducer).getBoxNameFromRequestRelation("dummyRelation"); + doReturn("dummyRelation").when(cellCtlODataProducer).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BUILD); - doReturn(null).when(cellCtlODataProducer).getRelation("dummyRelation", "dummyBoxName"); - PowerMockito.doNothing().when(cellCtlODataProducer, "createRelationEntity", "dummyRelation", "dummyBoxName"); + doReturn("dummyBox").when(cellCtlODataProducer).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BUILD); - doReturn(null).when(cellCtlODataProducer).getExtCell("http://personium/dummyExtCell/"); - PowerMockito.doNothing().when(cellCtlODataProducer, "createExtCellEntity", "http://personium/dummyExtCell/"); + Map entityKeyMap = new HashMap(); + entityKeyMap.put(Common.P_BOX_NAME.getName(), "dummyBox"); + PowerMockito.doReturn(entityKeyMap).when(cellCtlODataProducer, "getEntityKeyMapFromType", + "dummyRelation", "dummyBox", ReceivedMessage.TYPE_REQ_RELATION_BUILD); - PowerMockito.doNothing().when(cellCtlODataProducer, "createRelationExtCellLinks", "dummyRelation", - "dummyBoxName", "http://personium/dummyExtCell/"); + PowerMockito.doNothing().when(cellCtlODataProducer, "registerRelation", anyString(), anyObject(), anyObject()); // -------------------- // Expected result @@ -1164,122 +1171,224 @@ public void buildRelation_Normal_requestExtCell_does_not_endwith_slash() throws // Run method // -------------------- // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("buildRelation", EntitySetDocHandler.class); + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "updateRelation", EntitySetDocHandler.class, String.class); method.setAccessible(true); // Run method - method.invoke(cellCtlODataProducer, entitySetDocHandler); + method.invoke(cellCtlODataProducer, entitySetDocHandler, status); // -------------------- // Confirm result // -------------------- // Confirm function call + verify(cellCtlODataProducer, times(1)).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BUILD); + verify(cellCtlODataProducer, times(1)).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BUILD); PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke( - "createRelationEntity", "dummyRelation", "dummyBoxName"); - PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke( - "createExtCellEntity", "http://personium/dummyExtCell/"); - PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke( - "createRelationExtCellLinks", "dummyRelation", "dummyBoxName", "http://personium/dummyExtCell/"); + "getEntityKeyMapFromType", "dummyRelation", "dummyBox", ReceivedMessage.TYPE_REQ_RELATION_BUILD); + + ArgumentCaptor edmTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor entityKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor extCellKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke("registerRelation", + edmTypeCaptor.capture(), entityKeyMapCaptor.capture(), extCellKeyMapCaptor.capture()); + PowerMockito.verifyPrivate(cellCtlODataProducer, never()).invoke("deleteRelation", + anyString(), anyObject(), anyObject()); + + assertThat(edmTypeCaptor.getValue(), is(Relation.EDM_TYPE_NAME)); + assertThat(entityKeyMapCaptor.getValue().get(Common.P_BOX_NAME.getName()), is("dummyBox")); + assertThat(extCellKeyMapCaptor.getValue().get(ExtCell.P_URL.getName()), is("http://personium/dummyExtCell/")); } /** - * Test createRelationOEntityKey(). - * BoxName is not null. + * Test updateRelation(). + * Type is relationBreak. * @throws Exception Unexpected error */ + @SuppressWarnings("rawtypes") @Test - public void createRelationOEntityKey_Normal_boxName_is_not_null() throws Exception { + public void updateRelation_Normal_type_is_relation_break() throws Exception { + cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- - String relationName = "dummyRelationName"; - String boxName = "dummyBoxName"; + EntitySetDocHandler entitySetDocHandler = mock(EntitySetDocHandler.class); + String status = ReceivedMessage.STATUS_APPROVED; // -------------------- // Mock settings // -------------------- - // Nothing. + Map mockStaticFields = new HashMap(); + mockStaticFields.put(ReceivedMessage.P_TYPE.getName(), ReceivedMessage.TYPE_REQ_RELATION_BREAK); + mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION.getName(), "dummyRelation"); + mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell/"); + doReturn(mockStaticFields).when(entitySetDocHandler).getStaticFields(); + + doReturn("dummyRelation").when(cellCtlODataProducer).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BREAK); + + doReturn("dummyBox").when(cellCtlODataProducer).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BREAK); + + Map entityKeyMap = new HashMap(); + entityKeyMap.put(Common.P_BOX_NAME.getName(), "dummyBox"); + PowerMockito.doReturn(entityKeyMap).when(cellCtlODataProducer, "getEntityKeyMapFromType", + "dummyRelation", "dummyBox", ReceivedMessage.TYPE_REQ_RELATION_BREAK); + + PowerMockito.doNothing().when(cellCtlODataProducer, "deleteRelation", anyString(), anyObject(), anyObject()); // -------------------- // Expected result // -------------------- - OEntityKey expectedOEntityKey = OEntityKey.create( - Relation.P_NAME.getName(), relationName, - Common.P_BOX_NAME.getName(), boxName); + // Nothing. // -------------------- // Run method // -------------------- // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("createRelationOEntityKey", - String.class, String.class); + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "updateRelation", EntitySetDocHandler.class, String.class); method.setAccessible(true); // Run method - OEntityKey resultOEntityKey = (OEntityKey) method.invoke(cellCtlODataProducer, relationName, boxName); + method.invoke(cellCtlODataProducer, entitySetDocHandler, status); // -------------------- // Confirm result // -------------------- - assertThat(resultOEntityKey.toString(), is(expectedOEntityKey.toString())); + // Confirm function call + verify(cellCtlODataProducer, times(1)).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BREAK); + verify(cellCtlODataProducer, times(1)).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_RELATION_BREAK); + PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke( + "getEntityKeyMapFromType", "dummyRelation", "dummyBox", ReceivedMessage.TYPE_REQ_RELATION_BREAK); + + ArgumentCaptor edmTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor entityKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor extCellKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + PowerMockito.verifyPrivate(cellCtlODataProducer, never()).invoke("registerRelation", + anyString(), anyObject(), anyObject()); + PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke("deleteRelation", + edmTypeCaptor.capture(), entityKeyMapCaptor.capture(), extCellKeyMapCaptor.capture()); + + assertThat(edmTypeCaptor.getValue(), is(Relation.EDM_TYPE_NAME)); + assertThat(entityKeyMapCaptor.getValue().get(Common.P_BOX_NAME.getName()), is("dummyBox")); + assertThat(extCellKeyMapCaptor.getValue().get(ExtCell.P_URL.getName()), is("http://personium/dummyExtCell/")); } /** - * Test createRelationOEntityKey(). - * BoxName is null. + * Test updateRelation(). + * Type is roleGrant. * @throws Exception Unexpected error */ + @SuppressWarnings("rawtypes") @Test - public void createRelationOEntityKey_Normal_boxName_is_null() throws Exception { + public void updateRelation_Normal_type_is_role_grant() throws Exception { + cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- - String relationName = "dummyRelationName"; - String boxName = null; + EntitySetDocHandler entitySetDocHandler = mock(EntitySetDocHandler.class); + String status = ReceivedMessage.STATUS_APPROVED; // -------------------- // Mock settings // -------------------- - // Nothing. + Map mockStaticFields = new HashMap(); + mockStaticFields.put(ReceivedMessage.P_TYPE.getName(), ReceivedMessage.TYPE_REQ_ROLE_GRANT); + mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION.getName(), "dummyRelation"); + mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell/"); + doReturn(mockStaticFields).when(entitySetDocHandler).getStaticFields(); + + doReturn("dummyRelation").when(cellCtlODataProducer).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_ROLE_GRANT); + + doReturn("dummyBox").when(cellCtlODataProducer).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_ROLE_GRANT); + + Map entityKeyMap = new HashMap(); + entityKeyMap.put(Common.P_BOX_NAME.getName(), "dummyBox"); + PowerMockito.doReturn(entityKeyMap).when(cellCtlODataProducer, "getEntityKeyMapFromType", + "dummyRelation", "dummyBox", ReceivedMessage.TYPE_REQ_ROLE_GRANT); + + PowerMockito.doNothing().when(cellCtlODataProducer, "registerRelation", anyString(), anyObject(), anyObject()); // -------------------- // Expected result // -------------------- - OEntityKey expectedOEntityKey = OEntityKey.create( - Relation.P_NAME.getName(), relationName); + // Nothing. // -------------------- // Run method // -------------------- // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("createRelationOEntityKey", - String.class, String.class); + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "updateRelation", EntitySetDocHandler.class, String.class); method.setAccessible(true); // Run method - OEntityKey resultOEntityKey = (OEntityKey) method.invoke(cellCtlODataProducer, relationName, boxName); + method.invoke(cellCtlODataProducer, entitySetDocHandler, status); // -------------------- // Confirm result // -------------------- - assertThat(resultOEntityKey.toString(), is(expectedOEntityKey.toString())); + // Confirm function call + verify(cellCtlODataProducer, times(1)).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_ROLE_GRANT); + verify(cellCtlODataProducer, times(1)).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_ROLE_GRANT); + PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke( + "getEntityKeyMapFromType", "dummyRelation", "dummyBox", ReceivedMessage.TYPE_REQ_ROLE_GRANT); + + ArgumentCaptor edmTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor entityKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor extCellKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke("registerRelation", + edmTypeCaptor.capture(), entityKeyMapCaptor.capture(), extCellKeyMapCaptor.capture()); + PowerMockito.verifyPrivate(cellCtlODataProducer, never()).invoke("deleteRelation", + anyString(), anyObject(), anyObject()); + + assertThat(edmTypeCaptor.getValue(), is(Role.EDM_TYPE_NAME)); + assertThat(entityKeyMapCaptor.getValue().get(Common.P_BOX_NAME.getName()), is("dummyBox")); + assertThat(extCellKeyMapCaptor.getValue().get(ExtCell.P_URL.getName()), is("http://personium/dummyExtCell/")); } /** - * Test createRelationOEntityKey(). - * Error test. - * EntityKey parse failed. + * Test updateRelation(). + * Type is roleRevoke. * @throws Exception Unexpected error */ + @SuppressWarnings("rawtypes") @Test - public void createRelationOEntityKey_Error_entityKey_parse_failed() throws Exception { + public void updateRelation_Normal_type_is_role_revoke() throws Exception { + cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- - String relationName = "'dummy'"; - String boxName = null; + EntitySetDocHandler entitySetDocHandler = mock(EntitySetDocHandler.class); + String status = ReceivedMessage.STATUS_APPROVED; // -------------------- // Mock settings // -------------------- - // Nothing. + Map mockStaticFields = new HashMap(); + mockStaticFields.put(ReceivedMessage.P_TYPE.getName(), ReceivedMessage.TYPE_REQ_ROLE_REVOKE); + mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION.getName(), "dummyRelation"); + mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell/"); + doReturn(mockStaticFields).when(entitySetDocHandler).getStaticFields(); + + doReturn("dummyRelation").when(cellCtlODataProducer).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_ROLE_REVOKE); + + doReturn("dummyBox").when(cellCtlODataProducer).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_ROLE_REVOKE); + + Map entityKeyMap = new HashMap(); + entityKeyMap.put(Common.P_BOX_NAME.getName(), "dummyBox"); + PowerMockito.doReturn(entityKeyMap).when(cellCtlODataProducer, "getEntityKeyMapFromType", + "dummyRelation", "dummyBox", ReceivedMessage.TYPE_REQ_ROLE_REVOKE); + + PowerMockito.doNothing().when(cellCtlODataProducer, "deleteRelation", anyString(), anyObject(), anyObject()); // -------------------- // Expected result @@ -1290,47 +1399,54 @@ public void createRelationOEntityKey_Error_entityKey_parse_failed() throws Excep // Run method // -------------------- // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("createRelationOEntityKey", - String.class, String.class); + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "updateRelation", EntitySetDocHandler.class, String.class); method.setAccessible(true); // Run method - try { - method.invoke(cellCtlODataProducer, relationName, boxName); - fail("Not exception."); - } catch (InvocationTargetException e) { - // -------------------- - // Confirm result - // -------------------- - IllegalArgumentException cause = new IllegalArgumentException( - "bad valueString [''dummy''] as part of keyString [''dummy'']"); - PersoniumCoreException expected = - PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_PARSE_ERROR.reason(cause); - PersoniumCoreException exception = (PersoniumCoreException) e.getCause(); - assertThat(exception.getStatus(), is(expected.getStatus())); - assertThat(exception.getCode(), is(expected.getCode())); - assertThat(exception.getMessage(), is(expected.getMessage())); - assertThat(exception.getCause().getMessage(), is(expected.getCause().getMessage())); - } + method.invoke(cellCtlODataProducer, entitySetDocHandler, status); + + // -------------------- + // Confirm result + // -------------------- + // Confirm function call + verify(cellCtlODataProducer, times(1)).getNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_ROLE_REVOKE); + verify(cellCtlODataProducer, times(1)).getBoxNameFromRequestRelation( + "dummyRelation", ReceivedMessage.TYPE_REQ_ROLE_REVOKE); + PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke( + "getEntityKeyMapFromType", "dummyRelation", "dummyBox", ReceivedMessage.TYPE_REQ_ROLE_REVOKE); + + ArgumentCaptor edmTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor entityKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor extCellKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + PowerMockito.verifyPrivate(cellCtlODataProducer, never()).invoke("registerRelation", + anyString(), anyObject(), anyObject()); + PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke("deleteRelation", + edmTypeCaptor.capture(), entityKeyMapCaptor.capture(), extCellKeyMapCaptor.capture()); + + assertThat(edmTypeCaptor.getValue(), is(Role.EDM_TYPE_NAME)); + assertThat(entityKeyMapCaptor.getValue().get(Common.P_BOX_NAME.getName()), is("dummyBox")); + assertThat(extCellKeyMapCaptor.getValue().get(ExtCell.P_URL.getName()), is("http://personium/dummyExtCell/")); } /** - * Test createRelationEntity(). - * BoxName is not null. + * Test updateRelation(). + * Status is not approved. * @throws Exception Unexpected error */ @Test - public void createRelationEntity_Normal_boxName_is_not_null() throws Exception { + public void updateRelation_Normal_status_is_not_approved() throws Exception { cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- - String relationName = "dummyRelationName"; - String boxName = "dummyBoxName"; + EntitySetDocHandler entitySetDocHandler = null; + String status = ReceivedMessage.STATUS_REJECTED; // -------------------- // Mock settings // -------------------- - PowerMockito.doNothing().when(cellCtlODataProducer, "createEntity", anyString(), anyMap()); + // Nothing. // -------------------- // Expected result @@ -1341,354 +1457,227 @@ public void createRelationEntity_Normal_boxName_is_not_null() throws Exception { // Run method // -------------------- // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("createRelationEntity", - String.class, String.class); + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "updateRelation", EntitySetDocHandler.class, String.class); method.setAccessible(true); // Run method - method.invoke(cellCtlODataProducer, relationName, boxName); + method.invoke(cellCtlODataProducer, entitySetDocHandler, status); // -------------------- // Confirm result // -------------------- - // Confirm function call - Map staticFields = new HashMap(); - staticFields.put(Relation.P_NAME.getName(), relationName); - staticFields.put(Common.P_BOX_NAME.getName(), boxName); - PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke("createEntity", - Relation.EDM_TYPE_NAME, staticFields); + // OK if Exception has not occurred. } /** - * Test createRelationEntity(). - * BoxName is null. - * @throws Exception Unexpected error + * Test getNameFromRequestRelation(). + * Normal test. + * RequestRelation is ClassURL. + * @throws Exception Unexpected error. */ @Test - public void createRelationEntity_Normal_boxName_is_null() throws Exception { + public void getNameFromRequestRelation_Normal_requestRelation_is_classURL() throws Exception { cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- - String relationName = "dummyRelationName"; - String boxName = null; + String requestRelation = "personium-localunit:/dummyAppCell/__relation/__/dummyRelation"; + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; // -------------------- // Mock settings // -------------------- - PowerMockito.doNothing().when(cellCtlODataProducer, "createEntity", anyString(), anyMap()); + Cell mockCell = mock(Cell.class); + cellCtlODataProducer.cell = mockCell; + doReturn("http://personium").when(mockCell).getUnitUrl(); + + PowerMockito.mockStatic(UriUtils.class); + PowerMockito.doReturn("http://personium/dummyAppCell/__relation/__/dummyRelation").when( + UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation); + + PowerMockito.doReturn(Common.PATTERN_RELATION_CLASS_URL).when(cellCtlODataProducer, "getRegexFromType", type); // -------------------- // Expected result // -------------------- - // Nothing. + String expectedRelationName = "dummyRelation"; // -------------------- // Run method // -------------------- - // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("createRelationEntity", - String.class, String.class); - method.setAccessible(true); - // Run method - method.invoke(cellCtlODataProducer, relationName, boxName); + String actualRelationName = cellCtlODataProducer.getNameFromRequestRelation(requestRelation, type); // -------------------- // Confirm result // -------------------- - // Confirm function call - Map staticFields = new HashMap(); - staticFields.put(Relation.P_NAME.getName(), relationName); - PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke("createEntity", - Relation.EDM_TYPE_NAME, staticFields); + assertThat(actualRelationName, is(expectedRelationName)); } /** - * Test createEntity(). - * EntityKey type is complex. - * @throws Exception Unexpected error + * Test getNameFromRequestRelation(). + * Normal test. + * RequestRelation is Name. + * @throws Exception Unexpected error. */ @Test - public void createEntity_Normal_entitykey_type_is_complex() throws Exception { + public void getNameFromRequestRelation_Normal_requestRelation_is_name() throws Exception { cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- - String typeName = "dummyTypeName"; - Map staticFields = new HashMap(); - staticFields.put(Relation.P_NAME.getName(), "dummyRelationName"); - staticFields.put(Common.P_BOX_NAME.getName(), "dummyBoxName"); + String requestRelation = "dummyRelation"; + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; // -------------------- // Mock settings // -------------------- - EntitySetAccessor mockEsType = mock(EntitySetAccessor.class); - doReturn(mockEsType).when(cellCtlODataProducer).getAccessorForEntitySet(typeName); + Cell mockCell = mock(Cell.class); + cellCtlODataProducer.cell = mockCell; + doReturn("http://personium").when(mockCell).getUnitUrl(); - PowerMockito.doNothing().when(cellCtlODataProducer, "setLinksFromOEntityKey", - anyObject(), anyString(), anyObject()); + PowerMockito.mockStatic(UriUtils.class); + PowerMockito.doReturn(requestRelation).when( + UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation); - doNothing().when(cellCtlODataProducer).beforeCreate(anyString(), anyObject(), anyObject()); - doReturn(null).when(mockEsType).create(anyString(), anyObject()); - doNothing().when(cellCtlODataProducer).afterCreate(anyString(), anyObject(), anyObject()); + PowerMockito.doReturn(Common.PATTERN_RELATION_CLASS_URL).when(cellCtlODataProducer, "getRegexFromType", type); // -------------------- // Expected result // -------------------- - EntitySetDocHandler expectedOedh = new OEntityDocHandler(); - expectedOedh.setType(typeName); - expectedOedh.setStaticFields(staticFields); - expectedOedh.setBoxId(null); - expectedOedh.setNodeId(null); + String expectedRelationName = "dummyRelation"; // -------------------- // Run method // -------------------- - // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("createEntity", - String.class, Map.class); - method.setAccessible(true); - // Run method - method.invoke(cellCtlODataProducer, typeName, staticFields); + String actualRelationName = cellCtlODataProducer.getNameFromRequestRelation(requestRelation, type); // -------------------- // Confirm result // -------------------- - // Confirm function call - ArgumentCaptor entityKeyCaptor = ArgumentCaptor.forClass(OEntityKey.class); - ArgumentCaptor stringCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor docHandlerCaptor = ArgumentCaptor.forClass(EntitySetDocHandler.class); - ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(OEntity.class); - - PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke("setLinksFromOEntityKey", - entityKeyCaptor.capture(), stringCaptor.capture(), docHandlerCaptor.capture()); - assertThat(entityKeyCaptor.getValue(), is(OEntityKey.create(staticFields))); - assertThat(stringCaptor.getValue(), is(typeName)); - confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); - - verify(cellCtlODataProducer, times(1)).beforeCreate(stringCaptor.capture(), entityCaptor.capture(), - docHandlerCaptor.capture()); - assertThat(stringCaptor.getValue(), is(typeName)); - assertNull(entityCaptor.getValue()); - confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); - - verify(mockEsType, times(1)).create(stringCaptor.capture(), docHandlerCaptor.capture()); - confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); - - verify(cellCtlODataProducer, times(1)).afterCreate(stringCaptor.capture(), entityCaptor.capture(), - docHandlerCaptor.capture()); - assertThat(stringCaptor.getValue(), is(typeName)); - assertNull(entityCaptor.getValue()); - confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); + assertThat(actualRelationName, is(expectedRelationName)); } /** - * Test createEntity(). - * EntityKey type is not complex. - * @throws Exception Unexpected error + * Test getBoxNameFromRequestRelation(). + * Normal test. + * RequestRelation is RelationClassURL. + * @throws Exception Unexpected error. */ @Test - public void createEntity_Normal_entitykey_type_is_not_complex() throws Exception { + public void getBoxNameFromRequestRelation_Normal_requestRelation_is_classURL() throws Exception { cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- - String typeName = "dummyTypeName"; - Map staticFields = new HashMap(); - staticFields.put(Relation.P_NAME.getName(), "dummyRelationName"); + String requestRelation = "personium-localunit:/dummyAppCell/__relation/__/dummyRelation"; + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; // -------------------- // Mock settings // -------------------- - EntitySetAccessor mockEsType = mock(EntitySetAccessor.class); - doReturn(mockEsType).when(cellCtlODataProducer).getAccessorForEntitySet(typeName); + Cell mockCell = mock(Cell.class); + cellCtlODataProducer.cell = mockCell; + doReturn("http://personium").when(mockCell).getUnitUrl(); - PowerMockito.doNothing().when(cellCtlODataProducer, "setLinksFromOEntityKey", - anyObject(), anyString(), anyObject()); + PowerMockito.mockStatic(UriUtils.class); + PowerMockito.doReturn("http://personium/dummyAppCell/__relation/__/dummyRelation").when( + UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation); - doNothing().when(cellCtlODataProducer).beforeCreate(anyString(), anyObject(), anyObject()); - doReturn(null).when(mockEsType).create(anyString(), anyObject()); - doNothing().when(cellCtlODataProducer).afterCreate(anyString(), anyObject(), anyObject()); + PowerMockito.doReturn(Common.PATTERN_RELATION_CLASS_URL).when(cellCtlODataProducer, "getRegexFromType", type); + + Box mockBox = PowerMockito.mock(Box.class); + doReturn("dummyBoxName").when(mockBox).getName(); + doReturn(mockBox).when(mockCell).getBoxForSchema("http://personium/dummyAppCell/"); // -------------------- // Expected result // -------------------- - EntitySetDocHandler expectedOedh = new OEntityDocHandler(); - expectedOedh.setType(typeName); - expectedOedh.setStaticFields(staticFields); - expectedOedh.setBoxId(null); - expectedOedh.setNodeId(null); + String expectedBoxName = "dummyBoxName"; // -------------------- // Run method // -------------------- - // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("createEntity", - String.class, Map.class); - method.setAccessible(true); - // Run method - method.invoke(cellCtlODataProducer, typeName, staticFields); + String actualBoxName = cellCtlODataProducer.getBoxNameFromRequestRelation(requestRelation, type); // -------------------- // Confirm result // -------------------- - // Confirm function call - ArgumentCaptor entityKeyCaptor = ArgumentCaptor.forClass(OEntityKey.class); - ArgumentCaptor stringCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor docHandlerCaptor = ArgumentCaptor.forClass(EntitySetDocHandler.class); - ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(OEntity.class); - - PowerMockito.verifyPrivate(cellCtlODataProducer, times(0)).invoke("setLinksFromOEntityKey", - entityKeyCaptor.capture(), stringCaptor.capture(), docHandlerCaptor.capture()); - - verify(cellCtlODataProducer, times(1)).beforeCreate(stringCaptor.capture(), entityCaptor.capture(), - docHandlerCaptor.capture()); - assertThat(stringCaptor.getValue(), is(typeName)); - assertNull(entityCaptor.getValue()); - confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); - - verify(mockEsType, times(1)).create(stringCaptor.capture(), docHandlerCaptor.capture()); - confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); - - verify(cellCtlODataProducer, times(1)).afterCreate(stringCaptor.capture(), entityCaptor.capture(), - docHandlerCaptor.capture()); - assertThat(stringCaptor.getValue(), is(typeName)); - assertNull(entityCaptor.getValue()); - confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); - } - - /** - * Confirm EntitySetDocHandler. - * Indefinite values such as UUID and SystemDate are not checked. - * @param expected expected - * @param actual actual - */ - private void confirmEntitySetDocHandler(EntitySetDocHandler expected, EntitySetDocHandler actual) { - assertThat(expected.getType(), is(actual.getType())); - assertThat(expected.getStaticFields(), is(actual.getStaticFields())); - assertThat(expected.getBoxId(), is(actual.getBoxId())); - assertThat(expected.getNodeId(), is(actual.getNodeId())); + assertThat(actualBoxName, is(expectedBoxName)); } /** - * Test createEntity(). - * Error test. - * setLinksFromOEntityKey fail. - * @throws Exception Unexpected error + * Test getBoxNameFromRequestRelation(). + * Normal test. + * RequestRelation is RelationName. + * @throws Exception Unexpected error. */ @Test - public void createEntity_Error_setLinksFromOEntityKey_fail() throws Exception { + public void getBoxNameFromRequestRelation_Normal_requestRelation_is_name() throws Exception { cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- - String typeName = "dummyTypeName"; - Map staticFields = new HashMap(); - staticFields.put(Relation.P_NAME.getName(), "dummyRelationName"); - staticFields.put(Common.P_BOX_NAME.getName(), "dummyBoxName"); + String requestRelation = "dummyRelation"; + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; // -------------------- // Mock settings // -------------------- - EntitySetAccessor mockEsType = mock(EntitySetAccessor.class); - doReturn(mockEsType).when(cellCtlODataProducer).getAccessorForEntitySet(typeName); - - PowerMockito.doThrow(new NTKPNotFoundException("dummyMsg")).when(cellCtlODataProducer, - "setLinksFromOEntityKey", anyObject(), anyString(), anyObject()); - - // -------------------- - // Expected result - // -------------------- - // Nothing. - - // -------------------- - // Run method - // -------------------- - // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("createEntity", - String.class, Map.class); - method.setAccessible(true); - try { - // Run method - method.invoke(cellCtlODataProducer, typeName, staticFields); - fail("Not exception."); - } catch (InvocationTargetException e) { - // -------------------- - // Confirm result - // -------------------- - PersoniumCoreException expected = - PersoniumCoreException.OData.BODY_NTKP_NOT_FOUND_ERROR.params("dummyMsg"); - PersoniumCoreException exception = (PersoniumCoreException) e.getCause(); - assertThat(exception.getStatus(), is(expected.getStatus())); - assertThat(exception.getCode(), is(expected.getCode())); - assertThat(exception.getMessage(), is(expected.getMessage())); - } - } + Cell mockCell = mock(Cell.class); + cellCtlODataProducer.cell = mockCell; + doReturn("http://personium").when(mockCell).getUnitUrl(); - /** - * Test setLinksFromOEntityKey(). - * Normal test. - * @throws Exception Unexpected error - */ - @Test - public void setLinksFromOEntityKey_Normal() throws Exception { - // -------------------- - // Test method args - // -------------------- - OEntityKey key = OEntityKey.create( - Relation.P_NAME.getName(), "dummyRelationName", - Common.P_BOX_NAME.getName(), "dummyBoxName"); - String typeName = Relation.EDM_TYPE_NAME; - EntitySetDocHandler oedh = new OEntityDocHandler(); + PowerMockito.mockStatic(UriUtils.class); + PowerMockito.doReturn(requestRelation).when( + UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation); - // -------------------- - // Mock settings - // -------------------- - doNothing().when(cellCtlODataProducer).setLinksForOedh(anyObject(), anyObject(), anyObject()); + PowerMockito.doReturn(Common.PATTERN_RELATION_CLASS_URL).when(cellCtlODataProducer, "getRegexFromType", type); // -------------------- // Expected result // -------------------- - // Nothing. + String expectedBoxName = null; // -------------------- // Run method // -------------------- - // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("setLinksFromOEntityKey", - OEntityKey.class, String.class, EntitySetDocHandler.class); - method.setAccessible(true); - // Run method - method.invoke(cellCtlODataProducer, key, typeName, oedh); + String actualBoxName = cellCtlODataProducer.getBoxNameFromRequestRelation(requestRelation, type); // -------------------- // Confirm result // -------------------- - // Confirm function call - verify(cellCtlODataProducer, times(1)).setLinksForOedh(anyObject(), anyObject(), anyObject()); + assertThat(actualBoxName, is(expectedBoxName)); } /** - * Test setLinksFromOEntityKey(). + * Test getBoxNameFromRequestRelation(). * Error test. - * setLinksForOedh fail. - * @throws Exception Unexpected error + * Box associated with class URL does not exist. + * @throws Exception Unexpected error. */ @Test - public void setLinksFromOEntityKey_Error_setLinksForOedh_fail() throws Exception { + public void getBoxNameFromRequestRelation_Error_box_associated_with_classURL_does_not_exist() throws Exception { + cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- - OEntityKey key = OEntityKey.create( - Relation.P_NAME.getName(), "dummyRelationName", - Common.P_BOX_NAME.getName(), "dummyBoxName"); - String typeName = Relation.EDM_TYPE_NAME; - EntitySetDocHandler oedh = new OEntityDocHandler(); + String requestRelation = "personium-localunit:/dummyAppCell/__relation/__/dummyRelation"; + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; // -------------------- // Mock settings // -------------------- - doThrow(new NTKPNotFoundException("dummyMsg")).when(cellCtlODataProducer).setLinksForOedh( - anyObject(), anyObject(), anyObject()); + Cell mockCell = mock(Cell.class); + cellCtlODataProducer.cell = mockCell; + doReturn("http://personium").when(mockCell).getUnitUrl(); + + PowerMockito.mockStatic(UriUtils.class); + PowerMockito.doReturn("http://personium/dummyAppCell/__relation/__/dummyRelation").when( + UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation); + + PowerMockito.doReturn(Common.PATTERN_RELATION_CLASS_URL).when(cellCtlODataProducer, "getRegexFromType", type); + + doReturn(null).when(mockCell).getBoxForSchema("http://personium/dummyAppCell/"); // -------------------- // Expected result @@ -1698,396 +1687,1047 @@ public void setLinksFromOEntityKey_Error_setLinksForOedh_fail() throws Exception // -------------------- // Run method // -------------------- - // Load methods for private - Method method = CellCtlODataProducer.class.getDeclaredMethod("setLinksFromOEntityKey", - OEntityKey.class, String.class, EntitySetDocHandler.class); - method.setAccessible(true); try { - // Run method - method.invoke(cellCtlODataProducer, key, typeName, oedh); + cellCtlODataProducer.getBoxNameFromRequestRelation(requestRelation, type); fail("Not exception."); - } catch (InvocationTargetException e) { + } catch (PersoniumCoreException e) { // -------------------- // Confirm result // -------------------- - NTKPNotFoundException expected = new NTKPNotFoundException("dummyMsg"); - NTKPNotFoundException exception = (NTKPNotFoundException) e.getCause(); - assertThat(exception.getMessage(), is(expected.getMessage())); + PersoniumCoreException expected = PersoniumCoreException.ReceivedMessage + .BOX_THAT_MATCHES_RELATION_CLASS_URL_NOT_EXISTS.params( + "http://personium/dummyAppCell/__relation/__/dummyRelation"); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); } } /** - * Test breakRelation(). + * Test getBoxNameFromRequestRelation(). * Normal test. - * getBoxNameFromRequestRelation() is not null. + * Type is relationBuild. + * @throws Exception Unexpected error. */ @Test - public void breakRelation_Normal_getBoxNameFromRequestRelation_is_not_null() { + public void getRegexFromType_Normal_type_is_relation_build() throws Exception { // -------------------- // Test method args // -------------------- - EntitySetDocHandler entitySetDocHandler = mock(EntitySetDocHandler.class); + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; // -------------------- // Mock settings // -------------------- - Map mockStaticFields = new HashMap(); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION.getName(), - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell/"); - doReturn(mockStaticFields).when(entitySetDocHandler).getStaticFields(); - - doReturn("dummyRelation").when(cellCtlODataProducer).getRelationNameFromRequestRelation( - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - doReturn("dummyBoxName").when(cellCtlODataProducer).getBoxNameFromRequestRelation( - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - - EntitySetDocHandler relation = new OEntityDocHandler(); - EntitySetDocHandler extCell = new OEntityDocHandler(); - doReturn(relation).when(cellCtlODataProducer).getRelation("dummyRelation", "dummyBoxName"); - doReturn(extCell).when(cellCtlODataProducer).getExtCell("http://personium/dummyExtCell/"); - - doReturn(true).when(cellCtlODataProducer).deleteLinkEntity(relation, extCell); + // Nothing. // -------------------- // Expected result // -------------------- - // Nothing. + String expectedRegex = Common.PATTERN_RELATION_CLASS_URL; // -------------------- // Run method // -------------------- - cellCtlODataProducer.breakRelation(entitySetDocHandler); + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("getRegexFromType", String.class); + method.setAccessible(true); + // Run method + String actualRegex = (String) method.invoke(cellCtlODataProducer, type); // -------------------- // Confirm result // -------------------- - // Confirm function call - verify(cellCtlODataProducer, times(1)).deleteLinkEntity(relation, extCell); + assertThat(actualRegex, is(expectedRegex)); } /** - * Test breakRelation(). + * Test getBoxNameFromRequestRelation(). * Normal test. - * getBoxNameFromRequestRelation() is null. + * Type is relationBreak. + * @throws Exception Unexpected error. */ @Test - public void breakRelation_Normal_getBoxNameFromRequestRelation_is_null() { + public void getRegexFromType_Normal_type_is_relation_break() throws Exception { // -------------------- // Test method args // -------------------- - EntitySetDocHandler entitySetDocHandler = mock(EntitySetDocHandler.class); + String type = ReceivedMessage.TYPE_REQ_RELATION_BREAK; // -------------------- // Mock settings // -------------------- - Map mockStaticFields = new HashMap(); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION.getName(), - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - mockStaticFields.put(ReceivedMessage.P_BOX_NAME.getName(), "dummyBoxName"); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell/"); - doReturn(mockStaticFields).when(entitySetDocHandler).getStaticFields(); - - doReturn("dummyRelation").when(cellCtlODataProducer).getRelationNameFromRequestRelation( - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - doReturn(null).when(cellCtlODataProducer).getBoxNameFromRequestRelation( - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - - EntitySetDocHandler relation = new OEntityDocHandler(); - EntitySetDocHandler extCell = new OEntityDocHandler(); - doReturn(relation).when(cellCtlODataProducer).getRelation("dummyRelation", "dummyBoxName"); - doReturn(extCell).when(cellCtlODataProducer).getExtCell("http://personium/dummyExtCell/"); - - doReturn(true).when(cellCtlODataProducer).deleteLinkEntity(relation, extCell); + // Nothing. // -------------------- // Expected result // -------------------- - // Nothing. + String expectedRegex = Common.PATTERN_RELATION_CLASS_URL; // -------------------- // Run method // -------------------- - cellCtlODataProducer.breakRelation(entitySetDocHandler); + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("getRegexFromType", String.class); + method.setAccessible(true); + // Run method + String actualRegex = (String) method.invoke(cellCtlODataProducer, type); // -------------------- // Confirm result // -------------------- - // Confirm function call - verify(cellCtlODataProducer, times(1)).deleteLinkEntity(relation, extCell); + assertThat(actualRegex, is(expectedRegex)); } /** - * Test breakRelation(). - * Error test. - * relation is null. + * Test getBoxNameFromRequestRelation(). + * Normal test. + * Type is roleGrant. + * @throws Exception Unexpected error. */ @Test - public void breakRelation_Error_relation_is_null() { + public void getRegexFromType_Normal_type_is_role_grant() throws Exception { // -------------------- // Test method args // -------------------- - EntitySetDocHandler entitySetDocHandler = mock(EntitySetDocHandler.class); + String type = ReceivedMessage.TYPE_REQ_ROLE_GRANT; // -------------------- // Mock settings // -------------------- - Map mockStaticFields = new HashMap(); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION.getName(), - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell/"); - doReturn(mockStaticFields).when(entitySetDocHandler).getStaticFields(); - - doReturn("dummyRelation").when(cellCtlODataProducer).getRelationNameFromRequestRelation( - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - doReturn("dummyBoxName").when(cellCtlODataProducer).getBoxNameFromRequestRelation( - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - - doReturn(null).when(cellCtlODataProducer).getRelation("dummyRelation", "dummyBoxName"); + // Nothing. // -------------------- // Expected result // -------------------- - // Nothing. + String expectedRegex = Common.PATTERN_ROLE_CLASS_URL; // -------------------- // Run method // -------------------- - try { - cellCtlODataProducer.breakRelation(entitySetDocHandler); - fail("Not exception."); - } catch (PersoniumCoreException e) { - // -------------------- - // Confirm result - // -------------------- - PersoniumCoreException expected = - PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_DOES_NOT_EXISTS.params("dummyRelation"); - assertThat(e.getStatus(), is(expected.getStatus())); - assertThat(e.getCode(), is(expected.getCode())); - assertThat(e.getMessage(), is(expected.getMessage())); - } + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("getRegexFromType", String.class); + method.setAccessible(true); + // Run method + String actualRegex = (String) method.invoke(cellCtlODataProducer, type); + + // -------------------- + // Confirm result + // -------------------- + assertThat(actualRegex, is(expectedRegex)); } /** - * Test breakRelation(). - * Error test. - * extCell is null. + * Test getBoxNameFromRequestRelation(). + * Normal test. + * Type is roleRevoke. + * @throws Exception Unexpected error. */ @Test - public void breakRelation_Error_extCell_is_null() { + public void getRegexFromType_Normal_type_is_role_revoke() throws Exception { // -------------------- // Test method args // -------------------- - EntitySetDocHandler entitySetDocHandler = mock(EntitySetDocHandler.class); + String type = ReceivedMessage.TYPE_REQ_ROLE_REVOKE; // -------------------- // Mock settings // -------------------- - Map mockStaticFields = new HashMap(); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION.getName(), - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - mockStaticFields.put(ReceivedMessage.P_BOX_NAME.getName(), "dummyBoxName"); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell/"); - doReturn(mockStaticFields).when(entitySetDocHandler).getStaticFields(); - - doReturn("dummyRelation").when(cellCtlODataProducer).getRelationNameFromRequestRelation( - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - doReturn("dummyBoxName").when(cellCtlODataProducer).getBoxNameFromRequestRelation( - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - - EntitySetDocHandler relation = new OEntityDocHandler(); - doReturn(relation).when(cellCtlODataProducer).getRelation("dummyRelation", "dummyBoxName"); - doReturn(null).when(cellCtlODataProducer).getExtCell("http://personium/dummyExtCell/"); + // Nothing. // -------------------- // Expected result // -------------------- - // Nothing. + String expectedRegex = Common.PATTERN_ROLE_CLASS_URL; // -------------------- // Run method // -------------------- - try { - cellCtlODataProducer.breakRelation(entitySetDocHandler); - fail("Not exception."); - } catch (PersoniumCoreException e) { - // -------------------- - // Confirm result - // -------------------- - PersoniumCoreException expected = PersoniumCoreException.ReceivedMessage - .REQUEST_RELATION_TARGET_DOES_NOT_EXISTS.params("http://personium/dummyExtCell/"); - assertThat(e.getStatus(), is(expected.getStatus())); - assertThat(e.getCode(), is(expected.getCode())); - assertThat(e.getMessage(), is(expected.getMessage())); - } + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("getRegexFromType", String.class); + method.setAccessible(true); + // Run method + String actualRegex = (String) method.invoke(cellCtlODataProducer, type); + + // -------------------- + // Confirm result + // -------------------- + assertThat(actualRegex, is(expectedRegex)); } /** - * Test breakRelation(). - * Error test. - * deleteLinkEntity is false. + * Test getBoxNameFromRequestRelation(). + * Normal test. + * Type is other. + * @throws Exception Unexpected error. */ @Test - public void breakRelation_Error_deleteLinkEntity_is_false() { + public void getRegexFromType_Normal_type_is_other() throws Exception { // -------------------- // Test method args // -------------------- - EntitySetDocHandler entitySetDocHandler = mock(EntitySetDocHandler.class); + String type = ReceivedMessage.TYPE_MESSAGE; // -------------------- // Mock settings // -------------------- - Map mockStaticFields = new HashMap(); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION.getName(), - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - mockStaticFields.put(ReceivedMessage.P_BOX_NAME.getName(), "dummyBoxName"); - mockStaticFields.put(ReceivedMessage.P_REQUEST_RELATION_TARGET.getName(), "http://personium/dummyExtCell/"); - doReturn(mockStaticFields).when(entitySetDocHandler).getStaticFields(); - - doReturn("dummyRelation").when(cellCtlODataProducer).getRelationNameFromRequestRelation( - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - doReturn("dummyBoxName").when(cellCtlODataProducer).getBoxNameFromRequestRelation( - "http://personium/dummyAppCell/__relation/__/dummyRelation"); - - EntitySetDocHandler relation = new OEntityDocHandler(); - EntitySetDocHandler extCell = new OEntityDocHandler(); - doReturn(relation).when(cellCtlODataProducer).getRelation("dummyRelation", "dummyBoxName"); - doReturn(extCell).when(cellCtlODataProducer).getExtCell("http://personium/dummyExtCell/"); - - doReturn(false).when(cellCtlODataProducer).deleteLinkEntity(relation, extCell); + // Nothing. // -------------------- // Expected result // -------------------- - // Nothing. + String expectedRegex = ""; // -------------------- // Run method // -------------------- - try { - cellCtlODataProducer.breakRelation(entitySetDocHandler); - fail("Not exception."); - } catch (PersoniumCoreException e) { - // -------------------- - // Confirm result - // -------------------- - PersoniumCoreException expected = PersoniumCoreException.ReceivedMessage.LINK_DOES_NOT_EXISTS.params( - "dummyRelation", "http://personium/dummyExtCell/"); - assertThat(e.getStatus(), is(expected.getStatus())); - assertThat(e.getCode(), is(expected.getCode())); - assertThat(e.getMessage(), is(expected.getMessage())); - } + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("getRegexFromType", String.class); + method.setAccessible(true); + // Run method + String actualRegex = (String) method.invoke(cellCtlODataProducer, type); + + // -------------------- + // Confirm result + // -------------------- + assertThat(actualRegex, is(expectedRegex)); } /** - * Test getBoxNameFromRequestRelation(). + * Test getEntityKeyMapFromType(). * Normal test. - * RequestRelation is RelationClassURL. + * boxName is not null. * @throws Exception Unexpected error. */ + @SuppressWarnings("unchecked") @Test - public void getBoxNameFromRequestRelation_Normal_requestRelation_is_classURL() throws Exception { + public void getEntityKeyMapFromType_Normal_boxName_is_not_null() throws Exception { // -------------------- // Test method args // -------------------- - String requestRelation = "http://personium/dummyAppCell/__relation/__/dummyRelation"; + String name = "dummyName"; + String boxName = "dummyBox"; + String type = ReceivedMessage.TYPE_MESSAGE; // -------------------- // Mock settings // -------------------- - Cell mockCell = mock(Cell.class); - cellCtlODataProducer.cell = mockCell; - doReturn("http://personium").when(mockCell).getUnitUrl(); - - PowerMockito.mockStatic(UriUtils.class); - PowerMockito.doReturn(requestRelation).when(UriUtils.class, "convertSchemeFromLocalUnitToHttp", - "http://personium", requestRelation); - - Box mockBox = PowerMockito.mock(Box.class); - doReturn("dummyBoxName").when(mockBox).getName(); - doReturn(mockBox).when(mockCell).getBoxForSchema("http://personium/dummyAppCell/"); + // Nothing. // -------------------- // Expected result // -------------------- - String expectedBoxName = "dummyBoxName"; + Map expectedEntityKeyMap = new HashMap<>(); + expectedEntityKeyMap.put(Common.P_BOX_NAME.getName(), boxName); // -------------------- // Run method // -------------------- - String actualBoxName = cellCtlODataProducer.getBoxNameFromRequestRelation(requestRelation); + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "getEntityKeyMapFromType", String.class, String.class, String.class); + method.setAccessible(true); + // Run method + Map actualEntityKeyMap = (Map) method.invoke( + cellCtlODataProducer, name, boxName, type); // -------------------- // Confirm result // -------------------- - assertThat(actualBoxName, is(expectedBoxName)); + assertThat(actualEntityKeyMap.get(Common.P_BOX_NAME.getName()), + is(expectedEntityKeyMap.get(Common.P_BOX_NAME.getName()))); + assertNull(actualEntityKeyMap.get(Relation.P_NAME.getName())); + assertNull(actualEntityKeyMap.get(Role.P_NAME.getName())); } /** - * Test getBoxNameFromRequestRelation(). + * Test getEntityKeyMapFromType(). * Normal test. - * RequestRelation is RelationName. + * type is relationBuild. * @throws Exception Unexpected error. */ + @SuppressWarnings("unchecked") @Test - public void getBoxNameFromRequestRelation_Normal_requestRelation_is_name() throws Exception { + public void getEntityKeyMapFromType_Normal_type_is_relation_build() throws Exception { // -------------------- // Test method args // -------------------- - String requestRelation = "dummyRelation"; + String name = "dummyName"; + String boxName = null; + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; // -------------------- // Mock settings // -------------------- - Cell mockCell = mock(Cell.class); - cellCtlODataProducer.cell = mockCell; - doReturn("http://personium").when(mockCell).getUnitUrl(); + // Nothing. + + // -------------------- + // Expected result + // -------------------- + Map expectedEntityKeyMap = new HashMap<>(); + expectedEntityKeyMap.put(Relation.P_NAME.getName(), name); + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "getEntityKeyMapFromType", String.class, String.class, String.class); + method.setAccessible(true); + // Run method + Map actualEntityKeyMap = (Map) method.invoke( + cellCtlODataProducer, name, boxName, type); + + // -------------------- + // Confirm result + // -------------------- + assertNull(actualEntityKeyMap.get(Common.P_BOX_NAME.getName())); + assertThat(actualEntityKeyMap.get(Relation.P_NAME.getName()), + is(expectedEntityKeyMap.get(Relation.P_NAME.getName()))); + } + + /** + * Test getEntityKeyMapFromType(). + * Normal test. + * type is relationBreak. + * @throws Exception Unexpected error. + */ + @SuppressWarnings("unchecked") + @Test + public void getEntityKeyMapFromType_Normal_type_is_relation_break() throws Exception { + // -------------------- + // Test method args + // -------------------- + String name = "dummyName"; + String boxName = null; + String type = ReceivedMessage.TYPE_REQ_RELATION_BREAK; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + Map expectedEntityKeyMap = new HashMap<>(); + expectedEntityKeyMap.put(Relation.P_NAME.getName(), name); + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "getEntityKeyMapFromType", String.class, String.class, String.class); + method.setAccessible(true); + // Run method + Map actualEntityKeyMap = (Map) method.invoke( + cellCtlODataProducer, name, boxName, type); + + // -------------------- + // Confirm result + // -------------------- + assertNull(actualEntityKeyMap.get(Common.P_BOX_NAME.getName())); + assertThat(actualEntityKeyMap.get(Relation.P_NAME.getName()), + is(expectedEntityKeyMap.get(Relation.P_NAME.getName()))); + } + + /** + * Test getEntityKeyMapFromType(). + * Normal test. + * type is roleGrant. + * @throws Exception Unexpected error. + */ + @SuppressWarnings("unchecked") + @Test + public void getEntityKeyMapFromType_Normal_type_is_role_grant() throws Exception { + // -------------------- + // Test method args + // -------------------- + String name = "dummyName"; + String boxName = null; + String type = ReceivedMessage.TYPE_REQ_ROLE_GRANT; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + Map expectedEntityKeyMap = new HashMap<>(); + expectedEntityKeyMap.put(Role.P_NAME.getName(), name); + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "getEntityKeyMapFromType", String.class, String.class, String.class); + method.setAccessible(true); + // Run method + Map actualEntityKeyMap = (Map) method.invoke( + cellCtlODataProducer, name, boxName, type); + + // -------------------- + // Confirm result + // -------------------- + assertNull(actualEntityKeyMap.get(Common.P_BOX_NAME.getName())); + assertThat(actualEntityKeyMap.get(Role.P_NAME.getName()), + is(expectedEntityKeyMap.get(Role.P_NAME.getName()))); + } + + /** + * Test getEntityKeyMapFromType(). + * Normal test. + * type is roleRevoke. + * @throws Exception Unexpected error. + */ + @SuppressWarnings("unchecked") + @Test + public void getEntityKeyMapFromType_Normal_type_is_role_revoke() throws Exception { + // -------------------- + // Test method args + // -------------------- + String name = "dummyName"; + String boxName = null; + String type = ReceivedMessage.TYPE_REQ_ROLE_REVOKE; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + Map expectedEntityKeyMap = new HashMap<>(); + expectedEntityKeyMap.put(Role.P_NAME.getName(), name); + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "getEntityKeyMapFromType", String.class, String.class, String.class); + method.setAccessible(true); + // Run method + Map actualEntityKeyMap = (Map) method.invoke( + cellCtlODataProducer, name, boxName, type); + + // -------------------- + // Confirm result + // -------------------- + assertNull(actualEntityKeyMap.get(Common.P_BOX_NAME.getName())); + assertThat(actualEntityKeyMap.get(Role.P_NAME.getName()), + is(expectedEntityKeyMap.get(Role.P_NAME.getName()))); + } + + /** + * Test registerRelation(). + * Entity and extcell is not exists. + * @throws Exception Unexpected error + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void registerRelation_Normal_not_exists_entity_and_extcell() throws Exception { + cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); + // -------------------- + // Test method args + // -------------------- + String edmType = Relation.EDM_TYPE_NAME; + Map entityKeyMap = new HashMap<>(); + entityKeyMap.put("dummyKey1", "dummyValue1"); + Map extCellKeyMap = new HashMap<>(); + extCellKeyMap.put("dummyKey2", "dummyValue2"); + + // -------------------- + // Mock settings + // -------------------- + doReturn(null).when(cellCtlODataProducer).getEntitySetDocHandler(anyString(), anyMap()); + PowerMockito.doNothing().when(cellCtlODataProducer, + "createOEntity", anyString(), anyMapOf(String.class, Object.class)); + PowerMockito.doNothing().when(cellCtlODataProducer, "createExtCellLinks", anyString(), anyMap(), anyMap()); + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "registerRelation", String.class, Map.class, Map.class); + method.setAccessible(true); + // Run method + method.invoke(cellCtlODataProducer, edmType, entityKeyMap, extCellKeyMap); + + // -------------------- + // Confirm result + // -------------------- + // Confirm function call + ArgumentCaptor edmTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor entityKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor extCellKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + + + verify(cellCtlODataProducer, times(2)).getEntitySetDocHandler( + edmTypeCaptor.capture(), entityKeyMapCaptor.capture()); + List edmTypeCaptorValueList = edmTypeCaptor.getAllValues(); + List entityKeyMapCaptorValueList = entityKeyMapCaptor.getAllValues(); + assertThat(edmType, is(edmTypeCaptorValueList.get(0))); + assertThat(entityKeyMap, is(entityKeyMapCaptorValueList.get(0))); + assertThat(ExtCell.EDM_TYPE_NAME, is(edmTypeCaptorValueList.get(1))); + assertThat(extCellKeyMap, is(entityKeyMapCaptorValueList.get(1))); + + PowerMockito.verifyPrivate(cellCtlODataProducer, times(2)).invoke( + "createOEntity", edmTypeCaptor.capture(), entityKeyMapCaptor.capture()); + edmTypeCaptorValueList = edmTypeCaptor.getAllValues(); + entityKeyMapCaptorValueList = entityKeyMapCaptor.getAllValues(); + assertThat(edmType, is(edmTypeCaptorValueList.get(0))); + assertThat(entityKeyMap, is(entityKeyMapCaptorValueList.get(0))); + assertThat(ExtCell.EDM_TYPE_NAME, is(edmTypeCaptorValueList.get(1))); + assertThat(extCellKeyMap, is(entityKeyMapCaptorValueList.get(1))); + + PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke("createExtCellLinks", + edmTypeCaptor.capture(), entityKeyMapCaptor.capture(), extCellKeyMapCaptor.capture()); + assertThat(edmType, is(edmTypeCaptor.getValue())); + assertThat(entityKeyMap, is(entityKeyMapCaptor.getValue())); + assertThat(extCellKeyMap, is(extCellKeyMapCaptor.getValue())); + } + + /** + * Test registerRelation(). + * Entity and extcell is exists. + * @throws Exception Unexpected error + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void registerRelation_Normal_exists_entity_and_extcell() throws Exception { + cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); + // -------------------- + // Test method args + // -------------------- + String edmType = Relation.EDM_TYPE_NAME; + Map entityKeyMap = new HashMap<>(); + entityKeyMap.put("dummyKey1", "dummyValue1"); + Map extCellKeyMap = new HashMap<>(); + extCellKeyMap.put("dummyKey2", "dummyValue2"); + + // -------------------- + // Mock settings + // -------------------- + EntitySetDocHandler mockDocHandler = mock(EntitySetDocHandler.class); + doReturn(mockDocHandler).when(cellCtlODataProducer).getEntitySetDocHandler(anyString(), anyMap()); + PowerMockito.doNothing().when(cellCtlODataProducer, "createExtCellLinks", anyString(), anyMap(), anyMap()); + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "registerRelation", String.class, Map.class, Map.class); + method.setAccessible(true); + // Run method + method.invoke(cellCtlODataProducer, edmType, entityKeyMap, extCellKeyMap); + + // -------------------- + // Confirm result + // -------------------- + // Confirm function call + ArgumentCaptor edmTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor entityKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor extCellKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + + + verify(cellCtlODataProducer, times(2)).getEntitySetDocHandler( + edmTypeCaptor.capture(), entityKeyMapCaptor.capture()); + List edmTypeCaptorValueList = edmTypeCaptor.getAllValues(); + List entityKeyMapCaptorValueList = entityKeyMapCaptor.getAllValues(); + assertThat(edmType, is(edmTypeCaptorValueList.get(0))); + assertThat(entityKeyMap, is(entityKeyMapCaptorValueList.get(0))); + assertThat(ExtCell.EDM_TYPE_NAME, is(edmTypeCaptorValueList.get(1))); + assertThat(extCellKeyMap, is(entityKeyMapCaptorValueList.get(1))); + + PowerMockito.verifyPrivate(cellCtlODataProducer, never()).invoke( + "createOEntity", edmTypeCaptor.capture(), entityKeyMapCaptor.capture()); + + PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke("createExtCellLinks", + edmTypeCaptor.capture(), entityKeyMapCaptor.capture(), extCellKeyMapCaptor.capture()); + assertThat(edmType, is(edmTypeCaptor.getValue())); + assertThat(entityKeyMap, is(entityKeyMapCaptor.getValue())); + assertThat(extCellKeyMap, is(extCellKeyMapCaptor.getValue())); + } + + /** + * Test deleteRelation(). + * Normal test. + * @throws Exception Unexpected error + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void deleteRelation_Normal() throws Exception { + // -------------------- + // Test method args + // -------------------- + String edmType = Relation.EDM_TYPE_NAME; + Map entityKeyMap = new HashMap<>(); + entityKeyMap.put("dummyKey1", "dummyValue1"); + Map extCellKeyMap = new HashMap<>(); + extCellKeyMap.put("dummyKey2", "dummyValue2"); + + // -------------------- + // Mock settings + // -------------------- + EntitySetDocHandler entity = new OEntityDocHandler(); + EntitySetDocHandler extCell = new OEntityDocHandler(); + doReturn(entity).when(cellCtlODataProducer).getEntitySetDocHandler(edmType, entityKeyMap); + doReturn(extCell).when(cellCtlODataProducer).getEntitySetDocHandler(ExtCell.EDM_TYPE_NAME, extCellKeyMap); + + doReturn(true).when(cellCtlODataProducer).deleteLinkEntity(entity, extCell); + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "deleteRelation", String.class, Map.class, Map.class); + method.setAccessible(true); + // Run method + method.invoke(cellCtlODataProducer, edmType, entityKeyMap, extCellKeyMap); + + // -------------------- + // Confirm result + // -------------------- + // Confirm function call + ArgumentCaptor edmTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor entityKeyMapCaptor = ArgumentCaptor.forClass(Map.class); + + verify(cellCtlODataProducer, times(2)).getEntitySetDocHandler( + edmTypeCaptor.capture(), entityKeyMapCaptor.capture()); + List edmTypeCaptorValueList = edmTypeCaptor.getAllValues(); + List entityKeyMapCaptorValueList = entityKeyMapCaptor.getAllValues(); + assertThat(edmType, is(edmTypeCaptorValueList.get(0))); + assertThat(entityKeyMap, is(entityKeyMapCaptorValueList.get(0))); + assertThat(ExtCell.EDM_TYPE_NAME, is(edmTypeCaptorValueList.get(1))); + assertThat(extCellKeyMap, is(entityKeyMapCaptorValueList.get(1))); + + verify(cellCtlODataProducer, times(1)).deleteLinkEntity(entity, extCell); + } + + /** + * Test deleteRelation(). + * Error test. + * entity is null. + * @throws Exception Unexpected error + */ + @Test + public void deleteRelation_Error_entity_is_null() throws Exception { + // -------------------- + // Test method args + // -------------------- + String edmType = Relation.EDM_TYPE_NAME; + Map entityKeyMap = new HashMap<>(); + entityKeyMap.put("dummyKey1", "dummyValue1"); + Map extCellKeyMap = new HashMap<>(); + extCellKeyMap.put("dummyKey2", "dummyValue2"); + + // -------------------- + // Mock settings + // -------------------- + EntitySetDocHandler entity = null; + EntitySetDocHandler extCell = new OEntityDocHandler(); + doReturn(entity).when(cellCtlODataProducer).getEntitySetDocHandler(edmType, entityKeyMap); + doReturn(extCell).when(cellCtlODataProducer).getEntitySetDocHandler(ExtCell.EDM_TYPE_NAME, extCellKeyMap); + + doReturn(true).when(cellCtlODataProducer).deleteLinkEntity(entity, extCell); + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "deleteRelation", String.class, Map.class, Map.class); + method.setAccessible(true); + try { + // Run method + method.invoke(cellCtlODataProducer, edmType, entityKeyMap, extCellKeyMap); + fail("Not exception."); + } catch (InvocationTargetException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = + PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_DOES_NOT_EXISTS.params( + edmType, entityKeyMap.toString()); + PersoniumCoreException exception = (PersoniumCoreException) e.getCause(); + assertThat(exception.getStatus(), is(expected.getStatus())); + assertThat(exception.getCode(), is(expected.getCode())); + assertThat(exception.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test deleteRelation(). + * Error test. + * extCell is null. + * @throws Exception Unexpected error + */ + @Test + public void deleteRelation_Error_extCell_is_null() throws Exception { + // -------------------- + // Test method args + // -------------------- + String edmType = Relation.EDM_TYPE_NAME; + Map entityKeyMap = new HashMap<>(); + entityKeyMap.put("dummyKey1", "dummyValue1"); + Map extCellKeyMap = new HashMap<>(); + extCellKeyMap.put("dummyKey2", "dummyValue2"); + + // -------------------- + // Mock settings + // -------------------- + EntitySetDocHandler entity = new OEntityDocHandler(); + EntitySetDocHandler extCell = null; + doReturn(entity).when(cellCtlODataProducer).getEntitySetDocHandler(edmType, entityKeyMap); + doReturn(extCell).when(cellCtlODataProducer).getEntitySetDocHandler(ExtCell.EDM_TYPE_NAME, extCellKeyMap); + + doReturn(true).when(cellCtlODataProducer).deleteLinkEntity(entity, extCell); + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "deleteRelation", String.class, Map.class, Map.class); + method.setAccessible(true); + try { + // Run method + method.invoke(cellCtlODataProducer, edmType, entityKeyMap, extCellKeyMap); + fail("Not exception."); + } catch (InvocationTargetException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = + PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_TARGET_DOES_NOT_EXISTS.params( + ExtCell.EDM_TYPE_NAME, extCellKeyMap.toString()); + PersoniumCoreException exception = (PersoniumCoreException) e.getCause(); + assertThat(exception.getStatus(), is(expected.getStatus())); + assertThat(exception.getCode(), is(expected.getCode())); + assertThat(exception.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test deleteRelation(). + * Error test. + * deleteLinkEntity is false. + * @throws Exception Unexpected error + */ + @Test + public void deleteRelation_Error_deleteLinkEntity_is_false() throws Exception { + // -------------------- + // Test method args + // -------------------- + String edmType = Relation.EDM_TYPE_NAME; + Map entityKeyMap = new HashMap<>(); + entityKeyMap.put("dummyKey1", "dummyValue1"); + Map extCellKeyMap = new HashMap<>(); + extCellKeyMap.put("dummyKey2", "dummyValue2"); + + // -------------------- + // Mock settings + // -------------------- + EntitySetDocHandler entity = new OEntityDocHandler(); + EntitySetDocHandler extCell = new OEntityDocHandler(); + doReturn(entity).when(cellCtlODataProducer).getEntitySetDocHandler(edmType, entityKeyMap); + doReturn(extCell).when(cellCtlODataProducer).getEntitySetDocHandler(ExtCell.EDM_TYPE_NAME, extCellKeyMap); + + doReturn(false).when(cellCtlODataProducer).deleteLinkEntity(entity, extCell); + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod( + "deleteRelation", String.class, Map.class, Map.class); + method.setAccessible(true); + try { + // Run method + method.invoke(cellCtlODataProducer, edmType, entityKeyMap, extCellKeyMap); + fail("Not exception."); + } catch (InvocationTargetException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = + PersoniumCoreException.ReceivedMessage.LINK_DOES_NOT_EXISTS.params( + edmType, entityKeyMap.toString(), ExtCell.EDM_TYPE_NAME, extCellKeyMap.toString()); + PersoniumCoreException exception = (PersoniumCoreException) e.getCause(); + assertThat(exception.getStatus(), is(expected.getStatus())); + assertThat(exception.getCode(), is(expected.getCode())); + assertThat(exception.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test getEntitySetDocHandler(). + * Normal test. + */ + @Test + public void getEntitySetDocHandler_Normal() { + // -------------------- + // Test method args + // -------------------- + String edmType = Relation.EDM_TYPE_NAME; + Map entityKeyMap = new HashMap<>(); + entityKeyMap.put(Relation.P_NAME.getName(), "relationName"); + entityKeyMap.put(Common.P_BOX_NAME.getName(), "boxName"); + + // -------------------- + // Mock settings + // -------------------- + EntitySetDocHandler entitySetDocHandler = new OEntityDocHandler(); + entitySetDocHandler.setStaticFields(entityKeyMap); + doReturn(entitySetDocHandler).when(cellCtlODataProducer).retrieveWithKey(anyObject(), anyObject()); + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + EntitySetDocHandler actual = cellCtlODataProducer.getEntitySetDocHandler(edmType, entityKeyMap); + + // -------------------- + // Confirm result + // -------------------- + assertThat(actual, is(entitySetDocHandler)); + } + + /** + * Test createOEntity(). + * EntityKey type is complex. + * @throws Exception Unexpected error + */ + @Test + public void createOEntity_Normal_entitykey_type_is_complex() throws Exception { + cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); + // -------------------- + // Test method args + // -------------------- + String typeName = "dummyTypeName"; + Map staticFields = new HashMap(); + staticFields.put(Relation.P_NAME.getName(), "dummyRelationName"); + staticFields.put(Common.P_BOX_NAME.getName(), "dummyBoxName"); + + // -------------------- + // Mock settings + // -------------------- + EntitySetAccessor mockEsType = mock(EntitySetAccessor.class); + doReturn(mockEsType).when(cellCtlODataProducer).getAccessorForEntitySet(typeName); + + PowerMockito.doNothing().when(cellCtlODataProducer, "setLinksFromOEntityKey", + anyObject(), anyString(), anyObject()); + + doNothing().when(cellCtlODataProducer).beforeCreate(anyString(), anyObject(), anyObject()); + doReturn(null).when(mockEsType).create(anyString(), anyObject()); + doNothing().when(cellCtlODataProducer).afterCreate(anyString(), anyObject(), anyObject()); + + // -------------------- + // Expected result + // -------------------- + EntitySetDocHandler expectedOedh = new OEntityDocHandler(); + expectedOedh.setType(typeName); + expectedOedh.setStaticFields(staticFields); + expectedOedh.setBoxId(null); + expectedOedh.setNodeId(null); + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("createOEntity", + String.class, Map.class); + method.setAccessible(true); + // Run method + method.invoke(cellCtlODataProducer, typeName, staticFields); + + // -------------------- + // Confirm result + // -------------------- + // Confirm function call + ArgumentCaptor entityKeyCaptor = ArgumentCaptor.forClass(OEntityKey.class); + ArgumentCaptor stringCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor docHandlerCaptor = ArgumentCaptor.forClass(EntitySetDocHandler.class); + ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(OEntity.class); + + PowerMockito.verifyPrivate(cellCtlODataProducer, times(1)).invoke("setLinksFromOEntityKey", + entityKeyCaptor.capture(), stringCaptor.capture(), docHandlerCaptor.capture()); + assertThat(entityKeyCaptor.getValue(), is(OEntityKey.create(staticFields))); + assertThat(stringCaptor.getValue(), is(typeName)); + confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); + + verify(cellCtlODataProducer, times(1)).beforeCreate(stringCaptor.capture(), entityCaptor.capture(), + docHandlerCaptor.capture()); + assertThat(stringCaptor.getValue(), is(typeName)); + assertNull(entityCaptor.getValue()); + confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); - PowerMockito.mockStatic(UriUtils.class); - PowerMockito.doReturn(requestRelation).when(UriUtils.class, "convertSchemeFromLocalUnitToHttp", - "http://personium", requestRelation); + verify(mockEsType, times(1)).create(stringCaptor.capture(), docHandlerCaptor.capture()); + confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); + + verify(cellCtlODataProducer, times(1)).afterCreate(stringCaptor.capture(), entityCaptor.capture(), + docHandlerCaptor.capture()); + assertThat(stringCaptor.getValue(), is(typeName)); + assertNull(entityCaptor.getValue()); + confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); + } + + /** + * Test createOEntity(). + * EntityKey type is not complex. + * @throws Exception Unexpected error + */ + @Test + public void createOEntity_Normal_entitykey_type_is_not_complex() throws Exception { + cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); + // -------------------- + // Test method args + // -------------------- + String typeName = "dummyTypeName"; + Map staticFields = new HashMap(); + staticFields.put(Relation.P_NAME.getName(), "dummyRelationName"); + + // -------------------- + // Mock settings + // -------------------- + EntitySetAccessor mockEsType = mock(EntitySetAccessor.class); + doReturn(mockEsType).when(cellCtlODataProducer).getAccessorForEntitySet(typeName); + + PowerMockito.doNothing().when(cellCtlODataProducer, "setLinksFromOEntityKey", + anyObject(), anyString(), anyObject()); + + doNothing().when(cellCtlODataProducer).beforeCreate(anyString(), anyObject(), anyObject()); + doReturn(null).when(mockEsType).create(anyString(), anyObject()); + doNothing().when(cellCtlODataProducer).afterCreate(anyString(), anyObject(), anyObject()); // -------------------- // Expected result // -------------------- - String expectedBoxName = null; + EntitySetDocHandler expectedOedh = new OEntityDocHandler(); + expectedOedh.setType(typeName); + expectedOedh.setStaticFields(staticFields); + expectedOedh.setBoxId(null); + expectedOedh.setNodeId(null); // -------------------- // Run method // -------------------- - String actualBoxName = cellCtlODataProducer.getBoxNameFromRequestRelation(requestRelation); + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("createOEntity", + String.class, Map.class); + method.setAccessible(true); + // Run method + method.invoke(cellCtlODataProducer, typeName, staticFields); // -------------------- // Confirm result // -------------------- - assertThat(actualBoxName, is(expectedBoxName)); + // Confirm function call + ArgumentCaptor entityKeyCaptor = ArgumentCaptor.forClass(OEntityKey.class); + ArgumentCaptor stringCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor docHandlerCaptor = ArgumentCaptor.forClass(EntitySetDocHandler.class); + ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(OEntity.class); + + PowerMockito.verifyPrivate(cellCtlODataProducer, times(0)).invoke("setLinksFromOEntityKey", + entityKeyCaptor.capture(), stringCaptor.capture(), docHandlerCaptor.capture()); + + verify(cellCtlODataProducer, times(1)).beforeCreate(stringCaptor.capture(), entityCaptor.capture(), + docHandlerCaptor.capture()); + assertThat(stringCaptor.getValue(), is(typeName)); + assertNull(entityCaptor.getValue()); + confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); + + verify(mockEsType, times(1)).create(stringCaptor.capture(), docHandlerCaptor.capture()); + confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); + + verify(cellCtlODataProducer, times(1)).afterCreate(stringCaptor.capture(), entityCaptor.capture(), + docHandlerCaptor.capture()); + assertThat(stringCaptor.getValue(), is(typeName)); + assertNull(entityCaptor.getValue()); + confirmEntitySetDocHandler(expectedOedh, docHandlerCaptor.getValue()); } /** - * Test getBoxNameFromRequestRelation(). + * Confirm EntitySetDocHandler. + * Indefinite values such as UUID and SystemDate are not checked. + * @param expected expected + * @param actual actual + */ + private void confirmEntitySetDocHandler(EntitySetDocHandler expected, EntitySetDocHandler actual) { + assertThat(expected.getType(), is(actual.getType())); + assertThat(expected.getStaticFields(), is(actual.getStaticFields())); + assertThat(expected.getBoxId(), is(actual.getBoxId())); + assertThat(expected.getNodeId(), is(actual.getNodeId())); + } + + /** + * Test createOEntity(). * Error test. - * Box associated with class URL does not exist. - * @throws Exception Unexpected error. + * setLinksFromOEntityKey fail. + * @throws Exception Unexpected error */ @Test - public void getBoxNameFromRequestRelation_Error_box_associated_with_classURL_does_not_exist() throws Exception { + public void createOEntity_Error_setLinksFromOEntityKey_fail() throws Exception { + cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl())); // -------------------- // Test method args // -------------------- - String requestRelation = "http://personium/dummyAppCell/__relation/__/dummyRelation"; + String typeName = "dummyTypeName"; + Map staticFields = new HashMap(); + staticFields.put(Relation.P_NAME.getName(), "dummyRelationName"); + staticFields.put(Common.P_BOX_NAME.getName(), "dummyBoxName"); // -------------------- // Mock settings // -------------------- - Cell mockCell = mock(Cell.class); - cellCtlODataProducer.cell = mockCell; - doReturn("http://personium").when(mockCell).getUnitUrl(); - - PowerMockito.mockStatic(UriUtils.class); - PowerMockito.doReturn(requestRelation).when(UriUtils.class, "convertSchemeFromLocalUnitToHttp", - "http://personium", requestRelation); + EntitySetAccessor mockEsType = mock(EntitySetAccessor.class); + doReturn(mockEsType).when(cellCtlODataProducer).getAccessorForEntitySet(typeName); - doReturn(null).when(mockCell).getBoxForSchema("http://personium/dummyAppCell/"); + PowerMockito.doThrow(new NTKPNotFoundException("dummyMsg")).when(cellCtlODataProducer, + "setLinksFromOEntityKey", anyObject(), anyString(), anyObject()); // -------------------- // Expected result @@ -2097,98 +2737,224 @@ public void getBoxNameFromRequestRelation_Error_box_associated_with_classURL_doe // -------------------- // Run method // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("createOEntity", + String.class, Map.class); + method.setAccessible(true); try { - cellCtlODataProducer.getBoxNameFromRequestRelation(requestRelation); + // Run method + method.invoke(cellCtlODataProducer, typeName, staticFields); fail("Not exception."); - } catch (PersoniumCoreException e) { + } catch (InvocationTargetException e) { // -------------------- // Confirm result // -------------------- - PersoniumCoreException expected = PersoniumCoreException.ReceivedMessage - .BOX_THAT_MATCHES_RELATION_CLASS_URL_NOT_EXISTS.params(requestRelation); - assertThat(e.getStatus(), is(expected.getStatus())); - assertThat(e.getCode(), is(expected.getCode())); - assertThat(e.getMessage(), is(expected.getMessage())); + PersoniumCoreException expected = + PersoniumCoreException.OData.BODY_NTKP_NOT_FOUND_ERROR.params("dummyMsg"); + PersoniumCoreException exception = (PersoniumCoreException) e.getCause(); + assertThat(exception.getStatus(), is(expected.getStatus())); + assertThat(exception.getCode(), is(expected.getCode())); + assertThat(exception.getMessage(), is(expected.getMessage())); } } /** - * Test getRelationNameFromRequestRelation(). + * Test setLinksFromOEntityKey(). * Normal test. - * RequestRelation is RelationClassURL. - * @throws Exception Unexpected error. + * @throws Exception Unexpected error */ @Test - public void getRelationNameFromRequestRelation_Normal_requestRelation_is_classURL() throws Exception { + public void setLinksFromOEntityKey_Normal() throws Exception { // -------------------- // Test method args // -------------------- - String requestRelation = "http://personium/dummyAppCell/__relation/__/dummyRelation"; + OEntityKey key = OEntityKey.create( + Relation.P_NAME.getName(), "dummyRelationName", + Common.P_BOX_NAME.getName(), "dummyBoxName"); + String typeName = Relation.EDM_TYPE_NAME; + EntitySetDocHandler oedh = new OEntityDocHandler(); // -------------------- // Mock settings // -------------------- - Cell mockCell = mock(Cell.class); - cellCtlODataProducer.cell = mockCell; - doReturn("http://personium").when(mockCell).getUnitUrl(); - - PowerMockito.mockStatic(UriUtils.class); - PowerMockito.doReturn(requestRelation).when(UriUtils.class, "convertSchemeFromLocalUnitToHttp", - "http://personium", requestRelation); + doNothing().when(cellCtlODataProducer).setLinksForOedh(anyObject(), anyObject(), anyObject()); // -------------------- // Expected result // -------------------- - String expectedRelationName = "dummyRelation"; + // Nothing. // -------------------- // Run method // -------------------- - String actualRelationName = cellCtlODataProducer.getRelationNameFromRequestRelation(requestRelation); + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("setLinksFromOEntityKey", + OEntityKey.class, String.class, EntitySetDocHandler.class); + method.setAccessible(true); + // Run method + method.invoke(cellCtlODataProducer, key, typeName, oedh); // -------------------- // Confirm result // -------------------- - assertThat(actualRelationName, is(expectedRelationName)); + // Confirm function call + verify(cellCtlODataProducer, times(1)).setLinksForOedh(anyObject(), anyObject(), anyObject()); } /** - * Test getRelationNameFromRequestRelation(). - * Normal test. - * RequestRelation is RelationName. - * @throws Exception Unexpected error. + * Test setLinksFromOEntityKey(). + * Error test. + * setLinksForOedh fail. + * @throws Exception Unexpected error */ @Test - public void getRelationNameFromRequestRelation_Normal_requestRelation_is_name() throws Exception { + public void setLinksFromOEntityKey_Error_setLinksForOedh_fail() throws Exception { // -------------------- // Test method args // -------------------- - String requestRelation = "dummyRelation"; + OEntityKey key = OEntityKey.create( + Relation.P_NAME.getName(), "dummyRelationName", + Common.P_BOX_NAME.getName(), "dummyBoxName"); + String typeName = Relation.EDM_TYPE_NAME; + EntitySetDocHandler oedh = new OEntityDocHandler(); // -------------------- // Mock settings // -------------------- - Cell mockCell = mock(Cell.class); - cellCtlODataProducer.cell = mockCell; - doReturn("http://personium").when(mockCell).getUnitUrl(); + doThrow(new NTKPNotFoundException("dummyMsg")).when(cellCtlODataProducer).setLinksForOedh( + anyObject(), anyObject(), anyObject()); - PowerMockito.mockStatic(UriUtils.class); - PowerMockito.doReturn(requestRelation).when(UriUtils.class, "convertSchemeFromLocalUnitToHttp", - "http://personium", requestRelation); + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("setLinksFromOEntityKey", + OEntityKey.class, String.class, EntitySetDocHandler.class); + method.setAccessible(true); + try { + // Run method + method.invoke(cellCtlODataProducer, key, typeName, oedh); + fail("Not exception."); + } catch (InvocationTargetException e) { + // -------------------- + // Confirm result + // -------------------- + NTKPNotFoundException expected = new NTKPNotFoundException("dummyMsg"); + NTKPNotFoundException exception = (NTKPNotFoundException) e.getCause(); + assertThat(exception.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test createExtCellLinks(). + * Normal test. + * @throws Exception Unexpected error + */ + @Test + public void createExtCellLinks_Normal() throws Exception { + // -------------------- + // Test method args + // -------------------- + String edmType = Relation.EDM_TYPE_NAME; + Map entityKeyMap = new HashMap<>(); + entityKeyMap.put(Relation.P_NAME.getName(), "relationName"); + entityKeyMap.put(Common.P_BOX_NAME.getName(), "boxName"); + Map extCellKeyMap = new HashMap<>(); + extCellKeyMap.put(ExtCell.P_URL.getName(), "http://personium/ExtCell/"); + + // -------------------- + // Mock settings + // -------------------- + doNothing().when(cellCtlODataProducer).createLinks(anyObject(), anyObject()); // -------------------- // Expected result // -------------------- - String expectedRelationName = "dummyRelation"; + // Nothing. // -------------------- // Run method // -------------------- - String actualRelationName = cellCtlODataProducer.getRelationNameFromRequestRelation(requestRelation); + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("createExtCellLinks", + String.class, Map.class, Map.class); + method.setAccessible(true); + // Run method + method.invoke(cellCtlODataProducer, edmType, entityKeyMap, extCellKeyMap); // -------------------- // Confirm result // -------------------- - assertThat(actualRelationName, is(expectedRelationName)); + ArgumentCaptor entityIdCaptor = ArgumentCaptor.forClass(OEntityId.class); + ArgumentCaptor extCellEntityIdCaptor = ArgumentCaptor.forClass(OEntityId.class); + + verify(cellCtlODataProducer, times(1)).createLinks(entityIdCaptor.capture(), extCellEntityIdCaptor.capture()); + OEntityId actualEntityId = entityIdCaptor.getValue(); + OEntityKey actualOEntityKey = actualEntityId.getEntityKey(); + assertThat(actualEntityId.getEntitySetName(), is(Relation.EDM_TYPE_NAME)); + assertThat(actualOEntityKey.toKeyString(), + is("(" + Relation.P_NAME.getName() + "='relationName'," + Common.P_BOX_NAME.getName() + "='boxName')")); + + OEntityId actualExtCellEntityId = extCellEntityIdCaptor.getValue(); + OEntityKey actualExtCellOEntityKey = actualExtCellEntityId.getEntityKey(); + assertThat(actualExtCellEntityId.getEntitySetName(), is(ExtCell.EDM_TYPE_NAME)); + assertThat(actualExtCellOEntityKey.toKeyString(), is("('http://personium/ExtCell/')")); + } + + /** + * Test createExtCellLinks(). + * Error test. + * createLinks fail. + * @throws Exception Unexpected error + */ + @Test + public void createExtCellLinks_Error_createLinks_fail() throws Exception { + // -------------------- + // Test method args + // -------------------- + String edmType = Relation.EDM_TYPE_NAME; + Map entityKeyMap = new HashMap<>(); + entityKeyMap.put(Relation.P_NAME.getName(), "relationName"); + entityKeyMap.put(Common.P_BOX_NAME.getName(), "boxName"); + Map extCellKeyMap = new HashMap<>(); + extCellKeyMap.put(ExtCell.P_URL.getName(), "http://personium/ExtCell/"); + + // -------------------- + // Mock settings + // -------------------- + doThrow(PersoniumCoreException.OData.CONFLICT_LINKS).when(cellCtlODataProducer).createLinks( + anyObject(), anyObject()); + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = CellCtlODataProducer.class.getDeclaredMethod("createExtCellLinks", + String.class, Map.class, Map.class); + method.setAccessible(true); + try { + // Run method + method.invoke(cellCtlODataProducer, edmType, entityKeyMap, extCellKeyMap); + fail("Not exception."); + } catch (InvocationTargetException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_EXISTS_ERROR; + PersoniumCoreException exception = (PersoniumCoreException) e.getCause(); + assertThat(exception.getStatus(), is(expected.getStatus())); + assertThat(exception.getCode(), is(expected.getCode())); + assertThat(exception.getMessage(), is(expected.getMessage())); + } } } diff --git a/src/test/java/io/personium/core/model/impl/fs/DavCmpFsImplTest.java b/src/test/java/io/personium/core/model/impl/fs/DavCmpFsImplTest.java index f83fac8d5..671dc6193 100644 --- a/src/test/java/io/personium/core/model/impl/fs/DavCmpFsImplTest.java +++ b/src/test/java/io/personium/core/model/impl/fs/DavCmpFsImplTest.java @@ -19,6 +19,7 @@ import static java.lang.ClassLoader.getSystemResourceAsStream; import static javax.ws.rs.core.HttpHeaders.ETAG; import static org.apache.commons.codec.digest.DigestUtils.md5Hex; +import static org.apache.http.HttpStatus.SC_CREATED; import static org.apache.http.HttpStatus.SC_NO_CONTENT; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; @@ -26,17 +27,22 @@ import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.nio.file.Files; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; @@ -48,17 +54,25 @@ import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; +import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreException; +import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; import io.personium.core.auth.BoxPrivilege; +import io.personium.core.http.header.RangeHeaderHandler; import io.personium.core.model.DavCmp; import io.personium.core.model.DavDestination; import io.personium.core.model.DavRsCmp; +import io.personium.core.model.file.DataCryptor; +import io.personium.core.model.file.StreamingOutputForDavFile; +import io.personium.core.model.file.StreamingOutputForDavFileWithRange; import io.personium.core.model.lock.Lock; import io.personium.test.categories.Unit; @@ -66,7 +80,8 @@ * Unit Test class for DavCmpFsImpl. */ @RunWith(PowerMockRunner.class) -@PrepareForTest({DavCmpFsImpl.class, AccessContext.class}) +@PowerMockIgnore({"javax.crypto.*" }) +@PrepareForTest({DavCmpFsImpl.class, AccessContext.class, PersoniumUnitConfig.class, DavMetadataFile.class}) @Category({ Unit.class }) public class DavCmpFsImplTest { @@ -82,6 +97,10 @@ public class DavCmpFsImplTest { private static final String SOURCE_FILE = "source"; /** Dest file name for move. */ private static final String DEST_FILE = "target"; + /** AES key string. */ + private static final String AES_KEY = "abcdef0123456789"; + /** Cell ID(AES IV:dIlleCtseTmuinos). */ + private static final String CELL_ID = "PersoniumTestCellId"; /** Test class. */ private DavCmpFsImpl davCmpFsImpl; @@ -106,65 +125,384 @@ public static void afterClass() { testDir.delete(); } + /** + * Test doPutForCreate(). + * normal. + * DavEncryptEnabled is false. + * @throws Exception Unintended exception in test + */ + @Test + public void doPutForCreate_Normal_encrypt_false() throws Exception { + String contentPath = TEST_DIR_PATH + CONTENT_FILE; + File contentFile = new File(contentPath); + InputStream inputStream = null; + FileInputStream contentStream = null; + try { + // -------------------- + // Test method args + // -------------------- + String contentType = "text/plain"; + inputStream = getSystemResourceAsStream("davFile/file01.txt"); + + // -------------------- + // Mock settings + // -------------------- + davCmpFsImpl = PowerMockito.spy(DavCmpFsImpl.create("", null)); + PowerMockito.doNothing().when(davCmpFsImpl, "checkChildResourceCount"); + + PowerMockito.mockStatic(PersoniumUnitConfig.class); + PowerMockito.doReturn(false).when(PersoniumUnitConfig.class, "isDavEncryptEnabled"); + + Whitebox.setInternalState(davCmpFsImpl, "fsPath", TEST_DIR_PATH); + + PowerMockito.doReturn(contentPath).when(davCmpFsImpl, "getContentFilePath"); + + DavMetadataFile davMetaDataFile = mock(DavMetadataFile.class); + PowerMockito.mockStatic(DavMetadataFile.class); + PowerMockito.doReturn(davMetaDataFile).when(DavMetadataFile.class, + "prepareNewFile", anyObject(), anyString()); + + doNothing().when(davMetaDataFile).setContentType(anyString()); + doNothing().when(davMetaDataFile).setContentLength(anyLong()); + doNothing().when(davMetaDataFile).setEncryptionType(anyString()); + doNothing().when(davMetaDataFile).save(); + + doReturn("\"1-1487652733383\"").when(davCmpFsImpl).getEtag(); + + // -------------------- + // Expected result + // -------------------- + boolean contentFileExists = true; + String sourceFileMD5 = md5Hex(getSystemResourceAsStream("davFile/file01.txt")); + ResponseBuilder expected = Response.ok().status(SC_CREATED).header(ETAG, "\"1-1487652733383\""); + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = DavCmpFsImpl.class.getDeclaredMethod("doPutForCreate", String.class, InputStream.class); + method.setAccessible(true); + // Run method + ResponseBuilder actual = (ResponseBuilder) method.invoke(davCmpFsImpl, contentType, inputStream); + + // -------------------- + // Confirm result + // -------------------- + ArgumentCaptor contentTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor contentLengthCaptor = ArgumentCaptor.forClass(Long.class); + ArgumentCaptor encryptionTypeCaptor = ArgumentCaptor.forClass(String.class); + verify(davMetaDataFile, times(1)).setContentType(contentTypeCaptor.capture()); + verify(davMetaDataFile, times(1)).setContentLength(contentLengthCaptor.capture()); + verify(davMetaDataFile, times(1)).setEncryptionType(encryptionTypeCaptor.capture()); + verify(davMetaDataFile, times(1)).save(); + assertThat(contentTypeCaptor.getValue(), is(contentType)); + assertThat(contentLengthCaptor.getValue(), is(16L)); + assertThat(encryptionTypeCaptor.getValue(), is(DataCryptor.ENCRYPTION_TYPE_NONE)); + + assertThat(contentFile.exists(), is(contentFileExists)); + contentStream = new FileInputStream(contentFile); + assertThat(md5Hex(contentStream), is(sourceFileMD5)); + assertThat(actual.build().getStatus(), is(expected.build().getStatus())); + assertThat(actual.build().getMetadata().toString(), is(expected.build().getMetadata().toString())); + } finally { + if (inputStream != null) { + inputStream.close(); + } + if (contentStream != null) { + contentStream.close(); + } + contentFile.delete(); + } + } + + /** + * Test doPutForCreate(). + * normal. + * DavEncryptEnabled is true. + * @throws Exception Unintended exception in test + */ + @Test + public void doPutForCreate_Normal_encrypt_true() throws Exception { + String contentPath = TEST_DIR_PATH + CONTENT_FILE; + File contentFile = new File(contentPath); + InputStream inputStream = null; + FileInputStream contentStream = null; + try { + // -------------------- + // Test method args + // -------------------- + String contentType = "text/plain"; + inputStream = getSystemResourceAsStream("davFile/decrypt01.txt"); + + // -------------------- + // Mock settings + // -------------------- + davCmpFsImpl = PowerMockito.spy(DavCmpFsImpl.create("", null)); + PowerMockito.doNothing().when(davCmpFsImpl, "checkChildResourceCount"); + + PowerMockito.mockStatic(PersoniumUnitConfig.class); + PowerMockito.doReturn(true).when(PersoniumUnitConfig.class, "isDavEncryptEnabled"); + + doReturn(CELL_ID).when(davCmpFsImpl).getCellId(); + DataCryptor.setKeyString(AES_KEY); + + Whitebox.setInternalState(davCmpFsImpl, "fsPath", TEST_DIR_PATH); + + PowerMockito.doReturn(contentPath).when(davCmpFsImpl, "getContentFilePath"); + + DavMetadataFile davMetaDataFile = mock(DavMetadataFile.class); + PowerMockito.mockStatic(DavMetadataFile.class); + PowerMockito.doReturn(davMetaDataFile).when(DavMetadataFile.class, + "prepareNewFile", anyObject(), anyString()); + + doNothing().when(davMetaDataFile).setContentType(anyString()); + doNothing().when(davMetaDataFile).setContentLength(anyLong()); + doNothing().when(davMetaDataFile).setEncryptionType(anyString()); + doNothing().when(davMetaDataFile).save(); + + doReturn("\"1-1487652733383\"").when(davCmpFsImpl).getEtag(); + + // -------------------- + // Expected result + // -------------------- + boolean contentFileExists = true; + String sourceFileMD5 = md5Hex(getSystemResourceAsStream("davFile/encrypt01.txt")); + ResponseBuilder expected = Response.ok().status(SC_CREATED).header(ETAG, "\"1-1487652733383\""); + + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = DavCmpFsImpl.class.getDeclaredMethod("doPutForCreate", String.class, InputStream.class); + method.setAccessible(true); + // Run method + ResponseBuilder actual = (ResponseBuilder) method.invoke(davCmpFsImpl, contentType, inputStream); + + // -------------------- + // Confirm result + // -------------------- + ArgumentCaptor contentTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor contentLengthCaptor = ArgumentCaptor.forClass(Long.class); + ArgumentCaptor encryptionTypeCaptor = ArgumentCaptor.forClass(String.class); + verify(davMetaDataFile, times(1)).setContentType(contentTypeCaptor.capture()); + verify(davMetaDataFile, times(1)).setContentLength(contentLengthCaptor.capture()); + verify(davMetaDataFile, times(1)).setEncryptionType(encryptionTypeCaptor.capture()); + verify(davMetaDataFile, times(1)).save(); + assertThat(contentTypeCaptor.getValue(), is(contentType)); + assertThat(contentLengthCaptor.getValue(), is(98L)); + assertThat(encryptionTypeCaptor.getValue(), is(DataCryptor.ENCRYPTION_TYPE_AES)); + + assertThat(contentFile.exists(), is(contentFileExists)); + contentStream = new FileInputStream(contentFile); + assertThat(md5Hex(contentStream), is(sourceFileMD5)); + assertThat(actual.build().getStatus(), is(expected.build().getStatus())); + assertThat(actual.build().getMetadata().toString(), is(expected.build().getMetadata().toString())); + + } finally { + if (inputStream != null) { + inputStream.close(); + } + if (contentStream != null) { + contentStream.close(); + } + contentFile.delete(); + } + } + /** * Test doPutForUpdate(). * normal. + * DavEncryptEnabled is false. * @throws Exception Unintended exception in test */ @Test - public void doPutForUpdate_Normal() throws Exception { + public void doPutForUpdate_Normal_encrypt_false() throws Exception { String contentPath = TEST_DIR_PATH + CONTENT_FILE; String tempContentPath = TEST_DIR_PATH + TEMP_CONTENT_FILE; + InputStream inputStream = null; + FileInputStream contentStream = null; File contentFile = new File(contentPath); File tempContentFile = new File(tempContentPath); try { contentFile.createNewFile(); + // -------------------- // Test method args - String contentType = "application/json"; - InputStream inputStream = getSystemResourceAsStream("request/unit/cell-create.txt"); + // -------------------- + String contentType = "text/plain"; + inputStream = getSystemResourceAsStream("davFile/file01.txt"); String etag = "\"1-1487652733383\""; + // -------------------- + // Mock settings + // -------------------- + davCmpFsImpl = PowerMockito.spy(DavCmpFsImpl.create("", null)); + DavMetadataFile davMetaDataFile = mock(DavMetadataFile.class); + Whitebox.setInternalState(davCmpFsImpl, "metaFile", davMetaDataFile); + + doNothing().when(davCmpFsImpl).load(); + doReturn(true).when(davCmpFsImpl).exists(); + doReturn("\"1-1487652733383\"").when(davCmpFsImpl).getEtag(); + PowerMockito.doReturn(true).when(davCmpFsImpl, "matchesETag", anyString()); + + PowerMockito.mockStatic(PersoniumUnitConfig.class); + PowerMockito.doReturn(false).when(PersoniumUnitConfig.class, "isDavEncryptEnabled"); + + PowerMockito.doReturn(tempContentPath).when(davCmpFsImpl, "getTempContentFilePath"); + PowerMockito.doReturn(contentPath).when(davCmpFsImpl, "getContentFilePath"); + + doNothing().when(davMetaDataFile).setUpdated(anyLong()); + doNothing().when(davMetaDataFile).setContentType(anyString()); + doNothing().when(davMetaDataFile).setContentLength(anyLong()); + doNothing().when(davMetaDataFile).setEncryptionType(anyString()); + doNothing().when(davMetaDataFile).save(); + + // -------------------- // Expected result + // -------------------- boolean contentFileExists = true; boolean tempFileExists = false; - String sourceFileMD5 = md5Hex(getSystemResourceAsStream("request/unit/cell-create.txt")); + String sourceFileMD5 = md5Hex(getSystemResourceAsStream("davFile/file01.txt")); ResponseBuilder expected = Response.ok().status(SC_NO_CONTENT).header(ETAG, "\"1-1487652733383\""); + // -------------------- + // Run method + // -------------------- + // Load methods for private + Method method = DavCmpFsImpl.class.getDeclaredMethod("doPutForUpdate", + String.class, InputStream.class, String.class); + method.setAccessible(true); + // Run method + ResponseBuilder actual = (ResponseBuilder) method.invoke(davCmpFsImpl, contentType, inputStream, etag); + + // -------------------- + // Confirm result + // -------------------- + ArgumentCaptor contentTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor contentLengthCaptor = ArgumentCaptor.forClass(Long.class); + ArgumentCaptor encryptionTypeCaptor = ArgumentCaptor.forClass(String.class); + verify(davMetaDataFile, times(1)).setUpdated(anyLong()); + verify(davMetaDataFile, times(1)).setContentType(contentTypeCaptor.capture()); + verify(davMetaDataFile, times(1)).setContentLength(contentLengthCaptor.capture()); + verify(davMetaDataFile, times(1)).setEncryptionType(encryptionTypeCaptor.capture()); + verify(davMetaDataFile, times(1)).save(); + assertThat(contentTypeCaptor.getValue(), is(contentType)); + assertThat(contentLengthCaptor.getValue(), is(16L)); + assertThat(encryptionTypeCaptor.getValue(), is(DataCryptor.ENCRYPTION_TYPE_NONE)); + + assertThat(contentFile.exists(), is(contentFileExists)); + assertThat(tempContentFile.exists(), is(tempFileExists)); + contentStream = new FileInputStream(contentFile); + assertThat(md5Hex(contentStream), is(sourceFileMD5)); + assertThat(actual.build().getStatus(), is(expected.build().getStatus())); + assertThat(actual.build().getMetadata().toString(), is(expected.build().getMetadata().toString())); + } finally { + if (inputStream != null) { + inputStream.close(); + } + if (contentStream != null) { + contentStream.close(); + } + contentFile.delete(); + tempContentFile.delete(); + } + } + + /** + * Test doPutForUpdate(). + * normal. + * DavEncryptEnabled is true. + * @throws Exception Unintended exception in test + */ + @Test + public void doPutForUpdate_Normal_encrypt_true() throws Exception { + String contentPath = TEST_DIR_PATH + CONTENT_FILE; + String tempContentPath = TEST_DIR_PATH + TEMP_CONTENT_FILE; + InputStream inputStream = null; + FileInputStream contentStream = null; + File contentFile = new File(contentPath); + File tempContentFile = new File(tempContentPath); + try { + contentFile.createNewFile(); + // -------------------- + // Test method args + // -------------------- + String contentType = "text/plain"; + inputStream = getSystemResourceAsStream("davFile/decrypt01.txt"); + String etag = "\"1-1487652733383\""; + + // -------------------- // Mock settings + // -------------------- davCmpFsImpl = PowerMockito.spy(DavCmpFsImpl.create("", null)); DavMetadataFile davMetaDataFile = mock(DavMetadataFile.class); Whitebox.setInternalState(davCmpFsImpl, "metaFile", davMetaDataFile); + doNothing().when(davCmpFsImpl).load(); doReturn(true).when(davCmpFsImpl).exists(); doReturn("\"1-1487652733383\"").when(davCmpFsImpl).getEtag(); PowerMockito.doReturn(true).when(davCmpFsImpl, "matchesETag", anyString()); + + PowerMockito.mockStatic(PersoniumUnitConfig.class); + PowerMockito.doReturn(true).when(PersoniumUnitConfig.class, "isDavEncryptEnabled"); + + doReturn(CELL_ID).when(davCmpFsImpl).getCellId(); + DataCryptor.setKeyString(AES_KEY); + PowerMockito.doReturn(tempContentPath).when(davCmpFsImpl, "getTempContentFilePath"); PowerMockito.doReturn(contentPath).when(davCmpFsImpl, "getContentFilePath"); doNothing().when(davMetaDataFile).setUpdated(anyLong()); doNothing().when(davMetaDataFile).setContentType(anyString()); doNothing().when(davMetaDataFile).setContentLength(anyLong()); + doNothing().when(davMetaDataFile).setEncryptionType(anyString()); doNothing().when(davMetaDataFile).save(); + // -------------------- + // Expected result + // -------------------- + boolean contentFileExists = true; + boolean tempFileExists = false; + String sourceFileMD5 = md5Hex(getSystemResourceAsStream("davFile/encrypt01.txt")); + ResponseBuilder expected = Response.ok().status(SC_NO_CONTENT).header(ETAG, "\"1-1487652733383\""); + + // -------------------- + // Run method + // -------------------- // Load methods for private Method method = DavCmpFsImpl.class.getDeclaredMethod("doPutForUpdate", String.class, InputStream.class, String.class); method.setAccessible(true); - // Run method ResponseBuilder actual = (ResponseBuilder) method.invoke(davCmpFsImpl, contentType, inputStream, etag); + // -------------------- // Confirm result + // -------------------- + ArgumentCaptor contentTypeCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor contentLengthCaptor = ArgumentCaptor.forClass(Long.class); + ArgumentCaptor encryptionTypeCaptor = ArgumentCaptor.forClass(String.class); + verify(davMetaDataFile, times(1)).setUpdated(anyLong()); + verify(davMetaDataFile, times(1)).setContentType(contentTypeCaptor.capture()); + verify(davMetaDataFile, times(1)).setContentLength(contentLengthCaptor.capture()); + verify(davMetaDataFile, times(1)).setEncryptionType(encryptionTypeCaptor.capture()); + verify(davMetaDataFile, times(1)).save(); + assertThat(contentTypeCaptor.getValue(), is(contentType)); + assertThat(contentLengthCaptor.getValue(), is(98L)); + assertThat(encryptionTypeCaptor.getValue(), is(DataCryptor.ENCRYPTION_TYPE_AES)); + assertThat(contentFile.exists(), is(contentFileExists)); assertThat(tempContentFile.exists(), is(tempFileExists)); - FileInputStream contentStream = new FileInputStream(contentFile); + contentStream = new FileInputStream(contentFile); assertThat(md5Hex(contentStream), is(sourceFileMD5)); assertThat(actual.build().getStatus(), is(expected.build().getStatus())); assertThat(actual.build().getMetadata().toString(), is(expected.build().getMetadata().toString())); - - inputStream.close(); - contentStream.close(); } finally { + if (inputStream != null) { + inputStream.close(); + } + if (contentStream != null) { + contentStream.close(); + } contentFile.delete(); tempContentFile.delete(); } @@ -230,6 +568,270 @@ public void doPutForUpdate_Error_Not_match_ETag() throws Exception { } } + /** + * Test get(). + * normal. + * DavEncryptEnabled is false. + * @throws Exception Unintended exception in test + */ + @Test + public void get_Normal_encrypt_false() throws Exception { + String contentPath = TEST_DIR_PATH + CONTENT_FILE; + InputStream inputStream = null; + File contentFile = new File(contentPath); + try { + inputStream = getSystemResourceAsStream("davFile/file01.txt"); + Files.copy(inputStream, contentFile.toPath()); + // -------------------- + // Test method args + // -------------------- + String rangeHeaderField = null; + + // -------------------- + // Mock settings + // -------------------- + davCmpFsImpl = PowerMockito.spy(DavCmpFsImpl.create("", null)); + + Whitebox.setInternalState(davCmpFsImpl, "fsPath", TEST_DIR_PATH); + + doReturn("text/plain").when(davCmpFsImpl).getContentType(); + doReturn(98L).when(davCmpFsImpl).getContentLength(); + doReturn(DataCryptor.ENCRYPTION_TYPE_NONE).when(davCmpFsImpl).getEncryptionType(); + doReturn(CELL_ID).when(davCmpFsImpl).getCellId(); + doReturn("\"1-1487652733383\"").when(davCmpFsImpl).getEtag(); + + // -------------------- + // Expected result + // -------------------- + String sourceFileMD5 = md5Hex(getSystemResourceAsStream("davFile/file01.txt")); + ResponseBuilder expected = Response.ok().header(HttpHeaders.CONTENT_LENGTH, 98L) + .header(HttpHeaders.CONTENT_TYPE, "text/plain") + .header(ETAG, "\"1-1487652733383\"") + .header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); + + // -------------------- + // Run method + // -------------------- + ResponseBuilder actual = davCmpFsImpl.get(rangeHeaderField); + + // -------------------- + // Confirm result + // -------------------- + assertThat(actual.build().getStatus(), is(expected.build().getStatus())); + assertThat(actual.build().getMetadata().toString(), is(expected.build().getMetadata().toString())); + + StreamingOutputForDavFile entity = (StreamingOutputForDavFile) actual.build().getEntity(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + entity.write(output); + assertThat(md5Hex(output.toByteArray()), is(sourceFileMD5)); + } finally { + if (inputStream != null) { + inputStream.close(); + } + contentFile.delete(); + } + } + + /** + * Test get(). + * normal. + * DavEncryptEnabled is true. + * @throws Exception Unintended exception in test + */ + @Test + public void get_Normal_encrypt_true() throws Exception { + String contentPath = TEST_DIR_PATH + CONTENT_FILE; + InputStream inputStream = null; + File contentFile = new File(contentPath); + try { + inputStream = getSystemResourceAsStream("davFile/encrypt01.txt"); + Files.copy(inputStream, contentFile.toPath()); + // -------------------- + // Test method args + // -------------------- + String rangeHeaderField = null; + + // -------------------- + // Mock settings + // -------------------- + davCmpFsImpl = PowerMockito.spy(DavCmpFsImpl.create("", null)); + + Whitebox.setInternalState(davCmpFsImpl, "fsPath", TEST_DIR_PATH); + + doReturn("text/plain").when(davCmpFsImpl).getContentType(); + doReturn(98L).when(davCmpFsImpl).getContentLength(); + doReturn(DataCryptor.ENCRYPTION_TYPE_AES).when(davCmpFsImpl).getEncryptionType(); + DataCryptor.setKeyString(AES_KEY); + doReturn(CELL_ID).when(davCmpFsImpl).getCellId(); + doReturn("\"1-1487652733383\"").when(davCmpFsImpl).getEtag(); + + // -------------------- + // Expected result + // -------------------- + String sourceFileMD5 = md5Hex(getSystemResourceAsStream("davFile/decrypt01.txt")); + ResponseBuilder expected = Response.ok().header(HttpHeaders.CONTENT_LENGTH, 98L) + .header(HttpHeaders.CONTENT_TYPE, "text/plain") + .header(ETAG, "\"1-1487652733383\"") + .header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); + + // -------------------- + // Run method + // -------------------- + ResponseBuilder actual = davCmpFsImpl.get(rangeHeaderField); + + // -------------------- + // Confirm result + // -------------------- + assertThat(actual.build().getStatus(), is(expected.build().getStatus())); + assertThat(actual.build().getMetadata().toString(), is(expected.build().getMetadata().toString())); + + StreamingOutputForDavFile entity = (StreamingOutputForDavFile) actual.build().getEntity(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + entity.write(output); + assertThat(md5Hex(output.toByteArray()), is(sourceFileMD5)); + } finally { + if (inputStream != null) { + inputStream.close(); + } + contentFile.delete(); + } + } + + /** + * Test get(). + * normal. + * Range specification. + * DavEncryptEnabled is false. + * @throws Exception Unintended exception in test + */ + @Test + public void get_Normal_range_encrypt_false() throws Exception { + String contentPath = TEST_DIR_PATH + CONTENT_FILE; + InputStream inputStream = null; + File contentFile = new File(contentPath); + try { + inputStream = getSystemResourceAsStream("davFile/decrypt01.txt"); + Files.copy(inputStream, contentFile.toPath()); + // -------------------- + // Test method args + // -------------------- + String rangeHeaderField = "bytes=10-40"; + + // -------------------- + // Mock settings + // -------------------- + davCmpFsImpl = PowerMockito.spy(DavCmpFsImpl.create("", null)); + + Whitebox.setInternalState(davCmpFsImpl, "fsPath", TEST_DIR_PATH); + + doReturn("text/plain").when(davCmpFsImpl).getContentType(); + doReturn(98L).when(davCmpFsImpl).getContentLength(); + doReturn(DataCryptor.ENCRYPTION_TYPE_NONE).when(davCmpFsImpl).getEncryptionType(); + doReturn(CELL_ID).when(davCmpFsImpl).getCellId(); + doReturn("\"1-1487652733383\"").when(davCmpFsImpl).getEtag(); + + // -------------------- + // Expected result + // -------------------- + String sourceFileMD5 = md5Hex(getSystemResourceAsStream("davFile/range01.txt")); + ResponseBuilder expected = Response.status(HttpStatus.SC_PARTIAL_CONTENT) + .header(PersoniumCoreUtils.HttpHeaders.CONTENT_RANGE, "bytes 10-40/98") + .header(HttpHeaders.CONTENT_LENGTH, 31L) + .header(HttpHeaders.CONTENT_TYPE, "text/plain") + .header(ETAG, "\"1-1487652733383\"") + .header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); + + // -------------------- + // Run method + // -------------------- + ResponseBuilder actual = davCmpFsImpl.get(rangeHeaderField); + + // -------------------- + // Confirm result + // -------------------- + assertThat(actual.build().getStatus(), is(expected.build().getStatus())); + assertThat(actual.build().getMetadata().toString(), is(expected.build().getMetadata().toString())); + + StreamingOutputForDavFileWithRange entity = (StreamingOutputForDavFileWithRange) actual.build().getEntity(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + entity.write(output); + assertThat(md5Hex(output.toByteArray()), is(sourceFileMD5)); + } finally { + if (inputStream != null) { + inputStream.close(); + } + contentFile.delete(); + } + } + + /** + * Test get(). + * normal. + * Range specification. + * DavEncryptEnabled is true. + * @throws Exception Unintended exception in test + */ + @Test + public void get_Normal_range_encrypt_true() throws Exception { + String contentPath = TEST_DIR_PATH + CONTENT_FILE; + InputStream inputStream = null; + File contentFile = new File(contentPath); + try { + inputStream = getSystemResourceAsStream("davFile/encrypt01.txt"); + Files.copy(inputStream, contentFile.toPath()); + // -------------------- + // Test method args + // -------------------- + String rangeHeaderField = "bytes=10-40"; + + // -------------------- + // Mock settings + // -------------------- + davCmpFsImpl = PowerMockito.spy(DavCmpFsImpl.create("", null)); + + Whitebox.setInternalState(davCmpFsImpl, "fsPath", TEST_DIR_PATH); + + doReturn("text/plain").when(davCmpFsImpl).getContentType(); + doReturn(98L).when(davCmpFsImpl).getContentLength(); + doReturn(DataCryptor.ENCRYPTION_TYPE_AES).when(davCmpFsImpl).getEncryptionType(); + DataCryptor.setKeyString(AES_KEY); + doReturn(CELL_ID).when(davCmpFsImpl).getCellId(); + doReturn("\"1-1487652733383\"").when(davCmpFsImpl).getEtag(); + + // -------------------- + // Expected result + // -------------------- + String sourceFileMD5 = md5Hex(getSystemResourceAsStream("davFile/range01.txt")); + ResponseBuilder expected = Response.status(HttpStatus.SC_PARTIAL_CONTENT) + .header(PersoniumCoreUtils.HttpHeaders.CONTENT_RANGE, "bytes 10-40/98") + .header(HttpHeaders.CONTENT_LENGTH, 31L) + .header(HttpHeaders.CONTENT_TYPE, "text/plain") + .header(ETAG, "\"1-1487652733383\"") + .header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); + + // -------------------- + // Run method + // -------------------- + ResponseBuilder actual = davCmpFsImpl.get(rangeHeaderField); + + // -------------------- + // Confirm result + // -------------------- + assertThat(actual.build().getStatus(), is(expected.build().getStatus())); + assertThat(actual.build().getMetadata().toString(), is(expected.build().getMetadata().toString())); + + StreamingOutputForDavFile entity = (StreamingOutputForDavFile) actual.build().getEntity(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + entity.write(output); + assertThat(md5Hex(output.toByteArray()), is(sourceFileMD5)); + } finally { + if (inputStream != null) { + inputStream.close(); + } + contentFile.delete(); + } + } + /** * Test move(). * Dest DavNode not exists. diff --git a/src/test/java/io/personium/core/rs/cell/MessageODataResourceTest.java b/src/test/java/io/personium/core/rs/cell/MessageODataResourceTest.java index 271edecfe..08c83b6e7 100644 --- a/src/test/java/io/personium/core/rs/cell/MessageODataResourceTest.java +++ b/src/test/java/io/personium/core/rs/cell/MessageODataResourceTest.java @@ -444,4 +444,750 @@ public void validateSentBoxBoundSchema_Error_box_is_null() { assertThat(e.getMessage(), is(expected.getMessage())); } } + + /** + * Test validateStatus(). + * Normal test. + * Type is message. + */ + @Test + public void validateStatus_Normal_type_is_message() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_MESSAGE; + String status = ReceivedMessage.STATUS_UNREAD; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateStatus(type, status); + } catch (PersoniumCoreException e) { + fail("Exception occurred."); + } + } + + /** + * Test validateStatus(). + * Normal test. + * Type is relationBuild. + */ + @Test + public void validateStatus_Normal_type_is_relation_build() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; + String status = ReceivedMessage.STATUS_NONE; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateStatus(type, status); + } catch (PersoniumCoreException e) { + fail("Exception occurred."); + } + } + + /** + * Test validateStatus(). + * Normal test. + * Type is roleGrant. + */ + @Test + public void validateStatus_Normal_type_is_role_grant() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_ROLE_GRANT; + String status = ReceivedMessage.STATUS_NONE; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateStatus(type, status); + } catch (PersoniumCoreException e) { + fail("Exception occurred."); + } + } + + /** + * Test validateStatus(). + * Error test. + * Type is message. + */ + @Test + public void validateStatus_Error_type_is_message() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_MESSAGE; + String status = ReceivedMessage.STATUS_READ; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateStatus(type, status); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_STATUS.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateStatus(). + * Error test. + * Type is relationBuild. + */ + @Test + public void validateStatus_Error_type_is_relation_build() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; + String status = ReceivedMessage.STATUS_APPROVED; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateStatus(type, status); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_STATUS.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateStatus(). + * Error test. + * Type is relationBreak. + */ + @Test + public void validateStatus_Error_type_is_relation_break() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_RELATION_BREAK; + String status = ReceivedMessage.STATUS_REJECTED; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateStatus(type, status); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_STATUS.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateStatus(). + * Error test. + * Type is roleGrant. + */ + @Test + public void validateStatus_Error_type_is_role_grant() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_ROLE_GRANT; + String status = ReceivedMessage.STATUS_REJECTED; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateStatus(type, status); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_STATUS.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateStatus(). + * Error test. + * Type is roleRevoke. + */ + @Test + public void validateStatus_Error_type_is_role_revoke() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_ROLE_REVOKE; + String status = ReceivedMessage.STATUS_APPROVED; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateStatus(type, status); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_STATUS.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateReqRelation(). + * Normal test. + * Type is relationBuild. + */ + @Test + public void validateReqRelation_Normal_type_is_relation_build() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; + String requestRelation = "http://personium/AppCell/__relation/__/-relationName_+:/"; + String requestRelationTarget = "http://personium/ExtCell/"; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); + } catch (PersoniumCoreException e) { + fail("Exception occurred."); + } + } + + /** + * Test validateReqRelation(). + * Normal test. + * Type is roleGrant. + */ + @Test + public void validateReqRelation_Normal_type_is_role_grant() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_ROLE_GRANT; + String requestRelation = "http://personium/AppCell/__role/__/roleName-_/"; + String requestRelationTarget = "http://personium/ExtCell/"; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); + } catch (PersoniumCoreException e) { + fail("Exception occurred."); + } + } + + /** + * Test validateReqRelation(). + * Normal test. + * Type is message. + */ + @Test + public void validateReqRelation_Normal_type_is_message() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_MESSAGE; + String requestRelation = null; + String requestRelationTarget = null; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); + } catch (PersoniumCoreException e) { + fail("Exception occurred."); + } + } + + /** + * Test validateReqRelation(). + * Error test. + * Type is relationBuild and RequestRelation is null. + */ + @Test + public void validateReqRelation_Error_type_is_relation_build_and_requestRelation_is_null() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; + String requestRelation = null; + String requestRelationTarget = "http://personium/ExtCell/"; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_REQUEST_RELATION.getName() + + "," + ReceivedMessage.P_REQUEST_RELATION_TARGET.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateReqRelation(). + * Error test. + * Type is relationBreak and RequestRelationTarget is null. + */ + @Test + public void validateReqRelation_Error_type_is_relation_break_and_requestRelationTarget_is_null() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_RELATION_BREAK; + String requestRelation = "rerationName"; + String requestRelationTarget = null; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_REQUEST_RELATION.getName() + + "," + ReceivedMessage.P_REQUEST_RELATION_TARGET.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateReqRelation(). + * Error test. + * Type is roleGrant and RequestRelation is null. + */ + @Test + public void validateReqRelation_Error_type_is_role_grant_and_requestRelation_is_null() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_ROLE_GRANT; + String requestRelation = null; + String requestRelationTarget = "http://personium/ExtCell/"; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_REQUEST_RELATION.getName() + + "," + ReceivedMessage.P_REQUEST_RELATION_TARGET.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateReqRelation(). + * Error test. + * Type is roleRevoke and RequestRelationTarget is null. + */ + @Test + public void validateReqRelation_Error_type_is_role_revoke_and_requestRelationTarget_is_null() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_ROLE_REVOKE; + String requestRelation = "roleName"; + String requestRelationTarget = null; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_REQUEST_RELATION.getName() + + "," + ReceivedMessage.P_REQUEST_RELATION_TARGET.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateReqRelation(). + * Error test. + * Type is relationBuild and RequestRelation is invalid format. + */ + @Test + public void validateReqRelation_Error_type_is_relation_build_and_requestRelation_is_invalid_format() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; + String requestRelation = "http://personium/Cell/relationName"; + String requestRelationTarget = "http://personium/ExtCell/"; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_REQUEST_RELATION.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateReqRelation(). + * Error test. + * Type is relationBreak and RequestRelation is invalid format. + */ + @Test + public void validateReqRelation_Error_type_is_relation_break_and_requestRelation_is_invalid_format() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_RELATION_BREAK; + String requestRelation = "_rerationName-+:"; + String requestRelationTarget = "http://personium/ExtCell/"; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_REQUEST_RELATION.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateReqRelation(). + * Error test. + * Type is roleGrant and RequestRelation is invalid format. + */ + @Test + public void validateReqRelation_Error_type_is_role_grant_and_requestRelation_is_invalid_format() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_ROLE_GRANT; + String requestRelation = "http://personium/Cell/roleName"; + String requestRelationTarget = "http://personium/ExtCell/"; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_REQUEST_RELATION.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } + + /** + * Test validateReqRelation(). + * Error test. + * Type is roleRevoke and RequestRelation is invalid format. + */ + @Test + public void validateReqRelation_Error_type_is_role_revoke_and_requestRelation_is_invalid_format() { + // -------------------- + // Test method args + // -------------------- + String type = ReceivedMessage.TYPE_REQ_ROLE_REVOKE; + String requestRelation = "-roleName_"; + String requestRelationTarget = "http://personium/ExtCell/"; + + // -------------------- + // Mock settings + // -------------------- + // Nothing. + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); + fail("Not exception."); + } catch (PersoniumCoreException e) { + // -------------------- + // Confirm result + // -------------------- + PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params( + ReceivedMessage.P_REQUEST_RELATION.getName()); + assertThat(e.getStatus(), is(expected.getStatus())); + assertThat(e.getCode(), is(expected.getCode())); + assertThat(e.getMessage(), is(expected.getMessage())); + } + } } diff --git a/src/test/java/io/personium/core/rs/odata/AbstractODataResourceTest.java b/src/test/java/io/personium/core/rs/odata/AbstractODataResourceTest.java index 65e0d67cb..0d787b534 100644 --- a/src/test/java/io/personium/core/rs/odata/AbstractODataResourceTest.java +++ b/src/test/java/io/personium/core/rs/odata/AbstractODataResourceTest.java @@ -205,7 +205,7 @@ public void validatePropertyRegEx_Error_check_result_is_false() throws Exception * @throws Exception Unexpected error. */ @Test - public void validatePropertyMessageRequestRelation_Normal_relation_is_classURL() throws Exception { + public void validatePropertyMessageRequestRelation_Normal_relation_is_relationClassURL() throws Exception { String requestRelation = "http://personium/dummyAppCell/__relation/__/dummyRelation"; // -------------------- // Test method args @@ -221,6 +221,10 @@ public void validatePropertyMessageRequestRelation_Normal_relation_is_classURL() requestRelation, Common.PATTERN_RELATION_CLASS_URL); PowerMockito.doReturn(false).when(ODataUtils.class, "validateRegEx", requestRelation, Common.PATTERN_RELATION_NAME); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateClassUrl", + requestRelation, Common.PATTERN_ROLE_CLASS_URL); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateRegEx", + requestRelation, Common.PATTERN_NAME); // -------------------- // Expected result @@ -249,7 +253,7 @@ public void validatePropertyMessageRequestRelation_Normal_relation_is_classURL() * @throws Exception Unexpected error. */ @Test - public void validatePropertyMessageRequestRelation_Normal_relation_is_name() throws Exception { + public void validatePropertyMessageRequestRelation_Normal_relation_is_relationName() throws Exception { String requestRelation = "dummyRelation"; // -------------------- // Test method args @@ -265,6 +269,106 @@ public void validatePropertyMessageRequestRelation_Normal_relation_is_name() thr requestRelation, Common.PATTERN_RELATION_CLASS_URL); PowerMockito.doReturn(true).when(ODataUtils.class, "validateRegEx", requestRelation, Common.PATTERN_RELATION_NAME); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateClassUrl", + requestRelation, Common.PATTERN_ROLE_CLASS_URL); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateRegEx", + requestRelation, Common.PATTERN_NAME); + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + abstractODataResource.validatePropertyMessageRequestRelation(propName, op); + } catch (PersoniumCoreException e) { + fail("Exception occurred."); + } + + // -------------------- + // Confirm result + // -------------------- + // Nothing. + } + + /** + * Test validatePropertyMessageRequestRelation(). + * Normal test. + * isValidClassUrl return true; + * @throws Exception Unexpected error. + */ + @Test + public void validatePropertyMessageRequestRelation_Normal_relation_is_roleClassURL() throws Exception { + String requestRelation = "http://personium/dummyAppCell/__role/__/dummyRole"; + // -------------------- + // Test method args + // -------------------- + String propName = "RequestRelation"; + OProperty op = OProperties.string("RequestRelation", requestRelation); + + // -------------------- + // Mock settings + // -------------------- + PowerMockito.mockStatic(ODataUtils.class); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateClassUrl", + requestRelation, Common.PATTERN_RELATION_CLASS_URL); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateRegEx", + requestRelation, Common.PATTERN_RELATION_NAME); + PowerMockito.doReturn(true).when(ODataUtils.class, "validateClassUrl", + requestRelation, Common.PATTERN_ROLE_CLASS_URL); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateRegEx", + requestRelation, Common.PATTERN_NAME); + + // -------------------- + // Expected result + // -------------------- + // Nothing. + + // -------------------- + // Run method + // -------------------- + try { + abstractODataResource.validatePropertyMessageRequestRelation(propName, op); + } catch (PersoniumCoreException e) { + fail("Exception occurred."); + } + + // -------------------- + // Confirm result + // -------------------- + // Nothing. + } + + /** + * Test validatePropertyMessageRequestRelation(). + * Normal test. + * isValidRegEx return true; + * @throws Exception Unexpected error. + */ + @Test + public void validatePropertyMessageRequestRelation_Normal_relation_is_roleName() throws Exception { + String requestRelation = "dummyRole"; + // -------------------- + // Test method args + // -------------------- + String propName = "RequestRelation"; + OProperty op = OProperties.string("RequestRelation", requestRelation); + + // -------------------- + // Mock settings + // -------------------- + PowerMockito.mockStatic(ODataUtils.class); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateClassUrl", + requestRelation, Common.PATTERN_RELATION_CLASS_URL); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateRegEx", + requestRelation, Common.PATTERN_RELATION_NAME); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateClassUrl", + requestRelation, Common.PATTERN_ROLE_CLASS_URL); + PowerMockito.doReturn(true).when(ODataUtils.class, "validateRegEx", + requestRelation, Common.PATTERN_NAME); // -------------------- // Expected result @@ -309,6 +413,10 @@ public void validatePropertyMessageRequestRelation_Error_relation_is_unexpected_ requestRelation, Common.PATTERN_RELATION_CLASS_URL); PowerMockito.doReturn(false).when(ODataUtils.class, "validateRegEx", requestRelation, Common.PATTERN_RELATION_NAME); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateClassUrl", + requestRelation, Common.PATTERN_ROLE_CLASS_URL); + PowerMockito.doReturn(false).when(ODataUtils.class, "validateRegEx", + requestRelation, Common.PATTERN_NAME); // -------------------- // Expected result diff --git a/src/test/java/io/personium/core/webcontainer/listener/AllTests.java b/src/test/java/io/personium/core/webcontainer/listener/AllTests.java deleted file mode 100644 index eb745c42c..000000000 --- a/src/test/java/io/personium/core/webcontainer/listener/AllTests.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 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 io.personium.core.webcontainer.listener; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -/** - * パッケージ配下のテストケースを全て実行するためのテストスイート. - */ -@RunWith(Suite.class) -@SuiteClasses({ - RepairServiceLauncherTest.class -}) -public class AllTests { -} diff --git a/src/test/java/io/personium/core/webcontainer/listener/RepairServiceLauncherTest.java b/src/test/java/io/personium/core/webcontainer/listener/RepairServiceLauncherTest.java deleted file mode 100644 index b3ede92a2..000000000 --- a/src/test/java/io/personium/core/webcontainer/listener/RepairServiceLauncherTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * 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 io.personium.core.webcontainer.listener; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * io.personium.core.webcontainer.listener.RepairServiceLauncherのテスト. - */ -@RunWith(JUnit4.class) -public class RepairServiceLauncherTest { - - /** - * ExecutorServiceの起動_終了テスト. - */ - @Test - @Ignore - public void ExecutorServiceの起動_終了テスト() { - RepairServiceLauncher launcher = new RepairServiceLauncher(); - assertThat(launcher.executor.getPoolSize(), is(1)); - assertThat(launcher.executor.getTaskCount(), is(1L)); - - launcher.shutdown(); - assertThat(launcher.executor.isTerminated(), is(true)); - assertThat(launcher.executor.isShutdown(), is(true)); - } - - /** - * ExecutorServiceの終了時に実行中のタスクが強制終了されないことを確認. - * @throws InterruptedException タイムアウト - */ - @Test - public void ExecutorServiceの終了時に実行中のタスクが強制終了されないことを確認() throws InterruptedException { - RepairServiceLauncher launcher = new RepairServiceLauncher(); - - // 既存のタスクを中止。 - BlockingQueue queue = launcher.executor.getQueue(); - assertThat(queue.size(), is(1)); - launcher.executor.remove(queue.peek()); - - // 数秒かかるタスクを代わりに投入. - Runnable command = new Runnable() { - @Override - public void run() { - try { - Thread.sleep(8000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - }; - - launcher.executor.scheduleWithFixedDelay(command, 0, 10, TimeUnit.SECONDS); - - Thread.sleep(1000); - System.out.println("Shutting down service."); - // タスクが即時終了しないことを確認する。 - long tm1 = System.currentTimeMillis(); - launcher.shutdown(); - long tm2 = System.currentTimeMillis(); - assertTrue(tm2 - tm1 > 4000L); - - assertThat(launcher.executor.isTerminated(), is(true)); - assertThat(launcher.executor.isShutdown(), is(true)); - } - - /** - * ファイルの有無によりAdsRepairの起動が切り替えられること. - * @throws IllegalAccessException エラー - * @throws IllegalArgumentException エラー - * @throws SecurityException エラー - * @throws NoSuchFieldException エラー - * @throws IOException エラー - */ - @Test - public void ファイルの有無によりAdsRepairの起動が切り替えられること() - throws IllegalArgumentException, IllegalAccessException, - NoSuchFieldException, SecurityException, IOException { - - RepairServiceLauncher.RepairAdsService service = new RepairServiceLauncher.RepairAdsService(); - - Field flagFileField = service.getClass().getDeclaredField("invocationFlagFile"); - flagFileField.setAccessible(true); - flagFileField.set(service, "./testFlagFile"); - - File testFile = new File("./testFlagFile"); - testFile.deleteOnExit(); - - if (testFile.exists()) { - testFile.delete(); - } - - // ファイルが存在しないため、falseが返る。 - assertFalse(service.shouldInvoke()); - - // ディレクトリであるため、falseが返る。 - testFile.mkdir(); - assertFalse(service.shouldInvoke()); - testFile.delete(); - - testFile.createNewFile(); - assertTrue(service.shouldInvoke()); - - testFile.delete(); - - assertFalse(testFile.exists()); - } - -} diff --git a/src/test/java/io/personium/test/IntegrationTests.java b/src/test/java/io/personium/test/IntegrationTests.java index f67653205..ee838b37e 100644 --- a/src/test/java/io/personium/test/IntegrationTests.java +++ b/src/test/java/io/personium/test/IntegrationTests.java @@ -16,14 +16,13 @@ */ package io.personium.test; -import junit.framework.TestSuite; - import org.junit.experimental.categories.Categories; import org.junit.experimental.categories.Categories.IncludeCategory; import org.junit.runner.RunWith; import org.junit.runners.Suite.SuiteClasses; import io.personium.test.categories.Integration; +import junit.framework.TestSuite; /** * 結合テスト用テストスイート. @@ -34,7 +33,6 @@ io.personium.core.model.file.AllTests.class, io.personium.core.model.impl.es.AllTests.class, io.personium.core.model.impl.es.accessor.AllTests.class, - io.personium.core.model.impl.es.ads.AllTests.class, io.personium.core.model.lock.AllTests.class, io.personium.core.rs.AllTests.class, io.personium.test.jersey.AllTests.class, diff --git a/src/test/java/io/personium/test/PerformanceTests.java b/src/test/java/io/personium/test/PerformanceTests.java index 7e2f44803..62e209850 100644 --- a/src/test/java/io/personium/test/PerformanceTests.java +++ b/src/test/java/io/personium/test/PerformanceTests.java @@ -16,14 +16,13 @@ */ package io.personium.test; -import junit.framework.TestSuite; - import org.junit.experimental.categories.Categories; import org.junit.experimental.categories.Categories.IncludeCategory; import org.junit.runner.RunWith; import org.junit.runners.Suite.SuiteClasses; import io.personium.test.categories.Performance; +import junit.framework.TestSuite; /** * 結合テスト用テストスイート. @@ -34,7 +33,6 @@ io.personium.core.model.file.AllTests.class, io.personium.core.model.impl.es.AllTests.class, io.personium.core.model.impl.es.accessor.AllTests.class, - io.personium.core.model.impl.es.ads.AllTests.class, io.personium.core.model.lock.AllTests.class, io.personium.core.rs.AllTests.class, io.personium.test.jersey.AllTests.class, diff --git a/src/test/java/io/personium/test/RegressionTests.java b/src/test/java/io/personium/test/RegressionTests.java index 0901d426d..fcfedf232 100644 --- a/src/test/java/io/personium/test/RegressionTests.java +++ b/src/test/java/io/personium/test/RegressionTests.java @@ -16,14 +16,13 @@ */ package io.personium.test; -import junit.framework.TestSuite; - import org.junit.experimental.categories.Categories; import org.junit.experimental.categories.Categories.IncludeCategory; import org.junit.runner.RunWith; import org.junit.runners.Suite.SuiteClasses; import io.personium.test.categories.Regression; +import junit.framework.TestSuite; /** * 結合テスト用テストスイート. @@ -34,7 +33,6 @@ io.personium.core.model.file.AllTests.class, io.personium.core.model.impl.es.AllTests.class, io.personium.core.model.impl.es.accessor.AllTests.class, - io.personium.core.model.impl.es.ads.AllTests.class, io.personium.core.model.lock.AllTests.class, io.personium.core.rs.AllTests.class, io.personium.test.jersey.AllTests.class, diff --git a/src/test/java/io/personium/test/UnitTests.java b/src/test/java/io/personium/test/UnitTests.java index 818b5c405..39524348e 100644 --- a/src/test/java/io/personium/test/UnitTests.java +++ b/src/test/java/io/personium/test/UnitTests.java @@ -16,14 +16,13 @@ */ package io.personium.test; -import junit.framework.TestSuite; - import org.junit.experimental.categories.Categories; import org.junit.experimental.categories.Categories.IncludeCategory; import org.junit.runner.RunWith; import org.junit.runners.Suite.SuiteClasses; import io.personium.test.categories.Integration; +import junit.framework.TestSuite; /** * 結合テスト用テストスイート. @@ -34,7 +33,6 @@ io.personium.core.model.file.AllTests.class, io.personium.core.model.impl.es.AllTests.class, io.personium.core.model.impl.es.accessor.AllTests.class, - io.personium.core.model.impl.es.ads.AllTests.class, io.personium.core.model.lock.AllTests.class, io.personium.core.odata.AllTests.class, io.personium.core.rs.odata.AllTests.class, diff --git a/src/test/java/io/personium/test/jersey/PersoniumIntegTestRunner.java b/src/test/java/io/personium/test/jersey/PersoniumIntegTestRunner.java index f6fba6e0b..cb046f3ac 100644 --- a/src/test/java/io/personium/test/jersey/PersoniumIntegTestRunner.java +++ b/src/test/java/io/personium/test/jersey/PersoniumIntegTestRunner.java @@ -31,6 +31,7 @@ import io.personium.common.auth.token.LocalToken; import io.personium.common.auth.token.TransCellAccessToken; import io.personium.core.PersoniumUnitConfig; +import io.personium.core.model.file.DataCryptor; /** * IT用テストランナークラス. @@ -59,6 +60,7 @@ public PersoniumIntegTestRunner(Class klass) TransCellAccessToken.configureX509(PersoniumUnitConfig.getX509PrivateKey(), PersoniumUnitConfig.getX509Certificate(), PersoniumUnitConfig.getX509RootCertificate()); LocalToken.setKeyString(PersoniumUnitConfig.getTokenSecretKey()); + DataCryptor.setKeyString(PersoniumUnitConfig.getTokenSecretKey()); } @Override diff --git a/src/test/java/io/personium/test/jersey/box/CollectionTest.java b/src/test/java/io/personium/test/jersey/box/CollectionTest.java index 078c8b456..8293da2cc 100644 --- a/src/test/java/io/personium/test/jersey/box/CollectionTest.java +++ b/src/test/java/io/personium/test/jersey/box/CollectionTest.java @@ -39,6 +39,8 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import com.sun.jersey.test.framework.JerseyTest; + import io.personium.core.PersoniumCoreException; import io.personium.core.model.Box; import io.personium.test.categories.Integration; @@ -59,7 +61,6 @@ import io.personium.test.utils.RoleUtils; import io.personium.test.utils.TResponse; import io.personium.test.utils.TestMethodUtils; -import com.sun.jersey.test.framework.JerseyTest; /** * MKCOLのテスト. @@ -1433,7 +1434,7 @@ private void depthTest(final NodeList nodeList, final String resorce, final Stri BoxUtils.create(Setup.TEST_CELL1, testBox, TOKEN); // Boxに紐付かないRoleの作成 - RoleUtils.create(Setup.TEST_CELL1, TOKEN, null, testRole, HttpStatus.SC_CREATED); + RoleUtils.create(Setup.TEST_CELL1, TOKEN, testRole, null, HttpStatus.SC_CREATED); // ACLの設定 Http.request("box/acl-setting-single-collection.txt") @@ -1447,7 +1448,7 @@ private void depthTest(final NodeList nodeList, final String resorce, final Stri .statusCode(HttpStatus.SC_BAD_REQUEST); } finally { // Roleの削除 - RoleUtils.delete(Setup.TEST_CELL1, TOKEN, null, testRole); + RoleUtils.delete(Setup.TEST_CELL1, TOKEN, testRole, null); // Box1の削除 BoxUtils.delete(Setup.TEST_CELL1, TOKEN, testBox); @@ -1520,7 +1521,7 @@ private void depthTest(final NodeList nodeList, final String resorce, final Stri try { // 前準備 // 名前に大文字を含むロール登録 - RoleUtils.create(testcell, token, path, role, HttpStatus.SC_CREATED); + RoleUtils.create(testcell, token, role, path, HttpStatus.SC_CREATED); // ACLの設定 DavResourceUtils.setACLwithBox(testcell, token, HttpStatus.SC_OK, @@ -1545,7 +1546,7 @@ private void depthTest(final NodeList nodeList, final String resorce, final Stri } finally { // Role削除 - RoleUtils.delete(testcell, token, path, role); + RoleUtils.delete(testcell, token, role, path); } } } finally { @@ -1572,11 +1573,11 @@ private void depthTest(final NodeList nodeList, final String resorce, final Stri accountReadAcl, accountReadAcl, HttpStatus.SC_CREATED); // ロール追加(Read) - RoleUtils.create(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, null, - "roleRead", HttpStatus.SC_CREATED); + RoleUtils.create(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, "roleRead", + null, HttpStatus.SC_CREATED); // ロール追加(Read-Acl) - RoleUtils.create(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, null, - "roleReadAcl", HttpStatus.SC_CREATED); + RoleUtils.create(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, "roleReadAcl", + null, HttpStatus.SC_CREATED); // ロール結びつけ(BOXに結びつかないロールとアカウント結びつけ) ResourceUtils.linkAccountRole(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, @@ -1621,8 +1622,8 @@ private void depthTest(final NodeList nodeList, final String resorce, final Stri ResourceUtils.linkAccountRollDelete(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, accountRead, null, "roleRead"); // Roleの削除 - RoleUtils.delete(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, null, "roleRead"); - RoleUtils.delete(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, null, "roleReadAcl"); + RoleUtils.delete(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, "roleRead", null); + RoleUtils.delete(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, "roleReadAcl", null); // Accountの削除 AccountUtils.delete(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, accountReadAcl, HttpStatus.SC_NO_CONTENT); diff --git a/src/test/java/io/personium/test/jersey/box/acl/AclTest.java b/src/test/java/io/personium/test/jersey/box/acl/AclTest.java index 1ef627063..96b3ec746 100644 --- a/src/test/java/io/personium/test/jersey/box/acl/AclTest.java +++ b/src/test/java/io/personium/test/jersey/box/acl/AclTest.java @@ -32,14 +32,17 @@ import org.w3c.dom.Element; import org.w3c.dom.NodeList; +import com.sun.jersey.test.framework.JerseyTest; +import com.sun.jersey.test.framework.WebAppDescriptor; + import io.personium.core.PersoniumCoreException; import io.personium.core.auth.OAuth2Helper; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; import io.personium.test.jersey.AbstractCase; -import io.personium.test.jersey.PersoniumIntegTestRunner; import io.personium.test.jersey.ODataCommon; +import io.personium.test.jersey.PersoniumIntegTestRunner; import io.personium.test.setup.Setup; import io.personium.test.unit.core.UrlUtils; import io.personium.test.utils.AccountUtils; @@ -52,8 +55,6 @@ import io.personium.test.utils.RoleUtils; import io.personium.test.utils.TResponse; import io.personium.test.utils.TestMethodUtils; -import com.sun.jersey.test.framework.JerseyTest; -import com.sun.jersey.test.framework.WebAppDescriptor; /** * BOXレベルACLのテスト. @@ -268,7 +269,7 @@ public AclTest() { BoxUtils.create(TEST_CELL1, testBox, TOKEN); // Boxに紐付くRoleの作成 - RoleUtils.create(TEST_CELL1, TOKEN, testBox, testRole, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, testRole, testBox, HttpStatus.SC_CREATED); // 上記Boxに上記RoleでACL設定 DavResourceUtils.setACLwithBox(TEST_CELL1, TOKEN, HttpStatus.SC_OK, testBox, "", @@ -295,7 +296,7 @@ public AclTest() { } finally { // Roleの削除 - RoleUtils.delete(TEST_CELL1, TOKEN, testBox, testRole); + RoleUtils.delete(TEST_CELL1, TOKEN, testRole, testBox); // Box1の削除 BoxUtils.delete(TEST_CELL1, TOKEN, testBox); @@ -314,9 +315,9 @@ public AclTest() { BoxUtils.create(TEST_CELL1, testBox, TOKEN); // Boxに紐付くRoleの作成 - RoleUtils.create(TEST_CELL1, TOKEN, testBox, testRole, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, testRole, testBox, HttpStatus.SC_CREATED); // Boxに紐づかないRoleの作成 - RoleUtils.create(TEST_CELL1, TOKEN, null, testRole, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, testRole, null, HttpStatus.SC_CREATED); // 上記BoxにBoxに紐付かないRoleでACL設定 DavResourceUtils.setACLwithBox(TEST_CELL1, TOKEN, HttpStatus.SC_OK, testBox, "", ACL_SETTING_TEST, @@ -343,9 +344,9 @@ public AclTest() { } finally { // Roleの削除(Boxに紐づく) - RoleUtils.delete(TEST_CELL1, TOKEN, testBox, testRole); + RoleUtils.delete(TEST_CELL1, TOKEN, testRole, testBox); // Roleの削除(Boxに紐づかない) - RoleUtils.delete(TEST_CELL1, TOKEN, null, testRole); + RoleUtils.delete(TEST_CELL1, TOKEN, testRole, null); // Boxの削除 BoxUtils.delete(TEST_CELL1, TOKEN, testBox); } @@ -380,7 +381,7 @@ public AclTest() { BoxUtils.create(TEST_CELL1, testBox2, TOKEN); // Roleの作成 - RoleUtils.create(TEST_CELL1, TOKEN, testBox2, testRole02, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, testRole02, testBox2, HttpStatus.SC_CREATED); // 上記Boxに上記RoleでACL設定 DavResourceUtils.setACLwithBox(TEST_CELL1, TOKEN, HttpStatus.SC_OK, testBox1, "", @@ -408,7 +409,7 @@ public AclTest() { } finally { // Roleの削除 - RoleUtils.delete(TEST_CELL1, TOKEN, testBox2, testRole02); + RoleUtils.delete(TEST_CELL1, TOKEN, testRole02, testBox2); // Box1の削除 BoxUtils.delete(TEST_CELL1, TOKEN, testBox1); @@ -428,7 +429,7 @@ public AclTest() { BoxUtils.create(TEST_CELL1, testBox1, TOKEN); // Roleの作成 - RoleUtils.create(TEST_CELL1, TOKEN, testBox1, testRole, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, testRole, testBox1, HttpStatus.SC_CREATED); // 上記Boxに上記RoleでACL設定 DavResourceUtils.setACLwithRoleBaseUrl(TEST_CELL1, TOKEN, HttpStatus.SC_OK, testBox1, "", @@ -457,7 +458,7 @@ public AclTest() { } finally { // Roleの削除 - RoleUtils.delete(TEST_CELL1, TOKEN, testBox1, testRole); + RoleUtils.delete(TEST_CELL1, TOKEN, testRole, testBox1); // Box1の削除 BoxUtils.delete(TEST_CELL1, TOKEN, testBox1); @@ -518,8 +519,8 @@ public AclTest() { String roleDelete = "role002"; try { // box2に紐付くロール作成 - RoleUtils.create(TEST_CELL1, TOKEN, box2, roleNotDelete, HttpStatus.SC_CREATED); - RoleUtils.create(TEST_CELL1, TOKEN, box2, roleDelete, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, roleNotDelete, box2, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, roleDelete, box2, HttpStatus.SC_CREATED); // ACLをtestcell1/box2に設定 DavResourceUtils.setACLwithBox(TEST_CELL1, AbstractCase.BEARER_MASTER_TOKEN, HttpStatus.SC_OK, box2, "", @@ -527,7 +528,7 @@ public AclTest() { "", ""); // roleを削除 - RoleUtils.delete(TEST_CELL1, TOKEN, box2, roleDelete, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(TEST_CELL1, TOKEN, roleDelete, box2, HttpStatus.SC_NO_CONTENT); // PROPFINDでtestcell1/box2のACLを取得 TResponse tresponse = DavResourceUtils.propfind("box/propfind-box-allprop.txt", TOKEN, @@ -542,8 +543,8 @@ public AclTest() { } finally { // ロールの削除 - RoleUtils.delete(TEST_CELL1, TOKEN, box2, roleNotDelete, -1); - RoleUtils.delete(TEST_CELL1, TOKEN, box2, roleDelete, -1); + RoleUtils.delete(TEST_CELL1, TOKEN, roleNotDelete, box2, -1); + RoleUtils.delete(TEST_CELL1, TOKEN, roleDelete, box2, -1); // ACLの設定を元に戻す Http.request("box/acl-authtest.txt") @@ -567,14 +568,14 @@ public AclTest() { String roleDelete = "role002"; try { // box2に紐付くロール作成 - RoleUtils.create(TEST_CELL1, TOKEN, null, roleDelete, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, roleDelete, null, HttpStatus.SC_CREATED); // ACLをtestcell1/box2に設定 DavResourceUtils.setACLwithBox(TEST_CELL1, TOKEN, HttpStatus.SC_OK, box2, "", ACL_SETTING_TEST, roleDelete, null, "", ""); // roleを削除 - RoleUtils.delete(TEST_CELL1, TOKEN, null, roleDelete, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(TEST_CELL1, TOKEN, roleDelete, null, HttpStatus.SC_NO_CONTENT); // PROPFINDでtestcell1/box2のACLを取得 TResponse tresponse = DavResourceUtils.propfind("box/propfind-box-allprop.txt", TOKEN, @@ -586,7 +587,7 @@ public AclTest() { } finally { // ロールの削除 - RoleUtils.delete(TEST_CELL1, TOKEN, null, roleDelete, -1); + RoleUtils.delete(TEST_CELL1, TOKEN, roleDelete, null, -1); // ACLの設定を元に戻す Http.request("box/acl-authtest.txt") @@ -625,7 +626,7 @@ public AclTest() { BoxUtils.create(TEST_CELL1, testBox, TOKEN); // Boxに紐付くRoleの作成 - RoleUtils.create(TEST_CELL1, TOKEN, testBox, testRole, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, testRole, testBox, HttpStatus.SC_CREATED); // 存在しないBoxを指定でACL設定 DavResourceUtils.setACLwithBox(TEST_CELL1, TOKEN, HttpStatus.SC_BAD_REQUEST, testBox, "", @@ -633,7 +634,7 @@ public AclTest() { } finally { // Roleの削除 - RoleUtils.delete(TEST_CELL1, TOKEN, testBox, testRole); + RoleUtils.delete(TEST_CELL1, TOKEN, testRole, testBox); // Box1の削除 BoxUtils.delete(TEST_CELL1, TOKEN, testBox); @@ -652,7 +653,7 @@ public AclTest() { BoxUtils.create(TEST_CELL1, testBox, TOKEN); // Boxに紐付くRoleの作成 - RoleUtils.create(TEST_CELL1, TOKEN, testBox, testRole, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, testRole, testBox, HttpStatus.SC_CREATED); // 存在しないCellをxml:baseに指定してACL設定 DavResourceUtils.setACLwithRoleBaseUrl(TEST_CELL1, TOKEN, HttpStatus.SC_BAD_REQUEST, testBox, "", @@ -661,7 +662,7 @@ public AclTest() { } finally { // Roleの削除 - RoleUtils.delete(TEST_CELL1, TOKEN, testBox, testRole); + RoleUtils.delete(TEST_CELL1, TOKEN, testRole, testBox); // Box1の削除 BoxUtils.delete(TEST_CELL1, TOKEN, testBox); @@ -687,7 +688,7 @@ public AclTest() { ACL_SETTING_TEST, testRole, testBox, "", ""); } finally { // Roleの削除 - RoleUtils.delete(TEST_CELL1, TOKEN, null, testRole); + RoleUtils.delete(TEST_CELL1, TOKEN, testRole, null); // Box1の削除 BoxUtils.delete(TEST_CELL1, TOKEN, testBox); @@ -742,7 +743,7 @@ public AclTest() { BoxUtils.create(cellName, boxName, AbstractCase.MASTER_TOKEN_NAME, -1); DavResourceUtils.createODataCollection(AbstractCase.MASTER_TOKEN_NAME, -1, cellName, boxName, colName); AccountUtils.create(AbstractCase.MASTER_TOKEN_NAME, cellName, account, "password", -1); - RoleUtils.create(cellName, AbstractCase.MASTER_TOKEN_NAME, boxName, role1, -1); + RoleUtils.create(cellName, AbstractCase.MASTER_TOKEN_NAME, role1, boxName, -1); AccountUtils.createLinkWithRole(AbstractCase.MASTER_TOKEN_NAME, cellName, boxName, account, role1, -1); // BoxにACL設定 @@ -769,10 +770,10 @@ public AclTest() { // ACL設定がされたRoleの削除 AccountUtils.deleteLinksWithRole(cellName, boxName, AbstractCase.MASTER_TOKEN_NAME, account, role1, -1); - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, boxName, role1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, role1, boxName); // アクセスするアカウントはRoleと結びついていないとaceのチェック前で権限エラーとなるため、ACL設定がされていないRoleの作成 - RoleUtils.create(cellName, AbstractCase.MASTER_TOKEN_NAME, boxName, role2, -1); + RoleUtils.create(cellName, AbstractCase.MASTER_TOKEN_NAME, role2, boxName, -1); AccountUtils.createLinkWithRole(AbstractCase.MASTER_TOKEN_NAME, cellName, boxName, account, role2, -1); // ここから実際のテスト diff --git a/src/test/java/io/personium/test/jersey/box/dav/file/DavFileEncryptTest.java b/src/test/java/io/personium/test/jersey/box/dav/file/DavFileEncryptTest.java new file mode 100644 index 000000000..8a9369a9e --- /dev/null +++ b/src/test/java/io/personium/test/jersey/box/dav/file/DavFileEncryptTest.java @@ -0,0 +1,56 @@ +/** + * 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 io.personium.test.jersey.box.dav.file; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; + +import io.personium.core.PersoniumUnitConfig; +import io.personium.test.categories.Integration; +import io.personium.test.categories.Regression; +import io.personium.test.jersey.PersoniumIntegTestRunner; + +/** + * Encrypt DAV File related tests. + */ +@RunWith(PersoniumIntegTestRunner.class) +@Category({Integration.class, Regression.class }) +public class DavFileEncryptTest extends DavFileTest { + + /** dav.encrypt.enabled in properties. */ + private static String encryptEnabled = ""; + + /** + * Befor class. + */ + @BeforeClass + public static void beforClass() { + encryptEnabled = PersoniumUnitConfig.get("io.personium.core.security.dav.encrypt.enabled"); + PersoniumUnitConfig.set("io.personium.core.security.dav.encrypt.enabled", "true"); + } + + /** + * After class. + */ + @AfterClass + public static void afterClass() { + PersoniumUnitConfig.set("io.personium.core.security.dav.encrypt.enabled", + encryptEnabled != null ? encryptEnabled : "false"); // CHECKSTYLE IGNORE + } +} diff --git a/src/test/java/io/personium/test/jersey/cell/AclTest.java b/src/test/java/io/personium/test/jersey/cell/AclTest.java index 1fab67ce0..b51a7010d 100644 --- a/src/test/java/io/personium/test/jersey/cell/AclTest.java +++ b/src/test/java/io/personium/test/jersey/cell/AclTest.java @@ -529,9 +529,9 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S BoxUtils.create(TEST_CELL1, testBox, TOKEN); // Boxに紐付くRoleの作成 - RoleUtils.create(TEST_CELL1, TOKEN, testBox, testRole, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, testRole, testBox, HttpStatus.SC_CREATED); // Boxに紐づかないRoleの作成 - RoleUtils.create(TEST_CELL1, TOKEN, null, testRole, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, testRole, null, HttpStatus.SC_CREATED); // ACLをtestcell1に設定 Http.request("cell/acl-setting-single.txt") @@ -583,9 +583,9 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S .returns() .statusCode(HttpStatus.SC_OK); // Roleの削除(Boxに紐づく) - RoleUtils.delete(TEST_CELL1, TOKEN, testBox, testRole); + RoleUtils.delete(TEST_CELL1, TOKEN, testRole, testBox); // Roleの削除(Boxに紐づかない) - RoleUtils.delete(TEST_CELL1, TOKEN, null, testRole); + RoleUtils.delete(TEST_CELL1, TOKEN, testRole, null); // Boxの削除 BoxUtils.delete(TEST_CELL1, TOKEN, testBox); } @@ -769,8 +769,8 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S String box2 = "box2"; try { // box2に紐付くロール作成 - RoleUtils.create(TEST_CELL1, TOKEN, box2, "role02", HttpStatus.SC_CREATED); - RoleUtils.create(TEST_CELL1, TOKEN, box2, "role03", HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, "role02", box2, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, "role03", box2, HttpStatus.SC_CREATED); // role2・role3を含むACLをtestcell1に設定 Http.request("cell/acl-setting-base.txt") @@ -813,8 +813,8 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S } finally { // ロールの削除 - RoleUtils.delete(TEST_CELL1, TOKEN, box2, "role02"); - RoleUtils.delete(TEST_CELL1, TOKEN, box2, "role03"); + RoleUtils.delete(TEST_CELL1, TOKEN, "role02", box2); + RoleUtils.delete(TEST_CELL1, TOKEN, "role03", box2); // ACLの設定を元に戻す Http.request("cell/acl-default.txt") @@ -841,8 +841,8 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S String roleDelete = "role002"; try { // box2に紐付くロール作成 - RoleUtils.create(TEST_CELL1, TOKEN, box2, roleNotDelete, HttpStatus.SC_CREATED); - RoleUtils.create(TEST_CELL1, TOKEN, box2, roleDelete, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, roleNotDelete, box2, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, TOKEN, roleDelete, box2, HttpStatus.SC_CREATED); // ACLをtestcell1に設定 Http.request("cell/acl-setting-base.txt") @@ -855,7 +855,7 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S .statusCode(HttpStatus.SC_OK); // roleを削除 - RoleUtils.delete(TEST_CELL1, TOKEN, box2, roleDelete, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(TEST_CELL1, TOKEN, roleDelete, box2, HttpStatus.SC_NO_CONTENT); // PROPFINDでtestcell1のACLを取得 TResponse tresponse = CellUtils.propfind(TEST_CELL1, TOKEN, "0", @@ -870,8 +870,8 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S } finally { // ロールの削除 - RoleUtils.delete(TEST_CELL1, TOKEN, box2, roleNotDelete, -1); - RoleUtils.delete(TEST_CELL1, TOKEN, box2, roleDelete, -1); + RoleUtils.delete(TEST_CELL1, TOKEN, roleNotDelete, box2, -1); + RoleUtils.delete(TEST_CELL1, TOKEN, roleDelete, box2, -1); // ACLの設定を元に戻す Http.request("cell/acl-default.txt") @@ -1175,7 +1175,7 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S // ACL設定がされたRoleの削除 AccountUtils.deleteLinksWithRole(cellName, null, AbstractCase.MASTER_TOKEN_NAME, account, role1, -1); - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, null, role1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, role1, null); // アクセスするアカウントはRoleと結びついていないとaceのチェック前で権限エラーとなるため、ACL設定がされていないRoleの作成 RoleUtils.create(cellName, AbstractCase.MASTER_TOKEN_NAME, role2, -1); @@ -1296,12 +1296,12 @@ private void roleAclTest(List account) { String testRoleName2 = "testRole2"; String testRoleName3 = "testRole3"; // Roleの作成 POST authが必要 - RoleUtils.create(TEST_CELL1, account.get(0), null, testRoleName, HttpStatus.SC_FORBIDDEN); - RoleUtils.create(TEST_CELL1, account.get(1), null, testRoleName, HttpStatus.SC_CREATED); - RoleUtils.create(TEST_CELL1, account.get(3), null, testRoleName, HttpStatus.SC_FORBIDDEN); - RoleUtils.create(TEST_CELL1, account.get(9), null, testRoleName2, HttpStatus.SC_CREATED); - RoleUtils.create(TEST_CELL1, account.get(10), null, testRoleName3, HttpStatus.SC_CREATED); - RoleUtils.create(TEST_CELL1, account.get(11), null, testRoleName, HttpStatus.SC_FORBIDDEN); + RoleUtils.create(TEST_CELL1, account.get(0), testRoleName, null, HttpStatus.SC_FORBIDDEN); + RoleUtils.create(TEST_CELL1, account.get(1), testRoleName, null, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, account.get(3), testRoleName, null, HttpStatus.SC_FORBIDDEN); + RoleUtils.create(TEST_CELL1, account.get(9), testRoleName2, null, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, account.get(10), testRoleName3, null, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, account.get(11), testRoleName, null, HttpStatus.SC_FORBIDDEN); // Roleの取得 GET auth-readが必要 RoleUtils.list(account.get(0), TEST_CELL1, HttpStatus.SC_FORBIDDEN); @@ -1326,12 +1326,12 @@ private void roleAclTest(List account) { HttpStatus.SC_FORBIDDEN); // Roleの削除 DELETE authが必要 - RoleUtils.delete(TEST_CELL1, account.get(0), null, testRoleName, HttpStatus.SC_FORBIDDEN); - RoleUtils.delete(TEST_CELL1, account.get(1), null, testRoleName, HttpStatus.SC_NO_CONTENT); - RoleUtils.delete(TEST_CELL1, account.get(3), null, testRoleName, HttpStatus.SC_FORBIDDEN); - RoleUtils.delete(TEST_CELL1, account.get(9), null, testRoleName2, HttpStatus.SC_NO_CONTENT); - RoleUtils.delete(TEST_CELL1, account.get(10), null, testRoleName3, HttpStatus.SC_NO_CONTENT); - RoleUtils.delete(TEST_CELL1, account.get(11), null, testRoleName, HttpStatus.SC_FORBIDDEN); + RoleUtils.delete(TEST_CELL1, account.get(0), testRoleName, null, HttpStatus.SC_FORBIDDEN); + RoleUtils.delete(TEST_CELL1, account.get(1), testRoleName, null, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(TEST_CELL1, account.get(3), testRoleName, null, HttpStatus.SC_FORBIDDEN); + RoleUtils.delete(TEST_CELL1, account.get(9), testRoleName2, null, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(TEST_CELL1, account.get(10), testRoleName3, null, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(TEST_CELL1, account.get(11), testRoleName, null, HttpStatus.SC_FORBIDDEN); } @@ -2021,14 +2021,14 @@ private void logListAclTest(List account) { // 作成した$linkの削除 ResourceUtils.linkAccountRollDelete(TEST_CELL1, TOKEN, "account11", null, roleName); // 作成したRole削除 - RoleUtils.delete(TEST_CELL1, TOKEN, null, roleName); + RoleUtils.delete(TEST_CELL1, TOKEN, roleName, null); CellUtils.createNp(post, TEST_CELL1, Account.EDM_TYPE_NAME, "account11", "_" + Role.EDM_TYPE_NAME, roleBody, account.get(10), HttpStatus.SC_CREATED); // 作成した$linkの削除 ResourceUtils.linkAccountRollDelete(TEST_CELL1, TOKEN, "account11", null, roleName); // 作成したRole削除 - RoleUtils.delete(TEST_CELL1, TOKEN, null, roleName); + RoleUtils.delete(TEST_CELL1, TOKEN, roleName, null); // Relationとroleの$link→SOCIALとAUTH権限が必要 // Relationの作成 @@ -2053,7 +2053,7 @@ private void logListAclTest(List account) { ResourceUtils.linksDelete(TEST_CELL1, Relation.EDM_TYPE_NAME, relationName, "null", Role.EDM_TYPE_NAME, "_Box.Name=null,Name='" + roleName + "'", TOKEN); // 作成したRole削除 - RoleUtils.delete(TEST_CELL1, TOKEN, null, roleName); + RoleUtils.delete(TEST_CELL1, TOKEN, roleName, null); CellUtils.createNp(post, TEST_CELL1, Relation.EDM_TYPE_NAME, relationName, "_" + Role.EDM_TYPE_NAME, @@ -2062,7 +2062,7 @@ private void logListAclTest(List account) { ResourceUtils.linksDelete(TEST_CELL1, Relation.EDM_TYPE_NAME, relationName, "null", Role.EDM_TYPE_NAME, "_Box.Name=null,Name='" + roleName + "'", TOKEN); // 作成したRole削除 - RoleUtils.delete(TEST_CELL1, TOKEN, null, roleName); + RoleUtils.delete(TEST_CELL1, TOKEN, roleName, null); // RelationとextCellの$link→SOCIAL権限が必要 JSONObject extCellBody = new JSONObject(); @@ -2109,7 +2109,7 @@ private void logListAclTest(List account) { ResourceUtils.linkExtCellRoleDelete(TEST_CELL1, TOKEN, PersoniumCoreUtils.encodeUrlComp(extCellUrl), null, roleName); // Role削除 - RoleUtils.delete(TEST_CELL1, TOKEN, null, roleName); + RoleUtils.delete(TEST_CELL1, TOKEN, roleName, null); CellUtils.createNp(post, TEST_CELL1, ExtCell.EDM_TYPE_NAME, PersoniumCoreUtils.encodeUrlComp(extCellUrl), "_" + Role.EDM_TYPE_NAME, @@ -2118,7 +2118,7 @@ private void logListAclTest(List account) { ResourceUtils.linkExtCellRoleDelete(TEST_CELL1, TOKEN, PersoniumCoreUtils.encodeUrlComp(extCellUrl), null, roleName); // Role削除 - RoleUtils.delete(TEST_CELL1, TOKEN, null, roleName); + RoleUtils.delete(TEST_CELL1, TOKEN, roleName, null); } finally { // 作成した$linkの削除 diff --git a/src/test/java/io/personium/test/jersey/cell/DeleteTest.java b/src/test/java/io/personium/test/jersey/cell/DeleteTest.java index 76acebb7c..d917a70e4 100644 --- a/src/test/java/io/personium/test/jersey/cell/DeleteTest.java +++ b/src/test/java/io/personium/test/jersey/cell/DeleteTest.java @@ -41,9 +41,9 @@ import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; import io.personium.test.jersey.AbstractCase; +import io.personium.test.jersey.ODataCommon; import io.personium.test.jersey.PersoniumResponse; import io.personium.test.jersey.PersoniumRestAdapter; -import io.personium.test.jersey.ODataCommon; import io.personium.test.setup.Setup; import io.personium.test.unit.core.UrlUtils; import io.personium.test.utils.AccountUtils; @@ -412,7 +412,7 @@ public final void afterCell() { try { // Role作成 - RoleUtils.create(this.cellInfo.cellName, MASTER_TOKEN_NAME, null, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(this.cellInfo.cellName, MASTER_TOKEN_NAME, roleName, null, HttpStatus.SC_CREATED); // Cellを削除 PersoniumRestAdapter rest = new PersoniumRestAdapter(); @@ -433,8 +433,8 @@ public final void afterCell() { assertEquals(MediaType.APPLICATION_JSON, res.getResponseHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue()); // Role削除 - RoleUtils.delete(this.cellInfo.cellName, MASTER_TOKEN_NAME, null, - roleName, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(this.cellInfo.cellName, MASTER_TOKEN_NAME, roleName, + null, HttpStatus.SC_NO_CONTENT); // Cellを削除(Role削除済のため、削除可能) CellUtils.delete(MASTER_TOKEN_NAME, this.cellInfo.cellId, HttpStatus.SC_NO_CONTENT); @@ -443,8 +443,8 @@ public final void afterCell() { // Cell作成 CellUtils.create(this.cellInfo.cellName, MASTER_TOKEN_NAME, -1); // Role削除 - RoleUtils.delete(this.cellInfo.cellName, MASTER_TOKEN_NAME, null, - roleName, -1); + RoleUtils.delete(this.cellInfo.cellName, MASTER_TOKEN_NAME, roleName, + null, -1); } } diff --git a/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java b/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java index aefe2eb3c..07faf0840 100644 --- a/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java +++ b/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java @@ -16,6 +16,16 @@ */ package io.personium.test.jersey.cell; +import static io.personium.core.model.ctl.ReceivedMessage.STATUS_APPROVED; +import static io.personium.core.model.ctl.ReceivedMessage.STATUS_NONE; +import static io.personium.core.model.ctl.ReceivedMessage.STATUS_READ; +import static io.personium.core.model.ctl.ReceivedMessage.STATUS_REJECTED; +import static io.personium.core.model.ctl.ReceivedMessage.STATUS_UNREAD; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_MESSAGE; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_REQ_RELATION_BREAK; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_REQ_RELATION_BUILD; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_REQ_ROLE_GRANT; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_REQ_ROLE_REVOKE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -30,13 +40,13 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; -import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.model.ctl.Common; import io.personium.core.model.ctl.ExtCell; import io.personium.core.model.ctl.Relation; +import io.personium.core.model.ctl.Role; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; @@ -53,6 +63,7 @@ import io.personium.test.utils.ReceivedMessageUtils; import io.personium.test.utils.RelationUtils; import io.personium.test.utils.ResourceUtils; +import io.personium.test.utils.RoleUtils; import io.personium.test.utils.TResponse; /** @@ -79,11 +90,11 @@ public MessageApproveTest() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); - body.put("Status", "unread"); + body.put("Status", STATUS_UNREAD); String locationHeader = null; @@ -107,17 +118,17 @@ public MessageApproveTest() { requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"read\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_READ + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // 更新結果を取得 - checkMessageStatus(messageId, "read"); + checkMessageStatus(messageId, STATUS_READ); // もう一度未読みする - res = rest.post(requestUrl, "{\"Command\":\"unread\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_UNREAD + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // 更新結果を取得 - checkMessageStatus(messageId, "unread"); + checkMessageStatus(messageId, STATUS_UNREAD); } catch (PersoniumException e) { e.printStackTrace(); @@ -147,7 +158,7 @@ public MessageApproveTest() { requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); String requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"read\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_READ + "\" }", requestheaders); assertEquals(HttpStatus.SC_NOT_FOUND, res.getStatusCode()); checkErrorResponse(res.bodyAsJson(), PersoniumCoreException.OData.NO_SUCH_ENTITY.getCode()); @@ -166,11 +177,11 @@ public MessageApproveTest() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); - body.put("Status", "unread"); + body.put("Status", STATUS_UNREAD); String locationHeader = null; @@ -232,11 +243,11 @@ public MessageApproveTest() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); - body.put("Status", "unread"); + body.put("Status", STATUS_UNREAD); String locationHeader = null; @@ -261,14 +272,14 @@ public MessageApproveTest() { // approvedでメッセージ承認 requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode()); checkErrorResponse(res.bodyAsJson(), PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.getCode()); // rejectedでメッセージ承認 requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"rejected\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_REJECTED + "\" }", requestheaders); assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode()); checkErrorResponse(res.bodyAsJson(), PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.getCode()); @@ -297,12 +308,12 @@ public MessageApproveTest() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", relationName); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -329,7 +340,7 @@ public MessageApproveTest() { HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); @@ -346,7 +357,7 @@ public MessageApproveTest() { checkRelationExtCellLinks(relationName, expectedUriList); // Statusが変更されていることを確認 - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { e.printStackTrace(); @@ -377,12 +388,12 @@ public MessageApproveTest() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", relationName); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -404,7 +415,7 @@ public MessageApproveTest() { HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); @@ -421,7 +432,7 @@ public MessageApproveTest() { checkRelationExtCellLinks(relationName, expectedUriList); // Statusが変更されていることを確認 - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { e.printStackTrace(); @@ -459,12 +470,12 @@ public final void normal_approve_build_message_with_relationClassURL_for_allread JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -492,7 +503,7 @@ public final void normal_approve_build_message_with_relationClassURL_for_allread HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); // --------------- // Verification @@ -507,7 +518,7 @@ public final void normal_approve_build_message_with_relationClassURL_for_allread expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); checkRelationExtCellLinks(relationName, boxName, expectedUriList); // Check status changed - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -540,12 +551,12 @@ public final void normal_approve_build_message_with_relationClassURL_for_not_exi JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -568,7 +579,7 @@ public final void normal_approve_build_message_with_relationClassURL_for_not_exi HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); // --------------- // Verification @@ -583,7 +594,7 @@ public final void normal_approve_build_message_with_relationClassURL_for_not_exi expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); checkRelationExtCellLinks(relationName, boxName, expectedUriList); // Check status changed - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -616,12 +627,12 @@ public final void normal_approve_break_message_with_relationClassURL() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -643,11 +654,11 @@ public final void normal_approve_break_message_with_relationClassURL() { HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // BreakReceivedMessage - body.put("Type", "req.relation.break"); + body.put("Type", TYPE_REQ_RELATION_BREAK); body.put("__id", "12345678901234567890123456789013"); requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); breakResponse = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, @@ -662,7 +673,7 @@ public final void normal_approve_break_message_with_relationClassURL() { requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); // --------------- // Verification @@ -677,7 +688,7 @@ public final void normal_approve_break_message_with_relationClassURL() { JSONArray results = (JSONArray) ((JSONObject) linkResponse.bodyAsJson().get("d")).get("results"); assertEquals(0, results.size()); // Check status changed - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -713,12 +724,12 @@ public final void normal_reject_build_message_with_relationClassURL() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -742,7 +753,7 @@ public final void normal_reject_build_message_with_relationClassURL() { HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"rejected\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_REJECTED + "\" }", requestheaders); // --------------- // Verification @@ -751,7 +762,7 @@ public final void normal_reject_build_message_with_relationClassURL() { // Check relation not exists RelationUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, HttpStatus.SC_NOT_FOUND); // Check status changed - checkMessageStatus(messageId, "rejected"); + checkMessageStatus(messageId, STATUS_REJECTED); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -783,12 +794,12 @@ public final void normal_approve_build_message_with_unit_local_relationClassURL( JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.unitLocalRelationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -816,7 +827,7 @@ public final void normal_approve_build_message_with_unit_local_relationClassURL( HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); // --------------- // Verification @@ -831,7 +842,7 @@ public final void normal_approve_build_message_with_unit_local_relationClassURL( expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); checkRelationExtCellLinks(relationName, boxName, expectedUriList); // Check status changed - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -869,13 +880,13 @@ public final void normal_approve_boxbound_build_message_for_allready_exist_relat JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1)); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", relationName); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -903,7 +914,7 @@ public final void normal_approve_boxbound_build_message_for_allready_exist_relat HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); // --------------- // Verification @@ -918,7 +929,7 @@ public final void normal_approve_boxbound_build_message_for_allready_exist_relat expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); checkRelationExtCellLinks(relationName, boxName, expectedUriList); // Check status changed - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -951,13 +962,13 @@ public final void normal_approve_boxbound_build_message_for_not_exist_relation() JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1)); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", relationName); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -980,7 +991,7 @@ public final void normal_approve_boxbound_build_message_for_not_exist_relation() HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); // --------------- // Verification @@ -995,7 +1006,7 @@ public final void normal_approve_boxbound_build_message_for_not_exist_relation() expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); checkRelationExtCellLinks(relationName, boxName, expectedUriList); // Check status changed - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -1028,13 +1039,13 @@ public final void normal_approve_boxbound_break_message() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1)); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", relationName); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1056,11 +1067,11 @@ public final void normal_approve_boxbound_break_message() { HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // BreakReceivedMessage - body.put("Type", "req.relation.break"); + body.put("Type", TYPE_REQ_RELATION_BREAK); body.put("__id", "12345678901234567890123456789013"); requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); breakResponse = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, @@ -1075,7 +1086,7 @@ public final void normal_approve_boxbound_break_message() { requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); // --------------- // Verification @@ -1090,7 +1101,7 @@ public final void normal_approve_boxbound_break_message() { JSONArray results = (JSONArray) ((JSONObject) linkResponse.bodyAsJson().get("d")).get("results"); assertEquals(0, results.size()); // Check status changed - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -1126,13 +1137,13 @@ public final void normal_reject_boxbound_build_message() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1)); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", relationName); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1156,7 +1167,7 @@ public final void normal_reject_boxbound_build_message() { HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"rejected\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_REJECTED + "\" }", requestheaders); // --------------- // Verification @@ -1165,7 +1176,7 @@ public final void normal_reject_boxbound_build_message() { // Check relation not exists RelationUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, HttpStatus.SC_NOT_FOUND); // Check status changed - checkMessageStatus(messageId, "rejected"); + checkMessageStatus(messageId, STATUS_REJECTED); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -1197,13 +1208,13 @@ public final void normal_approve_boxbound_build_message_with_relationClassURL() JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA2)); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1234,7 +1245,7 @@ public final void normal_approve_boxbound_build_message_with_relationClassURL() HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); // --------------- // Verification @@ -1249,7 +1260,7 @@ public final void normal_approve_boxbound_build_message_with_relationClassURL() expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); checkRelationExtCellLinks(relationName, boxName, expectedUriList); // Check status changed - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -1284,13 +1295,13 @@ public final void normal_approve_boxbound_break_message_with_relationClassURL() JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA2)); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1316,11 +1327,11 @@ public final void normal_approve_boxbound_break_message_with_relationClassURL() HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // BreakReceivedMessage - body.put("Type", "req.relation.break"); + body.put("Type", TYPE_REQ_RELATION_BREAK); body.put("__id", "12345678901234567890123456789013"); requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); breakResponse = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, @@ -1335,7 +1346,7 @@ public final void normal_approve_boxbound_break_message_with_relationClassURL() requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); // --------------- // Verification @@ -1350,7 +1361,7 @@ public final void normal_approve_boxbound_break_message_with_relationClassURL() JSONArray results = (JSONArray) ((JSONObject) linkResponse.bodyAsJson().get("d")).get("results"); assertEquals(0, results.size()); // Check status changed - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -1374,6 +1385,940 @@ public final void normal_approve_boxbound_break_message_with_relationClassURL() } } + /** + * Normal test. + * Approve grant message with RoleClassURL for already existing role. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_approve_grant_message_with_roleClassURL_for_allready_exist_role() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX1; + + // Request body of relation + JSONObject roleBody = new JSONObject(); + roleBody.put(Role.P_NAME.getName(), roleName); + roleBody.put(Common.P_BOX_NAME.getName(), boxName); + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", UrlUtils.roleClassUrl(Setup.TEST_CELL_SCHEMA1, roleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // Role + RoleUtils.create(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleBody, HttpStatus.SC_CREATED); + // ExtCell + ExtCellUtils.create(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), + HttpStatus.SC_CREATED); + // ReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + response = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute approved message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + // Check role exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_OK); + // Check extcell exists + ExtCellUtils.get(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), HttpStatus.SC_OK); + // Check $links exists + ArrayList expectedUriList = new ArrayList(); + expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); + checkRoleExtCellLinks(roleName, boxName, expectedUriList); + // Check status changed + checkMessageStatus(messageId, STATUS_APPROVED); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete Role-ExtCell $links + ResourceUtils.linksDelete(Setup.TEST_CELL1, Role.EDM_TYPE_NAME, roleName, boxName, + ExtCell.EDM_TYPE_NAME, + "'" + PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")) + "'", MASTER_TOKEN_NAME); + // Delete Role + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + // Delete ExtCell + ExtCellUtils.delete(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell")); + } + } + + /** + * Normal test. + * Approve grant message with RoleClassURL for not existing role. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_approve_grant_message_with_roleClassURL_for_not_exist_role() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX1; + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", UrlUtils.roleClassUrl(Setup.TEST_CELL_SCHEMA1, roleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // ReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + response = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute approved message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + // Check relation exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_OK); + // Check extcell exists + ExtCellUtils.get(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), HttpStatus.SC_OK); + // Check $links exists + ArrayList expectedUriList = new ArrayList(); + expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); + checkRoleExtCellLinks(roleName, boxName, expectedUriList); + // Check status changed + checkMessageStatus(messageId, STATUS_APPROVED); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete Role-ExtCell $links + ResourceUtils.linksDelete(Setup.TEST_CELL1, Role.EDM_TYPE_NAME, roleName, boxName, + ExtCell.EDM_TYPE_NAME, + "'" + PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")) + "'", MASTER_TOKEN_NAME); + // Delete Role + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + // Delete ExtCell + ExtCellUtils.delete(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell")); + } + } + + /** + * Normal test. + * Approve revoke message with RoleClassURL. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_approve_revoke_message_with_roleClassURL() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX1; + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", UrlUtils.roleClassUrl(Setup.TEST_CELL_SCHEMA1, roleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse buildResponse = null; + TResponse breakResponse = null; + + try { + // --------------- + // Preparation + // --------------- + // BuildReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + buildResponse = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // Approved message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + + // BreakReceivedMessage + body.put("Type", TYPE_REQ_ROLE_REVOKE); + body.put("__id", "12345678901234567890123456789013"); + requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + breakResponse = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute approved message + rest = new PersoniumRestAdapter(); + requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + // Check relation exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_OK); + // Check extcell exists + ExtCellUtils.get(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), HttpStatus.SC_OK); + // Check $links not exists + TResponse linkResponse = getRoleExtCellLinks(roleName, boxName); + JSONArray results = (JSONArray) ((JSONObject) linkResponse.bodyAsJson().get("d")).get("results"); + assertEquals(0, results.size()); + // Check status changed + checkMessageStatus(messageId, STATUS_APPROVED); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (buildResponse != null) { + deleteOdataResource(buildResponse.getLocationHeader()); + } + if (breakResponse != null) { + deleteOdataResource(breakResponse.getLocationHeader()); + } + // Delete Role-ExtCell $links + ResourceUtils.linksDelete(Setup.TEST_CELL1, Role.EDM_TYPE_NAME, roleName, boxName, + ExtCell.EDM_TYPE_NAME, + "'" + PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")) + "'", MASTER_TOKEN_NAME); + // Delete Role + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + // Delete ExtCell + ExtCellUtils.delete(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell")); + } + } + + /** + * Normal test. + * Reject grant message with RoleClassURL. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_reject_grant_message_with_roleClassURL() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX1; + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", UrlUtils.roleClassUrl(Setup.TEST_CELL_SCHEMA1, roleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse response = null; + + try { + // --------------- + // Preparation + // --------------- + // ReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + response = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute rejected message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_REJECTED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + // Check relation not exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_NOT_FOUND); + // Check status changed + checkMessageStatus(messageId, STATUS_REJECTED); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete Relation + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + } + } + + /** + * Normal test. + * Approve grant message with unit local RoleClassURL. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_approve_grant_message_with_unit_local_roleClassURL() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX1; + + // Request body of role + JSONObject roleBody = new JSONObject(); + roleBody.put(Role.P_NAME.getName(), roleName); + roleBody.put(Common.P_BOX_NAME.getName(), boxName); + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", UrlUtils.unitLocalRoleClassUrl(Setup.TEST_CELL_SCHEMA1, roleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // Role + RoleUtils.create(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleBody, HttpStatus.SC_CREATED); + // ExtCell + ExtCellUtils.create(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), + HttpStatus.SC_CREATED); + // ReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + response = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute approved message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + // Check relation exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_OK); + // Check extcell exists + ExtCellUtils.get(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), HttpStatus.SC_OK); + // Check $links exists + ArrayList expectedUriList = new ArrayList(); + expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); + checkRoleExtCellLinks(roleName, boxName, expectedUriList); + // Check status changed + checkMessageStatus(messageId, STATUS_APPROVED); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete Role-ExtCell $links + ResourceUtils.linksDelete(Setup.TEST_CELL1, Role.EDM_TYPE_NAME, roleName, boxName, + ExtCell.EDM_TYPE_NAME, + "'" + PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")) + "'", MASTER_TOKEN_NAME); + // Delete Role + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + // Delete ExtCell + ExtCellUtils.delete(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell")); + } + } + + /** + * Normal test. + * Approve boxbound grant message for already existing role. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_approve_boxbound_grant_message_for_allready_exist_role() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX1; + + // Request body of role + JSONObject roleBody = new JSONObject(); + roleBody.put(Role.P_NAME.getName(), roleName); + roleBody.put(Common.P_BOX_NAME.getName(), boxName); + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1)); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", roleName); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // Role + RoleUtils.create(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleBody, HttpStatus.SC_CREATED); + // ExtCell + ExtCellUtils.create(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), + HttpStatus.SC_CREATED); + // ReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + response = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute approved message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + // Check role exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_OK); + // Check extcell exists + ExtCellUtils.get(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), HttpStatus.SC_OK); + // Check $links exists + ArrayList expectedUriList = new ArrayList(); + expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); + checkRoleExtCellLinks(roleName, boxName, expectedUriList); + // Check status changed + checkMessageStatus(messageId, STATUS_APPROVED); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete Role-ExtCell $links + ResourceUtils.linksDelete(Setup.TEST_CELL1, Role.EDM_TYPE_NAME, roleName, boxName, + ExtCell.EDM_TYPE_NAME, + "'" + PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")) + "'", MASTER_TOKEN_NAME); + // Delete Role + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + // Delete ExtCell + ExtCellUtils.delete(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell")); + } + } + + /** + * Normal test. + * Approve boxbound grant message for not existing role. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_approve_boxbound_grant_message_for_not_exist_role() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX1; + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1)); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", roleName); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // ReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + response = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute approved message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + // Check role exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_OK); + // Check extcell exists + ExtCellUtils.get(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), HttpStatus.SC_OK); + // Check $links exists + ArrayList expectedUriList = new ArrayList(); + expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); + checkRoleExtCellLinks(roleName, boxName, expectedUriList); + // Check status changed + checkMessageStatus(messageId, STATUS_APPROVED); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete Role-ExtCell $links + ResourceUtils.linksDelete(Setup.TEST_CELL1, Role.EDM_TYPE_NAME, roleName, boxName, + ExtCell.EDM_TYPE_NAME, + "'" + PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")) + "'", MASTER_TOKEN_NAME); + // Delete Role + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + // Delete ExtCell + ExtCellUtils.delete(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell")); + } + } + + /** + * Normal test. + * Approve boxbound revoke message. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_approve_boxbound_revoke_message() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX1; + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1)); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", roleName); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse buildResponse = null; + TResponse breakResponse = null; + + try { + // --------------- + // Preparation + // --------------- + // BuildReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + buildResponse = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // Approved message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + + // BreakReceivedMessage + body.put("Type", TYPE_REQ_ROLE_REVOKE); + body.put("__id", "12345678901234567890123456789013"); + requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + breakResponse = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute approved message + rest = new PersoniumRestAdapter(); + requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + // Check role exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_OK); + // Check extcell exists + ExtCellUtils.get(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), HttpStatus.SC_OK); + // Check $links not exists + TResponse linkResponse = getRoleExtCellLinks(roleName, boxName); + JSONArray results = (JSONArray) ((JSONObject) linkResponse.bodyAsJson().get("d")).get("results"); + assertEquals(0, results.size()); + // Check status changed + checkMessageStatus(messageId, STATUS_APPROVED); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (buildResponse != null) { + deleteOdataResource(buildResponse.getLocationHeader()); + } + if (breakResponse != null) { + deleteOdataResource(breakResponse.getLocationHeader()); + } + // Delete Role-ExtCell $links + ResourceUtils.linksDelete(Setup.TEST_CELL1, Role.EDM_TYPE_NAME, roleName, boxName, + ExtCell.EDM_TYPE_NAME, + "'" + PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")) + "'", MASTER_TOKEN_NAME); + // Delete Role + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + // Delete ExtCell + ExtCellUtils.delete(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell")); + } + } + + /** + * Normal test. + * Reject boxbound grant message. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_reject_boxbound_grant_message() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX1; + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1)); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", roleName); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse response = null; + + try { + // --------------- + // Preparation + // --------------- + // ReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + response = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute rejected message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_REJECTED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + // Check role not exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_NOT_FOUND); + // Check status changed + checkMessageStatus(messageId, STATUS_REJECTED); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete Role + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + } + } + + /** + * Normal test. + * Approve grant boxbound message with RoleClassURL. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_approve_boxbound_grant_message_with_roleClassURL() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX1; + + // Request body of relation + JSONObject roleBody = new JSONObject(); + roleBody.put(Role.P_NAME.getName(), roleName); + roleBody.put(Common.P_BOX_NAME.getName(), boxName); + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA2)); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", UrlUtils.roleClassUrl(Setup.TEST_CELL_SCHEMA1, roleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // Box + BoxUtils.createWithSchema(Setup.TEST_CELL1, "testBox002", MASTER_TOKEN_NAME, + UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA2)); + // Role + RoleUtils.create(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleBody, HttpStatus.SC_CREATED); + // ExtCell + ExtCellUtils.create(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), + HttpStatus.SC_CREATED); + // ReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + response = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute approved message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + // Check role exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_OK); + // Check extcell exists + ExtCellUtils.get(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), HttpStatus.SC_OK); + // Check $links exists + ArrayList expectedUriList = new ArrayList(); + expectedUriList.add(UrlUtils.extCellResource(Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"))); + checkRoleExtCellLinks(roleName, boxName, expectedUriList); + // Check status changed + checkMessageStatus(messageId, STATUS_APPROVED); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete Box + BoxUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, "testBox002", -1); + // Delete Role-ExtCell $links + ResourceUtils.linksDelete(Setup.TEST_CELL1, Role.EDM_TYPE_NAME, roleName, boxName, + ExtCell.EDM_TYPE_NAME, + "'" + PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")) + "'", MASTER_TOKEN_NAME); + // Delete Role + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + // Delete ExtCell + ExtCellUtils.delete(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell")); + } + } + + /** + * Normal test. + * Approve boxbound revoke message with RoleClassURL. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_approve_boxbound_revoke_message_with_roleClassURL() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX1; + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Schema", UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA2)); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", UrlUtils.roleClassUrl(Setup.TEST_CELL_SCHEMA1, roleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse buildResponse = null; + TResponse breakResponse = null; + + try { + // --------------- + // Preparation + // --------------- + // Box + BoxUtils.createWithSchema(Setup.TEST_CELL1, "testBox002", MASTER_TOKEN_NAME, + UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA2)); + + // BuildReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + buildResponse = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // Approved message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + + // BreakReceivedMessage + body.put("Type", TYPE_REQ_ROLE_REVOKE); + body.put("__id", "12345678901234567890123456789013"); + requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + breakResponse = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute approved message + rest = new PersoniumRestAdapter(); + requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); + // Check role exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_OK); + // Check extcell exists + ExtCellUtils.get(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), HttpStatus.SC_OK); + // Check $links not exists + TResponse linkResponse = getRoleExtCellLinks(roleName, boxName); + JSONArray results = (JSONArray) ((JSONObject) linkResponse.bodyAsJson().get("d")).get("results"); + assertEquals(0, results.size()); + // Check status changed + checkMessageStatus(messageId, STATUS_APPROVED); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (buildResponse != null) { + deleteOdataResource(buildResponse.getLocationHeader()); + } + if (breakResponse != null) { + deleteOdataResource(breakResponse.getLocationHeader()); + } + // Delete Box + BoxUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, "testBox002", -1); + // Delete Role-ExtCell $links + ResourceUtils.linksDelete(Setup.TEST_CELL1, Role.EDM_TYPE_NAME, roleName, boxName, + ExtCell.EDM_TYPE_NAME, + "'" + PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")) + "'", MASTER_TOKEN_NAME); + // Delete Role + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + // Delete ExtCell + ExtCellUtils.delete(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell")); + } + } + /** * Error test. * Approve build message with RelationClassURL. @@ -1389,12 +2334,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA2, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1417,7 +2362,7 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); // --------------- // Verification @@ -1432,7 +2377,7 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel ExtCellUtils.get(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell"), HttpStatus.SC_NOT_FOUND); // Check status - checkMessageStatus(messageId, "none"); + checkMessageStatus(messageId, STATUS_NONE); } catch (PersoniumException e) { fail(e.getStackTrace().toString()); } finally { @@ -1451,6 +2396,83 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel } } + /** + * Error test. + * Approve grant message with RoleClassURL. + * Box corresponding to the RoleClassURL can not be found. + */ + @SuppressWarnings("unchecked") + @Test + public final void error_approve_grant_message_not_found_box_corresponding_to_RoleClassURL() { + String roleName = "messageTestRole"; + String boxName = Setup.TEST_BOX2; + + // Request body of message + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); + body.put("Type", TYPE_REQ_ROLE_GRANT); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", STATUS_NONE); + body.put("RequestRelation", UrlUtils.roleClassUrl(Setup.TEST_CELL_SCHEMA2, roleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // ReceivedMessage + String requestUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); + response = ReceivedMessageUtils.receive(getCellIssueToken(requestUrl), Setup.TEST_CELL1, + body.toJSONString(), HttpStatus.SC_CREATED); + String messageId = (String) body.get("__id"); + + // --------------- + // Execution + // --------------- + // execute approved message + PersoniumRestAdapter rest = new PersoniumRestAdapter(); + HashMap requestheaders = new HashMap(); + requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); + requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); + + // --------------- + // Verification + // --------------- + PersoniumCoreException exception = PersoniumCoreException.ReceivedMessage + .BOX_THAT_MATCHES_RELATION_CLASS_URL_NOT_EXISTS.params(body.get("RequestRelation")); + assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode()); + checkErrorResponse(res.bodyAsJson(), exception.getCode(), exception.getMessage()); + // Check role not exists + RoleUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_NOT_FOUND); + // Check extcell not exists + ExtCellUtils.get(MASTER_TOKEN_NAME, Setup.TEST_CELL1, + UrlUtils.cellRoot("targetCell"), HttpStatus.SC_NOT_FOUND); + // Check status + checkMessageStatus(messageId, STATUS_NONE); + } catch (PersoniumException e) { + fail(e.getStackTrace().toString()); + } finally { + // Delete Received message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete Role-ExtCell $links + ResourceUtils.linksDelete(Setup.TEST_CELL1, Role.EDM_TYPE_NAME, roleName, boxName, + ExtCell.EDM_TYPE_NAME, + "'" + PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")) + "'", MASTER_TOKEN_NAME); + // Delete Role + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); + // Delete ExtCell + ExtCellUtils.delete(MASTER_TOKEN_NAME, Setup.TEST_CELL1, UrlUtils.cellRoot("targetCell")); + } + } + /** * 関係登録で関係登録済みのRelationを指定した場合400エラーとなること. */ @@ -1467,12 +2489,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", relationName); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1504,7 +2526,7 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode()); checkErrorResponse(res.bodyAsJson(), @@ -1539,12 +2561,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1565,7 +2587,7 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"rejected\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_REJECTED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); @@ -1573,7 +2595,7 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel RelationUtils.get(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, null, HttpStatus.SC_NOT_FOUND); // Statusが変更されていることを確認 - checkMessageStatus(messageId, "rejected"); + checkMessageStatus(messageId, STATUS_REJECTED); } catch (PersoniumException e) { e.printStackTrace(); @@ -1599,12 +2621,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1670,12 +2692,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1698,14 +2720,14 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel // 空文字でメッセージ承認 requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"read\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_READ + "\" }", requestheaders); assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode()); checkErrorResponse(res.bodyAsJson(), PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.getCode()); // 不正な文字列でメッセージ承認 requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"unread\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_UNREAD + "\" }", requestheaders); assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode()); checkErrorResponse(res.bodyAsJson(), PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.getCode()); @@ -1734,12 +2756,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", relationName); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1760,13 +2782,13 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // 再度メッセージ承認する requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode()); checkErrorResponse(res.bodyAsJson(), PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.getCode()); @@ -1800,12 +2822,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1826,13 +2848,13 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"rejected\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_REJECTED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // 再度メッセージ拒否する requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"rejected\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_REJECTED + "\" }", requestheaders); assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode()); checkErrorResponse(res.bodyAsJson(), PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.getCode()); @@ -1868,14 +2890,14 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel // approved String requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"approved\" }", + PersoniumResponse res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NOT_FOUND, res.getStatusCode()); checkErrorResponse(res.bodyAsJson(), PersoniumCoreException.OData.NO_SUCH_ENTITY.getCode()); // rejected requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"rejected\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_REJECTED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NOT_FOUND, res.getStatusCode()); checkErrorResponse(res.bodyAsJson(), PersoniumCoreException.OData.NO_SUCH_ENTITY.getCode()); @@ -1885,63 +2907,6 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel } } - /** - * 関係登録で不正なRelationTarget名を指定した場合409エラーとなること. - */ - @SuppressWarnings("unchecked") - @Test - public final void 関係登録で不正なRelationTarget名を指定した場合409エラーとなること() { - String relationName = "messageTestRelation"; - - // 受信メッセージのリクエストボディ - JSONObject body = new JSONObject(); - body.put("__id", "12345678901234567890123456789012"); - body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); - body.put("Title", "Title"); - body.put("Body", "Body"); - body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); - body.put("Priority", 3); - body.put("Status", "none"); - body.put("RequestRelation", relationName); - body.put("RequestRelationTarget", UrlUtils.cellRoot("('targetCell')")); - - String locationHeader = null; - - try { - // メッセージ受信を登録 - String requestUrl = UrlUtils.receivedMessage(Setup.TEST_CELL1); - PersoniumResponse res = createReceivedMessage(requestUrl, body); - locationHeader = res.getFirstHeader(HttpHeaders.LOCATION); - - String messageId = getMessageId(res); - - // メッセージ承認にする - PersoniumRestAdapter rest = new PersoniumRestAdapter(); - - // リクエストヘッダをセット - HashMap requestheaders = new HashMap(); - requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); - - requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", - requestheaders); - assertEquals(HttpStatus.SC_CONFLICT, res.getStatusCode()); - checkErrorResponse(res.bodyAsJson(), - PersoniumCoreException.ReceivedMessage.REQUEST_RELATION_TARGET_PARSE_ERROR.getCode()); - - } catch (PersoniumException e) { - e.printStackTrace(); - } finally { - // Relation削除 - RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, null, -1); - // 受信メッセージ削除 - if (locationHeader != null) { - deleteOdataResource(locationHeader); - } - } - } - /** * 関係削除のメッセージを承認できること. */ @@ -1954,12 +2919,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.build"); + body.put("Type", TYPE_REQ_RELATION_BUILD); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", relationName); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -1982,12 +2947,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // 関係削除用リクエストボディに変更する - body.put("Type", "req.relation.break"); + body.put("Type", TYPE_REQ_RELATION_BREAK); body.put("__id", "12345678901234567890123456789013"); // 関係削除メッセージ受信 @@ -2003,7 +2968,7 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // Relationが存在することの確認 @@ -2019,7 +2984,7 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel assertEquals(0, results.size()); // Statusが変更されていることを確認 - checkMessageStatus(messageId, "approved"); + checkMessageStatus(messageId, STATUS_APPROVED); } catch (PersoniumException e) { e.printStackTrace(); @@ -2053,12 +3018,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.break"); + body.put("Type", TYPE_REQ_RELATION_BREAK); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", relationName); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -2078,11 +3043,11 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"approved\" }", requestheaders); + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_APPROVED + "\" }", requestheaders); assertEquals(HttpStatus.SC_CONFLICT, res.getStatusCode()); // Statusが変更されていることを確認 - checkMessageStatus(messageId, "none"); + checkMessageStatus(messageId, STATUS_NONE); } catch (PersoniumException e) { e.printStackTrace(); @@ -2106,12 +3071,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "req.relation.break"); + body.put("Type", TYPE_REQ_RELATION_BREAK); body.put("Title", "Title"); body.put("Body", "Body"); body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); body.put("Priority", 3); - body.put("Status", "none"); + body.put("Status", STATUS_NONE); body.put("RequestRelation", UrlUtils.relationClassUrl(Setup.TEST_CELL_SCHEMA1, relationName)); body.put("RequestRelationTarget", UrlUtils.cellRoot("targetCell")); @@ -2132,12 +3097,12 @@ public final void error_approve_build_message_not_found_box_corresponding_to_Rel HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); requestUrl = UrlUtils.approvedMessage(Setup.TEST_CELL1, messageId); - res = rest.post(requestUrl, "{\"Command\":\"rejected\" }", + res = rest.post(requestUrl, "{\"Command\":\"" + STATUS_REJECTED + "\" }", requestheaders); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // Statusが変更されていることを確認 - checkMessageStatus(messageId, "rejected"); + checkMessageStatus(messageId, STATUS_REJECTED); } catch (PersoniumException e) { e.printStackTrace(); @@ -2168,7 +3133,7 @@ private PersoniumResponse createReceivedMessage(String requestUrl, JSONObject bo private String getCellIssueToken(String targetCellUrl) { String cellUrl = UrlUtils.cellRoot(Setup.TEST_CELL2); TransCellAccessToken token = new TransCellAccessToken(cellUrl, cellUrl, - targetCellUrl, new ArrayList(), ""); + targetCellUrl, new ArrayList(), ""); return token.toTokenString(); } @@ -2205,6 +3170,25 @@ private TResponse getRelationExtCellLinks(String relationName, String boxName) { .debug(); } + private TResponse getRoleExtCellLinks(String roleName, String boxName) { + String key; + if (boxName != null) { + key = "Name='" + roleName + "',_Box.Name='" + boxName + "'"; + } else { + key = "'" + roleName + "'"; + } + return Http.request("links-request-no-navkey.txt") + .with("method", "GET") + .with("token", MASTER_TOKEN_NAME) + .with("cellPath", Setup.TEST_CELL1) + .with("entitySet", Role.EDM_TYPE_NAME) + .with("key", key) + .with("navProp", "_" + ExtCell.EDM_TYPE_NAME) + .returns() + .statusCode(HttpStatus.SC_OK) + .debug(); + } + private void checkRelationExtCellLinks(String relationName, ArrayList expectedUriList) { checkRelationExtCellLinks(relationName, null, expectedUriList); } @@ -2215,4 +3199,10 @@ private void checkRelationExtCellLinks(String relationName, String boxName, Arra checkLinResponseBody(resList.bodyAsJson(), expectedUriList); } + private void checkRoleExtCellLinks(String roleName, String boxName, ArrayList expectedUriList) { + TResponse resList = getRoleExtCellLinks(roleName, boxName); + // Check response body + checkLinResponseBody(resList.bodyAsJson(), expectedUriList); + } + } diff --git a/src/test/java/io/personium/test/jersey/cell/MessageReceivedTest.java b/src/test/java/io/personium/test/jersey/cell/MessageReceivedTest.java index b043e1fc4..d0393c863 100644 --- a/src/test/java/io/personium/test/jersey/cell/MessageReceivedTest.java +++ b/src/test/java/io/personium/test/jersey/cell/MessageReceivedTest.java @@ -16,6 +16,9 @@ */ package io.personium.test.jersey.cell; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_MESSAGE; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_REQ_RELATION_BUILD; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_REQ_ROLE_GRANT; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; @@ -84,7 +87,7 @@ public MessageReceivedTest() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); @@ -111,7 +114,7 @@ public MessageReceivedTest() { expected.put("Body", "Body"); expected.put("_Box.Name", null); expected.put("RequestRelation", null); - expected.put("Type", "message"); + expected.put("Type", TYPE_MESSAGE); expected.put("Title", "Title"); expected.put("Priority", 3); expected.put("Status", "unread"); @@ -144,7 +147,7 @@ public MessageReceivedTest() { JSONObject body = new JSONObject(); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); @@ -183,7 +186,7 @@ public MessageReceivedTest() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); @@ -221,7 +224,7 @@ public MessageReceivedTest() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); @@ -256,7 +259,7 @@ public MessageReceivedTest() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); @@ -293,7 +296,7 @@ public MessageReceivedTest() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); @@ -337,7 +340,7 @@ public MessageReceivedTest() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); @@ -372,6 +375,7 @@ public MessageReceivedTest() { @SuppressWarnings("unchecked") @Test public final void normal_received_message_of_type_relation() { + String messageType = TYPE_REQ_RELATION_BUILD; String targetCellName = Setup.TEST_CELL1; String targetRelationName = "testRelation001"; String srcCellName = Setup.TEST_CELL2; @@ -380,7 +384,7 @@ public final void normal_received_message_of_type_relation() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(srcCellName)); - body.put("Type", "req.relation.build"); + body.put("Type", messageType); body.put("Schema", null); body.put("Title", "Title"); body.put("Body", "Body"); @@ -410,7 +414,7 @@ public final void normal_received_message_of_type_relation() { Map expected = new HashMap(); expected.put("Body", "Body"); expected.put("_Box.Name", null); - expected.put("Type", "req.relation.build"); + expected.put("Type", messageType); expected.put("Title", "Title"); expected.put("Priority", 3); expected.put("Status", "none"); @@ -440,6 +444,7 @@ public final void normal_received_message_of_type_relation() { @SuppressWarnings("unchecked") @Test public final void error_received_message_of_type_relation_requestRelation_invalid_format() { + String messageType = TYPE_REQ_RELATION_BUILD; String targetCellName = Setup.TEST_CELL1; String targetRelationName = "testRelation001"; String srcCellName = Setup.TEST_CELL2; @@ -448,7 +453,7 @@ public final void error_received_message_of_type_relation_requestRelation_invali JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(srcCellName)); - body.put("Type", "req.relation.build"); + body.put("Type", messageType); body.put("Schema", null); body.put("Title", "Title"); body.put("Body", "Body"); @@ -487,6 +492,130 @@ public final void error_received_message_of_type_relation_requestRelation_invali } } + /** + * Normal test. + * Received message of type role. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_received_message_of_type_role() { + String messageType = TYPE_REQ_ROLE_GRANT; + String targetCellName = Setup.TEST_CELL1; + String targetRoleName = "testRole001"; + String srcCellName = Setup.TEST_CELL2; + String appCellName = Setup.TEST_CELL_SCHEMA1; + + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(srcCellName)); + body.put("Type", messageType); + body.put("Schema", null); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", "none"); + body.put("RequestRelation", UrlUtils.roleClassUrl(appCellName, targetRoleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // Authorizationヘッダ + String targetCellUrl = UrlUtils.cellRoot(targetCellName); + + // --------------- + // Execution + // --------------- + response = ReceivedMessageUtils.receive(getCellIssueToken(targetCellUrl), targetCellName, + body.toJSONString(), HttpStatus.SC_CREATED); + + // --------------- + // Verification + // --------------- + Map expected = new HashMap(); + expected.put("Body", "Body"); + expected.put("_Box.Name", null); + expected.put("Type", messageType); + expected.put("Title", "Title"); + expected.put("Priority", 3); + expected.put("Status", "none"); + expected.put("RequestRelation", UrlUtils.roleClassUrl(appCellName, targetRoleName)); + expected.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + expected.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + expected.put("MulticastTo", null); + expected.put("From", UrlUtils.getBaseUrl() + "/testcell2/"); + + // Check response body + ODataCommon.checkResponseBody(response.bodyAsJson(), response.getLocationHeader(), + "CellCtl.ReceivedMessage", expected); + // Verify that the received message is saved + ReceivedMessageUtils.get(MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, (String) body.get("__id")); + } finally { + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + } + } + + /** + * Error test. + * Received message of type role. + * RequestRelation is invalid format. + */ + @SuppressWarnings("unchecked") + @Test + public final void error_received_message_of_type_role_requestRelation_invalid_format() { + String messageType = TYPE_REQ_ROLE_GRANT; + String targetCellName = Setup.TEST_CELL1; + String targetRoleName = "testRole001"; + String srcCellName = Setup.TEST_CELL2; + String appCellName = Setup.TEST_CELL_SCHEMA1; + + JSONObject body = new JSONObject(); + body.put("__id", "12345678901234567890123456789012"); + body.put("From", UrlUtils.cellRoot(srcCellName)); + body.put("Type", messageType); + body.put("Schema", null); + body.put("Title", "Title"); + body.put("Body", "Body"); + body.put("InReplyTo", "d3330643f57a42fd854558fb0a96a96a"); + body.put("Priority", 3); + body.put("Status", "none"); + body.put("RequestRelation", UrlUtils.roleUrl(appCellName, "box1", targetRoleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // Authorizationヘッダ + String targetCellUrl = UrlUtils.cellRoot(targetCellName); + + // --------------- + // Execution + // --------------- + response = ReceivedMessageUtils.receive(getCellIssueToken(targetCellUrl), targetCellName, + body.toJSONString(), HttpStatus.SC_BAD_REQUEST); + + // --------------- + // Verification + // --------------- + // Check response body + PersoniumCoreException exception = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR + .params("RequestRelation"); + String message = (String) ((JSONObject) response.bodyAsJson().get("message")).get("value"); + assertThat(message, is(exception.getMessage())); + } finally { + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + } + } + /** * Normal test. * Received schema message. @@ -494,6 +623,7 @@ public final void error_received_message_of_type_relation_requestRelation_invali @SuppressWarnings("unchecked") @Test public final void normal_received_schema_message() { + String messageType = TYPE_MESSAGE; String targetCellName = Setup.TEST_CELL1; String srcCellName = Setup.TEST_CELL2; String appCellName = Setup.TEST_CELL_SCHEMA1; @@ -501,7 +631,7 @@ public final void normal_received_schema_message() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(srcCellName)); - body.put("Type", "message"); + body.put("Type", messageType); body.put("Schema", UrlUtils.cellRoot(appCellName)); body.put("Title", "Title"); body.put("Body", "Body"); @@ -531,7 +661,7 @@ public final void normal_received_schema_message() { Map expected = new HashMap(); expected.put("Body", "Body"); expected.put("_Box.Name", Setup.TEST_BOX1); - expected.put("Type", "message"); + expected.put("Type", messageType); expected.put("Title", "Title"); expected.put("Priority", 3); expected.put("Status", "unread"); @@ -561,6 +691,7 @@ public final void normal_received_schema_message() { @SuppressWarnings("unchecked") @Test public final void error_received_schema_message_box_not_exists() { + String messageType = TYPE_MESSAGE; String targetCellName = Setup.TEST_CELL1; String srcCellName = Setup.TEST_CELL2; String appCellName = "testSchema001"; @@ -568,7 +699,7 @@ public final void error_received_schema_message_box_not_exists() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(srcCellName)); - body.put("Type", "message"); + body.put("Type", messageType); body.put("Schema", UrlUtils.cellRoot(appCellName)); body.put("Title", "Title"); body.put("Body", "Body"); @@ -623,7 +754,7 @@ public final void error_received_schema_message_box_not_exists() { JSONObject body1 = new JSONObject(); body1.put("__id", "12345678901234567890123456789012"); body1.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body1.put("Type", "message"); + body1.put("Type", TYPE_MESSAGE); body1.put("Title", "Title1"); body1.put("Body", "Hello"); body1.put("Priority", 3); @@ -633,7 +764,7 @@ public final void error_received_schema_message_box_not_exists() { JSONObject body2 = new JSONObject(); body2.put("__id", "12345678901234567890123456789013"); body2.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body2.put("Type", "message"); + body2.put("Type", TYPE_MESSAGE); body2.put("Title", "Title2"); body2.put("Body", "Good Bye"); body2.put("Priority", 2); @@ -690,7 +821,7 @@ public final void error_received_schema_message_box_not_exists() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title1"); body.put("Body", "Hello"); body.put("Priority", 3); @@ -738,7 +869,7 @@ public final void error_received_schema_message_box_not_exists() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title1"); body.put("Body", "Hello"); body.put("Priority", 3); @@ -1011,7 +1142,7 @@ public final void error_received_schema_message_box_not_exists() { ODataCommon.deleteOdataResource(response1.getLocationHeader()); } MessageSentTest.deleteReceivedMessage( - Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), "message", "test mail", "test body01"); + Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), TYPE_MESSAGE, "test mail", "test body01"); } } @@ -1103,7 +1234,7 @@ public final void error_received_schema_message_box_not_exists() { ODataCommon.deleteOdataResource(response1.getLocationHeader()); } MessageSentTest.deleteReceivedMessage( - Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), "message", "test mail", "test body01"); + Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), TYPE_MESSAGE, "test mail", "test body01"); } } @@ -1170,7 +1301,7 @@ public final void error_received_schema_message_box_not_exists() { ODataCommon.deleteOdataResource(response1.getLocationHeader()); } MessageSentTest.deleteReceivedMessage( - Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), "message", "test mail", "test body01"); + Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), TYPE_MESSAGE, "test mail", "test body01"); } } @@ -1263,7 +1394,7 @@ public final void error_received_schema_message_box_not_exists() { ODataCommon.deleteOdataResource(response1.getLocationHeader()); } MessageSentTest.deleteReceivedMessage( - Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), "message", "test mail", "test body01"); + Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), TYPE_MESSAGE, "test mail", "test body01"); } } @@ -1356,7 +1487,7 @@ public final void error_received_schema_message_box_not_exists() { ODataCommon.deleteOdataResource(response1.getLocationHeader()); } MessageSentTest.deleteReceivedMessage( - Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), "message", "test mail", "test body01"); + Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), TYPE_MESSAGE, "test mail", "test body01"); } } @@ -1424,7 +1555,7 @@ public final void error_received_schema_message_box_not_exists() { ODataCommon.deleteOdataResource(response1.getLocationHeader()); } MessageSentTest.deleteReceivedMessage( - Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), "message", "test mail", "test body01"); + Setup.TEST_CELL1, UrlUtils.cellRoot(Setup.TEST_CELL2), TYPE_MESSAGE, "test mail", "test body01"); } } @@ -1585,7 +1716,7 @@ public final void error_received_schema_message_box_not_exists() { JSONObject body = new JSONObject(); body.put("__id", id); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); @@ -1609,7 +1740,7 @@ private PersoniumResponse createReceivedMessage() { JSONObject body = new JSONObject(); body.put("__id", "12345678901234567890123456789012"); body.put("From", UrlUtils.cellRoot(Setup.TEST_CELL2)); - body.put("Type", "message"); + body.put("Type", TYPE_MESSAGE); body.put("Title", "Title"); body.put("Body", "Body"); body.put("Priority", 3); diff --git a/src/test/java/io/personium/test/jersey/cell/MessageSentTest.java b/src/test/java/io/personium/test/jersey/cell/MessageSentTest.java index 9379ef58d..f4357cfdf 100644 --- a/src/test/java/io/personium/test/jersey/cell/MessageSentTest.java +++ b/src/test/java/io/personium/test/jersey/cell/MessageSentTest.java @@ -16,6 +16,11 @@ */ package io.personium.test.jersey.cell; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_MESSAGE; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_REQ_RELATION_BREAK; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_REQ_RELATION_BUILD; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_REQ_ROLE_GRANT; +import static io.personium.core.model.ctl.ReceivedMessage.TYPE_REQ_ROLE_REVOKE; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; @@ -60,11 +65,7 @@ public class MessageSentTest extends ODataCommon { private static final String SENT_MESSAGE_TYPE = "CellCtl.SentMessage"; - static final String TEST_CELL1 = Setup.TEST_CELL1; - - static final String MESSAGE = "message"; - static final String REQ_RELATION_BUILD = "req.relation.build"; - static final String REQ_RELATION_BREAK = "req.relation.break"; + private static final String TEST_CELL1 = Setup.TEST_CELL1; /** * コンストラクタ. テスト対象のパッケージをsuperに渡す必要がある @@ -88,7 +89,7 @@ public MessageSentTest() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCell)); body.put("ToRelation", null); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -113,7 +114,7 @@ public MessageSentTest() { expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCell)); expected.put("ToRelation", null); - expected.put("Type", MESSAGE); + expected.put("Type", TYPE_MESSAGE); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -136,7 +137,7 @@ public MessageSentTest() { deleteOdataResource(response.getLocationHeader()); } // 自動生成された受信メッセージの削除 - deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title", "body"); + deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title", "body"); } } @@ -155,7 +156,7 @@ public MessageSentTest() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCell)); body.put("ToRelation", null); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -181,7 +182,7 @@ public MessageSentTest() { expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCell)); expected.put("ToRelation", null); - expected.put("Type", MESSAGE); + expected.put("Type", TYPE_MESSAGE); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -196,7 +197,7 @@ public MessageSentTest() { deleteOdataResource(response.getLocationHeader()); } // 自動生成された受信メッセージの削除 - deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title", "body"); + deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title", "body"); } } @@ -216,7 +217,7 @@ public MessageSentTest() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCell1) + "," + UrlUtils.cellRoot(targetCell2)); body.put("ToRelation", null); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -243,8 +244,8 @@ public MessageSentTest() { deleteOdataResource(response.getLocationHeader()); } // 自動生成された受信メッセージの削除 - deleteReceivedMessage(targetCell1, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title", "body"); - deleteReceivedMessage(targetCell2, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title", "body"); + deleteReceivedMessage(targetCell1, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title", "body"); + deleteReceivedMessage(targetCell2, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title", "body"); } } @@ -263,7 +264,7 @@ public MessageSentTest() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCell)); body.put("ToRelation", null); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -281,7 +282,7 @@ public MessageSentTest() { deleteOdataResource(response.getLocationHeader()); } // 自動生成された受信メッセージの削除 - deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title", "body"); + deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title", "body"); } } @@ -296,7 +297,7 @@ public MessageSentTest() { JSONObject body = new JSONObject(); body.put("BoxBound", false); body.put("InReplyTo", null); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -336,7 +337,7 @@ public MessageSentTest() { body1.put("InReplyTo", null); body1.put("To", UrlUtils.cellRoot(targetCell)); body1.put("ToRelation", null); - body1.put("Type", MESSAGE); + body1.put("Type", TYPE_MESSAGE); body1.put("Title", "title1"); body1.put("Body", "Hello"); body1.put("Priority", 3); @@ -349,7 +350,7 @@ public MessageSentTest() { body2.put("InReplyTo", null); body2.put("To", UrlUtils.cellRoot(targetCell)); body2.put("ToRelation", null); - body2.put("Type", MESSAGE); + body2.put("Type", TYPE_MESSAGE); body2.put("Title", "title2"); body2.put("Body", "Good Bye"); body2.put("Priority", 2); @@ -382,9 +383,9 @@ public MessageSentTest() { deleteOdataResource(response2.getLocationHeader()); } // 自動生成された受信メッセージの削除 - deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title1", "Hello"); + deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title1", "Hello"); // 自動生成された受信メッセージの削除 - deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title2", "Good Bye"); + deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title2", "Good Bye"); } } @@ -403,7 +404,7 @@ public MessageSentTest() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCell)); body.put("ToRelation", null); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -426,7 +427,7 @@ public MessageSentTest() { deleteOdataResource(response.getLocationHeader()); } // 自動生成された受信メッセージの削除 - deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title", "body"); + deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title", "body"); } } @@ -445,7 +446,7 @@ public MessageSentTest() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCell)); body.put("ToRelation", null); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -468,7 +469,7 @@ public MessageSentTest() { SentMessageUtils.delete(MASTER_TOKEN_NAME, TEST_CELL1, HttpStatus.SC_NO_CONTENT, id); } // 自動生成された受信メッセージの削除 - deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title", "body"); + deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title", "body"); } } @@ -487,7 +488,7 @@ public MessageSentTest() { body.put("BoxBound", false); body.put("InReplyTo", null); body.put("ToRelation", "cellrelation"); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -512,7 +513,7 @@ public MessageSentTest() { expected.put("InReplyTo", null); expected.put("To", null); expected.put("ToRelation", "cellrelation"); - expected.put("Type", MESSAGE); + expected.put("Type", TYPE_MESSAGE); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -543,7 +544,7 @@ public MessageSentTest() { expected.put("Body", "body"); expected.put("_Box.Name", null); expected.put("RequestRelation", null); - expected.put("Type", MESSAGE); + expected.put("Type", TYPE_MESSAGE); expected.put("Title", "title"); expected.put("Priority", 3); expected.put("Status", "unread"); @@ -560,7 +561,7 @@ public MessageSentTest() { deleteOdataResource(response.getLocationHeader()); } // 自動生成された受信メッセージの削除 - deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title", "body"); + deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title", "body"); } } @@ -579,7 +580,7 @@ public MessageSentTest() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCell)); body.put("ToRelation", "cellrelation"); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -604,7 +605,7 @@ public MessageSentTest() { expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCell)); expected.put("ToRelation", "cellrelation"); - expected.put("Type", MESSAGE); + expected.put("Type", TYPE_MESSAGE); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -630,7 +631,7 @@ public MessageSentTest() { deleteOdataResource(response.getLocationHeader()); } // 自動生成された受信メッセージの削除 - deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title", "body"); + deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title", "body"); } } @@ -649,7 +650,7 @@ public MessageSentTest() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCell) + "," + UrlUtils.cellRoot("testcell999")); body.put("ToRelation", "cellrelation"); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -679,7 +680,7 @@ public MessageSentTest() { expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCell) + "," + UrlUtils.cellRoot("testcell999")); expected.put("ToRelation", "cellrelation"); - expected.put("Type", MESSAGE); + expected.put("Type", TYPE_MESSAGE); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -705,7 +706,7 @@ public MessageSentTest() { deleteOdataResource(response.getLocationHeader()); } // 自動生成された受信メッセージの削除 - deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), MESSAGE, "title", "body"); + deleteReceivedMessage(targetCell, UrlUtils.cellRoot(Setup.TEST_CELL1), TYPE_MESSAGE, "title", "body"); } } @@ -717,6 +718,7 @@ public MessageSentTest() { @SuppressWarnings("unchecked") @Test public final void normal_send_message_of_type_relation_build_relationClassURL() { + String messageType = TYPE_REQ_RELATION_BUILD; String targetCellName = Setup.TEST_CELL2; String targetRelationName = "testRelation001"; String srcCellName = TEST_CELL1; @@ -728,7 +730,7 @@ public final void normal_send_message_of_type_relation_build_relationClassURL() body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", REQ_RELATION_BUILD); + body.put("Type", messageType); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -764,7 +766,7 @@ public final void normal_send_message_of_type_relation_build_relationClassURL() expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCellName)); expected.put("ToRelation", null); - expected.put("Type", REQ_RELATION_BUILD); + expected.put("Type", messageType); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -788,7 +790,7 @@ public final void normal_send_message_of_type_relation_build_relationClassURL() deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), REQ_RELATION_BUILD, "title", "body"); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); } } @@ -800,6 +802,7 @@ public final void normal_send_message_of_type_relation_build_relationClassURL() @SuppressWarnings("unchecked") @Test public final void normal_send_message_of_type_relation_build_unit_local_relationClassURL() { + String messageType = TYPE_REQ_RELATION_BUILD; String targetCellName = Setup.TEST_CELL2; String targetRelationName = "testRelation001"; String srcCellName = TEST_CELL1; @@ -811,7 +814,7 @@ public final void normal_send_message_of_type_relation_build_unit_local_relation body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", REQ_RELATION_BUILD); + body.put("Type", messageType); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -847,7 +850,7 @@ public final void normal_send_message_of_type_relation_build_unit_local_relation expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCellName)); expected.put("ToRelation", null); - expected.put("Type", REQ_RELATION_BUILD); + expected.put("Type", messageType); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -871,7 +874,7 @@ public final void normal_send_message_of_type_relation_build_unit_local_relation deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), REQ_RELATION_BUILD, "title", "body"); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); } } @@ -883,6 +886,7 @@ public final void normal_send_message_of_type_relation_build_unit_local_relation @SuppressWarnings("unchecked") @Test public final void normal_send_message_of_type_relation_build_relationName() { + String messageType = TYPE_REQ_RELATION_BUILD; String targetCellName = Setup.TEST_CELL2; String targetRelationName = "testRelation001"; String srcCellName = TEST_CELL1; @@ -893,7 +897,7 @@ public final void normal_send_message_of_type_relation_build_relationName() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", REQ_RELATION_BUILD); + body.put("Type", messageType); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -929,7 +933,7 @@ public final void normal_send_message_of_type_relation_build_relationName() { expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCellName)); expected.put("ToRelation", null); - expected.put("Type", REQ_RELATION_BUILD); + expected.put("Type", messageType); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -953,7 +957,7 @@ public final void normal_send_message_of_type_relation_build_relationName() { deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), REQ_RELATION_BUILD, "title", "body"); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); } } @@ -965,6 +969,7 @@ public final void normal_send_message_of_type_relation_build_relationName() { @SuppressWarnings("unchecked") @Test public final void error_send_message_of_type_relation_build_requestRelation_invalid_format() { + String messageType = TYPE_REQ_RELATION_BUILD; String targetCellName = Setup.TEST_CELL2; String targetRelationName = "testRelation001"; String srcCellName = TEST_CELL1; @@ -976,7 +981,7 @@ public final void error_send_message_of_type_relation_build_requestRelation_inva body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", REQ_RELATION_BUILD); + body.put("Type", messageType); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -1011,7 +1016,7 @@ public final void error_send_message_of_type_relation_build_requestRelation_inva deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), REQ_RELATION_BUILD, "title", "body"); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); } } @@ -1023,6 +1028,7 @@ public final void error_send_message_of_type_relation_build_requestRelation_inva @SuppressWarnings("unchecked") @Test public final void normal_send_message_of_type_relation_break_relationClassURL() { + String messageType = TYPE_REQ_RELATION_BREAK; String targetCellName = Setup.TEST_CELL2; String targetRelationName = "testRelation001"; String srcCellName = TEST_CELL1; @@ -1034,7 +1040,7 @@ public final void normal_send_message_of_type_relation_break_relationClassURL() body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", REQ_RELATION_BREAK); + body.put("Type", messageType); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -1070,7 +1076,7 @@ public final void normal_send_message_of_type_relation_break_relationClassURL() expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCellName)); expected.put("ToRelation", null); - expected.put("Type", REQ_RELATION_BREAK); + expected.put("Type", messageType); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -1094,7 +1100,7 @@ public final void normal_send_message_of_type_relation_break_relationClassURL() deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), REQ_RELATION_BREAK, "title", "body"); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); } } @@ -1106,6 +1112,7 @@ public final void normal_send_message_of_type_relation_break_relationClassURL() @SuppressWarnings("unchecked") @Test public final void normal_send_message_of_type_relation_break_unit_local_relationClassURL() { + String messageType = TYPE_REQ_RELATION_BREAK; String targetCellName = Setup.TEST_CELL2; String targetRelationName = "testRelation001"; String srcCellName = TEST_CELL1; @@ -1117,7 +1124,7 @@ public final void normal_send_message_of_type_relation_break_unit_local_relation body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", REQ_RELATION_BREAK); + body.put("Type", messageType); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -1153,7 +1160,7 @@ public final void normal_send_message_of_type_relation_break_unit_local_relation expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCellName)); expected.put("ToRelation", null); - expected.put("Type", REQ_RELATION_BREAK); + expected.put("Type", messageType); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -1177,7 +1184,7 @@ public final void normal_send_message_of_type_relation_break_unit_local_relation deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), REQ_RELATION_BREAK, "title", "body"); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); } } @@ -1189,6 +1196,7 @@ public final void normal_send_message_of_type_relation_break_unit_local_relation @SuppressWarnings("unchecked") @Test public final void normal_send_message_of_type_relation_break_relationName() { + String messageType = TYPE_REQ_RELATION_BREAK; String targetCellName = Setup.TEST_CELL2; String targetRelationName = "testRelation001"; String srcCellName = TEST_CELL1; @@ -1199,7 +1207,7 @@ public final void normal_send_message_of_type_relation_break_relationName() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", REQ_RELATION_BREAK); + body.put("Type", messageType); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -1235,7 +1243,7 @@ public final void normal_send_message_of_type_relation_break_relationName() { expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCellName)); expected.put("ToRelation", null); - expected.put("Type", REQ_RELATION_BREAK); + expected.put("Type", messageType); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -1259,7 +1267,7 @@ public final void normal_send_message_of_type_relation_break_relationName() { deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), REQ_RELATION_BREAK, "title", "body"); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); } } @@ -1271,6 +1279,7 @@ public final void normal_send_message_of_type_relation_break_relationName() { @SuppressWarnings("unchecked") @Test public final void error_send_message_of_type_relation_break_requestRelation_invalid_format() { + String messageType = TYPE_REQ_RELATION_BREAK; String targetCellName = Setup.TEST_CELL2; String targetRelationName = "testRelation001"; String srcCellName = TEST_CELL1; @@ -1281,7 +1290,7 @@ public final void error_send_message_of_type_relation_break_requestRelation_inva body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", REQ_RELATION_BREAK); + body.put("Type", messageType); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -1316,66 +1325,43 @@ public final void error_send_message_of_type_relation_break_requestRelation_inva deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), REQ_RELATION_BREAK, "title", "body"); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); } } /** * Normal test. - * Send BoxBound message of type Message. + * Send message of type RoleGrant. + * RequestRelation is RoleClassURL. */ @SuppressWarnings("unchecked") @Test - public final void normal_send_boxbound_message_of_type_message() { + public final void normal_send_message_of_type_role_grant_roleClassURL() { + String messageType = TYPE_REQ_ROLE_GRANT; String targetCellName = Setup.TEST_CELL2; + String targetRoleName = "testRole001"; String srcCellName = TEST_CELL1; String appCellName = Setup.TEST_CELL_SCHEMA1; // Set request body JSONObject body = new JSONObject(); - body.put("BoxBound", true); + body.put("BoxBound", false); body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", MESSAGE); + body.put("Type", messageType); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); - body.put("RequestRelation", null); - body.put("RequestRelationTarget", null); + body.put("RequestRelation", UrlUtils.roleClassUrl(appCellName, targetRoleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); TResponse response = null; try { // --------------- // Preparation // --------------- - // Create role - RoleUtils.create(srcCellName, MASTER_TOKEN_NAME, "testRole001", HttpStatus.SC_CREATED); - // Set acl to role - Http.request("cell/acl-setting-cell-none-root.txt") - .with("url", srcCellName) - .with("token", MASTER_TOKEN_NAME) - .with("role1", "testRole001") - .with("roleBaseUrl", UrlUtils.roleResource(srcCellName, null, "")).returns() - .statusCode(HttpStatus.SC_OK); - // Set links account and role - ResourceUtils.linkAccountRole(srcCellName, MASTER_TOKEN_NAME, "account4", null, - "testRole001", HttpStatus.SC_NO_CONTENT); - - // App auth - TResponse authnRes = CellUtils.tokenAuthenticationWithTarget(appCellName, "account0", - "password0", srcCellName); - String appToken = (String) authnRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); - // authz - TResponse authzRes = Http.request("authn/password-cl-cp.txt") - .with("remoteCell", srcCellName) - .with("username", "account4") - .with("password", "password4") - .with("client_id", UrlUtils.cellRoot(appCellName)) - .with("client_secret", appToken) - .returns() - .statusCode(HttpStatus.SC_OK); - String token = (String) authzRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + String token = MASTER_TOKEN_NAME; // --------------- // Execution @@ -1395,16 +1381,16 @@ public final void normal_send_boxbound_message_of_type_message() { JSONArray expectedResults = new JSONArray(); expectedResults.add(expectedResult); JSONObject expected = new JSONObject(); - expected.put("_Box.Name", Setup.TEST_BOX1); + expected.put("_Box.Name", null); expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCellName)); expected.put("ToRelation", null); - expected.put("Type", MESSAGE); + expected.put("Type", messageType); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); - expected.put("RequestRelation", null); - expected.put("RequestRelationTarget", null); + expected.put("RequestRelation", UrlUtils.roleClassUrl(appCellName, targetRoleName)); + expected.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); expected.put("Result", expectedResults); // Check response body ODataCommon.checkResponseBody(response.bodyAsJson(), response.getLocationHeader(), @@ -1416,48 +1402,42 @@ public final void normal_send_boxbound_message_of_type_message() { // Verify that the sent message is saved SentMessageUtils.get(MASTER_TOKEN_NAME, srcCellName, HttpStatus.SC_OK, id); // Verify that the received message is saved - TResponse receivedResponse = ReceivedMessageUtils.get( - MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); - // Verify that boxname is stored in the received message - results = (JSONObject) ((JSONObject) receivedResponse.bodyAsJson().get("d")).get("results"); - assertThat((String) results.get("_Box.Name"), is(Setup.TEST_BOX1)); + ReceivedMessageUtils.get(MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); } finally { // Delete sent message if (response != null) { deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), MESSAGE, "title", "body"); - // Delete Role and Account $links - ResourceUtils.linkAccountRollDelete(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001"); - // Delete role - RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, null, "testRole001", -1); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); } } /** * Normal test. - * Send BoxBound message of type RelationBuild. + * Send message of type RoleGrant. + * RequestRelation is unit local RoleClassURL. */ @SuppressWarnings("unchecked") @Test - public final void normal_send_boxbound_message_of_type_relation_build() { + public final void normal_send_message_of_type_role_grant_unit_local_roleClassURL() { + String messageType = TYPE_REQ_ROLE_GRANT; String targetCellName = Setup.TEST_CELL2; - String targetRelationName = "testRelation001"; + String targetRoleName = "testRole001"; String srcCellName = TEST_CELL1; String appCellName = Setup.TEST_CELL_SCHEMA1; // Set request body JSONObject body = new JSONObject(); - body.put("BoxBound", true); + body.put("BoxBound", false); body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", REQ_RELATION_BUILD); + body.put("Type", messageType); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); - body.put("RequestRelation", UrlUtils.relationClassUrl(appCellName, targetRelationName)); + body.put("RequestRelation", UrlUtils.unitLocalRoleClassUrl(appCellName, targetRoleName)); body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); TResponse response = null; @@ -1465,33 +1445,7 @@ public final void normal_send_boxbound_message_of_type_relation_build() { // --------------- // Preparation // --------------- - // Create role - RoleUtils.create(srcCellName, MASTER_TOKEN_NAME, "testRole001", HttpStatus.SC_CREATED); - // Set acl to role - Http.request("cell/acl-setting-cell-none-root.txt") - .with("url", srcCellName) - .with("token", MASTER_TOKEN_NAME) - .with("role1", "testRole001") - .with("roleBaseUrl", UrlUtils.roleResource(srcCellName, null, "")).returns() - .statusCode(HttpStatus.SC_OK); - // Set links account and role - ResourceUtils.linkAccountRole(srcCellName, MASTER_TOKEN_NAME, "account4", null, - "testRole001", HttpStatus.SC_NO_CONTENT); - - // App auth - TResponse authnRes = CellUtils.tokenAuthenticationWithTarget(appCellName, "account0", - "password0", srcCellName); - String appToken = (String) authnRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); - // authz - TResponse authzRes = Http.request("authn/password-cl-cp.txt") - .with("remoteCell", srcCellName) - .with("username", "account4") - .with("password", "password4") - .with("client_id", UrlUtils.cellRoot(appCellName)) - .with("client_secret", appToken) - .returns() - .statusCode(HttpStatus.SC_OK); - String token = (String) authzRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + String token = MASTER_TOKEN_NAME; // --------------- // Execution @@ -1511,15 +1465,15 @@ public final void normal_send_boxbound_message_of_type_relation_build() { JSONArray expectedResults = new JSONArray(); expectedResults.add(expectedResult); JSONObject expected = new JSONObject(); - expected.put("_Box.Name", Setup.TEST_BOX1); + expected.put("_Box.Name", null); expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCellName)); expected.put("ToRelation", null); - expected.put("Type", REQ_RELATION_BUILD); + expected.put("Type", messageType); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); - expected.put("RequestRelation", UrlUtils.relationClassUrl(appCellName, targetRelationName)); + expected.put("RequestRelation", UrlUtils.unitLocalRoleClassUrl(appCellName, targetRoleName)); expected.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); expected.put("Result", expectedResults); // Check response body @@ -1532,48 +1486,125 @@ public final void normal_send_boxbound_message_of_type_relation_build() { // Verify that the sent message is saved SentMessageUtils.get(MASTER_TOKEN_NAME, srcCellName, HttpStatus.SC_OK, id); // Verify that the received message is saved - TResponse receivedResponse = ReceivedMessageUtils.get( - MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); - // Verify that boxname is stored in the received message - results = (JSONObject) ((JSONObject) receivedResponse.bodyAsJson().get("d")).get("results"); - assertThat((String) results.get("_Box.Name"), is(Setup.TEST_BOX1)); + ReceivedMessageUtils.get(MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); } finally { // Delete sent message if (response != null) { deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), REQ_RELATION_BUILD, "title", "body"); - // Delete Role and Account $links - ResourceUtils.linkAccountRollDelete(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001"); - // Delete role - RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, null, "testRole001", -1); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); } } /** * Normal test. - * Send BoxBound message of type RelationBreak. + * Send message of type RoleGrant. + * RequestRelation is RoleName. */ @SuppressWarnings("unchecked") @Test - public final void normal_send_boxbound_message_of_type_relation_break() { + public final void normal_send_message_of_type_role_grant_roleName() { + String messageType = TYPE_REQ_ROLE_GRANT; String targetCellName = Setup.TEST_CELL2; - String targetRelationName = "testRelation001"; + String targetRoleName = "testRole001"; + String srcCellName = TEST_CELL1; + + // Set request body + JSONObject body = new JSONObject(); + body.put("BoxBound", false); + body.put("InReplyTo", null); + body.put("To", UrlUtils.cellRoot(targetCellName)); + body.put("ToRelation", null); + body.put("Type", messageType); + body.put("Title", "title"); + body.put("Body", "body"); + body.put("Priority", 3); + body.put("RequestRelation", targetRoleName); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + String token = MASTER_TOKEN_NAME; + + // --------------- + // Execution + // --------------- + // Send message + response = SentMessageUtils.sent(token, srcCellName, + body.toJSONString(), HttpStatus.SC_CREATED); + + // --------------- + // Verification + // --------------- + // Set expected response body + JSONObject expectedResult = new JSONObject(); + expectedResult.put("To", UrlUtils.cellRoot(targetCellName)); + expectedResult.put("Code", Integer.toString(HttpStatus.SC_CREATED)); + expectedResult.put("Reason", "Created."); + JSONArray expectedResults = new JSONArray(); + expectedResults.add(expectedResult); + JSONObject expected = new JSONObject(); + expected.put("_Box.Name", null); + expected.put("InReplyTo", null); + expected.put("To", UrlUtils.cellRoot(targetCellName)); + expected.put("ToRelation", null); + expected.put("Type", messageType); + expected.put("Title", "title"); + expected.put("Body", "body"); + expected.put("Priority", 3); + expected.put("RequestRelation", targetRoleName); + expected.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + expected.put("Result", expectedResults); + // Check response body + ODataCommon.checkResponseBody(response.bodyAsJson(), response.getLocationHeader(), + SENT_MESSAGE_TYPE, expected); + + // Get message id + JSONObject results = (JSONObject) ((JSONObject) response.bodyAsJson().get("d")).get("results"); + String id = (String) results.get("__id"); + // Verify that the sent message is saved + SentMessageUtils.get(MASTER_TOKEN_NAME, srcCellName, HttpStatus.SC_OK, id); + // Verify that the received message is saved + ReceivedMessageUtils.get(MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); + } finally { + // Delete sent message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete received message + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); + } + } + + /** + * Error test. + * Send message of type RoleGrant. + * RequestRelation is invalid format. + */ + @SuppressWarnings("unchecked") + @Test + public final void error_send_message_of_type_role_grant_requestRelation_invalid_format() { + String messageType = TYPE_REQ_ROLE_GRANT; + String targetCellName = Setup.TEST_CELL2; + String targetRoleName = "testRole001"; String srcCellName = TEST_CELL1; String appCellName = Setup.TEST_CELL_SCHEMA1; // Set request body JSONObject body = new JSONObject(); - body.put("BoxBound", true); + body.put("BoxBound", false); body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", REQ_RELATION_BREAK); + body.put("Type", messageType); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); - body.put("RequestRelation", UrlUtils.relationClassUrl(appCellName, targetRelationName)); + body.put("RequestRelation", UrlUtils.roleUrl(appCellName, "box1", targetRoleName)); body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); TResponse response = null; @@ -1581,33 +1612,66 @@ public final void normal_send_boxbound_message_of_type_relation_break() { // --------------- // Preparation // --------------- - // Create role - RoleUtils.create(srcCellName, MASTER_TOKEN_NAME, "testRole001", HttpStatus.SC_CREATED); - // Set acl to role - Http.request("cell/acl-setting-cell-none-root.txt") - .with("url", srcCellName) - .with("token", MASTER_TOKEN_NAME) - .with("role1", "testRole001") - .with("roleBaseUrl", UrlUtils.roleResource(srcCellName, null, "")).returns() - .statusCode(HttpStatus.SC_OK); - // Set links account and role - ResourceUtils.linkAccountRole(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001", - HttpStatus.SC_NO_CONTENT); + String token = MASTER_TOKEN_NAME; - // App auth - TResponse authnRes = CellUtils.tokenAuthenticationWithTarget(appCellName, "account0", "password0", - srcCellName); - String appToken = (String) authnRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); - // authz - TResponse authzRes = Http.request("authn/password-cl-cp.txt") - .with("remoteCell", srcCellName) - .with("username", "account4") - .with("password", "password4") - .with("client_id", UrlUtils.cellRoot(appCellName)) - .with("client_secret", appToken) - .returns() - .statusCode(HttpStatus.SC_OK); - String token = (String) authzRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + // --------------- + // Execution + // --------------- + // Send message + response = SentMessageUtils.sent(token, srcCellName, + body.toJSONString(), HttpStatus.SC_BAD_REQUEST); + + // --------------- + // Verification + // --------------- + // Check response body + PersoniumCoreException exception = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR + .params("RequestRelation"); + String message = (String) ((JSONObject) response.bodyAsJson().get("message")).get("value"); + assertThat(message, is(exception.getMessage())); + } finally { + // Delete sent message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete received message + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); + } + } + + /** + * Normal test. + * Send message of type RoleRevoke. + * RequestRelation is RoleClassURL. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_send_message_of_type_role_revoke_roleClassURL() { + String messageType = TYPE_REQ_ROLE_REVOKE; + String targetCellName = Setup.TEST_CELL2; + String targetRoleName = "testRole001"; + String srcCellName = TEST_CELL1; + String appCellName = Setup.TEST_CELL_SCHEMA1; + + // Set request body + JSONObject body = new JSONObject(); + body.put("BoxBound", false); + body.put("InReplyTo", null); + body.put("To", UrlUtils.cellRoot(targetCellName)); + body.put("ToRelation", null); + body.put("Type", messageType); + body.put("Title", "title"); + body.put("Body", "body"); + body.put("Priority", 3); + body.put("RequestRelation", UrlUtils.roleClassUrl(appCellName, targetRoleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + String token = MASTER_TOKEN_NAME; // --------------- // Execution @@ -1627,15 +1691,816 @@ public final void normal_send_boxbound_message_of_type_relation_break() { JSONArray expectedResults = new JSONArray(); expectedResults.add(expectedResult); JSONObject expected = new JSONObject(); - expected.put("_Box.Name", Setup.TEST_BOX1); + expected.put("_Box.Name", null); expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCellName)); expected.put("ToRelation", null); - expected.put("Type", REQ_RELATION_BREAK); + expected.put("Type", messageType); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); - expected.put("RequestRelation", UrlUtils.relationClassUrl(appCellName, targetRelationName)); + expected.put("RequestRelation", UrlUtils.roleClassUrl(appCellName, targetRoleName)); + expected.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + expected.put("Result", expectedResults); + // Check response body + ODataCommon.checkResponseBody(response.bodyAsJson(), response.getLocationHeader(), + SENT_MESSAGE_TYPE, expected); + + // Get message id + JSONObject results = (JSONObject) ((JSONObject) response.bodyAsJson().get("d")).get("results"); + String id = (String) results.get("__id"); + // Verify that the sent message is saved + SentMessageUtils.get(MASTER_TOKEN_NAME, srcCellName, HttpStatus.SC_OK, id); + // Verify that the received message is saved + ReceivedMessageUtils.get(MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); + } finally { + // Delete sent message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete received message + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); + } + } + + /** + * Normal test. + * Send message of type RoleRevoke. + * RequestRelation is unit local RoleClassURL. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_send_message_of_type_role_revoke_unit_local_roleClassURL() { + String messageType = TYPE_REQ_ROLE_REVOKE; + String targetCellName = Setup.TEST_CELL2; + String targetRoleName = "testRole001"; + String srcCellName = TEST_CELL1; + String appCellName = Setup.TEST_CELL_SCHEMA1; + + // Set request body + JSONObject body = new JSONObject(); + body.put("BoxBound", false); + body.put("InReplyTo", null); + body.put("To", UrlUtils.cellRoot(targetCellName)); + body.put("ToRelation", null); + body.put("Type", messageType); + body.put("Title", "title"); + body.put("Body", "body"); + body.put("Priority", 3); + body.put("RequestRelation", UrlUtils.unitLocalRoleClassUrl(appCellName, targetRoleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + String token = MASTER_TOKEN_NAME; + + // --------------- + // Execution + // --------------- + // Send message + response = SentMessageUtils.sent(token, srcCellName, + body.toJSONString(), HttpStatus.SC_CREATED); + + // --------------- + // Verification + // --------------- + // Set expected response body + JSONObject expectedResult = new JSONObject(); + expectedResult.put("To", UrlUtils.cellRoot(targetCellName)); + expectedResult.put("Code", Integer.toString(HttpStatus.SC_CREATED)); + expectedResult.put("Reason", "Created."); + JSONArray expectedResults = new JSONArray(); + expectedResults.add(expectedResult); + JSONObject expected = new JSONObject(); + expected.put("_Box.Name", null); + expected.put("InReplyTo", null); + expected.put("To", UrlUtils.cellRoot(targetCellName)); + expected.put("ToRelation", null); + expected.put("Type", messageType); + expected.put("Title", "title"); + expected.put("Body", "body"); + expected.put("Priority", 3); + expected.put("RequestRelation", UrlUtils.unitLocalRoleClassUrl(appCellName, targetRoleName)); + expected.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + expected.put("Result", expectedResults); + // Check response body + ODataCommon.checkResponseBody(response.bodyAsJson(), response.getLocationHeader(), + SENT_MESSAGE_TYPE, expected); + + // Get message id + JSONObject results = (JSONObject) ((JSONObject) response.bodyAsJson().get("d")).get("results"); + String id = (String) results.get("__id"); + // Verify that the sent message is saved + SentMessageUtils.get(MASTER_TOKEN_NAME, srcCellName, HttpStatus.SC_OK, id); + // Verify that the received message is saved + ReceivedMessageUtils.get(MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); + } finally { + // Delete sent message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete received message + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); + } + } + + /** + * Normal test. + * Send message of type RoleRevoke. + * RequestRelation is RoleName. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_send_message_of_type_role_revoke_roleName() { + String messageType = TYPE_REQ_ROLE_REVOKE; + String targetCellName = Setup.TEST_CELL2; + String targetRoleName = "testRole001"; + String srcCellName = TEST_CELL1; + + // Set request body + JSONObject body = new JSONObject(); + body.put("BoxBound", false); + body.put("InReplyTo", null); + body.put("To", UrlUtils.cellRoot(targetCellName)); + body.put("ToRelation", null); + body.put("Type", messageType); + body.put("Title", "title"); + body.put("Body", "body"); + body.put("Priority", 3); + body.put("RequestRelation", targetRoleName); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + String token = MASTER_TOKEN_NAME; + + // --------------- + // Execution + // --------------- + // Send message + response = SentMessageUtils.sent(token, srcCellName, + body.toJSONString(), HttpStatus.SC_CREATED); + + // --------------- + // Verification + // --------------- + // Set expected response body + JSONObject expectedResult = new JSONObject(); + expectedResult.put("To", UrlUtils.cellRoot(targetCellName)); + expectedResult.put("Code", Integer.toString(HttpStatus.SC_CREATED)); + expectedResult.put("Reason", "Created."); + JSONArray expectedResults = new JSONArray(); + expectedResults.add(expectedResult); + JSONObject expected = new JSONObject(); + expected.put("_Box.Name", null); + expected.put("InReplyTo", null); + expected.put("To", UrlUtils.cellRoot(targetCellName)); + expected.put("ToRelation", null); + expected.put("Type", messageType); + expected.put("Title", "title"); + expected.put("Body", "body"); + expected.put("Priority", 3); + expected.put("RequestRelation", targetRoleName); + expected.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + expected.put("Result", expectedResults); + // Check response body + ODataCommon.checkResponseBody(response.bodyAsJson(), response.getLocationHeader(), + SENT_MESSAGE_TYPE, expected); + + // Get message id + JSONObject results = (JSONObject) ((JSONObject) response.bodyAsJson().get("d")).get("results"); + String id = (String) results.get("__id"); + // Verify that the sent message is saved + SentMessageUtils.get(MASTER_TOKEN_NAME, srcCellName, HttpStatus.SC_OK, id); + // Verify that the received message is saved + ReceivedMessageUtils.get(MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); + } finally { + // Delete sent message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete received message + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); + } + } + + /** + * Error test. + * Send message of type RoleRevoke. + * RequestRelation is invalid format. + */ + @SuppressWarnings("unchecked") + @Test + public final void error_send_message_of_type_role_revoke_requestRelation_invalid_format() { + String messageType = TYPE_REQ_ROLE_REVOKE; + String targetCellName = Setup.TEST_CELL2; + String targetRoleName = "testRole001"; + String srcCellName = TEST_CELL1; + + // Set request body + JSONObject body = new JSONObject(); + body.put("BoxBound", false); + body.put("InReplyTo", null); + body.put("To", UrlUtils.cellRoot(targetCellName)); + body.put("ToRelation", null); + body.put("Type", messageType); + body.put("Title", "title"); + body.put("Body", "body"); + body.put("Priority", 3); + body.put("RequestRelation", UrlUtils.roleUrl(targetCellName, "box1", targetRoleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + String token = MASTER_TOKEN_NAME; + + // --------------- + // Execution + // --------------- + // Send message + response = SentMessageUtils.sent(token, srcCellName, + body.toJSONString(), HttpStatus.SC_BAD_REQUEST); + + // --------------- + // Verification + // --------------- + // Check response body + PersoniumCoreException exception = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR + .params("RequestRelation"); + String message = (String) ((JSONObject) response.bodyAsJson().get("message")).get("value"); + assertThat(message, is(exception.getMessage())); + } finally { + // Delete sent message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete received message + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); + } + } + + /** + * Normal test. + * Send BoxBound message of type Message. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_send_boxbound_message_of_type_message() { + String messageType = TYPE_MESSAGE; + String targetCellName = Setup.TEST_CELL2; + String srcCellName = TEST_CELL1; + String appCellName = Setup.TEST_CELL_SCHEMA1; + + // Set request body + JSONObject body = new JSONObject(); + body.put("BoxBound", true); + body.put("InReplyTo", null); + body.put("To", UrlUtils.cellRoot(targetCellName)); + body.put("ToRelation", null); + body.put("Type", messageType); + body.put("Title", "title"); + body.put("Body", "body"); + body.put("Priority", 3); + body.put("RequestRelation", null); + body.put("RequestRelationTarget", null); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // Create role + RoleUtils.create(srcCellName, MASTER_TOKEN_NAME, "testRole001", HttpStatus.SC_CREATED); + // Set acl to role + Http.request("cell/acl-setting-cell-none-root.txt") + .with("url", srcCellName) + .with("token", MASTER_TOKEN_NAME) + .with("role1", "testRole001") + .with("roleBaseUrl", UrlUtils.roleResource(srcCellName, null, "")).returns() + .statusCode(HttpStatus.SC_OK); + // Set links account and role + ResourceUtils.linkAccountRole(srcCellName, MASTER_TOKEN_NAME, "account4", null, + "testRole001", HttpStatus.SC_NO_CONTENT); + + // App auth + TResponse authnRes = CellUtils.tokenAuthenticationWithTarget(appCellName, "account0", + "password0", srcCellName); + String appToken = (String) authnRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + // authz + TResponse authzRes = Http.request("authn/password-cl-cp.txt") + .with("remoteCell", srcCellName) + .with("username", "account4") + .with("password", "password4") + .with("client_id", UrlUtils.cellRoot(appCellName)) + .with("client_secret", appToken) + .returns() + .statusCode(HttpStatus.SC_OK); + String token = (String) authzRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + + // --------------- + // Execution + // --------------- + // Send message + response = SentMessageUtils.sent(token, srcCellName, + body.toJSONString(), HttpStatus.SC_CREATED); + + // --------------- + // Verification + // --------------- + // Set expected response body + JSONObject expectedResult = new JSONObject(); + expectedResult.put("To", UrlUtils.cellRoot(targetCellName)); + expectedResult.put("Code", Integer.toString(HttpStatus.SC_CREATED)); + expectedResult.put("Reason", "Created."); + JSONArray expectedResults = new JSONArray(); + expectedResults.add(expectedResult); + JSONObject expected = new JSONObject(); + expected.put("_Box.Name", Setup.TEST_BOX1); + expected.put("InReplyTo", null); + expected.put("To", UrlUtils.cellRoot(targetCellName)); + expected.put("ToRelation", null); + expected.put("Type", messageType); + expected.put("Title", "title"); + expected.put("Body", "body"); + expected.put("Priority", 3); + expected.put("RequestRelation", null); + expected.put("RequestRelationTarget", null); + expected.put("Result", expectedResults); + // Check response body + ODataCommon.checkResponseBody(response.bodyAsJson(), response.getLocationHeader(), + SENT_MESSAGE_TYPE, expected); + + // Get message id + JSONObject results = (JSONObject) ((JSONObject) response.bodyAsJson().get("d")).get("results"); + String id = (String) results.get("__id"); + // Verify that the sent message is saved + SentMessageUtils.get(MASTER_TOKEN_NAME, srcCellName, HttpStatus.SC_OK, id); + // Verify that the received message is saved + TResponse receivedResponse = ReceivedMessageUtils.get( + MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); + // Verify that boxname is stored in the received message + results = (JSONObject) ((JSONObject) receivedResponse.bodyAsJson().get("d")).get("results"); + assertThat((String) results.get("_Box.Name"), is(Setup.TEST_BOX1)); + } finally { + // Delete sent message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete received message + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); + // Delete Role and Account $links + ResourceUtils.linkAccountRollDelete(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001"); + // Delete role + RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, "testRole001", null, -1); + } + } + + /** + * Normal test. + * Send BoxBound message of type RelationBuild. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_send_boxbound_message_of_type_relation_build() { + String messageType = TYPE_REQ_RELATION_BUILD; + String targetCellName = Setup.TEST_CELL2; + String targetRelationName = "testRelation001"; + String srcCellName = TEST_CELL1; + String appCellName = Setup.TEST_CELL_SCHEMA1; + + // Set request body + JSONObject body = new JSONObject(); + body.put("BoxBound", true); + body.put("InReplyTo", null); + body.put("To", UrlUtils.cellRoot(targetCellName)); + body.put("ToRelation", null); + body.put("Type", messageType); + body.put("Title", "title"); + body.put("Body", "body"); + body.put("Priority", 3); + body.put("RequestRelation", UrlUtils.relationClassUrl(appCellName, targetRelationName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // Create role + RoleUtils.create(srcCellName, MASTER_TOKEN_NAME, "testRole001", HttpStatus.SC_CREATED); + // Set acl to role + Http.request("cell/acl-setting-cell-none-root.txt") + .with("url", srcCellName) + .with("token", MASTER_TOKEN_NAME) + .with("role1", "testRole001") + .with("roleBaseUrl", UrlUtils.roleResource(srcCellName, null, "")).returns() + .statusCode(HttpStatus.SC_OK); + // Set links account and role + ResourceUtils.linkAccountRole(srcCellName, MASTER_TOKEN_NAME, "account4", null, + "testRole001", HttpStatus.SC_NO_CONTENT); + + // App auth + TResponse authnRes = CellUtils.tokenAuthenticationWithTarget(appCellName, "account0", + "password0", srcCellName); + String appToken = (String) authnRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + // authz + TResponse authzRes = Http.request("authn/password-cl-cp.txt") + .with("remoteCell", srcCellName) + .with("username", "account4") + .with("password", "password4") + .with("client_id", UrlUtils.cellRoot(appCellName)) + .with("client_secret", appToken) + .returns() + .statusCode(HttpStatus.SC_OK); + String token = (String) authzRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + + // --------------- + // Execution + // --------------- + // Send message + response = SentMessageUtils.sent(token, srcCellName, + body.toJSONString(), HttpStatus.SC_CREATED); + + // --------------- + // Verification + // --------------- + // Set expected response body + JSONObject expectedResult = new JSONObject(); + expectedResult.put("To", UrlUtils.cellRoot(targetCellName)); + expectedResult.put("Code", Integer.toString(HttpStatus.SC_CREATED)); + expectedResult.put("Reason", "Created."); + JSONArray expectedResults = new JSONArray(); + expectedResults.add(expectedResult); + JSONObject expected = new JSONObject(); + expected.put("_Box.Name", Setup.TEST_BOX1); + expected.put("InReplyTo", null); + expected.put("To", UrlUtils.cellRoot(targetCellName)); + expected.put("ToRelation", null); + expected.put("Type", messageType); + expected.put("Title", "title"); + expected.put("Body", "body"); + expected.put("Priority", 3); + expected.put("RequestRelation", UrlUtils.relationClassUrl(appCellName, targetRelationName)); + expected.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + expected.put("Result", expectedResults); + // Check response body + ODataCommon.checkResponseBody(response.bodyAsJson(), response.getLocationHeader(), + SENT_MESSAGE_TYPE, expected); + + // Get message id + JSONObject results = (JSONObject) ((JSONObject) response.bodyAsJson().get("d")).get("results"); + String id = (String) results.get("__id"); + // Verify that the sent message is saved + SentMessageUtils.get(MASTER_TOKEN_NAME, srcCellName, HttpStatus.SC_OK, id); + // Verify that the received message is saved + TResponse receivedResponse = ReceivedMessageUtils.get( + MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); + // Verify that boxname is stored in the received message + results = (JSONObject) ((JSONObject) receivedResponse.bodyAsJson().get("d")).get("results"); + assertThat((String) results.get("_Box.Name"), is(Setup.TEST_BOX1)); + } finally { + // Delete sent message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete received message + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); + // Delete Role and Account $links + ResourceUtils.linkAccountRollDelete(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001"); + // Delete role + RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, "testRole001", null, -1); + } + } + + /** + * Normal test. + * Send BoxBound message of type RelationBreak. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_send_boxbound_message_of_type_relation_break() { + String messageType = TYPE_REQ_RELATION_BREAK; + String targetCellName = Setup.TEST_CELL2; + String targetRelationName = "testRelation001"; + String srcCellName = TEST_CELL1; + String appCellName = Setup.TEST_CELL_SCHEMA1; + + // Set request body + JSONObject body = new JSONObject(); + body.put("BoxBound", true); + body.put("InReplyTo", null); + body.put("To", UrlUtils.cellRoot(targetCellName)); + body.put("ToRelation", null); + body.put("Type", messageType); + body.put("Title", "title"); + body.put("Body", "body"); + body.put("Priority", 3); + body.put("RequestRelation", UrlUtils.relationClassUrl(appCellName, targetRelationName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // Create role + RoleUtils.create(srcCellName, MASTER_TOKEN_NAME, "testRole001", HttpStatus.SC_CREATED); + // Set acl to role + Http.request("cell/acl-setting-cell-none-root.txt") + .with("url", srcCellName) + .with("token", MASTER_TOKEN_NAME) + .with("role1", "testRole001") + .with("roleBaseUrl", UrlUtils.roleResource(srcCellName, null, "")).returns() + .statusCode(HttpStatus.SC_OK); + // Set links account and role + ResourceUtils.linkAccountRole(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001", + HttpStatus.SC_NO_CONTENT); + + // App auth + TResponse authnRes = CellUtils.tokenAuthenticationWithTarget(appCellName, "account0", "password0", + srcCellName); + String appToken = (String) authnRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + // authz + TResponse authzRes = Http.request("authn/password-cl-cp.txt") + .with("remoteCell", srcCellName) + .with("username", "account4") + .with("password", "password4") + .with("client_id", UrlUtils.cellRoot(appCellName)) + .with("client_secret", appToken) + .returns() + .statusCode(HttpStatus.SC_OK); + String token = (String) authzRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + + // --------------- + // Execution + // --------------- + // Send message + response = SentMessageUtils.sent(token, srcCellName, + body.toJSONString(), HttpStatus.SC_CREATED); + + // --------------- + // Verification + // --------------- + // Set expected response body + JSONObject expectedResult = new JSONObject(); + expectedResult.put("To", UrlUtils.cellRoot(targetCellName)); + expectedResult.put("Code", Integer.toString(HttpStatus.SC_CREATED)); + expectedResult.put("Reason", "Created."); + JSONArray expectedResults = new JSONArray(); + expectedResults.add(expectedResult); + JSONObject expected = new JSONObject(); + expected.put("_Box.Name", Setup.TEST_BOX1); + expected.put("InReplyTo", null); + expected.put("To", UrlUtils.cellRoot(targetCellName)); + expected.put("ToRelation", null); + expected.put("Type", messageType); + expected.put("Title", "title"); + expected.put("Body", "body"); + expected.put("Priority", 3); + expected.put("RequestRelation", UrlUtils.relationClassUrl(appCellName, targetRelationName)); + expected.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + expected.put("Result", expectedResults); + // Check response body + ODataCommon.checkResponseBody(response.bodyAsJson(), response.getLocationHeader(), + SENT_MESSAGE_TYPE, expected); + + // Get message id + JSONObject results = (JSONObject) ((JSONObject) response.bodyAsJson().get("d")).get("results"); + String id = (String) results.get("__id"); + // Verify that the sent message is saved + SentMessageUtils.get(MASTER_TOKEN_NAME, srcCellName, HttpStatus.SC_OK, id); + // Verify that the received message is saved + TResponse receivedResponse = ReceivedMessageUtils.get( + MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); + // Verify that boxname is stored in the received message + results = (JSONObject) ((JSONObject) receivedResponse.bodyAsJson().get("d")).get("results"); + assertThat((String) results.get("_Box.Name"), is(Setup.TEST_BOX1)); + } finally { + // Delete sent message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete received message + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); + // Delete Role and Account $links + ResourceUtils.linkAccountRollDelete(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001"); + // Delete role + RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, "testRole001", null, -1); + } + } + + /** + * Normal test. + * Send BoxBound message of type RoleGrant. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_send_boxbound_message_of_type_role_grant() { + String messageType = TYPE_REQ_ROLE_GRANT; + String targetCellName = Setup.TEST_CELL2; + String targetRoleName = "testRole002"; + String srcCellName = TEST_CELL1; + String appCellName = Setup.TEST_CELL_SCHEMA1; + + // Set request body + JSONObject body = new JSONObject(); + body.put("BoxBound", true); + body.put("InReplyTo", null); + body.put("To", UrlUtils.cellRoot(targetCellName)); + body.put("ToRelation", null); + body.put("Type", messageType); + body.put("Title", "title"); + body.put("Body", "body"); + body.put("Priority", 3); + body.put("RequestRelation", UrlUtils.roleClassUrl(appCellName, targetRoleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // Create role + RoleUtils.create(srcCellName, MASTER_TOKEN_NAME, "testRole001", HttpStatus.SC_CREATED); + // Set acl to role + Http.request("cell/acl-setting-cell-none-root.txt") + .with("url", srcCellName) + .with("token", MASTER_TOKEN_NAME) + .with("role1", "testRole001") + .with("roleBaseUrl", UrlUtils.roleResource(srcCellName, null, "")).returns() + .statusCode(HttpStatus.SC_OK); + // Set links account and role + ResourceUtils.linkAccountRole(srcCellName, MASTER_TOKEN_NAME, "account4", null, + "testRole001", HttpStatus.SC_NO_CONTENT); + + // App auth + TResponse authnRes = CellUtils.tokenAuthenticationWithTarget(appCellName, "account0", + "password0", srcCellName); + String appToken = (String) authnRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + // authz + TResponse authzRes = Http.request("authn/password-cl-cp.txt") + .with("remoteCell", srcCellName) + .with("username", "account4") + .with("password", "password4") + .with("client_id", UrlUtils.cellRoot(appCellName)) + .with("client_secret", appToken) + .returns() + .statusCode(HttpStatus.SC_OK); + String token = (String) authzRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + + // --------------- + // Execution + // --------------- + // Send message + response = SentMessageUtils.sent(token, srcCellName, + body.toJSONString(), HttpStatus.SC_CREATED); + + // --------------- + // Verification + // --------------- + // Set expected response body + JSONObject expectedResult = new JSONObject(); + expectedResult.put("To", UrlUtils.cellRoot(targetCellName)); + expectedResult.put("Code", Integer.toString(HttpStatus.SC_CREATED)); + expectedResult.put("Reason", "Created."); + JSONArray expectedResults = new JSONArray(); + expectedResults.add(expectedResult); + JSONObject expected = new JSONObject(); + expected.put("_Box.Name", Setup.TEST_BOX1); + expected.put("InReplyTo", null); + expected.put("To", UrlUtils.cellRoot(targetCellName)); + expected.put("ToRelation", null); + expected.put("Type", messageType); + expected.put("Title", "title"); + expected.put("Body", "body"); + expected.put("Priority", 3); + expected.put("RequestRelation", UrlUtils.roleClassUrl(appCellName, targetRoleName)); + expected.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + expected.put("Result", expectedResults); + // Check response body + ODataCommon.checkResponseBody(response.bodyAsJson(), response.getLocationHeader(), + SENT_MESSAGE_TYPE, expected); + + // Get message id + JSONObject results = (JSONObject) ((JSONObject) response.bodyAsJson().get("d")).get("results"); + String id = (String) results.get("__id"); + // Verify that the sent message is saved + SentMessageUtils.get(MASTER_TOKEN_NAME, srcCellName, HttpStatus.SC_OK, id); + // Verify that the received message is saved + TResponse receivedResponse = ReceivedMessageUtils.get( + MASTER_TOKEN_NAME, targetCellName, HttpStatus.SC_OK, id); + // Verify that boxname is stored in the received message + results = (JSONObject) ((JSONObject) receivedResponse.bodyAsJson().get("d")).get("results"); + assertThat((String) results.get("_Box.Name"), is(Setup.TEST_BOX1)); + } finally { + // Delete sent message + if (response != null) { + deleteOdataResource(response.getLocationHeader()); + } + // Delete received message + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); + // Delete Role and Account $links + ResourceUtils.linkAccountRollDelete(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001"); + // Delete role + RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, "testRole001", null, -1); + } + } + + /** + * Normal test. + * Send BoxBound message of type RoleRevoke. + */ + @SuppressWarnings("unchecked") + @Test + public final void normal_send_boxbound_message_of_type_role_revoke() { + String messageType = TYPE_REQ_ROLE_REVOKE; + String targetCellName = Setup.TEST_CELL2; + String targetRoleName = "testRole002"; + String srcCellName = TEST_CELL1; + String appCellName = Setup.TEST_CELL_SCHEMA1; + + // Set request body + JSONObject body = new JSONObject(); + body.put("BoxBound", true); + body.put("InReplyTo", null); + body.put("To", UrlUtils.cellRoot(targetCellName)); + body.put("ToRelation", null); + body.put("Type", messageType); + body.put("Title", "title"); + body.put("Body", "body"); + body.put("Priority", 3); + body.put("RequestRelation", UrlUtils.roleClassUrl(appCellName, targetRoleName)); + body.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); + + TResponse response = null; + try { + // --------------- + // Preparation + // --------------- + // Create role + RoleUtils.create(srcCellName, MASTER_TOKEN_NAME, "testRole001", HttpStatus.SC_CREATED); + // Set acl to role + Http.request("cell/acl-setting-cell-none-root.txt") + .with("url", srcCellName) + .with("token", MASTER_TOKEN_NAME) + .with("role1", "testRole001") + .with("roleBaseUrl", UrlUtils.roleResource(srcCellName, null, "")).returns() + .statusCode(HttpStatus.SC_OK); + // Set links account and role + ResourceUtils.linkAccountRole(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001", + HttpStatus.SC_NO_CONTENT); + + // App auth + TResponse authnRes = CellUtils.tokenAuthenticationWithTarget(appCellName, "account0", "password0", + srcCellName); + String appToken = (String) authnRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + // authz + TResponse authzRes = Http.request("authn/password-cl-cp.txt") + .with("remoteCell", srcCellName) + .with("username", "account4") + .with("password", "password4") + .with("client_id", UrlUtils.cellRoot(appCellName)) + .with("client_secret", appToken) + .returns() + .statusCode(HttpStatus.SC_OK); + String token = (String) authzRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + + // --------------- + // Execution + // --------------- + // Send message + response = SentMessageUtils.sent(token, srcCellName, + body.toJSONString(), HttpStatus.SC_CREATED); + + // --------------- + // Verification + // --------------- + // Set expected response body + JSONObject expectedResult = new JSONObject(); + expectedResult.put("To", UrlUtils.cellRoot(targetCellName)); + expectedResult.put("Code", Integer.toString(HttpStatus.SC_CREATED)); + expectedResult.put("Reason", "Created."); + JSONArray expectedResults = new JSONArray(); + expectedResults.add(expectedResult); + JSONObject expected = new JSONObject(); + expected.put("_Box.Name", Setup.TEST_BOX1); + expected.put("InReplyTo", null); + expected.put("To", UrlUtils.cellRoot(targetCellName)); + expected.put("ToRelation", null); + expected.put("Type", messageType); + expected.put("Title", "title"); + expected.put("Body", "body"); + expected.put("Priority", 3); + expected.put("RequestRelation", UrlUtils.roleClassUrl(appCellName, targetRoleName)); expected.put("RequestRelationTarget", UrlUtils.cellRoot(srcCellName)); expected.put("Result", expectedResults); // Check response body @@ -1659,11 +2524,11 @@ public final void normal_send_boxbound_message_of_type_relation_break() { deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), REQ_RELATION_BREAK, "title", "body"); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), messageType, "title", "body"); // Delete Role and Account $links ResourceUtils.linkAccountRollDelete(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001"); // Delete role - RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, null, "testRole001", -1); + RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, "testRole001", null, -1); } } @@ -1686,7 +2551,7 @@ public final void error_send_boxbound_message_box_not_exists_on_sender() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -1752,7 +2617,7 @@ public final void error_send_boxbound_message_box_not_exists_on_sender() { deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), MESSAGE, "title", "body"); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), TYPE_MESSAGE, "title", "body"); // Delete Account AccountUtils.delete(appCellName, MASTER_TOKEN_NAME, "account0", -1); // Delete Cell @@ -1760,7 +2625,7 @@ public final void error_send_boxbound_message_box_not_exists_on_sender() { // Delete Role and Account $links ResourceUtils.linkAccountRollDelete(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001"); // Delete role - RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, null, "testRole001", -1); + RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, "testRole001", null, -1); } } @@ -1783,7 +2648,7 @@ public final void error_send_boxbound_message_box_not_exists_on_receiver() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCellName)); body.put("ToRelation", null); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -1855,7 +2720,7 @@ public final void error_send_boxbound_message_box_not_exists_on_receiver() { expected.put("InReplyTo", null); expected.put("To", UrlUtils.cellRoot(targetCellName)); expected.put("ToRelation", null); - expected.put("Type", MESSAGE); + expected.put("Type", TYPE_MESSAGE); expected.put("Title", "title"); expected.put("Body", "body"); expected.put("Priority", 3); @@ -1879,7 +2744,7 @@ public final void error_send_boxbound_message_box_not_exists_on_receiver() { deleteOdataResource(response.getLocationHeader()); } // Delete received message - deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), MESSAGE, "title", "body"); + deleteReceivedMessage(targetCellName, UrlUtils.cellRoot(srcCellName), TYPE_MESSAGE, "title", "body"); // Delete Box BoxUtils.delete(srcCellName, MASTER_TOKEN_NAME, "testBox001", -1); // Delete Account @@ -1889,7 +2754,7 @@ public final void error_send_boxbound_message_box_not_exists_on_receiver() { // Delete Role and Account $links ResourceUtils.linkAccountRollDelete(srcCellName, MASTER_TOKEN_NAME, "account4", null, "testRole001"); // Delete role - RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, null, "testRole001", -1); + RoleUtils.delete(srcCellName, MASTER_TOKEN_NAME, "testRole001", null, -1); } } @@ -1905,7 +2770,7 @@ public final void error_send_boxbound_message_box_not_exists_on_receiver() { body.put("BoxBound", false); body.put("InReplyTo", null); body.put("ToRelation", "norelation"); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -1947,7 +2812,7 @@ public final void error_send_boxbound_message_box_not_exists_on_receiver() { body.put("BoxBound", false); body.put("InReplyTo", null); body.put("ToRelation", relationName); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); @@ -1992,7 +2857,7 @@ public final void error_send_boxbound_message_box_not_exists_on_receiver() { body.put("InReplyTo", null); body.put("To", UrlUtils.cellRoot(targetCell)); body.put("ToRelation", null); - body.put("Type", MESSAGE); + body.put("Type", TYPE_MESSAGE); body.put("Title", "title"); body.put("Body", "body"); body.put("Priority", 3); diff --git a/src/test/java/io/personium/test/jersey/cell/UnitUserCellCRUDTest.java b/src/test/java/io/personium/test/jersey/cell/UnitUserCellCRUDTest.java index cd9597e96..43e8c012d 100644 --- a/src/test/java/io/personium/test/jersey/cell/UnitUserCellCRUDTest.java +++ b/src/test/java/io/personium/test/jersey/cell/UnitUserCellCRUDTest.java @@ -197,8 +197,8 @@ public void after() { UNIT_USER_ACCOUNT, UNIT_USER_ACCOUNT_PASS, HttpStatus.SC_CREATED); // ロール追加(ユニットアドミンロール) - RoleUtils.create(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, null, - UNIT_ADMIN_ROLE, HttpStatus.SC_CREATED); + RoleUtils.create(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, UNIT_ADMIN_ROLE, + null, HttpStatus.SC_CREATED); // ロール結びつけ(BOXに結びつかないロールとアカウント結びつけ) ResourceUtils.linkAccountRole(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, @@ -238,7 +238,7 @@ public void after() { ResourceUtils.linkAccountRollDelete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, UNIT_USER_ACCOUNT, null, UNIT_ADMIN_ROLE); // ロール削除(BOXに結びつかない) - RoleUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, null, UNIT_ADMIN_ROLE); + RoleUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, UNIT_ADMIN_ROLE, null); // アカウント削除 AccountUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, UNIT_USER_ACCOUNT, -1); diff --git a/src/test/java/io/personium/test/jersey/cell/auth/AuthAccountUpdateTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthAccountUpdateTest.java index 99593fbef..2f5072a58 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/AuthAccountUpdateTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/AuthAccountUpdateTest.java @@ -21,6 +21,8 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import com.sun.jersey.test.framework.JerseyTest; + import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; @@ -36,7 +38,6 @@ import io.personium.test.utils.Http; import io.personium.test.utils.ResourceUtils; import io.personium.test.utils.RoleUtils; -import com.sun.jersey.test.framework.JerseyTest; /** * 認証(Account名更新)のテスト. @@ -111,7 +112,7 @@ public AuthAccountUpdateTest() { ResourceUtils.linkAccountRollDelete(cellName, AbstractCase.MASTER_TOKEN_NAME, accountNameUpdated, null, roleName); // Roleの削除 - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, roleName, null, -1); // Accountの削除 AccountUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, accountNameUpdated, -1); AccountUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, accountName, -1); @@ -179,7 +180,7 @@ public AuthAccountUpdateTest() { ResourceUtils.linkAccountRollDelete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, accountNameUpdated, null, roleName); // Roleの削除 - RoleUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, roleName, null, -1); // Accountの削除 AccountUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, accountNameUpdated, -1); AccountUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, accountName, -1); @@ -238,7 +239,7 @@ public AuthAccountUpdateTest() { DavResourceUtils.setACL(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_OK, "", "box/acl-authtest.txt", Setup.TEST_BOX1, ""); // Roleの削除 - RoleUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, roleName, null, -1); // Accountの削除 AccountUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, accountNameUpdated, -1); AccountUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, accountName, -1); @@ -345,7 +346,7 @@ public AuthAccountUpdateTest() { ResourceUtils.linkAccountRollDelete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, accountNameUpdated, null, roleName); // Roleの削除 - RoleUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, roleName, null, -1); // Accountの削除 AccountUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, accountNameUpdated, -1); AccountUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, accountName, -1); diff --git a/src/test/java/io/personium/test/jersey/cell/auth/AuthBasicTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthBasicTest.java index 19cfb11e4..89eeeb636 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/AuthBasicTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/AuthBasicTest.java @@ -35,13 +35,16 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import com.sun.jersey.test.framework.JerseyTest; +import com.sun.jersey.test.framework.WebAppDescriptor; + import io.personium.core.PersoniumCoreAuthzException; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; import io.personium.test.jersey.AbstractCase; -import io.personium.test.jersey.PersoniumIntegTestRunner; import io.personium.test.jersey.ODataCommon; +import io.personium.test.jersey.PersoniumIntegTestRunner; import io.personium.test.jersey.box.acl.jaxb.Acl; import io.personium.test.setup.Setup; import io.personium.test.unit.core.UrlUtils; @@ -55,8 +58,6 @@ import io.personium.test.utils.RoleUtils; import io.personium.test.utils.TResponse; import io.personium.test.utils.UserDataUtils; -import com.sun.jersey.test.framework.JerseyTest; -import com.sun.jersey.test.framework.WebAppDescriptor; /** * Basic認証のテスト. @@ -490,7 +491,7 @@ private void createBaseData() throws JAXBException { DavResourceUtils.createODataCollection(AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_CREATED, MY_CELL, TEST_BOX1, TEST_ODATA); // 認証に必要な情報 - RoleUtils.create(MY_CELL, AbstractCase.MASTER_TOKEN_NAME, TEST_BOX1, TEST_ROLE, HttpStatus.SC_CREATED); + RoleUtils.create(MY_CELL, AbstractCase.MASTER_TOKEN_NAME, TEST_ROLE, TEST_BOX1, HttpStatus.SC_CREATED); AccountUtils.create(AbstractCase.MASTER_TOKEN_NAME, MY_CELL, TEST_ACCOUNT, TEST_ACCOUNT_PASSWORD, HttpStatus.SC_CREATED); AccountUtils.createLinkWithRole(AbstractCase.MASTER_TOKEN_NAME, MY_CELL, TEST_BOX1, TEST_ACCOUNT, diff --git a/src/test/java/io/personium/test/jersey/cell/auth/AuthCheckTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthCheckTest.java index ae19306fc..c752e0dee 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/AuthCheckTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/AuthCheckTest.java @@ -137,8 +137,8 @@ public AuthCheckTest() { userName, pass, HttpStatus.SC_CREATED); // ロール追加(BOXに結びつかない) - RoleUtils.create(testCellName, AbstractCase.MASTER_TOKEN_NAME, null, - roleNameNoneBox, HttpStatus.SC_CREATED); + RoleUtils.create(testCellName, AbstractCase.MASTER_TOKEN_NAME, roleNameNoneBox, + null, HttpStatus.SC_CREATED); // ロール結びつけ(BOXに結びつかないロールとアカウント結びつけ) ResourceUtils.linkAccountRole(testCellName, AbstractCase.MASTER_TOKEN_NAME, @@ -170,7 +170,7 @@ public AuthCheckTest() { AccountUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, userName, HttpStatus.SC_NO_CONTENT); // ロール削除(BOXに結びつかない) - RoleUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, null, roleNameNoneBox); + RoleUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, roleNameNoneBox, null); // 本テスト用セルの削除 CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, testCellName, -1); @@ -209,8 +209,8 @@ public AuthCheckTest() { userName, pass, HttpStatus.SC_CREATED); // ロール追加(スキーマありBOXに結びつつく) - RoleUtils.create(testCellName, AbstractCase.MASTER_TOKEN_NAME, boxNameWithScheme, - roleNameWithBox2, HttpStatus.SC_CREATED); + RoleUtils.create(testCellName, AbstractCase.MASTER_TOKEN_NAME, roleNameWithBox2, + boxNameWithScheme, HttpStatus.SC_CREATED); // ロール結びつけ(スキーマありBOXに結びつくロールとアカウント結びつけ) ResourceUtils.linkAccountRole(testCellName, AbstractCase.MASTER_TOKEN_NAME, userName, @@ -242,7 +242,7 @@ public AuthCheckTest() { AccountUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, userName, HttpStatus.SC_NO_CONTENT); // ロール削除(スキーマありBOXに結びつつく) - RoleUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, boxNameWithScheme, roleNameWithBox2); + RoleUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, roleNameWithBox2, boxNameWithScheme); // Box削除(スキーマあり) BoxUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, boxNameWithScheme); // 本テスト用セルの削除 @@ -279,8 +279,8 @@ public AuthCheckTest() { userName, pass, HttpStatus.SC_CREATED); // ロール追加(スキーマなしBOXに結びつつく) - RoleUtils.create(testCellName, AbstractCase.MASTER_TOKEN_NAME, boxNameNoneScheme, - roleNameWithBox1, HttpStatus.SC_CREATED); + RoleUtils.create(testCellName, AbstractCase.MASTER_TOKEN_NAME, roleNameWithBox1, + boxNameNoneScheme, HttpStatus.SC_CREATED); // ロール結びつけ(スキーマなしBOXに結びつくロールとアカウント結びつけ) ResourceUtils.linkAccountRole(testCellName, AbstractCase.MASTER_TOKEN_NAME, userName, @@ -314,7 +314,7 @@ public AuthCheckTest() { userName, HttpStatus.SC_NO_CONTENT); // ロール削除(スキーマなしBOXに結びつつく) - RoleUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, boxNameNoneScheme, roleNameWithBox1); + RoleUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, roleNameWithBox1, boxNameNoneScheme); // Box削除(スキーマ無し) BoxUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, boxNameNoneScheme); @@ -358,7 +358,7 @@ public AuthCheckTest() { AccountUtils.create(AbstractCase.MASTER_TOKEN_NAME, testCellName3, userName3, pass, HttpStatus.SC_CREATED); // Cell1のロールを作成する - RoleUtils.create(testCellName1, masterToken, null, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(testCellName1, masterToken, roleName, null, HttpStatus.SC_CREATED); // Cell1のExtCellを作成する ExtCellUtils.create(masterToken, testCellName1, UrlUtils.cellRoot(testCellName2)); // Cell1にRelationを作成する @@ -408,7 +408,7 @@ public AuthCheckTest() { // Cell2のアカウント削除 AccountUtils.delete(testCellName2, masterToken, userName2, HttpStatus.SC_NO_CONTENT); // Cell1のロール削除 - RoleUtils.delete(testCellName1, masterToken, null, roleName); + RoleUtils.delete(testCellName1, masterToken, roleName, null); // 本テスト用セルの削除(Cell1) CellUtils.delete(masterToken, testCellName1, -1); // 本テスト用セルの削除(Cell2) @@ -443,23 +443,23 @@ public AuthCheckTest() { AccountUtils.create(AbstractCase.MASTER_TOKEN_NAME, CELL_NAME2, USER_NAME4, PASSWORD, HttpStatus.SC_CREATED); // Cell2のユーザ1用のロール作成及び結びつけ - RoleUtils.create(CELL_NAME2, masterToken, BOX_NAME1, ROLE_NAME1, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME2, masterToken, ROLE_NAME1, BOX_NAME1, HttpStatus.SC_CREATED); ResourceUtils.linkAccountRole(CELL_NAME2, masterToken, USER_NAME1, BOX_NAME1, ROLE_NAME1, HttpStatus.SC_NO_CONTENT); // Cell2のユーザ2用のロール作成及び結びつけ - RoleUtils.create(CELL_NAME2, masterToken, null, ROLE_NAME2, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME2, masterToken, ROLE_NAME2, null, HttpStatus.SC_CREATED); ResourceUtils.linkAccountRole(CELL_NAME2, masterToken, USER_NAME2, null, ROLE_NAME2, HttpStatus.SC_NO_CONTENT); // Cell2のユーザ3用のロール作成及び結びつけ - RoleUtils.create(CELL_NAME2, masterToken, null, ROLE_NAME3, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME2, masterToken, ROLE_NAME3, null, HttpStatus.SC_CREATED); ResourceUtils.linkAccountRole(CELL_NAME2, masterToken, USER_NAME3, null, ROLE_NAME3, HttpStatus.SC_NO_CONTENT); // Cell2のユーザ4用のロール作成及び結びつけ - RoleUtils.create(CELL_NAME2, masterToken, BOX_NAME2, ROLE_NAME4, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME2, masterToken, ROLE_NAME4, BOX_NAME2, HttpStatus.SC_CREATED); ResourceUtils.linkAccountRole(CELL_NAME2, masterToken, USER_NAME4, BOX_NAME2, ROLE_NAME4, HttpStatus.SC_NO_CONTENT); // Cell1のロールを作成する - RoleUtils.create(CELL_NAME1, masterToken, null, ROLE_NAME, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME1, masterToken, ROLE_NAME, null, HttpStatus.SC_CREATED); // Cell1のExtCellを作成する ExtCellUtils.create(masterToken, CELL_NAME1, UrlUtils.cellRoot(CELL_NAME2)); // Cell1にRelationを作成する @@ -550,16 +550,16 @@ public AuthCheckTest() { ExtCellUtils.delete(masterToken, CELL_NAME1, UrlUtils.cellRoot(CELL_NAME2), HttpStatus.SC_NO_CONTENT); // Cell1のロール削除 - RoleUtils.delete(CELL_NAME1, masterToken, null, ROLE_NAME); + RoleUtils.delete(CELL_NAME1, masterToken, ROLE_NAME, null); // Cell2のユーザのロール結びつけ削除 ResourceUtils.linkAccountRollDelete(CELL_NAME2, masterToken, USER_NAME4, BOX_NAME2, ROLE_NAME4); - RoleUtils.delete(CELL_NAME2, masterToken, BOX_NAME2, ROLE_NAME4); + RoleUtils.delete(CELL_NAME2, masterToken, ROLE_NAME4, BOX_NAME2); ResourceUtils.linkAccountRollDelete(CELL_NAME2, masterToken, USER_NAME3, null, ROLE_NAME3); - RoleUtils.delete(CELL_NAME2, masterToken, null, ROLE_NAME3); + RoleUtils.delete(CELL_NAME2, masterToken, ROLE_NAME3, null); ResourceUtils.linkAccountRollDelete(CELL_NAME2, masterToken, USER_NAME2, null, ROLE_NAME2); - RoleUtils.delete(CELL_NAME2, masterToken, null, ROLE_NAME2); + RoleUtils.delete(CELL_NAME2, masterToken, ROLE_NAME2, null); ResourceUtils.linkAccountRollDelete(CELL_NAME2, masterToken, USER_NAME1, BOX_NAME1, ROLE_NAME1); - RoleUtils.delete(CELL_NAME2, masterToken, BOX_NAME1, ROLE_NAME1); + RoleUtils.delete(CELL_NAME2, masterToken, ROLE_NAME1, BOX_NAME1); // Cell2のアカウント削除 AccountUtils.delete(CELL_NAME2, masterToken, USER_NAME4, HttpStatus.SC_NO_CONTENT); AccountUtils.delete(CELL_NAME2, masterToken, USER_NAME3, HttpStatus.SC_NO_CONTENT); @@ -590,7 +590,7 @@ public AuthCheckTest() { AccountUtils.create(AbstractCase.MASTER_TOKEN_NAME, TEST_CELL1, userName, pass, HttpStatus.SC_CREATED); // Boxに紐付くロールの作成 - RoleUtils.create(TEST_CELL1, masterToken, boxName, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, masterToken, roleName, boxName, HttpStatus.SC_CREATED); // RoleとAccountの結びつけ ResourceUtils.linkAccountRole(TEST_CELL1, masterToken, userName, boxName, roleName, HttpStatus.SC_NO_CONTENT); @@ -609,7 +609,7 @@ public AuthCheckTest() { // RoleとAccountの結びつけの削除 ResourceUtils.linkAccountRollDelete(TEST_CELL1, masterToken, userName, boxName, roleName); // Roleの削除 - RoleUtils.delete(TEST_CELL1, masterToken, boxName, roleName); + RoleUtils.delete(TEST_CELL1, masterToken, roleName, boxName); // Accountの削除 AccountUtils.delete(TEST_CELL1, masterToken, userName, HttpStatus.SC_NO_CONTENT); } @@ -634,9 +634,9 @@ public AuthCheckTest() { AccountUtils.create(AbstractCase.MASTER_TOKEN_NAME, TEST_CELL1, userName.toUpperCase(), pass, HttpStatus.SC_CREATED); // Boxに紐付くロールの作成 (小文字) - RoleUtils.create(TEST_CELL1, masterToken, boxName, roleName.toLowerCase(), HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, masterToken, roleName.toLowerCase(), boxName, HttpStatus.SC_CREATED); // Boxに紐付くロールの作成 (大文字) - RoleUtils.create(TEST_CELL1, masterToken, boxName, roleName.toUpperCase(), HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, masterToken, roleName.toUpperCase(), boxName, HttpStatus.SC_CREATED); // RoleとAccountの結びつけ(小文字) ResourceUtils.linkAccountRole(TEST_CELL1, masterToken, userName.toLowerCase(), boxName, roleName.toLowerCase(), HttpStatus.SC_NO_CONTENT); @@ -686,8 +686,8 @@ public AuthCheckTest() { ResourceUtils.linkAccountRollDelete(TEST_CELL1, masterToken, userName.toUpperCase(), boxName, roleName.toUpperCase()); // Roleの削除 - RoleUtils.delete(TEST_CELL1, masterToken, boxName, roleName.toLowerCase()); - RoleUtils.delete(TEST_CELL1, masterToken, boxName, roleName.toUpperCase()); + RoleUtils.delete(TEST_CELL1, masterToken, roleName.toLowerCase(), boxName); + RoleUtils.delete(TEST_CELL1, masterToken, roleName.toUpperCase(), boxName); // Accountの削除 AccountUtils.delete(TEST_CELL1, masterToken, userName.toLowerCase(), HttpStatus.SC_NO_CONTENT); AccountUtils.delete(TEST_CELL1, masterToken, userName.toUpperCase(), HttpStatus.SC_NO_CONTENT); @@ -724,8 +724,8 @@ public AuthCheckTest() { userName, pass, HttpStatus.SC_CREATED); // ロール追加(スキーマなしBOXに結びつつく) - RoleUtils.create(testCellName, AbstractCase.MASTER_TOKEN_NAME, boxNameNoneScheme, - roleNameWithBox1, HttpStatus.SC_CREATED); + RoleUtils.create(testCellName, AbstractCase.MASTER_TOKEN_NAME, roleNameWithBox1, + boxNameNoneScheme, HttpStatus.SC_CREATED); // ロール結びつけ(スキーマなしBOXに結びつくロールとアカウント結びつけ) ResourceUtils.linkAccountRole(testCellName, AbstractCase.MASTER_TOKEN_NAME, userName, @@ -743,7 +743,7 @@ public AuthCheckTest() { // ロール RoleUtils.create(testCellName2, AbstractCase.MASTER_TOKEN_NAME, - boxNameNoneScheme, roleNameWithBox1, HttpStatus.SC_CREATED); + roleNameWithBox1, boxNameNoneScheme, HttpStatus.SC_CREATED); // extCellとロールの結びつけ ResourceUtils.linkExtCelltoRole(PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot(testCellName)), @@ -795,10 +795,10 @@ public AuthCheckTest() { AccountUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, userName, -1); // ロール削除 - RoleUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, boxNameNoneScheme, - roleNameWithBox1, -1); + RoleUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, roleNameWithBox1, + boxNameNoneScheme, -1); RoleUtils.delete(testCellName2, AbstractCase.MASTER_TOKEN_NAME, - boxNameNoneScheme, roleNameWithBox1, -1); + roleNameWithBox1, boxNameNoneScheme, -1); // Box削除 BoxUtils.delete(testCellName, AbstractCase.MASTER_TOKEN_NAME, boxNameNoneScheme, -1); @@ -859,8 +859,8 @@ public AuthCheckTest() { AccountUtils.create(AbstractCase.MASTER_TOKEN_NAME, TEST_CELL1, notDelRoleUser, pass, HttpStatus.SC_CREATED); // Boxに紐付くロールの作成 - RoleUtils.create(TEST_CELL1, masterToken, Setup.TEST_BOX1, roleNotDelete, HttpStatus.SC_CREATED); - RoleUtils.create(TEST_CELL1, masterToken, Setup.TEST_BOX1, roleDelete, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, masterToken, roleNotDelete, Setup.TEST_BOX1, HttpStatus.SC_CREATED); + RoleUtils.create(TEST_CELL1, masterToken, roleDelete, Setup.TEST_BOX1, HttpStatus.SC_CREATED); // RoleとAccountの結びつけ ResourceUtils.linkAccountRole(TEST_CELL1, masterToken, notDelRoleUser, Setup.TEST_BOX1, roleNotDelete, HttpStatus.SC_NO_CONTENT); @@ -870,7 +870,7 @@ public AuthCheckTest() { "", "", ""); // testRole002の削除 - RoleUtils.delete(TEST_CELL1, masterToken, Setup.TEST_BOX1, roleDelete, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(TEST_CELL1, masterToken, roleDelete, Setup.TEST_BOX1, HttpStatus.SC_NO_CONTENT); // PROPFIND TResponse tresponse = DavResourceUtils.propfind("box/propfind-box-allprop.txt", masterToken, @@ -896,8 +896,8 @@ public AuthCheckTest() { ResourceUtils.linkAccountRollDelete(TEST_CELL1, masterToken, notDelRoleUser, Setup.TEST_BOX1, roleNotDelete); // Roleの削除 - RoleUtils.delete(TEST_CELL1, masterToken, Setup.TEST_BOX1, roleNotDelete, -1); - RoleUtils.delete(TEST_CELL1, masterToken, Setup.TEST_BOX1, roleDelete, -1); + RoleUtils.delete(TEST_CELL1, masterToken, roleNotDelete, Setup.TEST_BOX1, -1); + RoleUtils.delete(TEST_CELL1, masterToken, roleDelete, Setup.TEST_BOX1, -1); // Accountの削除 AccountUtils.delete(TEST_CELL1, masterToken, notDelRoleUser, HttpStatus.SC_NO_CONTENT); } @@ -932,11 +932,11 @@ public AuthCheckTest() { CellUtils.create(cellName, accessToken1, HttpStatus.SC_CREATED); // ロールの作成 - RoleUtils.create(cellName, accessToken1, null, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(cellName, accessToken1, roleName, null, HttpStatus.SC_CREATED); setCellACL(cellName, roleName, accessToken1); // ロールの削除 - RoleUtils.delete(cellName, accessToken1, null, roleName, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(cellName, accessToken1, roleName, null, HttpStatus.SC_NO_CONTENT); // セルレベルAPI操作 // アカウント一覧取得 @@ -946,7 +946,7 @@ public AuthCheckTest() { AccountUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, user1, -1); AccountUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, user2, -1); // ロールの削除 - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, roleName, null, -1); // Cellの削除 CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, cellName, -1); CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, UNIT_USER_CELL, -1); @@ -982,7 +982,7 @@ public AuthCheckTest() { CellUtils.create(cellName, accessToken1, HttpStatus.SC_CREATED); // ロールの作成 - RoleUtils.create(cellName, accessToken1, null, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(cellName, accessToken1, roleName, null, HttpStatus.SC_CREATED); // CellにACLの設定 // ACLをtestcell1に設定 setCellACL(cellName, roleName, accessToken1); @@ -999,8 +999,8 @@ public AuthCheckTest() { AccountUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, user1, -1); AccountUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, user2, -1); // ロールの削除 - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, null, roleName, -1); - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, null, roleName + "updated", -1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, roleName, null, -1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, roleName + "updated", null, -1); // Cellの削除 CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, cellName, -1); CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, UNIT_USER_CELL, -1); @@ -1036,14 +1036,14 @@ public AuthCheckTest() { CellUtils.create(cellName, accessToken1, HttpStatus.SC_CREATED); // ロールの作成 - RoleUtils.create(cellName, accessToken1, null, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(cellName, accessToken1, roleName, null, HttpStatus.SC_CREATED); setCellACL(cellName, roleName, accessToken1); // ロールの削除 - RoleUtils.delete(cellName, accessToken1, null, roleName, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(cellName, accessToken1, roleName, null, HttpStatus.SC_NO_CONTENT); // ロールの作成 - RoleUtils.create(cellName, accessToken1, null, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(cellName, accessToken1, roleName, null, HttpStatus.SC_CREATED); // セルレベルAPI操作 // アカウント一覧取得 AccountUtils.get(accessToken2, HttpStatus.SC_FORBIDDEN, cellName, user1); @@ -1058,7 +1058,7 @@ public AuthCheckTest() { AccountUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, user1, -1); AccountUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, user2, -1); // ロールの削除 - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, roleName, null, -1); // Cellの削除 CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, cellName, -1); CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, UNIT_USER_CELL, -1); @@ -1098,12 +1098,12 @@ public AuthCheckTest() { BoxUtils.create(cellName, boxName, accessToken1, HttpStatus.SC_CREATED); // ロールの作成 - RoleUtils.create(cellName, accessToken1, boxName, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(cellName, accessToken1, roleName, boxName, HttpStatus.SC_CREATED); setBoxACL(cellName, boxName, roleName, accessToken1); // ロールの削除 - RoleUtils.delete(cellName, accessToken1, boxName, roleName, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(cellName, accessToken1, roleName, boxName, HttpStatus.SC_NO_CONTENT); // セルレベルAPI操作 // アカウント一覧取得 @@ -1113,7 +1113,7 @@ public AuthCheckTest() { AccountUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, user1, -1); AccountUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, user2, -1); // ロールの削除 - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, boxName, roleName, -1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, roleName, boxName, -1); // Boxの削除 BoxUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, boxName, -1); // Cellの削除 diff --git a/src/test/java/io/personium/test/jersey/cell/auth/AuthCookieTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthCookieTest.java index ff5a8f244..390d8cbf9 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/AuthCookieTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/AuthCookieTest.java @@ -34,6 +34,9 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import com.sun.jersey.test.framework.JerseyTest; +import com.sun.jersey.test.framework.WebAppDescriptor; + import io.personium.common.auth.token.AbstractOAuth2Token; import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; @@ -55,8 +58,6 @@ import io.personium.test.utils.ResourceUtils; import io.personium.test.utils.RoleUtils; import io.personium.test.utils.TResponse; -import com.sun.jersey.test.framework.JerseyTest; -import com.sun.jersey.test.framework.WebAppDescriptor; /** * 認証のテスト. @@ -145,8 +146,8 @@ public AuthCookieTest() { USERNAME, PASS, HttpStatus.SC_CREATED); // ロール追加(BOXに結びつかない) - RoleUtils.create(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, null, - ROLENAMENONEBOX, HttpStatus.SC_CREATED); + RoleUtils.create(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, ROLENAMENONEBOX, + null, HttpStatus.SC_CREATED); // ロール結びつけ(BOXに結びつかないロールとアカウント結びつけ) ResourceUtils.linkAccountRole(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, @@ -167,7 +168,7 @@ public AuthCookieTest() { AccountUtils.delete(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, USERNAME, HttpStatus.SC_NO_CONTENT); // ロール削除(BOXに結びつかない) - RoleUtils.delete(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, null, ROLENAMENONEBOX); + RoleUtils.delete(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, ROLENAMENONEBOX, null); // 本テスト用セルの削除 CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, TESTCELL_NAME, -1); } @@ -188,8 +189,8 @@ public AuthCookieTest() { USERNAME, PASS, HttpStatus.SC_CREATED); // ロール追加(BOXに結びつかない) - RoleUtils.create(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, null, - ROLENAMENONEBOX, HttpStatus.SC_CREATED); + RoleUtils.create(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, ROLENAMENONEBOX, + null, HttpStatus.SC_CREATED); // ロール結びつけ(BOXに結びつかないロールとアカウント結びつけ) ResourceUtils.linkAccountRole(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, @@ -210,7 +211,7 @@ public AuthCookieTest() { AccountUtils.delete(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, USERNAME, HttpStatus.SC_NO_CONTENT); // ロール削除(BOXに結びつかない) - RoleUtils.delete(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, null, ROLENAMENONEBOX); + RoleUtils.delete(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, ROLENAMENONEBOX, null); // 本テスト用セルの削除 CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, TESTCELL_NAME, -1); } @@ -244,8 +245,8 @@ public AuthCookieTest() { USERNAME, PASS, HttpStatus.SC_CREATED); // ロール追加(BOXに結びつかない) - RoleUtils.create(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, null, - ROLENAMENONEBOX, HttpStatus.SC_CREATED); + RoleUtils.create(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, ROLENAMENONEBOX, + null, HttpStatus.SC_CREATED); // ロール結びつけ(BOXに結びつかないロールとアカウント結びつけ) ResourceUtils.linkAccountRole(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, @@ -266,7 +267,7 @@ public AuthCookieTest() { AccountUtils.delete(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, USERNAME, HttpStatus.SC_NO_CONTENT); // ロール削除(BOXに結びつかない) - RoleUtils.delete(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, null, ROLENAMENONEBOX); + RoleUtils.delete(TESTCELL_NAME, AbstractCase.MASTER_TOKEN_NAME, ROLENAMENONEBOX, null); // 本テスト用セルの削除 CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, TESTCELL_NAME, -1); } diff --git a/src/test/java/io/personium/test/jersey/cell/auth/AuthTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthTest.java index 516b1b59c..5d8870a47 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/AuthTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/AuthTest.java @@ -31,6 +31,8 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import com.sun.jersey.test.framework.JerseyTest; + import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; import io.personium.common.auth.token.CellLocalRefreshToken; import io.personium.common.auth.token.Role; @@ -54,7 +56,6 @@ import io.personium.test.utils.ResourceUtils; import io.personium.test.utils.RoleUtils; import io.personium.test.utils.TResponse; -import com.sun.jersey.test.framework.JerseyTest; /** * 認証のテスト. @@ -493,7 +494,7 @@ public AuthTest() { tresponse.statusCode(HttpStatus.SC_NO_CONTENT); // ロール削除 - RoleUtils.delete(TEST_CELL2, MASTER_TOKEN, null, testrole); + RoleUtils.delete(TEST_CELL2, MASTER_TOKEN, testrole, null); // 1.ExtCell更新(元に戻す) ExtCellUtils.update(MASTER_TOKEN, TEST_CELL2, localunitCell1Url, httpCell1Url, HttpStatus.SC_NO_CONTENT); @@ -624,7 +625,7 @@ public AuthTest() { RelationUtils.delete(TEST_CELL2, MASTER_TOKEN, testrelation, null, HttpStatus.SC_NO_CONTENT); // ロール削除 - RoleUtils.delete(TEST_CELL2, MASTER_TOKEN, null, testrole); + RoleUtils.delete(TEST_CELL2, MASTER_TOKEN, testrole, null); // 1.ExtCell更新(元に戻す) ExtCellUtils.update(MASTER_TOKEN, TEST_CELL2, localunitCell1Url, httpCell1Url, HttpStatus.SC_NO_CONTENT); diff --git a/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthCellLevelTest.java b/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthCellLevelTest.java index 1965ebd6d..3342e7133 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthCellLevelTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthCellLevelTest.java @@ -594,7 +594,7 @@ public void after() { AuthTestCommon.checkAuthenticateHeaderNotExists(res); } finally { - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, testBox, testRole, -1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, testRole, testBox, -1); } } @@ -646,8 +646,8 @@ public void after() { AuthTestCommon.checkAuthenticateHeaderNotExists(res); } finally { - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, null, testRole, -1); - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, testBox, testRole, -1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, testRole, null, -1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, testRole, testBox, -1); } } @@ -683,7 +683,7 @@ public void after() { String testRoleKey = RoleUtils.keyString(testRole, testBox); try { // 事前準備 - RoleUtils.create(cellName, AbstractCase.MASTER_TOKEN_NAME, testBox, testRole, HttpStatus.SC_CREATED); + RoleUtils.create(cellName, AbstractCase.MASTER_TOKEN_NAME, testRole, testBox, HttpStatus.SC_CREATED); // 401エラーとなること TResponse res = RoleUtils.deleteLinkWithAuthSchema(cellName, testRoleKey, "Box", testBox, authorization, @@ -698,8 +698,8 @@ public void after() { AuthTestCommon.checkAuthenticateHeaderNotExists(res); } finally { - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, null, testRole, -1); - RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, testBox, testRole, -1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, testRole, null, -1); + RoleUtils.delete(cellName, AbstractCase.MASTER_TOKEN_NAME, testRole, testBox, -1); } } diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/AccountRoleLinkTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/AccountRoleLinkTest.java index 4e43136b0..e207b2f3e 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/AccountRoleLinkTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/AccountRoleLinkTest.java @@ -29,8 +29,8 @@ import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; import io.personium.test.jersey.AbstractCase; -import io.personium.test.jersey.PersoniumRequest; import io.personium.test.jersey.PersoniumIntegTestRunner; +import io.personium.test.jersey.PersoniumRequest; import io.personium.test.setup.Setup; import io.personium.test.utils.AccountUtils; import io.personium.test.utils.Http; @@ -384,7 +384,7 @@ public AccountRoleLinkTest() { AccountUtils.deleteLinksWithRole(Setup.TEST_CELL1, null, MASTER_TOKEN_NAME, testAccountName4Uri, testRoleName, -1); AccountUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, testAccountName4Uri, -1); - RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, null, testRoleName, -1); + RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, testRoleName, null, -1); } } diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/AccountTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/AccountTest.java index b9cdfd9fe..b167f6642 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/AccountTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/AccountTest.java @@ -46,9 +46,9 @@ import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; import io.personium.test.jersey.AbstractCase; +import io.personium.test.jersey.ODataCommon; import io.personium.test.jersey.PersoniumRequest; import io.personium.test.jersey.PersoniumResponse; -import io.personium.test.jersey.ODataCommon; import io.personium.test.unit.core.UrlUtils; import io.personium.test.utils.AccountUtils; import io.personium.test.utils.Http; @@ -222,7 +222,7 @@ public final void crud() throws TokenParseException, TokenDsigException, TokenRo try { // 準備。アカウント、ロール作ってリンクさせる。 AccountUtils.create(token, cellName, accountName, pass, HttpStatus.SC_CREATED); - RoleUtils.create(cellName, token, boxName, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(cellName, token, roleName, boxName, HttpStatus.SC_CREATED); ResourceUtils.linkAccountRole(cellName, token, accountName, boxName, roleName, HttpStatus.SC_NO_CONTENT); // 削除できないことの確認 @@ -233,7 +233,7 @@ public final void crud() throws TokenParseException, TokenDsigException, TokenRo AccountUtils.delete(cellName, token, accountName, HttpStatus.SC_NO_CONTENT); } finally { ResourceUtils.linkAccountRollDelete(cellName, token, accountName, boxName, roleName); - RoleUtils.delete(accountName, token, boxName, roleName, -1); + RoleUtils.delete(accountName, token, roleName, boxName, -1); AccountUtils.delete(cellName, token, accountName, -1); } diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/AccountViaNPTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/AccountViaNPTest.java index 7f0263c1b..e2d028cca 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/AccountViaNPTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/AccountViaNPTest.java @@ -87,7 +87,7 @@ public AccountViaNPTest() { "Account", "'" + accountName + "'", -1); // Role削除 - RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, roleName, null, -1); // Account削除 AccountUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, accountName, -1); @@ -123,7 +123,7 @@ public AccountViaNPTest() { "Account", "'" + accountName + "'", -1); // Role削除 - RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, roleName, null, -1); // Account削除 AccountUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, accountName, -1); @@ -158,7 +158,7 @@ public AccountViaNPTest() { "Account", "'" + accountName + "'", -1); // Role削除 - RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, roleName, null, -1); // Account削除 AccountUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, accountName, -1); @@ -189,7 +189,7 @@ public AccountViaNPTest() { RoleUtils.deleteLink(CELL_NAME, MASTER_TOKEN_NAME, RoleUtils.keyString(roleName), "Account", "'" + accountName + "'", -1); // Role削除 - RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, roleName, null, -1); // Account削除 AccountUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, accountName, -1); } diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/BoxRoleLinkTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/BoxRoleLinkTest.java index c4ae56bd6..aa468893d 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/BoxRoleLinkTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/BoxRoleLinkTest.java @@ -28,12 +28,14 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import com.sun.jersey.test.framework.JerseyTest; + import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; import io.personium.test.jersey.AbstractCase; -import io.personium.test.jersey.PersoniumIntegTestRunner; import io.personium.test.jersey.ODataCommon; +import io.personium.test.jersey.PersoniumIntegTestRunner; import io.personium.test.setup.Setup; import io.personium.test.unit.core.UrlUtils; import io.personium.test.utils.BoxUtils; @@ -42,7 +44,6 @@ import io.personium.test.utils.RelationUtils; import io.personium.test.utils.RoleUtils; import io.personium.test.utils.TResponse; -import com.sun.jersey.test.framework.JerseyTest; /** * BoxとRoleの$linksのテスト. @@ -157,8 +158,8 @@ public final void before() { HttpStatus.SC_CONFLICT); } finally { // Role削除 - RoleUtils.delete(cellName, TOKEN, null, roleName, -1); - RoleUtils.delete(cellName, TOKEN, baseBoxName, roleName, -1); + RoleUtils.delete(cellName, TOKEN, roleName, null, -1); + RoleUtils.delete(cellName, TOKEN, roleName, baseBoxName, -1); // Box削除 BoxUtils.delete(cellName, TOKEN, baseBoxName, -1); @@ -190,7 +191,7 @@ public final void before() { HttpStatus.SC_CONFLICT); } finally { // Role削除 - RoleUtils.delete(cellName, TOKEN, boxName, roleName, -1); + RoleUtils.delete(cellName, TOKEN, roleName, boxName, -1); // Box削除 BoxUtils.delete(cellName, TOKEN, boxName, -1); @@ -713,19 +714,19 @@ public final void before() { BoxUtils.create(CELL_NAME, boxName, TOKEN, HttpStatus.SC_CREATED); // 上のBoxと結びつくRole作成 - RoleUtils.create(CELL_NAME, TOKEN, boxName, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME, TOKEN, roleName, boxName, HttpStatus.SC_CREATED); // Boxの削除(結びつくロールがあるため、409) BoxUtils.delete(CELL_NAME, TOKEN, boxName, HttpStatus.SC_CONFLICT); // 結びつくロールの削除 - RoleUtils.delete(CELL_NAME, TOKEN, boxName, roleName, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, boxName, HttpStatus.SC_NO_CONTENT); // Boxの削除(結びつくロールが無くなったため、204) BoxUtils.delete(CELL_NAME, TOKEN, boxName, HttpStatus.SC_NO_CONTENT); } finally { // 結びつくロールの削除 - RoleUtils.delete(CELL_NAME, TOKEN, boxName, roleName, -1); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, boxName, -1); // Boxの削除 BoxUtils.delete(CELL_NAME, TOKEN, boxName, -1); @@ -780,10 +781,10 @@ public final void before() { BoxUtils.create(CELL_NAME, boxName, TOKEN, HttpStatus.SC_CREATED); // 上のBoxと結びつくRole作成 - RoleUtils.create(CELL_NAME, TOKEN, boxName, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME, TOKEN, roleName, boxName, HttpStatus.SC_CREATED); // 上のBoxと結びつかないRole作成 - RoleUtils.create(CELL_NAME, TOKEN, null, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME, TOKEN, roleName, null, HttpStatus.SC_CREATED); String roleKeyName = "_Box.Name='" + boxName + "',Name='" + roleName + "'"; @@ -793,20 +794,20 @@ public final void before() { deleteRoleBoxLink(roleKeyName, boxName, HttpStatus.SC_CONFLICT); // ロールの削除 - RoleUtils.delete(CELL_NAME, TOKEN, null, roleName, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, null, HttpStatus.SC_NO_CONTENT); // BoxとRoleのLink削除(単一キーのRoleが存在しないので削除できる) deleteBoxRoleLink(boxName, roleKeyName, HttpStatus.SC_NO_CONTENT); // 結びつくロールの削除 - RoleUtils.delete(CELL_NAME, TOKEN, null, roleName, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, null, HttpStatus.SC_NO_CONTENT); // Boxの削除 BoxUtils.delete(CELL_NAME, TOKEN, boxName, HttpStatus.SC_NO_CONTENT); } finally { // 結びつくロールの削除 - RoleUtils.delete(CELL_NAME, TOKEN, boxName, roleName, -1); - RoleUtils.delete(CELL_NAME, TOKEN, null, roleName, -1); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, boxName, -1); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, null, -1); // Boxの削除 BoxUtils.delete(CELL_NAME, TOKEN, boxName, -1); @@ -825,10 +826,10 @@ public final void before() { BoxUtils.create(CELL_NAME, boxName, TOKEN, HttpStatus.SC_CREATED); // 上のBoxと結びつくRole作成 - RoleUtils.create(CELL_NAME, TOKEN, boxName, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME, TOKEN, roleName, boxName, HttpStatus.SC_CREATED); // 上のBoxと結びつかないRole作成 - RoleUtils.create(CELL_NAME, TOKEN, null, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME, TOKEN, roleName, null, HttpStatus.SC_CREATED); String roleKeyName = "_Box.Name='" + boxName + "',Name='" + roleName + "'"; @@ -838,20 +839,20 @@ public final void before() { createRoleBoxLink(roleName, boxName, HttpStatus.SC_CONFLICT); // ロールの削除 - RoleUtils.delete(CELL_NAME, TOKEN, null, roleName, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, null, HttpStatus.SC_NO_CONTENT); // BoxとRoleのLink削除 deleteBoxRoleLink(boxName, roleKeyName, HttpStatus.SC_NO_CONTENT); // 結びつくロールの削除 - RoleUtils.delete(CELL_NAME, TOKEN, null, roleName, HttpStatus.SC_NO_CONTENT); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, null, HttpStatus.SC_NO_CONTENT); // Boxの削除 BoxUtils.delete(CELL_NAME, TOKEN, boxName, HttpStatus.SC_NO_CONTENT); } finally { // 結びつくロールの削除 - RoleUtils.delete(CELL_NAME, TOKEN, boxName, roleName, -1); - RoleUtils.delete(CELL_NAME, TOKEN, null, roleName, -1); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, boxName, -1); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, null, -1); // Boxの削除 BoxUtils.delete(CELL_NAME, TOKEN, boxName, -1); @@ -866,14 +867,14 @@ public final void before() { final String roleName = "boxLinkRole"; try { // Role作成 - RoleUtils.create(CELL_NAME, TOKEN, null, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME, TOKEN, roleName, null, HttpStatus.SC_CREATED); // Boxに紐付くRoleのlink一覧取得 RoleUtils.list(TOKEN, CELL_NAME, "\\$expand=_Box&\\$filter=startswith(Name,'boxLinkRole')", HttpStatus.SC_OK); } finally { // ロールの削除 - RoleUtils.delete(CELL_NAME, TOKEN, null, roleName, -1); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, null, -1); } } @@ -892,18 +893,18 @@ public final void before() { DavResourceUtils.createODataCollection(TOKEN, HttpStatus.SC_CREATED, CELL_NAME, boxName, "test"); // 上のBoxと結びつくRole作成 - RoleUtils.create(CELL_NAME, TOKEN, boxName, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME, TOKEN, roleName, boxName, HttpStatus.SC_CREATED); // 上のBoxと結びつくRole作成 - RoleUtils.create(CELL_NAME, TOKEN, boxName, "boxLinkRole2", HttpStatus.SC_CREATED); + RoleUtils.create(CELL_NAME, TOKEN, "boxLinkRole2", boxName, HttpStatus.SC_CREATED); // Roleに紐付くBoxのlink一覧取得 RoleUtils.list(TOKEN, CELL_NAME, "\\$expand=_Box&\\$filter=startswith(Name,'boxLinkRole')", HttpStatus.SC_OK); } finally { // 結びつくロールの削除 - RoleUtils.delete(CELL_NAME, TOKEN, boxName, roleName, -1); - RoleUtils.delete(CELL_NAME, TOKEN, boxName, "boxLinkRole2", -1); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, boxName, -1); + RoleUtils.delete(CELL_NAME, TOKEN, "boxLinkRole2", boxName, -1); // Collectionの削除 DavResourceUtils.deleteCollection(CELL_NAME, boxName, "test", TOKEN, -1); diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/BoxRoleViaNPTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/BoxRoleViaNPTest.java index a251ebd0d..32c6c0194 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/BoxRoleViaNPTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/BoxRoleViaNPTest.java @@ -24,17 +24,18 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import com.sun.jersey.test.framework.JerseyTest; + import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; import io.personium.test.jersey.AbstractCase; -import io.personium.test.jersey.PersoniumIntegTestRunner; import io.personium.test.jersey.ODataCommon; +import io.personium.test.jersey.PersoniumIntegTestRunner; import io.personium.test.setup.Setup; import io.personium.test.utils.BoxUtils; import io.personium.test.utils.RoleUtils; import io.personium.test.utils.TResponse; -import com.sun.jersey.test.framework.JerseyTest; /** * BoxとRoleのNP経由登録/一覧のテスト. @@ -80,7 +81,7 @@ public BoxRoleViaNPTest() { } finally { // Role削除 - RoleUtils.delete(CELL_NAME, TOKEN, boxName, roleName, -1); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, boxName, -1); // Box削除 BoxUtils.delete(CELL_NAME, TOKEN, boxName, -1); @@ -111,7 +112,7 @@ public BoxRoleViaNPTest() { } finally { // Role削除 - RoleUtils.delete(CELL_NAME, TOKEN, baseBoxName, roleName, -1); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, baseBoxName, -1); // Box削除 BoxUtils.delete(CELL_NAME, TOKEN, boxName, -1); @@ -141,7 +142,7 @@ public BoxRoleViaNPTest() { } finally { // Role削除 - RoleUtils.delete(CELL_NAME, TOKEN, null, roleName, -1); + RoleUtils.delete(CELL_NAME, TOKEN, roleName, null, -1); // Box削除 BoxUtils.delete(CELL_NAME, TOKEN, boxName, -1); diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellDeleteTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellDeleteTest.java index 6193bdbbb..c09650879 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellDeleteTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellDeleteTest.java @@ -64,7 +64,7 @@ public ExtCellDeleteTest() { try { // 準備。ExtCell、ロール作ってリンクさせる。 ExtCellUtils.create(token, cellName, extCellUrl, HttpStatus.SC_CREATED); - RoleUtils.create(cellName, token, boxName, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(cellName, token, roleName, boxName, HttpStatus.SC_CREATED); ResourceUtils.linkExtCelltoRole(PersoniumCoreUtils.encodeUrlComp(extCellUrl), cellName, roleUrl, token, HttpStatus.SC_NO_CONTENT); @@ -78,7 +78,7 @@ public ExtCellDeleteTest() { } finally { ResourceUtils.linkExtCellRoleDelete(cellName, token, PersoniumCoreUtils.encodeUrlComp(extCellUrl), boxName, roleName); - RoleUtils.delete(cellName, token, boxName, roleName, -1); + RoleUtils.delete(cellName, token, roleName, boxName, -1); ExtCellUtils.delete(token, cellName, extCellUrl, -1); } } diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleDeleteTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleDeleteTest.java index 75e17ac32..b0e87ef33 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleDeleteTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleDeleteTest.java @@ -171,7 +171,7 @@ private void deleteExtRole() { relationBody.put("_Box.Name", null); RelationUtils.create(cellName, token, relationBody, -1); ExtRoleUtils.create(token, cellName, extRoleBody, HttpStatus.SC_CREATED); - RoleUtils.create(cellName, token, boxName, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(cellName, token, roleName, boxName, HttpStatus.SC_CREATED); ResourceUtils.linksExtRoleToRole(cellName, PersoniumCoreUtils.encodeUrlComp(extRoleName), "'relation'", "null", UrlUtils.roleUrl(cellName, null, roleName), token); @@ -185,7 +185,7 @@ private void deleteExtRole() { } finally { ResourceUtils.linksDeleteExtRoleToRole(cellName, PersoniumCoreUtils.encodeUrlComp(extRoleName), "relation", "null", roleName, token); - RoleUtils.delete(cellName, token, boxName, roleName, -1); + RoleUtils.delete(cellName, token, roleName, boxName, -1); ExtRoleUtils.delete(token, cellName, extRoleName, "'relation'", "null", -1); RelationUtils.delete(cellName, token, "relation", null, -1); } diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/RelationDeleteTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/RelationDeleteTest.java index 1fd028457..7bd6714e1 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/RelationDeleteTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/RelationDeleteTest.java @@ -194,7 +194,7 @@ public RelationDeleteTest() { body.put("Name", relationName); body.put("_Box.Name", null); RelationUtils.create(cellName, token, body, HttpStatus.SC_CREATED); - RoleUtils.create(cellName, token, boxName, roleName, HttpStatus.SC_CREATED); + RoleUtils.create(cellName, token, roleName, boxName, HttpStatus.SC_CREATED); ResourceUtils.linksWithBody(cellName, Relation.EDM_TYPE_NAME, relationName, "null", Role.EDM_TYPE_NAME, UrlUtils.roleUrl(cellName, null, roleName), token, HttpStatus.SC_NO_CONTENT); @@ -209,7 +209,7 @@ public RelationDeleteTest() { } finally { ResourceUtils.linksDelete(cellName, Relation.EDM_TYPE_NAME, relationName, "null", Role.EDM_TYPE_NAME, "_Box.Name=null,Name='" + roleName + "'", token); - RoleUtils.delete(cellName, token, boxName, roleName, -1); + RoleUtils.delete(cellName, token, roleName, boxName, -1); RelationUtils.delete(cellName, token, relationName, null, -1); } } diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/RoleCreateTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/RoleCreateTest.java index 9fcc0dd7e..7db439f44 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/RoleCreateTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/RoleCreateTest.java @@ -31,9 +31,9 @@ import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; import io.personium.test.jersey.AbstractCase; +import io.personium.test.jersey.ODataCommon; import io.personium.test.jersey.PersoniumRequest; import io.personium.test.jersey.PersoniumResponse; -import io.personium.test.jersey.ODataCommon; import io.personium.test.setup.Setup; import io.personium.test.unit.core.UrlUtils; import io.personium.test.utils.Http; @@ -545,7 +545,7 @@ public RoleCreateTest() { RoleUtils.createViaNP(Setup.TEST_CELL1, Setup.MASTER_TOKEN_NAME, "Box", "'" + Setup.TEST_BOX1 + "'", roleName, HttpStatus.SC_CREATED); } finally { - RoleUtils.delete(Setup.TEST_CELL1, Setup.MASTER_TOKEN_NAME, Setup.TEST_BOX1, roleName, -1); + RoleUtils.delete(Setup.TEST_CELL1, Setup.MASTER_TOKEN_NAME, roleName, Setup.TEST_BOX1, -1); } } diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/RoleViaNPTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/RoleViaNPTest.java index 33a5467f8..1e86d7f93 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/RoleViaNPTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/RoleViaNPTest.java @@ -94,7 +94,7 @@ public RoleViaNPTest() { "Relation", RelationUtils.keyString(relationName), -1); // Role削除 - RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, roleName, null, -1); // Relation削除 RelationUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, relationName, null, -1); @@ -122,7 +122,7 @@ public RoleViaNPTest() { roleName, HttpStatus.SC_CONFLICT); } finally { // Role削除 - RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, null, roleName, -1); + RoleUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, roleName, null, -1); // Relation削除 RelationUtils.delete(CELL_NAME, MASTER_TOKEN_NAME, relationName, null, -1); diff --git a/src/test/java/io/personium/test/unit/core/UrlUtils.java b/src/test/java/io/personium/test/unit/core/UrlUtils.java index f327ce7d6..993eb963b 100644 --- a/src/test/java/io/personium/test/unit/core/UrlUtils.java +++ b/src/test/java/io/personium/test/unit/core/UrlUtils.java @@ -495,6 +495,26 @@ public static String unitLocalRelationClassUrl(final String cellName, final Stri return String.format("%s%s/__relation/__/%s", UriUtils.SCHEME_UNIT_URI, cellName, relationName); } + /** + * Get RoleClassURL. + * @param cellName Cell name + * @param roleName Role name + * @return RoleClassURL + */ + public static String roleClassUrl(final String cellName, final String roleName) { + return String.format("%s/%s/__role/__/%s", baseUrl, cellName, roleName); + } + + /** + * Get unit local RoleClassURL. + * @param cellName Cell name + * @param roleName Role name + * @return unit local RoleClassURL + */ + public static String unitLocalRoleClassUrl(final String cellName, final String roleName) { + return String.format("%s%s/__role/__/%s", UriUtils.SCHEME_UNIT_URI, cellName, roleName); + } + /** * ExtRoleのURL取得. * @param cellName セル名 diff --git a/src/test/java/io/personium/test/unit/core/bar/BarFileContentsTest.java b/src/test/java/io/personium/test/unit/core/bar/BarFileContentsTest.java index 9b2873c62..464f16e8d 100644 --- a/src/test/java/io/personium/test/unit/core/bar/BarFileContentsTest.java +++ b/src/test/java/io/personium/test/unit/core/bar/BarFileContentsTest.java @@ -1,548 +1,544 @@ -/** - * 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 io.personium.test.unit.core.bar; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import io.personium.core.bar.BarFileReadRunner; -import io.personium.core.model.DavCmp; -import io.personium.core.model.impl.es.DavCmpEsImpl; -import io.personium.core.model.impl.fs.DavCmpFsImpl; -import io.personium.test.categories.Unit; - -/** - * BarFileのバリデートのユニットテストクラス. - */ -@Category({Unit.class }) -public class BarFileContentsTest { - private static DavCmp newDavCmp(String name) { - return newDavCmpFsImpl(name); - } - private static DavCmp newDavCmpFsImpl(String name) { - return DavCmpFsImpl.create(name, null); - } - private static DavCmp newDavCmpEsImpl(String name) { - return new DavCmpEsImpl(name, null, null, null, null); - } - - private static final String ODATA_COL_NAME = "odataCol"; - private static final String WEBDAV_COL_NAME = "davCol"; - private static final String SVC_COL_NAME = "svcCol"; - - /** - * . - */ - private class TestBarRunner extends BarFileReadRunner { - TestBarRunner() { - super(null, null, null, null, null, null, null, null); - } - - /** - * barファイルの90_contents配下のエントリのタイプを取得する. - * @param entryName barファイルのエントリ名 - * @param odataCols ODataコレクションの一覧 - * @param webdavCols WebDAVコレクションの一覧 - * @param serviceCols サービスコレクションの一覧 - * @param davFiles WebDAVファイルの一覧 - * @return エントリのタイプ - */ - protected int getEntryType(String entryName, - Map odataCols, - Map webdavCols, - Map serviceCols, - Map davFiles) { - return super.getEntryType(entryName, odataCols, webdavCols, serviceCols, davFiles); - } - - /** - * bar/90_contents/{col_name}配下のエントリが正しい定義であるかどうかを確認する. - * @param entryName エントリ名(コレクション名) - * @param colMap コレクションのMapオブジェクト - * @param doneKeys 処理済みのODataコレクション用エントリリスト - * @return 判定処理結果 - */ - protected boolean isValidODataContents(String entryName, Map colMap, - List doneKeys) { - return super.isValidODataContents(entryName, colMap, doneKeys); - } - - } - - /** - * 90_contents直下のODataコレクションの場合TYPE_ODATA_COLLECTIONが返却されること. - */ - @Test - public void contents直下のODataコレクションの場合TYPE_ODATA_COLLECTIONが返却されること() { - - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); - DavCmp svcCol = newDavCmp(SVC_COL_NAME); - - Map odataCols = new HashMap(); - Map webDavCols = new HashMap(); - Map svcCols = new HashMap(); - - - String key = "bar/90_contents/" + ODATA_COL_NAME; - odataCols.put(key, odataCol); - - key = "bar/90_contents/" + WEBDAV_COL_NAME; - webDavCols.put(key, webDavCol); - - key = "bar/90_contents/" + SVC_COL_NAME; - svcCols.put(key, svcCol); - - Map davFileMap = new HashMap(); - - String entryName = "bar/90_contents/" + ODATA_COL_NAME; - - TestBarRunner testBarRunner = new TestBarRunner(); - int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); - assertEquals(1, res); - - } - - /** - * ODataコレクション配下のエントリの場合TYPE_ODATA_COLLECTIONが返却されること. - */ - @Test - public void ODataコレクション配下のエントリの場合TYPE_ODATA_COLLECTIONが返却されること() { - String odatacolName = "odataCol"; - String webDavColName = "davCol"; - String svcColName = "svcCol"; - - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); - DavCmp svcCol = newDavCmp(SVC_COL_NAME); - - Map odataCols = new HashMap(); - Map webDavCols = new HashMap(); - Map svcCols = new HashMap(); - - String entryName = "bar/90_contents/odataCol/90_data/entityType/1.json"; - - String key = "bar/90_contents/" + odatacolName; - odataCols.put(key, odataCol); - - key = "bar/90_contents/" + webDavColName; - webDavCols.put(key, webDavCol); - - key = "bar/90_contents/" + svcColName; - svcCols.put(key, svcCol); - - Map davFileMap = new HashMap(); - - TestBarRunner testBarRunner = new TestBarRunner(); - int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); - assertEquals(1, res); - - } - - /** - * WebDavコレクション配下のODataコレクションの場合TYPE_ODATA_COLLECTIONが返却されること. - */ - @Test - public void WebDavコレクション配下のODataコレクションの場合TYPE_ODATA_COLLECTIONが返却されること() { - String odatacolName = "odataCol"; - String webDavColName = "davCol"; - String svcColName = "svcCol"; - - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); - DavCmp svcCol = newDavCmp(SVC_COL_NAME); - - Map odataCols = new HashMap(); - Map webDavCols = new HashMap(); - Map svcCols = new HashMap(); - - - String entryName = "bar/90_contents/davCol/" + odatacolName; - - String key = "bar/90_contents/davCol/" + odatacolName; - odataCols.put(key, odataCol); - - key = "bar/90_contents/" + webDavColName; - webDavCols.put(key, webDavCol); - - key = "bar/90_contents/" + svcColName; - svcCols.put(key, svcCol); - - Map davFileMap = new HashMap(); - - TestBarRunner testBarRunner = new TestBarRunner(); - int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); - assertEquals(1, res); - - } - - /** - * 90_contents直下のWebDAVコレクションの場合TYPE_WEBDAV_COLLECTIONが返却されること. - */ - @Test - public void contents直下のODataコレクションの場合TYPE_WEBDAV_COLLECTIONが返却されること() { - String entryName = "bar/90_contents/davCol"; - - String odatacolName = "odataCol"; - String webDavColName = "davCol"; - String svcColName = "svcCol"; - - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); - DavCmp svcCol = newDavCmp(SVC_COL_NAME); - - Map odataCols = new HashMap(); - Map webDavCols = new HashMap(); - Map svcCols = new HashMap(); - - String key = "bar/90_contents/" + odatacolName; - odataCols.put(key, odataCol); - - key = "bar/90_contents/" + webDavColName; - webDavCols.put(key, webDavCol); - - key = "bar/90_contents/" + svcColName; - svcCols.put(key, svcCol); - - Map davFileMap = new HashMap(); - - TestBarRunner testBarRunner = new TestBarRunner(); - int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); - assertEquals(0, res); - - } - - /** - * WebDAVコレクション配下のファイルの場合TYPE_DAV_FILEが返却されること. - */ - @Test - public void WebDAVコレクション配下のファイルの場合TYPE_DAV_FILEが返却されること() { - String entryName = "bar/90_contents/davCol/hoge.jpg"; - - String odatacolName = "odataCol"; - String webDavColName = "davCol"; - String svcColName = "svcCol"; - - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); - DavCmp svcCol = newDavCmp(SVC_COL_NAME); - - Map odataCols = new HashMap(); - Map webDavCols = new HashMap(); - Map svcCols = new HashMap(); - - String key = "bar/90_contents/" + odatacolName; - odataCols.put(key, odataCol); - - key = "bar/90_contents/" + webDavColName; - webDavCols.put(key, webDavCol); - - key = "bar/90_contents/" + svcColName; - svcCols.put(key, svcCol); - - Map davFileMap = new HashMap(); - davFileMap.put("bar/90_contents/" + webDavColName + "/hoge.jpg", "image/jpeg"); - - TestBarRunner testBarRunner = new TestBarRunner(); - - int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); - assertEquals(3, res); - - } - - /** - * 90_contents直下のServiceコレクションの場合TYPE_SERVICE_COLLECTIONが返却されること. - */ - @Test - public void contents直下のServiceコレクションの場合TYPE_SERVICE_COLLECTIONが返却されること() { - String entryName = "bar/90_contents/svcCol"; - - String odatacolName = "odataCol"; - String webDavColName = "davCol"; - String svcColName = "svcCol"; - - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); - DavCmp svcCol = newDavCmp(SVC_COL_NAME); - - Map odataCols = new HashMap(); - Map webDavCols = new HashMap(); - Map svcCols = new HashMap(); - - String key = "bar/90_contents/" + odatacolName; - odataCols.put(key, odataCol); - - key = "bar/90_contents/" + webDavColName; - webDavCols.put(key, webDavCol); - - key = "bar/90_contents/" + svcColName; - svcCols.put(key, svcCol); - - Map davFileMap = new HashMap(); - - TestBarRunner testBarRunner = new TestBarRunner(); - int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); - assertEquals(2, res); - - } - - /** - * Serviceコレクション配下のファイルの場合TYPE_SVC_FILEが返却されること. - */ - @Test - public void Serviceコレクション配下のファイルの場合TYPE_SVC_FILEが返却されること() { - String entryName = "bar/90_contents/svcCol/hoge.js"; - - String odatacolName = "odataCol"; - String webDavColName = "davCol"; - String svcColName = "svcCol"; - - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); - DavCmp svcCol = newDavCmp(SVC_COL_NAME); - - Map odataCols = new HashMap(); - Map webDavCols = new HashMap(); - Map svcCols = new HashMap(); - - String key = "bar/90_contents/" + odatacolName; - odataCols.put(key, odataCol); - - key = "bar/90_contents/" + webDavColName; - webDavCols.put(key, webDavCol); - - key = "bar/90_contents/" + svcColName; - svcCols.put(key, svcCol); - - Map davFileMap = new HashMap(); - davFileMap.put("bar/90_contents/svcCol/__src/hoge.js", "text/javascript"); - - TestBarRunner testBarRunner = new TestBarRunner(); - int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); - assertEquals(4, res); - - } - - /** - * 存在しないコレクションのファイルの場合TYPE_MISMATCHが返却されること. - */ - @Test - public void 存在しないコレクションのファイルの場合TYPE_MISMATCHが返却されること() { - String entryName = "bar/90_contents/dummyCol"; - - String odatacolName = "odataCol"; - String webDavColName = "davCol"; - String svcColName = "svcCol"; - - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); - DavCmp svcCol = newDavCmp(SVC_COL_NAME); - - Map odataCols = new HashMap(); - Map webDavCols = new HashMap(); - Map svcCols = new HashMap(); - - String key = "bar/90_contents/" + odatacolName; - odataCols.put(key, odataCol); - - key = "bar/90_contents/" + webDavColName; - webDavCols.put(key, webDavCol); - - key = "bar/90_contents/" + svcColName; - svcCols.put(key, svcCol); - - Map davFileMap = new HashMap(); - - TestBarRunner testBarRunner = new TestBarRunner(); - int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); - assertEquals(-1, res); - - } - - /** - * ODataコレクション配下の階層が正しい場合trueが返却されること. - */ - @Test - public void ODataコレクション配下の階層が正しい場合trueが返却されること() { - - String key = "bar/90_contents/odataCol/"; - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - - Map odataCols = new HashMap<>(); - odataCols.put(key, odataCol); - - List doneKeys = new ArrayList(); - TestBarRunner testBarRunner = new TestBarRunner(); - - String entryName = "bar/90_contents/odataCol/"; - boolean res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - - entryName = "bar/90_contents/odataCol/00_$metadata.xml"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - - entryName = "bar/90_contents/odataCol/10_odatarelations.json"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - - entryName = "bar/90_contents/odataCol/90_data/"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - - entryName = "bar/90_contents/odataCol/90_data/entity1/"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - - entryName = "bar/90_contents/odataCol/90_data/entity1/1.json"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - } - - /** - * WebDavコレクション配下のODataコレクション配下の階層が正しい場合trueが返却されること. - */ - @Test - public void WebDavコレクション配下のODataコレクション配下の階層が正しい場合trueが返却されること() { - - String key = "bar/90_contents/webdavCol/odataCol/"; - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - - Map odataCols = new HashMap<>(); - odataCols.put(key, odataCol); - - List doneKeys = new ArrayList(); - TestBarRunner testBarRunner = new TestBarRunner(); - - String entryName = "bar/90_contents/webdavCol/"; - doneKeys.add(entryName); - - entryName = "bar/90_contents/webdavCol/odataCol/"; - boolean res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - - entryName = "bar/90_contents/webdavCol/odataCol/00_$metadata.xml"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - - entryName = "bar/90_contents/webdavCol/odataCol/10_odatarelations.json"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - - entryName = "bar/90_contents/webdavCol/odataCol/90_data/"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - - entryName = "bar/90_contents/webdavCol/odataCol/90_data/entity1/"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - - entryName = "bar/90_contents/webdavCol/odataCol/90_data/entity1/1.json"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - } - - /** - * ODataコレクション直下のファイル順序が不正な場合falseが返却されること. - */ - @Test - public void ODataコレクション直下のファイル順序が不正な場合falseが返却されること() { - - String key = "bar/90_contents/webdavCol/odataCol/"; - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - - Map odataCols = new HashMap<>(); - odataCols.put(key, odataCol); - - List doneKeys = new ArrayList(); - TestBarRunner testBarRunner = new TestBarRunner(); - - String entryName = "bar/90_contents/webdavCol/"; - doneKeys.add(entryName); - - entryName = "bar/90_contents/webdavCol/odataCol/"; - boolean res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(true, res); - doneKeys.add(entryName); - - // 10_odatarelations.jsonが最初に来た場合 - entryName = "bar/90_contents/webdavCol/odataCol/10_odatarelations.json"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(false, res); - - // 90_dataが最初に来た場合 - entryName = "bar/90_contents/webdavCol/odataCol/90_data/"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(false, res); - - // ユーザデータが最初に来た場合 - entryName = "bar/90_contents/webdavCol/odataCol/90_data/entity1/"; - res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(false, res); - } - - /** - * ODataコレクション配下のユーザデータディレクトリが存在しない場合falseが返却されること. - */ - @Test - public void ODataコレクション配下のユーザデータディレクトリが存在しない場合falseが返却されること() { - - String key = "bar/90_contents/webdavCol/odataCol/"; - DavCmp odataCol = newDavCmp(ODATA_COL_NAME); - - Map odataCols = new HashMap<>(); - odataCols.put(key, odataCol); - - List doneKeys = new ArrayList(); - TestBarRunner testBarRunner = new TestBarRunner(); - - String entryName = "bar/90_contents/webdavCol/"; - doneKeys.add(entryName); - - entryName = "bar/90_contents/webdavCol/odataCol/"; - doneKeys.add(entryName); - - entryName = "bar/90_contents/webdavCol/odataCol/00_$metadata.xml"; - doneKeys.add(entryName); - - entryName = "bar/90_contents/webdavCol/odataCol/10_odatarelations.json"; - doneKeys.add(entryName); - - entryName = "bar/90_contents/webdavCol/odataCol/entity1/"; - boolean res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); - assertEquals(false, res); - } -} +/** + * 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 io.personium.test.unit.core.bar; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import io.personium.core.bar.BarFileReadRunner; +import io.personium.core.model.DavCmp; +import io.personium.core.model.impl.fs.DavCmpFsImpl; +import io.personium.test.categories.Unit; + +/** + * BarFileのバリデートのユニットテストクラス. + */ +@Category({Unit.class }) +public class BarFileContentsTest { + private static DavCmp newDavCmp(String name) { + return newDavCmpFsImpl(name); + } + private static DavCmp newDavCmpFsImpl(String name) { + return DavCmpFsImpl.create(name, null); + } + + private static final String ODATA_COL_NAME = "odataCol"; + private static final String WEBDAV_COL_NAME = "davCol"; + private static final String SVC_COL_NAME = "svcCol"; + + /** + * . + */ + private class TestBarRunner extends BarFileReadRunner { + TestBarRunner() { + super(null, null, null, null, null, null, null, null); + } + + /** + * barファイルの90_contents配下のエントリのタイプを取得する. + * @param entryName barファイルのエントリ名 + * @param odataCols ODataコレクションの一覧 + * @param webdavCols WebDAVコレクションの一覧 + * @param serviceCols サービスコレクションの一覧 + * @param davFiles WebDAVファイルの一覧 + * @return エントリのタイプ + */ + protected int getEntryType(String entryName, + Map odataCols, + Map webdavCols, + Map serviceCols, + Map davFiles) { + return super.getEntryType(entryName, odataCols, webdavCols, serviceCols, davFiles); + } + + /** + * bar/90_contents/{col_name}配下のエントリが正しい定義であるかどうかを確認する. + * @param entryName エントリ名(コレクション名) + * @param colMap コレクションのMapオブジェクト + * @param doneKeys 処理済みのODataコレクション用エントリリスト + * @return 判定処理結果 + */ + protected boolean isValidODataContents(String entryName, Map colMap, + List doneKeys) { + return super.isValidODataContents(entryName, colMap, doneKeys); + } + + } + + /** + * 90_contents直下のODataコレクションの場合TYPE_ODATA_COLLECTIONが返却されること. + */ + @Test + public void contents直下のODataコレクションの場合TYPE_ODATA_COLLECTIONが返却されること() { + + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); + DavCmp svcCol = newDavCmp(SVC_COL_NAME); + + Map odataCols = new HashMap(); + Map webDavCols = new HashMap(); + Map svcCols = new HashMap(); + + + String key = "bar/90_contents/" + ODATA_COL_NAME; + odataCols.put(key, odataCol); + + key = "bar/90_contents/" + WEBDAV_COL_NAME; + webDavCols.put(key, webDavCol); + + key = "bar/90_contents/" + SVC_COL_NAME; + svcCols.put(key, svcCol); + + Map davFileMap = new HashMap(); + + String entryName = "bar/90_contents/" + ODATA_COL_NAME; + + TestBarRunner testBarRunner = new TestBarRunner(); + int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); + assertEquals(1, res); + + } + + /** + * ODataコレクション配下のエントリの場合TYPE_ODATA_COLLECTIONが返却されること. + */ + @Test + public void ODataコレクション配下のエントリの場合TYPE_ODATA_COLLECTIONが返却されること() { + String odatacolName = "odataCol"; + String webDavColName = "davCol"; + String svcColName = "svcCol"; + + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); + DavCmp svcCol = newDavCmp(SVC_COL_NAME); + + Map odataCols = new HashMap(); + Map webDavCols = new HashMap(); + Map svcCols = new HashMap(); + + String entryName = "bar/90_contents/odataCol/90_data/entityType/1.json"; + + String key = "bar/90_contents/" + odatacolName; + odataCols.put(key, odataCol); + + key = "bar/90_contents/" + webDavColName; + webDavCols.put(key, webDavCol); + + key = "bar/90_contents/" + svcColName; + svcCols.put(key, svcCol); + + Map davFileMap = new HashMap(); + + TestBarRunner testBarRunner = new TestBarRunner(); + int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); + assertEquals(1, res); + + } + + /** + * WebDavコレクション配下のODataコレクションの場合TYPE_ODATA_COLLECTIONが返却されること. + */ + @Test + public void WebDavコレクション配下のODataコレクションの場合TYPE_ODATA_COLLECTIONが返却されること() { + String odatacolName = "odataCol"; + String webDavColName = "davCol"; + String svcColName = "svcCol"; + + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); + DavCmp svcCol = newDavCmp(SVC_COL_NAME); + + Map odataCols = new HashMap(); + Map webDavCols = new HashMap(); + Map svcCols = new HashMap(); + + + String entryName = "bar/90_contents/davCol/" + odatacolName; + + String key = "bar/90_contents/davCol/" + odatacolName; + odataCols.put(key, odataCol); + + key = "bar/90_contents/" + webDavColName; + webDavCols.put(key, webDavCol); + + key = "bar/90_contents/" + svcColName; + svcCols.put(key, svcCol); + + Map davFileMap = new HashMap(); + + TestBarRunner testBarRunner = new TestBarRunner(); + int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); + assertEquals(1, res); + + } + + /** + * 90_contents直下のWebDAVコレクションの場合TYPE_WEBDAV_COLLECTIONが返却されること. + */ + @Test + public void contents直下のODataコレクションの場合TYPE_WEBDAV_COLLECTIONが返却されること() { + String entryName = "bar/90_contents/davCol"; + + String odatacolName = "odataCol"; + String webDavColName = "davCol"; + String svcColName = "svcCol"; + + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); + DavCmp svcCol = newDavCmp(SVC_COL_NAME); + + Map odataCols = new HashMap(); + Map webDavCols = new HashMap(); + Map svcCols = new HashMap(); + + String key = "bar/90_contents/" + odatacolName; + odataCols.put(key, odataCol); + + key = "bar/90_contents/" + webDavColName; + webDavCols.put(key, webDavCol); + + key = "bar/90_contents/" + svcColName; + svcCols.put(key, svcCol); + + Map davFileMap = new HashMap(); + + TestBarRunner testBarRunner = new TestBarRunner(); + int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); + assertEquals(0, res); + + } + + /** + * WebDAVコレクション配下のファイルの場合TYPE_DAV_FILEが返却されること. + */ + @Test + public void WebDAVコレクション配下のファイルの場合TYPE_DAV_FILEが返却されること() { + String entryName = "bar/90_contents/davCol/hoge.jpg"; + + String odatacolName = "odataCol"; + String webDavColName = "davCol"; + String svcColName = "svcCol"; + + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); + DavCmp svcCol = newDavCmp(SVC_COL_NAME); + + Map odataCols = new HashMap(); + Map webDavCols = new HashMap(); + Map svcCols = new HashMap(); + + String key = "bar/90_contents/" + odatacolName; + odataCols.put(key, odataCol); + + key = "bar/90_contents/" + webDavColName; + webDavCols.put(key, webDavCol); + + key = "bar/90_contents/" + svcColName; + svcCols.put(key, svcCol); + + Map davFileMap = new HashMap(); + davFileMap.put("bar/90_contents/" + webDavColName + "/hoge.jpg", "image/jpeg"); + + TestBarRunner testBarRunner = new TestBarRunner(); + + int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); + assertEquals(3, res); + + } + + /** + * 90_contents直下のServiceコレクションの場合TYPE_SERVICE_COLLECTIONが返却されること. + */ + @Test + public void contents直下のServiceコレクションの場合TYPE_SERVICE_COLLECTIONが返却されること() { + String entryName = "bar/90_contents/svcCol"; + + String odatacolName = "odataCol"; + String webDavColName = "davCol"; + String svcColName = "svcCol"; + + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); + DavCmp svcCol = newDavCmp(SVC_COL_NAME); + + Map odataCols = new HashMap(); + Map webDavCols = new HashMap(); + Map svcCols = new HashMap(); + + String key = "bar/90_contents/" + odatacolName; + odataCols.put(key, odataCol); + + key = "bar/90_contents/" + webDavColName; + webDavCols.put(key, webDavCol); + + key = "bar/90_contents/" + svcColName; + svcCols.put(key, svcCol); + + Map davFileMap = new HashMap(); + + TestBarRunner testBarRunner = new TestBarRunner(); + int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); + assertEquals(2, res); + + } + + /** + * Serviceコレクション配下のファイルの場合TYPE_SVC_FILEが返却されること. + */ + @Test + public void Serviceコレクション配下のファイルの場合TYPE_SVC_FILEが返却されること() { + String entryName = "bar/90_contents/svcCol/hoge.js"; + + String odatacolName = "odataCol"; + String webDavColName = "davCol"; + String svcColName = "svcCol"; + + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); + DavCmp svcCol = newDavCmp(SVC_COL_NAME); + + Map odataCols = new HashMap(); + Map webDavCols = new HashMap(); + Map svcCols = new HashMap(); + + String key = "bar/90_contents/" + odatacolName; + odataCols.put(key, odataCol); + + key = "bar/90_contents/" + webDavColName; + webDavCols.put(key, webDavCol); + + key = "bar/90_contents/" + svcColName; + svcCols.put(key, svcCol); + + Map davFileMap = new HashMap(); + davFileMap.put("bar/90_contents/svcCol/__src/hoge.js", "text/javascript"); + + TestBarRunner testBarRunner = new TestBarRunner(); + int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); + assertEquals(4, res); + + } + + /** + * 存在しないコレクションのファイルの場合TYPE_MISMATCHが返却されること. + */ + @Test + public void 存在しないコレクションのファイルの場合TYPE_MISMATCHが返却されること() { + String entryName = "bar/90_contents/dummyCol"; + + String odatacolName = "odataCol"; + String webDavColName = "davCol"; + String svcColName = "svcCol"; + + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + DavCmp webDavCol = newDavCmp(WEBDAV_COL_NAME); + DavCmp svcCol = newDavCmp(SVC_COL_NAME); + + Map odataCols = new HashMap(); + Map webDavCols = new HashMap(); + Map svcCols = new HashMap(); + + String key = "bar/90_contents/" + odatacolName; + odataCols.put(key, odataCol); + + key = "bar/90_contents/" + webDavColName; + webDavCols.put(key, webDavCol); + + key = "bar/90_contents/" + svcColName; + svcCols.put(key, svcCol); + + Map davFileMap = new HashMap(); + + TestBarRunner testBarRunner = new TestBarRunner(); + int res = testBarRunner.getEntryType(entryName, odataCols, webDavCols, svcCols, davFileMap); + assertEquals(-1, res); + + } + + /** + * ODataコレクション配下の階層が正しい場合trueが返却されること. + */ + @Test + public void ODataコレクション配下の階層が正しい場合trueが返却されること() { + + String key = "bar/90_contents/odataCol/"; + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + + Map odataCols = new HashMap<>(); + odataCols.put(key, odataCol); + + List doneKeys = new ArrayList(); + TestBarRunner testBarRunner = new TestBarRunner(); + + String entryName = "bar/90_contents/odataCol/"; + boolean res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + + entryName = "bar/90_contents/odataCol/00_$metadata.xml"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + + entryName = "bar/90_contents/odataCol/10_odatarelations.json"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + + entryName = "bar/90_contents/odataCol/90_data/"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + + entryName = "bar/90_contents/odataCol/90_data/entity1/"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + + entryName = "bar/90_contents/odataCol/90_data/entity1/1.json"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + } + + /** + * WebDavコレクション配下のODataコレクション配下の階層が正しい場合trueが返却されること. + */ + @Test + public void WebDavコレクション配下のODataコレクション配下の階層が正しい場合trueが返却されること() { + + String key = "bar/90_contents/webdavCol/odataCol/"; + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + + Map odataCols = new HashMap<>(); + odataCols.put(key, odataCol); + + List doneKeys = new ArrayList(); + TestBarRunner testBarRunner = new TestBarRunner(); + + String entryName = "bar/90_contents/webdavCol/"; + doneKeys.add(entryName); + + entryName = "bar/90_contents/webdavCol/odataCol/"; + boolean res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + + entryName = "bar/90_contents/webdavCol/odataCol/00_$metadata.xml"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + + entryName = "bar/90_contents/webdavCol/odataCol/10_odatarelations.json"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + + entryName = "bar/90_contents/webdavCol/odataCol/90_data/"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + + entryName = "bar/90_contents/webdavCol/odataCol/90_data/entity1/"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + + entryName = "bar/90_contents/webdavCol/odataCol/90_data/entity1/1.json"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + } + + /** + * ODataコレクション直下のファイル順序が不正な場合falseが返却されること. + */ + @Test + public void ODataコレクション直下のファイル順序が不正な場合falseが返却されること() { + + String key = "bar/90_contents/webdavCol/odataCol/"; + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + + Map odataCols = new HashMap<>(); + odataCols.put(key, odataCol); + + List doneKeys = new ArrayList(); + TestBarRunner testBarRunner = new TestBarRunner(); + + String entryName = "bar/90_contents/webdavCol/"; + doneKeys.add(entryName); + + entryName = "bar/90_contents/webdavCol/odataCol/"; + boolean res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(true, res); + doneKeys.add(entryName); + + // 10_odatarelations.jsonが最初に来た場合 + entryName = "bar/90_contents/webdavCol/odataCol/10_odatarelations.json"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(false, res); + + // 90_dataが最初に来た場合 + entryName = "bar/90_contents/webdavCol/odataCol/90_data/"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(false, res); + + // ユーザデータが最初に来た場合 + entryName = "bar/90_contents/webdavCol/odataCol/90_data/entity1/"; + res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(false, res); + } + + /** + * ODataコレクション配下のユーザデータディレクトリが存在しない場合falseが返却されること. + */ + @Test + public void ODataコレクション配下のユーザデータディレクトリが存在しない場合falseが返却されること() { + + String key = "bar/90_contents/webdavCol/odataCol/"; + DavCmp odataCol = newDavCmp(ODATA_COL_NAME); + + Map odataCols = new HashMap<>(); + odataCols.put(key, odataCol); + + List doneKeys = new ArrayList(); + TestBarRunner testBarRunner = new TestBarRunner(); + + String entryName = "bar/90_contents/webdavCol/"; + doneKeys.add(entryName); + + entryName = "bar/90_contents/webdavCol/odataCol/"; + doneKeys.add(entryName); + + entryName = "bar/90_contents/webdavCol/odataCol/00_$metadata.xml"; + doneKeys.add(entryName); + + entryName = "bar/90_contents/webdavCol/odataCol/10_odatarelations.json"; + doneKeys.add(entryName); + + entryName = "bar/90_contents/webdavCol/odataCol/entity1/"; + boolean res = testBarRunner.isValidODataContents(entryName, odataCols, doneKeys); + assertEquals(false, res); + } +} diff --git a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/AdsAcessorTest.java b/src/test/java/io/personium/test/unit/core/model/impl/es/repair/AdsAcessorTest.java deleted file mode 100644 index 7e3aaa5e4..000000000 --- a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/AdsAcessorTest.java +++ /dev/null @@ -1,332 +0,0 @@ -/** - * 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 io.personium.test.unit.core.model.impl.es.repair; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import org.json.simple.JSONObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.es.EsType; -import io.personium.common.es.response.PersoniumIndexResponse; -import io.personium.common.es.response.PersoniumSearchResponse; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.impl.es.EsModel; -import io.personium.core.model.impl.es.ads.Ads; -import io.personium.core.model.impl.es.ads.AdsConnectionException; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.ads.JdbcAds; -import io.personium.core.model.impl.es.repair.AdsAccessor; -import io.personium.core.model.impl.es.repair.EsAccessor; -import io.personium.test.categories.Unit; - -/** - * EsAcessorユニットテストクラス. - */ -@Category({Unit.class }) -public class AdsAcessorTest { - private static final String ROUTING_ID = "routingId"; - - static Logger log = LoggerFactory.getLogger(AdsAcessorTest.class); - - private String idxName = PersoniumUnitConfig.getEsUnitPrefix() + "_anon"; - private String[] idList = {"documentId1" }; - private Ads ads; - - /** - * すべてのテスト毎に1度実行される処理. - * @throws InterruptedException InterruptedException - * @throws AdsConnectionException AdsConnectionException - */ - @Before - @SuppressWarnings("unchecked") - public void before() throws InterruptedException, AdsConnectionException { - ads = new JdbcAds(); - - // Typeの定義 - // (Type 名に # は使えないっぽい。) - EsType type = EsModel.type(idxName, "UserData", ROUTING_ID, 0, 0); - // ドキュメント登録 - JSONObject json1 = new JSONObject(); - json1.put("c", ROUTING_ID); - json1.put("p", Long.parseLong("1406595596944")); - json1.put("u", Long.parseLong("1406595596944")); - PersoniumIndexResponse res1 = type.create("documentId1", json1); - assertEquals(idList[0], res1.getId()); - } - - /** - * すべてのテスト毎に1度実行される処理. - * @throws InterruptedException InterruptedException - */ - @After - public void after() throws InterruptedException { - // 作成したインデックスを消す - EsType type = EsModel.type(idxName, "UserData", ROUTING_ID, 0, 0); - type.delete("documentId1"); - } - - /** - * ADSにCellを登録できること. - * @throws AdsException AdsException - */ - @Test - public void ADSにCellを登録できること() throws AdsException { - try { - AdsAccessor.initializedAds(); - // Elasticsearchへリペア対象のデータを取得 - List list = Arrays.asList(idList); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // ADSへリペアを実施する - AdsAccessor.createAds(idxName, "Cell", esResponse); - - // MySQLにデータが登録されていることを確認 - List adsResponce = ads.searchCellList(idxName, list); - assertEquals(1, adsResponce.size()); - } finally { - AdsAccessor.deleteAds(idxName, "Cell", "documentId1"); - } - } - - /** - * ADSにLinkを登録できること. - * @throws AdsException AdsException - */ - @SuppressWarnings("unchecked") - @Test - public void ADSにLinkを登録できること() throws AdsException { - try { - // Typeの定義 - // (Type 名に # は使えないっぽい。) - EsType type = EsModel.type(idxName, "UserData", ROUTING_ID, 0, 0); - // ドキュメント登録 - JSONObject json1 = new JSONObject(); - json1.put("c", ROUTING_ID); - json1.put("t1", "UserData"); - json1.put("t2", "UserData"); - json1.put("k1", "_u8jGStVRNmS2dypzsQAHC"); - json1.put("k2", "_u8jGStVRNmS2dypzsQAHD"); - json1.put("p", Long.parseLong("1406595596944")); - json1.put("u", Long.parseLong("1406595596944")); - PersoniumIndexResponse res1 = type.create("documentId2", json1); - assertEquals("documentId2", res1.getId()); - - AdsAccessor.initializedAds(); - // Elasticsearchへリペア対象のデータを取得 - List list = new ArrayList(); - list.add("documentId2"); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // ADSへリペアを実施する - AdsAccessor.createAds(idxName, "link", esResponse); - - // MySQLにデータが登録されていることを確認 - List adsResponce = ads.searchLinkList(idxName, list); - assertEquals(1, adsResponce.size()); - } finally { - AdsAccessor.deleteAds(idxName, "link", "documentId2"); - } - } - - /** - * ADSにDavを登録できること. - * @throws AdsException AdsException - */ - @Test - public void ADSにDavを登録できること() throws AdsException { - try { - AdsAccessor.initializedAds(); - // Elasticsearchへリペア対象のデータを取得 - List list = Arrays.asList(idList); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // ADSへリペアを実施する - AdsAccessor.createAds(idxName, "dav", esResponse); - - // MySQLにデータが登録されていることを確認 - List adsResponce = ads.searchDavNodeList(idxName, list); - assertEquals(1, adsResponce.size()); - } finally { - AdsAccessor.deleteAds(idxName, "dav", "documentId1"); - } - } - - /** - * ADSにEntityを登録できること. - * @throws AdsException AdsException - */ - @Test - public void ADSにEntityを登録できること() throws AdsException { - try { - AdsAccessor.initializedAds(); - // Elasticsearchへリペア対象のデータを取得 - List list = Arrays.asList(idList); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // ADSへリペアを実施する - AdsAccessor.createAds(idxName, "Box", esResponse); - - // MySQLにデータが登録されていることを確認 - List adsResponce = ads.searchEntityList(idxName, list); - assertEquals(1, adsResponce.size()); - } finally { - AdsAccessor.deleteAds(idxName, "Box", "documentId1"); - } - } - - /** - * ADSにCellを更新できること. - * @throws AdsException AdsException - */ - @Test - public void ADSにCellを更新できること() throws AdsException { - try { - AdsAccessor.initializedAds(); - // Elasticsearchへリペア対象のデータを取得 - List list = Arrays.asList(idList); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - AdsAccessor.createAds(idxName, "Cell", esResponse); - - Map map = esResponse.getHits().getHits()[0].getSource(); - map.put("b", "box"); - // ADSへリペアを実施する(Update) - AdsAccessor.updateAds(idxName, "Cell", esResponse); - - // MySQLにデータが登録されていることを確認 - List adsResponce = ads.searchCellList(idxName, list); - assertEquals(1, adsResponce.size()); - assertEquals("box", ((JSONObject) adsResponce.get(0).get("source")).get("b")); - } finally { - AdsAccessor.deleteAds(idxName, "Cell", "documentId1"); - } - } - - /** - * ADSにLinkを更新できること. - * @throws AdsException AdsException - */ - @SuppressWarnings("unchecked") - @Test - public void ADSにLinkを更新できること() throws AdsException { - try { - // Typeの定義 - // (Type 名に # は使えないっぽい。) - EsType type = EsModel.type(idxName, "UserData", ROUTING_ID, 0, 0); - // ドキュメント登録 - JSONObject json1 = new JSONObject(); - json1.put("c", ROUTING_ID); - json1.put("t1", "UserData"); - json1.put("t2", "UserData"); - json1.put("k1", "_u8jGStVRNmS2dypzsQAHC"); - json1.put("k2", "_u8jGStVRNmS2dypzsQAHD"); - json1.put("p", Long.parseLong("1406595596944")); - json1.put("u", Long.parseLong("1406595596944")); - PersoniumIndexResponse res1 = type.create("documentId2", json1); - assertEquals("documentId2", res1.getId()); - - AdsAccessor.initializedAds(); - // Elasticsearchへリペア対象のデータを取得 - List list = new ArrayList(); - list.add("documentId2"); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // ADSへリペアを実施する - AdsAccessor.createAds(idxName, "link", esResponse); - - Map map = esResponse.getHits().getHits()[0].getSource(); - map.put("t1", "Account"); - map.put("t2", "Role"); - AdsAccessor.updateAds(idxName, "link", esResponse); - - // MySQLにデータが登録されていることを確認 - List adsResponce = ads.searchLinkList(idxName, list); - assertEquals(1, adsResponce.size()); - assertEquals("Account", ((JSONObject) adsResponce.get(0).get("source")).get("t1")); - assertEquals("Role", ((JSONObject) adsResponce.get(0).get("source")).get("t2")); - } finally { - AdsAccessor.deleteAds(idxName, "link", "documentId2"); - } - } - - /** - * ADSにDavを更新できること. - * @throws AdsException AdsException - */ - @Test - @Ignore - // DcSearchResponseを変更しても、update時にはこのデータを使わないため、テストが出来ない。 - public void ADSにDavを更新できること() throws AdsException { - try { - AdsAccessor.initializedAds(); - // Elasticsearchへリペア対象のデータを取得 - List list = Arrays.asList(idList); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - AdsAccessor.createAds(idxName, "dav", esResponse); - - Map map = esResponse.getHits().getHits()[0].getSource(); - map.put("b", "box"); - // ADSへリペアを実施する - AdsAccessor.updateAds(idxName, "dav", esResponse); - - // MySQLにデータが登録されていることを確認 - List adsResponce = ads.searchDavNodeList(idxName, list); - assertEquals(1, adsResponce.size()); - assertEquals("box", ((JSONObject) adsResponce.get(0).get("source")).get("b")); - } finally { - AdsAccessor.deleteAds(idxName, "dav", "documentId1"); - } - } - - /** - * ADSにEntityを更新できること. - * @throws AdsException AdsException - */ - @Test - public void ADSにEntityを更新できること() throws AdsException { - try { - AdsAccessor.initializedAds(); - // Elasticsearchへリペア対象のデータを取得 - List list = Arrays.asList(idList); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - AdsAccessor.createAds(idxName, "Box", esResponse); - - Map map = esResponse.getHits().getHits()[0].getSource(); - map.put("b", "box"); - // ADSへリペアを実施する - AdsAccessor.updateAds(idxName, "Box", esResponse); - - // MySQLにデータが登録されていることを確認 - List adsResponce = ads.searchEntityList(idxName, list); - assertEquals(1, adsResponce.size()); - assertEquals("box", ((JSONObject) adsResponce.get(0).get("source")).get("b")); - } finally { - AdsAccessor.deleteAds(idxName, "Box", "documentId1"); - } - } -} diff --git a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/AllTests.java b/src/test/java/io/personium/test/unit/core/model/impl/es/repair/AllTests.java deleted file mode 100644 index a17e166f9..000000000 --- a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/AllTests.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * 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 io.personium.test.unit.core.model.impl.es.repair; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -/** - * パッケージ配下のテストケースを全て実行するためのテストスイート. - */ -@RunWith(Suite.class) -@SuiteClasses({ - AdsAcessorTest.class, - EsAcessorTest.class, - RepairAdsTest.class, - RepairAdsCompleteTest.class, - RepairAdsIntegrationTest.class -}) -public class AllTests { -} diff --git a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/EsAcessorTest.java b/src/test/java/io/personium/test/unit/core/model/impl/es/repair/EsAcessorTest.java deleted file mode 100644 index 1073a1273..000000000 --- a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/EsAcessorTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * 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 io.personium.test.unit.core.model.impl.es.repair; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.json.simple.JSONObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.es.EsIndex; -import io.personium.common.es.EsType; -import io.personium.common.es.response.PersoniumIndexResponse; -import io.personium.common.es.response.PersoniumSearchHit; -import io.personium.common.es.response.PersoniumSearchResponse; -import io.personium.common.es.util.PersoniumUUID; -import io.personium.core.model.impl.es.EsModel; -import io.personium.core.model.impl.es.repair.EsAccessor; -import io.personium.test.categories.Unit; - -import java.util.Arrays; - -/** - * EsAcessorユニットテストクラス. - */ -@Category({Unit.class }) -public class EsAcessorTest { - private static final String ROUTING_ID = "routingId"; - - static Logger log = LoggerFactory.getLogger(EsAcessorTest.class); - - private String idxName = "test" + PersoniumUUID.randomUUID(); - private String[] idList = {"documentId1", "documentId2" }; - - /** - * すべてのテスト毎に1度実行される処理. - * @throws InterruptedException InterruptedException - */ - @Before - @SuppressWarnings("unchecked") - public void before() throws InterruptedException { - // データ検索確認用のテストデータを作成(EsModelのテストをベースにデータ作成) - EsIndex idx = EsModel.idxUser(idxName); - // インデックスの作成 - idx.create(); - // Typeの定義 - // (Type 名に # は使えないっぽい。) - EsType type = EsModel.type(idx.getName(), "tType2", ROUTING_ID, 0, 0); - // ドキュメント登録 - JSONObject json1 = new JSONObject(); - json1.put("key1-1", "value1"); - json1.put("key1-2", "value2"); - PersoniumIndexResponse res1 = type.create("documentId1", json1); - assertEquals(idList[0], res1.getId()); - JSONObject json2 = new JSONObject(); - json2.put("key2-1", "value1"); - json2.put("key2-2", "value2"); - PersoniumIndexResponse res2 = type.create("documentId2", json2); - assertEquals(idList[1], res2.getId()); - } - - /** - * すべてのテスト毎に1度実行される処理. - * @throws InterruptedException InterruptedException - */ - @After - public void after() throws InterruptedException { - // 作成したインデックスを消す - EsIndex idx = EsModel.idxUser(idxName); - idx.delete(); - } - - /** - * EsAcessorの基礎的なテスト. - */ - @Test - public void EsModelの基礎的なテスト() { - - List list = Arrays.asList(idList); - PersoniumSearchResponse response = EsAccessor.search(idxName, ROUTING_ID, list, "tType2"); - assertEquals(2, response.getHits().getHits().length); - for (PersoniumSearchHit hit : response.getHits().getHits()) { - assertTrue(list.contains(hit.getId())); - } - } - -} diff --git a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsCompleteTest.java b/src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsCompleteTest.java deleted file mode 100644 index 0e2abb000..000000000 --- a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsCompleteTest.java +++ /dev/null @@ -1,685 +0,0 @@ -/** - * 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 io.personium.test.unit.core.model.impl.es.repair; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.ads.AbstractAdsWriteFailureLog; -import io.personium.common.ads.AdsWriteFailureLogException; -import io.personium.common.ads.AdsWriteFailureLogWriter; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.impl.es.repair.RepairAds; -import io.personium.test.categories.Unit; - -/** - * RepairAdsTest ユニットテストクラス. - */ -@Category({Unit.class }) -public class RepairAdsCompleteTest { - - static Logger log = LoggerFactory.getLogger(RepairAdsCompleteTest.class); - private static final String PIO_VERSION_DUMMY = "1.4.1-test"; - private static final String TEST_ADS_LOGDIR = "./testdir"; - - /** - * すべてのテスト実行前の処理. - */ - @BeforeClass - public static void beforeClass() { - // 他のテスト中で作成されたADS書込み失敗ログの削除 - File logDir = new File(PersoniumUnitConfig.getAdsWriteFailureLogDir()); - File[] files = logDir.listFiles(); - for (File file : files) { - file.delete(); - } - } - - /** - * 各テストの開始前に実行される処理. - */ - @Before - public void before() { - // テスト用ログディレクトリが各テストで削除しきれていない場合を考慮して、最初にディレクトリを削除しておく - File logDir = new File(TEST_ADS_LOGDIR); - if (logDir.exists()) { - File[] files = logDir.listFiles(); - for (File file : files) { - file.delete(); - } - logDir.delete(); - } - } - - /** - * 出力中のADS書き込み失敗ログファイルのみが存在しない場合にリペア終了判定でfalseが返却されること. - */ - @Test - public void 出力中のADS書き込み失敗ログファイルのみが存在しない場合にリペア終了判定でfalseが返却されること() { - RepairAds repair = RepairAds.getInstance(); - AdsWriteFailureLogWriter writer = AdsWriteFailureLogWriter.getInstance("./", PIO_VERSION_DUMMY, true); - File dir = new File(TEST_ADS_LOGDIR); - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - baseDir.set(writer, TEST_ADS_LOGDIR); - if (!dir.mkdir()) { - fail("mkdir failed(environment error): " + dir.getAbsolutePath()); - } - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - - File file = null; - String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ROTATE, PIO_VERSION_DUMMY, - System.currentTimeMillis()); - File rotated = new File(dir, fileName); - try { - Class clazz = RepairAds.class; - Field baseDir = clazz.getDeclaredField("adsLogBaseDir"); - baseDir.setAccessible(true); - baseDir.set(repair, new File(TEST_ADS_LOGDIR)); - Field version = clazz.getDeclaredField("pcsVersion"); - version.setAccessible(true); - version.set(repair, PIO_VERSION_DUMMY); - Method method = clazz.getDeclaredMethod("isRepairCompleted"); - method.setAccessible(true); - - rotated.createNewFile(); - file = getAdsWriteFailureLog(writer); - assertFalse((Boolean) method.invoke(repair)); - } catch (Exception e) { - e.printStackTrace(); - fail("check failed"); - } finally { - try { - writer.closeActiveFile(); - } catch (AdsWriteFailureLogException e) { - e.printStackTrace(); - } - if (null != file) { - file.delete(); - } - if (null != rotated) { - rotated.delete(); - } - if (null != dir) { - dir.delete(); - } - } - } - - /** - * 出力中のADS書き込み失敗ログファイルのみが存在する場合にリペア終了判定でfalseが返却されること. - */ - @Test - public void 出力中のADS書き込み失敗ログファイルのみが存在する場合にリペア終了判定でfalseが返却されること() { - RepairAds repair = RepairAds.getInstance(); - AdsWriteFailureLogWriter writer = AdsWriteFailureLogWriter.getInstance("./", PIO_VERSION_DUMMY, true); - File dir = new File(TEST_ADS_LOGDIR); - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - baseDir.set(writer, TEST_ADS_LOGDIR); - if (!dir.mkdir()) { - fail("mkdir failed(environment error): " + dir.getAbsolutePath()); - } - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - - File file = null; - try { - Class clazz = RepairAds.class; - Field baseDir = clazz.getDeclaredField("adsLogBaseDir"); - baseDir.setAccessible(true); - baseDir.set(repair, new File(TEST_ADS_LOGDIR)); - Field version = clazz.getDeclaredField("pcsVersion"); - version.setAccessible(true); - version.set(repair, PIO_VERSION_DUMMY); - Method method = clazz.getDeclaredMethod("isRepairCompleted"); - method.setAccessible(true); - - writer.openActiveFile(); - file = getAdsWriteFailureLog(writer); - assertFalse((Boolean) method.invoke(repair)); - } catch (Exception e) { - e.printStackTrace(); - fail("check failed"); - } finally { - try { - writer.closeActiveFile(); - } catch (AdsWriteFailureLogException e) { - e.printStackTrace(); - } - if (null != file) { - file.delete(); - } - if (null != dir) { - dir.delete(); - } - } - } - - /** - * 出力中とローテートされたADS書き込み失敗ログファイルが存在する場合にリペア終了判定でfalseが返却されること. - */ - @Test - public void 出力中とローテートされたADS書き込み失敗ログファイルが存在する場合にリペア終了判定でfalseが返却されること() { - RepairAds repair = RepairAds.getInstance(); - AdsWriteFailureLogWriter writer = AdsWriteFailureLogWriter.getInstance("./", PIO_VERSION_DUMMY, true); - File dir = new File(TEST_ADS_LOGDIR); - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - baseDir.set(writer, TEST_ADS_LOGDIR); - if (!dir.mkdir()) { - fail("mkdir failed(environment error): " + dir.getAbsolutePath()); - } - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - - File file = null; - String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ROTATE, PIO_VERSION_DUMMY, - System.currentTimeMillis()); - File rotated = new File(dir, fileName); - try { - Class clazz = RepairAds.class; - Field baseDir = clazz.getDeclaredField("adsLogBaseDir"); - baseDir.setAccessible(true); - baseDir.set(repair, new File(TEST_ADS_LOGDIR)); - Field version = clazz.getDeclaredField("pcsVersion"); - version.setAccessible(true); - version.set(repair, PIO_VERSION_DUMMY); - Method method = clazz.getDeclaredMethod("isRepairCompleted"); - method.setAccessible(true); - - rotated.createNewFile(); - writer.openActiveFile(); - file = getAdsWriteFailureLog(writer); - assertFalse((Boolean) method.invoke(repair)); - } catch (Exception e) { - e.printStackTrace(); - fail("check failed"); - } finally { - try { - writer.closeActiveFile(); - } catch (AdsWriteFailureLogException e) { - e.printStackTrace(); - } - if (null != file) { - file.delete(); - } - if (null != rotated) { - rotated.delete(); - } - if (null != dir) { - dir.delete(); - } - } - } - - /** - * 論理削除されたADS書き込み失敗ログファイルだけが存在する場合にリペア終了判定でtrueが返却されること. - */ - @Test - public void 論理削除されたADS書き込み失敗ログファイルだけが存在する場合にリペア終了判定でtrueが返却されること() { - RepairAds repair = RepairAds.getInstance(); - AdsWriteFailureLogWriter writer = AdsWriteFailureLogWriter.getInstance("./", PIO_VERSION_DUMMY, true); - File dir = new File(TEST_ADS_LOGDIR); - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - baseDir.set(writer, TEST_ADS_LOGDIR); - if (!dir.mkdir()) { - fail("mkdir failed(environment error): " + dir.getAbsolutePath()); - } - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - - File file = null; - String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ROTATE, PIO_VERSION_DUMMY, - System.currentTimeMillis()) + AbstractAdsWriteFailureLog.LOGICAL_DELETED_LOGNAME_SUFFIX; - File rotated = new File(dir, fileName); - try { - Class clazz = RepairAds.class; - Field baseDir = clazz.getDeclaredField("adsLogBaseDir"); - baseDir.setAccessible(true); - baseDir.set(repair, new File(TEST_ADS_LOGDIR)); - Field version = clazz.getDeclaredField("pcsVersion"); - version.setAccessible(true); - version.set(repair, PIO_VERSION_DUMMY); - Method method = clazz.getDeclaredMethod("isRepairCompleted"); - method.setAccessible(true); - - rotated.createNewFile(); - file = getAdsWriteFailureLog(writer); - assertTrue((Boolean) method.invoke(repair)); - } catch (Exception e) { - e.printStackTrace(); - fail("check failed"); - } finally { - try { - writer.closeActiveFile(); - } catch (AdsWriteFailureLogException e) { - e.printStackTrace(); - } - if (null != file) { - file.delete(); - } - if (null != rotated) { - rotated.delete(); - } - if (null != dir) { - dir.delete(); - } - } - } - - /** - * エラー用のADS書き込み失敗ログファイルだけが存在する場合にリペア終了判定でfalseが返却されること. - */ - @Test - public void エラー用のADS書き込み失敗ログファイルだけが存在する場合にリペア終了判定でfalseが返却されること() { - RepairAds repair = RepairAds.getInstance(); - AdsWriteFailureLogWriter writer = AdsWriteFailureLogWriter.getInstance("./", PIO_VERSION_DUMMY, true); - File dir = new File(TEST_ADS_LOGDIR); - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - baseDir.set(writer, TEST_ADS_LOGDIR); - if (!dir.mkdir()) { - fail("mkdir failed(environment error): " + dir.getAbsolutePath()); - } - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - - File file = null; - String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ACTIVE, PIO_VERSION_DUMMY, - System.currentTimeMillis()) + AbstractAdsWriteFailureLog.ERROR_LOGNAME_SUFFIX; - File rotated = new File(dir, fileName); - try { - Class clazz = RepairAds.class; - Field baseDir = clazz.getDeclaredField("adsLogBaseDir"); - baseDir.setAccessible(true); - baseDir.set(repair, new File(TEST_ADS_LOGDIR)); - Field version = clazz.getDeclaredField("pcsVersion"); - version.setAccessible(true); - version.set(repair, PIO_VERSION_DUMMY); - Method method = clazz.getDeclaredMethod("isRepairCompleted"); - method.setAccessible(true); - - rotated.createNewFile(); - file = getAdsWriteFailureErrorLog(writer); - assertFalse((Boolean) method.invoke(repair)); - } catch (Exception e) { - e.printStackTrace(); - fail("check failed"); - } finally { - try { - writer.closeActiveFile(); - } catch (AdsWriteFailureLogException e) { - e.printStackTrace(); - } - if (null != file) { - file.delete(); - } - if (null != rotated) { - rotated.delete(); - } - if (null != dir) { - dir.delete(); - } - } - } - - /** - * リトライ用のADS書き込み失敗ログファイルだけが存在する場合にリペア終了判定でfalseが返却されること. - */ - @Test - public void リトライ用のADS書き込み失敗ログファイルだけが存在する場合にリペア終了判定でfalseが返却されること() { - RepairAds repair = RepairAds.getInstance(); - AdsWriteFailureLogWriter writer = AdsWriteFailureLogWriter.getInstance("./", PIO_VERSION_DUMMY, true); - File dir = new File(TEST_ADS_LOGDIR); - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - baseDir.set(writer, TEST_ADS_LOGDIR); - if (!dir.mkdir()) { - fail("mkdir failed(environment error): " + dir.getAbsolutePath()); - } - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - - File file = null; - String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ACTIVE, PIO_VERSION_DUMMY, - System.currentTimeMillis()) + AbstractAdsWriteFailureLog.RETRY_LOGNAME_SUFFIX; - File rotated = new File(dir, fileName); - try { - Class clazz = RepairAds.class; - Field baseDir = clazz.getDeclaredField("adsLogBaseDir"); - baseDir.setAccessible(true); - baseDir.set(repair, new File(TEST_ADS_LOGDIR)); - Field version = clazz.getDeclaredField("pcsVersion"); - version.setAccessible(true); - version.set(repair, PIO_VERSION_DUMMY); - Method method = clazz.getDeclaredMethod("isRepairCompleted"); - method.setAccessible(true); - - rotated.createNewFile(); - file = getAdsWriteFailureRetryLog(writer); - assertFalse((Boolean) method.invoke(repair)); - } catch (Exception e) { - e.printStackTrace(); - fail("check failed"); - } finally { - try { - writer.closeActiveFile(); - } catch (AdsWriteFailureLogException e) { - e.printStackTrace(); - } - if (null != file) { - file.delete(); - } - if (null != rotated) { - rotated.delete(); - } - if (null != dir) { - dir.delete(); - } - } - } - - /** - * ローテートされたリトライ用のADS書き込み失敗ログファイルだけが存在する場合にリペア終了判定でfalseが返却されること. - */ - @Test - public void ローテートされたリトライ用のADS書き込み失敗ログファイルだけが存在する場合にリペア終了判定でfalseが返却されること() { - RepairAds repair = RepairAds.getInstance(); - AdsWriteFailureLogWriter writer = AdsWriteFailureLogWriter.getInstance("./", PIO_VERSION_DUMMY, true); - File dir = new File(TEST_ADS_LOGDIR); - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - baseDir.set(writer, TEST_ADS_LOGDIR); - if (!dir.mkdir()) { - fail("mkdir failed(environment error): " + dir.getAbsolutePath()); - } - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - - File file = null; - String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ROTATE, PIO_VERSION_DUMMY, - System.currentTimeMillis()) + AbstractAdsWriteFailureLog.RETRY_LOGNAME_SUFFIX; - File rotated = new File(dir, fileName); - try { - Class clazz = RepairAds.class; - Field baseDir = clazz.getDeclaredField("adsLogBaseDir"); - baseDir.setAccessible(true); - baseDir.set(repair, new File(TEST_ADS_LOGDIR)); - Field version = clazz.getDeclaredField("pcsVersion"); - version.setAccessible(true); - version.set(repair, PIO_VERSION_DUMMY); - Method method = clazz.getDeclaredMethod("isRepairCompleted"); - method.setAccessible(true); - - rotated.createNewFile(); - file = getAdsWriteFailureRotatedRetryLog(writer); - assertFalse((Boolean) method.invoke(repair)); - } catch (Exception e) { - e.printStackTrace(); - fail("check failed"); - } finally { - try { - writer.closeActiveFile(); - } catch (AdsWriteFailureLogException e) { - e.printStackTrace(); - } - if (null != file) { - file.delete(); - } - if (null != rotated) { - rotated.delete(); - } - if (null != dir) { - dir.delete(); - } - } - } - - /** - * ローテートされたエラー用のADS書き込み失敗ログファイルだけが存在する場合にリペア終了判定でfalseが返却されること. - */ - @Test - public void ローテートされたエラー用のADS書き込み失敗ログファイルだけが存在する場合にリペア終了判定でfalseが返却されること() { - RepairAds repair = RepairAds.getInstance(); - AdsWriteFailureLogWriter writer = AdsWriteFailureLogWriter.getInstance("./", PIO_VERSION_DUMMY, true); - File dir = new File(TEST_ADS_LOGDIR); - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - baseDir.set(writer, TEST_ADS_LOGDIR); - if (!dir.mkdir()) { - fail("mkdir failed(environment error): " + dir.getAbsolutePath()); - } - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - - File file = null; - String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ROTATE, PIO_VERSION_DUMMY, - System.currentTimeMillis()) + AbstractAdsWriteFailureLog.ERROR_LOGNAME_SUFFIX; - File rotated = new File(dir, fileName); - try { - Class clazz = RepairAds.class; - Field baseDir = clazz.getDeclaredField("adsLogBaseDir"); - baseDir.setAccessible(true); - baseDir.set(repair, new File(TEST_ADS_LOGDIR)); - Field version = clazz.getDeclaredField("pcsVersion"); - version.setAccessible(true); - version.set(repair, PIO_VERSION_DUMMY); - Method method = clazz.getDeclaredMethod("isRepairCompleted"); - method.setAccessible(true); - - rotated.createNewFile(); - file = getAdsWriteFailureRotatedErrorLog(writer); - assertFalse((Boolean) method.invoke(repair)); - } catch (Exception e) { - e.printStackTrace(); - fail("check failed"); - } finally { - try { - writer.closeActiveFile(); - } catch (AdsWriteFailureLogException e) { - e.printStackTrace(); - } - if (null != file) { - file.delete(); - } - if (null != rotated) { - rotated.delete(); - } - if (null != dir) { - dir.delete(); - } - } - } - - /** - * オープン済みの出力中ADS書き込み失敗ログのパスを取得する. - * @param writer writer - * @return ログのパス - */ - private File getAdsWriteFailureLog(AdsWriteFailureLogWriter writer) { - File file = null; - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - String baseDirV = (String) baseDir.get(writer); - clazz = writer.getClass(); - Field createdTime = clazz.getDeclaredField("createdTime"); - createdTime.setAccessible(true); - Long createdTimeV = (Long) createdTime.get(writer); - final String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ACTIVE, PIO_VERSION_DUMMY, - createdTimeV); - file = new File(baseDirV, fileName); - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - return file; - } - - /** - * 出力中のエラー用ADS書き込み失敗ログのパスを取得する. - * @param writer writer - * @return ログのパス - */ - private File getAdsWriteFailureErrorLog(AdsWriteFailureLogWriter writer) { - File file = null; - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - String baseDirV = (String) baseDir.get(writer); - clazz = writer.getClass(); - Field createdTime = clazz.getDeclaredField("createdTime"); - createdTime.setAccessible(true); - Long createdTimeV = (Long) createdTime.get(writer); - final String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ACTIVE, PIO_VERSION_DUMMY, - createdTimeV) + AbstractAdsWriteFailureLog.ERROR_LOGNAME_SUFFIX; - file = new File(baseDirV, fileName); - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - return file; - } - - /** - * 出力中のリトライ用のADS書き込み失敗ログのパスを取得する. - * @param writer writer - * @return ログのパス - */ - private File getAdsWriteFailureRetryLog(AdsWriteFailureLogWriter writer) { - File file = null; - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - String baseDirV = (String) baseDir.get(writer); - clazz = writer.getClass(); - Field createdTime = clazz.getDeclaredField("createdTime"); - createdTime.setAccessible(true); - Long createdTimeV = (Long) createdTime.get(writer); - final String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ACTIVE, PIO_VERSION_DUMMY, - createdTimeV) + AbstractAdsWriteFailureLog.RETRY_LOGNAME_SUFFIX; - file = new File(baseDirV, fileName); - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - return file; - } - - /** - * 出力中のエラー用ADS書き込み失敗ログのパスを取得する. - * @param writer writer - * @return ログのパス - */ - private File getAdsWriteFailureRotatedErrorLog(AdsWriteFailureLogWriter writer) { - File file = null; - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - String baseDirV = (String) baseDir.get(writer); - clazz = writer.getClass(); - Field createdTime = clazz.getDeclaredField("createdTime"); - createdTime.setAccessible(true); - Long createdTimeV = (Long) createdTime.get(writer); - final String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ROTATE, PIO_VERSION_DUMMY, - createdTimeV) + AbstractAdsWriteFailureLog.ERROR_LOGNAME_SUFFIX; - file = new File(baseDirV, fileName); - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - return file; - } - - /** - * 出力中のリトライ用のADS書き込み失敗ログのパスを取得する. - * @param writer writer - * @return ログのパス - */ - private File getAdsWriteFailureRotatedRetryLog(AdsWriteFailureLogWriter writer) { - File file = null; - try { - Class clazz = AbstractAdsWriteFailureLog.class; - Field baseDir = clazz.getDeclaredField("baseDir"); - baseDir.setAccessible(true); - String baseDirV = (String) baseDir.get(writer); - clazz = writer.getClass(); - Field createdTime = clazz.getDeclaredField("createdTime"); - createdTime.setAccessible(true); - Long createdTimeV = (Long) createdTime.get(writer); - final String fileName = String.format(AbstractAdsWriteFailureLog.LOGNAME_FORMAT_ROTATE, PIO_VERSION_DUMMY, - createdTimeV) + AbstractAdsWriteFailureLog.RETRY_LOGNAME_SUFFIX; - file = new File(baseDirV, fileName); - } catch (Exception e) { - e.printStackTrace(); - fail("configuration failed."); - } - return file; - } - -} diff --git a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsIntegrationTest.java b/src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsIntegrationTest.java deleted file mode 100644 index 0f5dc5ed3..000000000 --- a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsIntegrationTest.java +++ /dev/null @@ -1,376 +0,0 @@ -/** - * 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 io.personium.test.unit.core.model.impl.es.repair; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MediaType; - -import org.apache.http.HttpStatus; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; - -import com.sun.jersey.test.framework.WebAppDescriptor; - -import io.personium.common.ads.AdsWriteFailureLogException; -import io.personium.common.ads.AdsWriteFailureLogInfo; -import io.personium.common.ads.AdsWriteFailureLogWriter; -import io.personium.common.es.EsIndex; -import io.personium.common.es.EsType; -import io.personium.common.es.response.PersoniumSearchHit; -import io.personium.common.es.response.PersoniumSearchResponse; -import io.personium.common.es.util.IndexNameEncoder; -import io.personium.core.PersoniumCoreLog; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.Cell; -import io.personium.core.model.impl.es.EsModel; -import io.personium.core.model.impl.es.ads.Ads; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.ads.JdbcAds; -import io.personium.core.model.impl.es.doc.CellDocHandler; -import io.personium.core.model.impl.es.doc.EntitySetDocHandler; -import io.personium.core.model.impl.es.doc.UserDataDocHandler; -import io.personium.core.model.impl.es.odata.UserDataODataProducer; -import io.personium.core.model.lock.Lock; -import io.personium.core.model.lock.LockKeyComposer; -import io.personium.core.webcontainer.listener.RepairServiceLauncher; -import io.personium.test.categories.Unit; -import io.personium.test.jersey.AbstractCase; -import io.personium.test.jersey.PersoniumIntegTestRunner; -import io.personium.test.utils.BoxUtils; -import io.personium.test.utils.CellUtils; -import io.personium.test.utils.DavResourceUtils; -import io.personium.test.utils.EntityTypeUtils; -import io.personium.test.utils.UserDataUtils; - -/** - * マスタ自動復旧機能のcoreとの結合テストクラス. - */ -@RunWith(PersoniumIntegTestRunner.class) -@Category({Unit.class }) -public class RepairAdsIntegrationTest extends AbstractCase { - - private String cellName = "repairAdsTestCell"; - private String owner = "repairadstest"; - - private Ads ads; - - private static final Map INIT_PARAMS = new HashMap(); - static { - INIT_PARAMS.put("com.sun.jersey.config.property.packages", - "io.personium.core.rs"); - INIT_PARAMS.put("com.sun.jersey.spi.container.ContainerRequestFilters", - "io.personium.core.jersey.filter.PersoniumCoreContainerFilter"); - INIT_PARAMS.put("com.sun.jersey.spi.container.ContainerResponseFilters", - "io.personium.core.jersey.filter.PersoniumCoreContainerFilter"); - } - - /** - * コンストラクタ. - */ - public RepairAdsIntegrationTest() { - super(new WebAppDescriptor.Builder(INIT_PARAMS).build()); - } - - /** - * core経由で登録されたCellデータをMySQLに登録できること. - * @throws AdsException MySQL操作失敗 - */ - @Before - public void before() throws AdsException { - try { - ads = new JdbcAds(); - } catch (AdsException e) { - return; - } - } - - /** - * personium経由で登録されたCellデータをMySQLに登録できること. - * @throws AdsException MySQL操作失敗 - */ - @Test - public void persnoium経由で登録されたCellデータをMySQLに登録できること() throws AdsException { - String indexName = PersoniumUnitConfig.getEsUnitPrefix() + "_" + IndexNameEncoder.encodeEsIndexName("ad"); - String dbName = PersoniumUnitConfig.getEsUnitPrefix() + "_" + IndexNameEncoder.encodeEsIndexName(owner); - - // ESアクセス情報 - String esTypeName = Cell.EDM_TYPE_NAME; - String routingId = EsIndex.CELL_ROUTING_KEY_NAME; - String searchFieldName = "Name"; - String searchFieldValue = cellName; - - try { - // personium.io経由でCell登録(UnitUser指定) - CellUtils.create(cellName, MASTER_TOKEN_NAME, owner, HttpStatus.SC_CREATED); - - // ESからデータ取得 - PersoniumSearchHit esHit = searchFromEs(indexName, esTypeName, routingId, - searchFieldName, searchFieldValue); - String id = esHit.getId(); - EntitySetDocHandler esDocument = new CellDocHandler(esHit); - - // MySQLから該当データ検索(比較用に控えておく) - List idList = new ArrayList(); - idList.add(id); - // MySQLにデータが登録されていることを確認 - List adsResponceBefore = ads.searchCellList(dbName, idList); - assertEquals(1, adsResponceBefore.size()); - // MySQLから該当データ削除 - ads.deleteCell(dbName, id); - - // 取得したデータを元にジャーナルログ作成 - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - esDocument.getCellId(), null, null); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - esDocument.getUnitUserName(), esDocument.getType(), lockKey, - esDocument.getCellId(), esDocument.getId(), - AdsWriteFailureLogInfo.OperationKind.CREATE, 1, esDocument.getUpdated()); - recordAdsWriteFailureLog(loginfo); - - // リペア実行 - RepairServiceLauncher.RepairAdsService service = new RepairServiceLauncher.RepairAdsService(); - service.run(); - - // データがリペアされていることを確認(データが存在すること) - List adsResponceAfter = ads.searchCellList(dbName, idList); - - // データがリペアされていることを確認(削除前とリペア後のCellが一致すること) - assertEquals(((JSONObject) adsResponceBefore.get(0)).get("id"), ((JSONObject) adsResponceAfter.get(0)) - .get("id")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("u"), ((JSONObject) adsResponceAfter - .get(0).get("source")).get("u")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("d"), ((JSONObject) adsResponceAfter - .get(0).get("source")).get("d")); - assertEquals( - ((JSONObject) adsResponceBefore.get(0).get("source")).get("s"), - ((JSONObject) adsResponceBefore.get(0).get("source")).get("s")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("b"), ((JSONObject) adsResponceAfter - .get(0).get("source")).get("b")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("c"), ((JSONObject) adsResponceAfter - .get(0).get("source")).get("c")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("p"), ((JSONObject) adsResponceAfter - .get(0).get("source")).get("p")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("a"), ((JSONObject) adsResponceAfter - .get(0).get("source")).get("a")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("n"), ((JSONObject) adsResponceAfter - .get(0).get("source")).get("n")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("ll"), ((JSONObject) adsResponceAfter - .get(0).get("source")).get("ll")); - assertEquals( - ((JSONObject) adsResponceBefore.get(0).get("source")).get("h"), - ((JSONObject) adsResponceBefore.get(0).get("source")).get("h")); - assertEquals( - ((JSONObject) adsResponceBefore.get(0)).get("type"), - ((JSONObject) adsResponceAfter.get(0)).get("type")); - - // personium.io経由でCell削除 - CellUtils.delete(MASTER_TOKEN_NAME, cellName, HttpStatus.SC_NO_CONTENT); - // データが削除されていること - adsResponceAfter = ads.searchCellList(dbName, idList); - assertEquals(0, adsResponceAfter.size()); - } finally { - CellUtils.delete(MASTER_TOKEN_NAME, cellName, -1); - } - } - - /** - * core経由で登録されたODATAデータをMySQLに登録できること. - * @throws AdsException MySQL操作失敗 - */ - @SuppressWarnings("unchecked") - @Test - public void core経由で登録されたODATAデータをMySQLに登録できること() throws AdsException { - - String userDataIndexName = PersoniumUnitConfig.getEsUnitPrefix() - + "_" + IndexNameEncoder.encodeEsIndexName(owner); - - // ESアクセス情報 - String userDataEsTypeName = UserDataODataProducer.USER_ODATA_NAMESPACE; - String userDataSearchFieldName = "__id"; - String userDataSearchFieldValue = "userDataId"; - - String boxName = "testBox"; - String colName = "testCol"; - String entityType = "testEntityType"; - String userDataId = "userDataId"; - try { - JSONObject body = new JSONObject(); - body.put("__id", userDataId); - - // 事前にデータ登録 - CellUtils.create(cellName, MASTER_TOKEN_NAME, owner, HttpStatus.SC_CREATED); - BoxUtils.create(cellName, boxName, MASTER_TOKEN_NAME, HttpStatus.SC_CREATED); - DavResourceUtils - .createODataCollection(MASTER_TOKEN_NAME, HttpStatus.SC_CREATED, cellName, boxName, colName); - EntityTypeUtils.create(cellName, MASTER_TOKEN_NAME, boxName, colName, entityType, - HttpStatus.SC_CREATED); - UserDataUtils - .create(MASTER_TOKEN_NAME, HttpStatus.SC_CREATED, body, cellName, boxName, colName, entityType); - - // ESからデータ取得 - String cellIndexName = PersoniumUnitConfig.getEsUnitPrefix() - + "_" + IndexNameEncoder.encodeEsIndexName("ad"); - PersoniumSearchHit cellEsHit = searchFromEs(cellIndexName, Cell.EDM_TYPE_NAME, - EsIndex.CELL_ROUTING_KEY_NAME, "Name", cellName); - String cellId = cellEsHit.getId(); - PersoniumSearchHit userDataEsHit = searchFromEs(userDataIndexName, userDataEsTypeName, cellId, - userDataSearchFieldName, - userDataSearchFieldValue); - EntitySetDocHandler esDocument = new UserDataDocHandler(userDataEsHit); - - // MySQLから該当データ検索(比較用に控えておく) - List idList = new ArrayList(); - idList.add(userDataEsHit.getId()); - // MySQLにデータが登録されていることを確認 - List adsResponceBefore = ads.searchEntityList(userDataIndexName, idList); - assertEquals(1, adsResponceBefore.size()); - // MySQLから該当データ削除 - ads.deleteEntity(userDataIndexName, userDataEsHit.getId()); - - // 取得したデータを元にジャーナルログ作成 - String lockKey = LockKeyComposer.fullKeyFromCategoryAndKey(Lock.CATEGORY_ODATA, - esDocument.getCellId(), esDocument.getBoxId(), esDocument.getNodeId()); - AdsWriteFailureLogInfo loginfo = new AdsWriteFailureLogInfo( - userDataIndexName, esDocument.getType(), lockKey, - esDocument.getCellId(), esDocument.getId(), - AdsWriteFailureLogInfo.OperationKind.CREATE, 1, esDocument.getUpdated()); - recordAdsWriteFailureLog(loginfo); - - // リペア実行 - RepairServiceLauncher.RepairAdsService service = new RepairServiceLauncher.RepairAdsService(); - service.run(); - - // データがリペアされていることを確(データが存在すること) - List adsResponceAfter = ads.searchEntityList(userDataIndexName, idList); - - assertEquals(((JSONObject) adsResponceBefore.get(0)).get("id"), ((JSONObject) adsResponceAfter.get(0)) - .get("id")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("u"), ((JSONObject) - adsResponceAfter - .get(0).get("source")).get("u")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("d"), ((JSONObject) - adsResponceAfter - .get(0).get("source")).get("d")); - assertEquals( - ((JSONObject) adsResponceBefore.get(0).get("source")).get("s"), - ((JSONObject) adsResponceAfter.get(0).get("source")).get("s")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("b"), ((JSONObject) - adsResponceAfter - .get(0).get("source")).get("b")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("c"), ((JSONObject) - adsResponceAfter - .get(0).get("source")).get("c")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("p"), ((JSONObject) - adsResponceAfter - .get(0).get("source")).get("p")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("a"), ((JSONObject) - adsResponceAfter - .get(0).get("source")).get("a")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("n"), ((JSONObject) - adsResponceAfter - .get(0).get("source")).get("n")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("ll"), ((JSONObject) - adsResponceAfter - .get(0).get("source")).get("ll")); - assertEquals(((JSONObject) adsResponceBefore.get(0).get("source")).get("t"), ((JSONObject) - adsResponceAfter - .get(0).get("source")).get("t")); - assertEquals( - ((JSONObject) adsResponceBefore.get(0).get("source")).get("h"), - ((JSONObject) adsResponceBefore.get(0).get("source")).get("h")); - assertEquals(((JSONObject) adsResponceBefore.get(0)).get("type"), - ((JSONObject) adsResponceAfter.get(0)).get("type")); - } finally { - UserDataUtils.delete(MASTER_TOKEN_NAME, -1, cellName, boxName, colName, entityType, - userDataId); - EntityTypeUtils.delete(colName, MASTER_TOKEN_NAME, MediaType.APPLICATION_JSON, entityType, boxName, - cellName, -1); - DavResourceUtils.deleteCollection(cellName, boxName, colName, MASTER_TOKEN_NAME, -1); - BoxUtils.delete(cellName, MASTER_TOKEN_NAME, boxName, -1); - CellUtils.delete(MASTER_TOKEN_NAME, cellName, -1); - } - } - - /** - * Elasticsearchから指定のデータを検索する. - * @param indexName インデックス名 - * @param esTypeName ESのtype名 - * @param routingId ESのルーティングID - * @param searchFieldName ES検索条件のフィールド名("untouched"は不要) - * @param searchFieldValue ES検索条件の値 - * @return 検索結果 - */ - @SuppressWarnings("unchecked") - PersoniumSearchHit searchFromEs(String indexName, - String esTypeName, - String routingId, - String searchFieldName, - String searchFieldValue) { - EsType type = EsModel.type(indexName, esTypeName, routingId, 0, 0); - String query = "{" - + " \"query\": {" - + " \"filtered\": {" - + " \"query\": {\"match_all\": {}}," - + " \"filter\": {\"term\": {" - + " \"s." + searchFieldName + ".untouched\": \"" + searchFieldValue + "\"" - + " }}" - + " }" - + " }, " - + " \"size\": 1" - + "}"; - PersoniumSearchResponse esResponse; - try { - esResponse = type.search((Map) new JSONParser().parse(query)); - assertEquals("Failed to retrieve test data from Elasticsearch.", 1, esResponse.getHits().getCount()); - PersoniumSearchHit esHit = esResponse.getHits().getAt(0); - return esHit; - } catch (ParseException e) { - fail("Failed to parse query for ES. " + e.getMessage()); - } - return null; - } - - /** - * Ads書込み失敗ログ出力. - * @param loginfo リペア用のエラー情報 - */ - protected void recordAdsWriteFailureLog(AdsWriteFailureLogInfo loginfo) { - AdsWriteFailureLogWriter adsWriteFailureLogWriter = AdsWriteFailureLogWriter.getInstance( - PersoniumUnitConfig.getAdsWriteFailureLogDir(), - PersoniumUnitConfig.getCoreVersion(), - PersoniumUnitConfig.getAdsWriteFailureLogPhysicalDelete()); - try { - adsWriteFailureLogWriter.writeActiveFile(loginfo); - } catch (AdsWriteFailureLogException e2) { - PersoniumCoreLog.Server.WRITE_ADS_FAILURE_LOG_ERROR.reason(e2).writeLog(); - PersoniumCoreLog.Server.WRITE_ADS_FAILURE_LOG_INFO.params(loginfo.toString()); - } - } - -} diff --git a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsTest.java b/src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsTest.java deleted file mode 100644 index 56e93b505..000000000 --- a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/RepairAdsTest.java +++ /dev/null @@ -1,488 +0,0 @@ -/** - * 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 io.personium.test.unit.core.model.impl.es.repair; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.json.simple.JSONObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.personium.common.ads.AdsWriteFailureLogException; -import io.personium.common.ads.AdsWriteFailureLogInfo; -import io.personium.common.es.EsType; -import io.personium.common.es.response.PersoniumIndexResponse; -import io.personium.common.es.response.PersoniumSearchResponse; -import io.personium.common.es.util.PersoniumUUID; -import io.personium.core.PersoniumUnitConfig; -import io.personium.core.model.impl.es.EsModel; -import io.personium.core.model.impl.es.ads.Ads; -import io.personium.core.model.impl.es.ads.AdsConnectionException; -import io.personium.core.model.impl.es.ads.AdsException; -import io.personium.core.model.impl.es.ads.JdbcAds; -import io.personium.core.model.impl.es.doc.EntitySetDocHandler; -import io.personium.core.model.impl.es.doc.OEntityDocHandler; -import io.personium.core.model.impl.es.repair.AdsAccessor; -import io.personium.core.model.impl.es.repair.EsAccessor; -import io.personium.core.model.impl.es.repair.RepairAds; -import io.personium.core.model.impl.es.repair.RepairAdsException; -import io.personium.test.categories.Unit; - -/** - * RepairAdsTest ユニットテストクラス. - */ -@Category({Unit.class }) -public class RepairAdsTest { - - private static final String ROUTING_ID = "routingId"; - - static Logger log = LoggerFactory.getLogger(RepairAdsTest.class); - - private String idxName = PersoniumUnitConfig.getEsUnitPrefix() + "_anon"; - private String id = "repair_" + PersoniumUUID.randomUUID(); - private String[] idList = {id }; - private Ads ads; - - /** - * すべてのテスト毎に1度実行される処理. - * @throws InterruptedException InterruptedException - * @throws AdsConnectionException AdsConnectionException - */ - @Before - @SuppressWarnings("unchecked") - public void before() throws InterruptedException, AdsConnectionException { - ads = new JdbcAds(); - - // Typeの定義 - // (Type 名に # は使えないっぽい。) - EsType type = EsModel.type(idxName, "UserData", ROUTING_ID, 0, 0); - // ドキュメント登録 - JSONObject json1 = new JSONObject(); - json1.put("c", ROUTING_ID); - json1.put("p", Long.parseLong("1406595596944")); - json1.put("u", Long.parseLong("1406595596944")); - PersoniumIndexResponse res1 = type.create(id, json1); - assertEquals(idList[0], res1.getId()); - } - - /** - * すべてのテスト毎に1度実行される処理. - * @throws InterruptedException InterruptedException - */ - @After - public void after() throws InterruptedException { - // 作成したインデックスを消す - EsType type = EsModel.type(idxName, "UserData", ROUTING_ID, 0, 0); - type.delete(id); - } - - /** - * Journalログのディレクトリが不正の場合_DcRepairAdsExceptionが発生すること. - * @throws RepairAdsException DcRepairAdsException - */ - @Ignore - @Test - public void Journalログのディレクトリが不正の場合_DcRepairAdsExceptionが発生すること() throws RepairAdsException { - // RepairAds repair = RepairAds.getInstance(); - // repair.readProperties(); - // repair.correctAdsWriteFailureLogFiles(); - } - - /** - * Journalログのローテートファイルが存在しない場合_DcRepairAdsExceptionが発生すること. - */ - @Ignore - @Test - public void Journalログのローテートファイルが存在しない場合_DcRepairAdsExceptionが発生すること() { - } - - /** - * Elasticsearchの検索結果が2件以上の場合_AdsExceptionが発生すること. - * @throws RepairAdsException DcRepairAdsException - * @throws AdsWriteFailureLogException AdsWriteFailureLogException - * @throws AdsException AdsException - */ - @Ignore - // ESへ同じUUIDを登録することが不可能のため。パワーモックを使用すると行けるかも。 - @Test - public void Elasticsearchの検索結果が2件以上の場合_AdsExceptionが発生すること() - throws RepairAdsException, AdsWriteFailureLogException, AdsException { - try { - AdsAccessor.initializedAds(); - RepairAds repair = RepairAds.getInstance(); - - StringBuilder sbuf = new StringBuilder(); - sbuf.append(PersoniumUnitConfig.getEsUnitPrefix() + "_anon\t"); - sbuf.append("ComplexTypeProperty\t"); - sbuf.append("odata-gsX3t2q3Qz6jdIn30fFMaQ\t"); - sbuf.append("aCUuueHzTKCPchE0yxTZZA\t"); - sbuf.append(id + "\t"); - sbuf.append("CREATE\t"); - sbuf.append("1\t"); - sbuf.append("1408595358931"); - AdsWriteFailureLogInfo logInfo = AdsWriteFailureLogInfo.parse(sbuf.toString()); - - List list = new ArrayList(); - list.add("abc"); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - List adsResponse = AdsAccessor.getIdListOnAds(logInfo); - repair.repairToAds(logInfo, esResponse, adsResponse); - fail(); - } catch (AdsException e) { - System.out.println("OK"); - } - } - - /** - * ADSの検索結果が2件以上の場合_AdsExceptionが発生すること. - * @throws AdsWriteFailureLogException AdsWriteFailureLogException - * @throws AdsException AdsException - */ - @Ignore - // ADSへ同じUUIDを登録することが不可能のため。パワーモックを使用すると行けるかも。 - @Test - public void ADSの検索結果が2件以上の場合_AdsExceptionが発生すること() throws AdsWriteFailureLogException, AdsException { - try { - AdsAccessor.initializedAds(); - - RepairAds repair = RepairAds.getInstance(); - - // AdsWriteFailureLogInfoを生成 - StringBuilder sbuf = new StringBuilder(); - sbuf.append(PersoniumUnitConfig.getEsUnitPrefix() + "_anon\t"); - sbuf.append("ComplexTypeProperty\t"); - sbuf.append("odata-gsX3t2q3Qz6jdIn30fFMaQ\t"); - sbuf.append("aCUuueHzTKCPchE0yxTZZA\t"); - sbuf.append(id + "\t"); - sbuf.append("CREATE\t"); - sbuf.append("1\t"); - sbuf.append("1408595358931"); - AdsWriteFailureLogInfo logInfo = AdsWriteFailureLogInfo.parse(sbuf.toString()); - - // 前準備で登録したデータをESから取得する - List list = new ArrayList(); - list.add(id); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // ADSへ同じデータを2件登録する - AdsAccessor.createAds(idxName, "Cell", esResponse); - // AdsAccessor.createAds(idxName, "Cell", esResponse); - - // ADSから対象データを検索する(2件ヒット) - List adsResponse = AdsAccessor.getIdListOnAds(logInfo); - - // DcRepairAdsExceptionが発生すること - repair.repairToAds(logInfo, esResponse, adsResponse); - fail(); - } catch (RepairAdsException e) { - System.out.println("OK"); - } finally { - // ADSのデータを削除 - ads.deleteCell(idxName, id); - // ads.deleteCell(idxName, id); - } - } - - /** - * リペア対象のデータがESに存在し、ADSに存在しない場合にADSに登録処理がされること. - * @throws AdsWriteFailureLogException AdsWriteFailureLogException - * @throws RepairAdsException DcRepairAdsException - * @throws AdsException AdsException - */ - @Test - public void リペア対象のデータがESに存在_ADSに存在しない場合にADSに登録処理がされること() - throws AdsWriteFailureLogException, RepairAdsException, AdsException { - try { - AdsAccessor.initializedAds(); - - RepairAds repair = RepairAds.getInstance(); - - // AdsWriteFailureLogInfoを生成 - StringBuilder sbuf = new StringBuilder(); - sbuf.append(PersoniumUnitConfig.getEsUnitPrefix() + "_anon\t"); - sbuf.append("ComplexTypeProperty\t"); - sbuf.append("odata-gsX3t2q3Qz6jdIn30fFMaQ\t"); - sbuf.append("aCUuueHzTKCPchE0yxTZZA\t"); - sbuf.append(id + "\t"); - sbuf.append("CREATE\t"); - sbuf.append("1\t"); - sbuf.append("1408595358931"); - AdsWriteFailureLogInfo logInfo = AdsWriteFailureLogInfo.parse(sbuf.toString()); - - // 前準備で登録したデータをESから取得する - List list = new ArrayList(); - list.add(id); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // ADSから対象データを検索する - List adsResponseBefore = AdsAccessor.getIdListOnAds(logInfo); - - // ADSにデータが登録されること - repair.repairToAds(logInfo, esResponse, adsResponseBefore); - - // ADSから対象データを検索する - List adsResponseAfter = AdsAccessor.getIdListOnAds(logInfo); - - // ADSのデータが1件であること - assertEquals(1, adsResponseAfter.size()); - } finally { - ads.deleteEntity(idxName, id); - } - } - - /** - * リペア対象のデータがESとADSに存在し、ジャーナルログのデータバージョンとESのデータバージョンが同じ場合_更新処理がされること. - * @throws AdsWriteFailureLogException AdsWriteFailureLogException - * @throws RepairAdsException DcRepairAdsException - * @throws AdsException AdsException - */ - @SuppressWarnings("unchecked") - @Test - public void リペア対象のデータがESとADSに存在かつジャーナルログのデータバージョンとESのデータバージョンが同じ場合_更新処理がされること() - throws AdsWriteFailureLogException, RepairAdsException, AdsException { - try { - AdsAccessor.initializedAds(); - - RepairAds repair = RepairAds.getInstance(); - - // ADSにデータを登録する - List list = new ArrayList(); - list.add(id); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - AdsAccessor.createAds(idxName, "Entity", esResponse); - - // ESにデータ更新をする(バージョンが2) - EsType type = EsModel.type(idxName, "UserData", ROUTING_ID, 0, 0); - // ドキュメント登録 - JSONObject json1 = new JSONObject(); - json1.put("c", ROUTING_ID); - json1.put("p", Long.parseLong("1406595596955")); - json1.put("u", Long.parseLong("1406595596955")); - type.update(id, json1); - - // AdsWriteFailureLogInfoを生成 - StringBuilder sbuf = new StringBuilder(); - sbuf.append(PersoniumUnitConfig.getEsUnitPrefix() + "_anon\t"); - sbuf.append("ComplexTypeProperty\t"); - sbuf.append("odata-gsX3t2q3Qz6jdIn30fFMaQ\t"); - sbuf.append("aCUuueHzTKCPchE0yxTZZA\t"); - sbuf.append(id + "\t"); - sbuf.append("UPDATE\t"); - sbuf.append("2\t"); - sbuf.append("1408595358931"); - AdsWriteFailureLogInfo logInfo = AdsWriteFailureLogInfo.parse(sbuf.toString()); - - // 前準備で登録したデータをESから取得する - esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // ADSから対象データを検索する(ヒット) - List adsResponseBefore = AdsAccessor.getIdListOnAds(logInfo); - - // ADSのデータが更新されること - repair.repairToAds(logInfo, esResponse, adsResponseBefore); - - // ADSから対象データを検索する - List adsResponseAfter = AdsAccessor.getIdListOnAds(logInfo); - - // チェック - // 登録前と登録後のデータ取得件数が等しい - assertEquals(adsResponseBefore.size(), adsResponseAfter.size()); - - // データ更新日時が更新前と異なること - JSONObject jsonBefore = (JSONObject) adsResponseBefore.get(0).get("source"); - JSONObject jsonAfter = (JSONObject) adsResponseAfter.get(0).get("source"); - if (jsonBefore.get("u").equals(jsonAfter.get("u"))) { - fail(); - } - } finally { - ads.deleteEntity(idxName, id); - } - } - - /** - * リペア対象のデータがADSに存在し、ESに存在しない場合にADSに削除処理がされること. - * @throws AdsWriteFailureLogException AdsWriteFailureLogException - * @throws RepairAdsException DcRepairAdsException - * @throws AdsException AdsException - */ - @Test - public void リペア対象のデータがADSに存在しESに存在しない場合にADSに削除処理がされること() - throws AdsWriteFailureLogException, RepairAdsException, AdsException { - AdsAccessor.initializedAds(); - - RepairAds repair = RepairAds.getInstance(); - - // AdsWriteFailureLogInfoを生成 - StringBuilder sbuf = new StringBuilder(); - sbuf.append(PersoniumUnitConfig.getEsUnitPrefix() + "_anon\t"); - sbuf.append("ComplexTypeProperty\t"); - sbuf.append("odata-gsX3t2q3Qz6jdIn30fFMaQ\t"); - sbuf.append("aCUuueHzTKCPchE0yxTZZA\t"); - sbuf.append(id + "\t"); - sbuf.append("CREATE\t"); - sbuf.append("1\t"); - sbuf.append("1408595358931"); - AdsWriteFailureLogInfo logInfo = AdsWriteFailureLogInfo.parse(sbuf.toString()); - - // 前準備で登録したデータをESから取得する - List list = new ArrayList(); - list.add(id); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // ADSにデータを登録 - EntitySetDocHandler oedh = new OEntityDocHandler(esResponse.getHits().getHits()[0]); - ads.createEntity(idxName, oedh); - - // ESからデータを削除する - EsType type = EsModel.type(idxName, "UserData", ROUTING_ID, 0, 0); - type.delete(id); - - // ADSから対象データを検索する(ヒット) - List adsResponseBefore = AdsAccessor.getIdListOnAds(logInfo); - // ESから対象データを検索する(0件) - esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // ADSにデータが削除されること - repair.repairToAds(logInfo, esResponse, adsResponseBefore); - - // ADSから対象データを検索する - List adsResponseAfter = AdsAccessor.getIdListOnAds(logInfo); - // ADSのデータが0件であること - assertEquals(0, adsResponseAfter.size()); - } - - /** - * リペア対象のデータがADSとESに存在しない場合にリペア処理が無視されること. - * @throws AdsWriteFailureLogException AdsWriteFailureLogException - * @throws RepairAdsException DcRepairAdsException - * @throws AdsException AdsException - */ - @Test - public void リペア対象のデータがADSとESに存在しない場合にリペア処理が無視されること() - throws AdsWriteFailureLogException, RepairAdsException, AdsException { - AdsAccessor.initializedAds(); - - RepairAds repair = RepairAds.getInstance(); - - // AdsWriteFailureLogInfoを生成 - StringBuilder sbuf = new StringBuilder(); - sbuf.append(PersoniumUnitConfig.getEsUnitPrefix() + "_anon\t"); - sbuf.append("ComplexTypeProperty\t"); - sbuf.append("odata-gsX3t2q3Qz6jdIn30fFMaQ\t"); - sbuf.append("aCUuueHzTKCPchE0yxTZZA\t"); - sbuf.append("dummy_repair\t"); - sbuf.append("CREATE\t"); - sbuf.append("1\t"); - sbuf.append("1408595358931"); - AdsWriteFailureLogInfo logInfo = AdsWriteFailureLogInfo.parse(sbuf.toString()); - - // 前準備で登録したデータをESから取得する - List list = new ArrayList(); - list.add("dummy_repair"); - - // ADSから対象データを検索する(0件) - List adsResponseBefore = AdsAccessor.getIdListOnAds(logInfo); - // ESから対象データを検索する(0件) - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // 対象データのリペア処理が無視されること - repair.repairToAds(logInfo, esResponse, adsResponseBefore); - - // ADSから対象データを検索する - List adsResponseAfter = AdsAccessor.getIdListOnAds(logInfo); - // ADSのデータが0件であること - assertEquals(0, adsResponseAfter.size()); - } - - /** - * リペア対象のデータがESとADSに存在し、ジャーナルログのデータバージョンとESのデータバージョンが異なる場合_処理が無視されること. - * @throws AdsWriteFailureLogException AdsWriteFailureLogException - * @throws RepairAdsException DcRepairAdsException - * @throws AdsException AdsException - */ - @SuppressWarnings("unchecked") - @Test - public void リペア対象のデータがESとADSに存在してジャーナルログのデータバージョンとESのデータバージョンが異なる場合_処理が無視されること() - throws AdsWriteFailureLogException, RepairAdsException, AdsException { - try { - AdsAccessor.initializedAds(); - - RepairAds repair = RepairAds.getInstance(); - - // ADSにデータを登録する - List list = new ArrayList(); - list.add(id); - PersoniumSearchResponse esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - AdsAccessor.createAds(idxName, "Entity", esResponse); - - // ESにデータ更新をする(バージョンが2) - EsType type = EsModel.type(idxName, "UserData", ROUTING_ID, 0, 0); - // ドキュメント登録 - JSONObject json1 = new JSONObject(); - json1.put("c", ROUTING_ID); - json1.put("p", Long.parseLong("1406595596955")); - json1.put("u", Long.parseLong("1406595596955")); - type.update(id, json1); - - // AdsWriteFailureLogInfoを生成 - StringBuilder sbuf = new StringBuilder(); - sbuf.append(PersoniumUnitConfig.getEsUnitPrefix() + "_anon\t"); - sbuf.append("ComplexTypeProperty\t"); - sbuf.append("odata-gsX3t2q3Qz6jdIn30fFMaQ\t"); - sbuf.append("aCUuueHzTKCPchE0yxTZZA\t"); - sbuf.append(id + "\t"); - sbuf.append("UPDATE\t"); - sbuf.append("1\t"); - sbuf.append("1408595358931"); - AdsWriteFailureLogInfo logInfo = AdsWriteFailureLogInfo.parse(sbuf.toString()); - - // 前準備で登録したデータをESから取得する - esResponse = EsAccessor.search(idxName, ROUTING_ID, list, "UserData"); - - // ADSから対象データを検索する(ヒット) - List adsResponseBefore = AdsAccessor.getIdListOnAds(logInfo); - - // ADSのデータが更新されること - repair.repairToAds(logInfo, esResponse, adsResponseBefore); - - // ADSから対象データを検索する - List adsResponseAfter = AdsAccessor.getIdListOnAds(logInfo); - - // チェック - // 登録前と登録後のデータ取得件数が等しい - assertEquals(adsResponseBefore.size(), adsResponseAfter.size()); - - // データ更新日時が更新前と異なること - JSONObject jsonBefore = (JSONObject) adsResponseBefore.get(0).get("source"); - JSONObject jsonAfter = (JSONObject) adsResponseAfter.get(0).get("source"); - assertEquals(jsonBefore.get("u"), jsonAfter.get("u")); - } finally { - ads.deleteEntity(idxName, id); - } - } - -} diff --git a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/package-info.java b/src/test/java/io/personium/test/unit/core/model/impl/es/repair/package-info.java deleted file mode 100644 index 7e9a10a62..000000000 --- a/src/test/java/io/personium/test/unit/core/model/impl/es/repair/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * 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. - */ -/** - * JUnit test for ads repair. - */ -package io.personium.test.unit.core.model.impl.es.repair; - diff --git a/src/test/java/io/personium/test/unit/core/rs/odata/validate/ReceivedMessageValidateTest.java b/src/test/java/io/personium/test/unit/core/rs/odata/validate/ReceivedMessageValidateTest.java index 2a4dce171..09f39a84f 100644 --- a/src/test/java/io/personium/test/unit/core/rs/odata/validate/ReceivedMessageValidateTest.java +++ b/src/test/java/io/personium/test/unit/core/rs/odata/validate/ReceivedMessageValidateTest.java @@ -455,85 +455,4 @@ public ReceivedMessageValidateTest() { assertEquals(expected.getValue(), result.getValue()); } - /** - * TypeがmessageでStatusがunreadの場合にPersoniumCoreExceptionが発生しないこと. - */ - @Test - public final void TypeがmessageでStatusがunreadの場合にPersoniumCoreExceptionが発生しないこと() { - MessageODataResource.validateStatus("message", "unread"); - } - - /** - * TypeがmessageでStatusがnoneの場合にPersoniumCoreExceptionが発生すること. - */ - @Test(expected = PersoniumCoreException.class) - public final void TypeがmessageでStatusがnoneの場合にPersoniumCoreExceptionが発生すること() { - MessageODataResource.validateStatus("message", "none"); - } - - /** - * Typeがreq.relation.buildでStatusがnoneの場合にPersoniumCoreExceptionが発生しないこと. - */ - @Test - public final void Typeがreq_relation_buildでStatusがnoneの場合にPersoniumCoreExceptionが発生しないこと() { - MessageODataResource.validateStatus("req.relation.build", "none"); - } - - /** - * Typeがreq.relation.breakでStatusがnoneの場合にPersoniumCoreExceptionが発生しないこと. - */ - @Test - public final void Typeがreq_relation_breakでStatusがnoneの場合にPersoniumCoreExceptionが発生しないこと() { - MessageODataResource.validateStatus("req.relation.break", "none"); - } - - /** - * Typeがreq.relation.buildでStatusがunreadの場合にPersoniumCoreExceptionが発生すること. - */ - @Test(expected = PersoniumCoreException.class) - public final void Typeがreq_relation_buildでStatusがunreadの場合にPersoniumCoreExceptionが発生すること() { - MessageODataResource.validateStatus("req.relation.build", "unread"); - } - - /** - * Typeがreq.relation.breakでStatusがunreadの場合にPersoniumCoreExceptionが発生すること. - */ - @Test(expected = PersoniumCoreException.class) - public final void Typeがreq_relation_breakでStatusがunreadの場合にPersoniumCoreExceptionが発生すること() { - MessageODataResource.validateStatus("req.relation.break", "unread"); - } - - /** - * Typeがreq.relation.breakでRequestRelationとRequestRelationTargetの指定がある場合にPersoniumCoreExceptionが発生しないこと. - */ - @Test - public final void - Typeがreq_relation_breakでRequestRelationとRequestRelationTargetの指定がある場合にPersoniumCoreExceptionが発生しないこと() { - MessageODataResource.validateReqRelation("req.relation.break", "http://xxx.com/xx", "http://xxx.com/xx"); - } - - /** - * Typeがreq.relation.breakでRequestRelationがnullの場合にPersoniumCoreExceptionが発生すること. - */ - @Test(expected = PersoniumCoreException.class) - public final void Typeがreq_relation_breakでRequestRelationがnullの場合にPersoniumCoreExceptionが発生すること() { - MessageODataResource.validateReqRelation("req.relation.break", null, "http://example.com/test"); - } - - /** - * Typeがreq.relation.breakでRequestRelationTargetがnullの場合にPersoniumCoreExceptionが発生すること. - */ - @Test(expected = PersoniumCoreException.class) - public final void Typeがreq_relation_breakでRequestRelationTargetがnullの場合にPersoniumCoreExceptionが発生すること() { - MessageODataResource.validateReqRelation("req.relation.break", "http://example.com/test", null); - } - - /** - * TypeがmessageでRequestRelationがnullの場合にPersoniumCoreExceptionが発生しないこと. - */ - @Test - public final void TypeがmessageでRequestRelationがnullの場合にPersoniumCoreExceptionが発生しないこと() { - MessageODataResource.validateReqRelation("message", null, "http://example.com/test"); - } - } diff --git a/src/test/java/io/personium/test/unit/core/rs/odata/validate/SentMessageValidateTest.java b/src/test/java/io/personium/test/unit/core/rs/odata/validate/SentMessageValidateTest.java index 0cb1abf22..5eb33a21d 100644 --- a/src/test/java/io/personium/test/unit/core/rs/odata/validate/SentMessageValidateTest.java +++ b/src/test/java/io/personium/test/unit/core/rs/odata/validate/SentMessageValidateTest.java @@ -26,7 +26,6 @@ import io.personium.core.PersoniumCoreException; import io.personium.core.model.ctl.Common; -import io.personium.core.model.ctl.ReceivedMessage; import io.personium.core.model.ctl.SentMessage; import io.personium.core.rs.cell.MessageODataResource; import io.personium.core.rs.odata.AbstractODataResource; @@ -575,102 +574,6 @@ public SentMessageValidateTest() { MessageODataResource.validateToAndToRelation(to, toRelation); } - /** - * Typeが関係登録依頼でRequestRelationがない場合にPersoniumCoreExceptionが発生すること. - */ - @Test(expected = PersoniumCoreException.class) - public final void Typeが関係登録依頼でRequestRelationがない場合にPersoniumCoreExceptionが発生すること() { - String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; - String requestRelation = (String) OProperties.null_( - SentMessage.P_REQUEST_RELATION.getName(), - EdmSimpleType.STRING).getValue(); - String requestRelationTarget = "http://example.com/reqRelation"; - MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); - } - - /** - * Typeが関係登録依頼でRequestRelationがある場合にPersoniumCoreExceptionが発生しないこと. - */ - @Test - public final void Typeが関係登録依頼でRequestRelationがある場合にPersoniumCoreExceptionが発生しないこと() { - String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; - String requestRelation = "http://example.com/reqRelation"; - String requestRelationTarget = "http://example.com/reqRelation"; - MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); - } - - /** - * Typeが関係削除依頼でRequestRelationがない場合にPersoniumCoreExceptionが発生すること. - */ - @Test(expected = PersoniumCoreException.class) - public final void Typeが関係削除依頼でRequestRelationがない場合にPersoniumCoreExceptionが発生すること() { - String type = ReceivedMessage.TYPE_REQ_RELATION_BREAK; - String requestRelation = (String) OProperties.null_( - SentMessage.P_REQUEST_RELATION.getName(), - EdmSimpleType.STRING).getValue(); - String requestRelationTarget = "http://example.com/reqRelation"; - MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); - } - - /** - * Typeが関係削除依頼でRequestRelationがある場合にPersoniumCoreExceptionが発生しないこと. - */ - @Test - public final void Typeが関係削除依頼でRequestRelationがある場合にPersoniumCoreExceptionが発生しないこと() { - String type = ReceivedMessage.TYPE_REQ_RELATION_BREAK; - String requestRelation = "http://example.com/reqRelation"; - String requestRelationTarget = "http://example.com/reqRelation"; - MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); - } - - /** - * Typeが関係登録依頼でRequestRelationTargetがない場合にPersoniumCoreExceptionが発生すること. - */ - @Test(expected = PersoniumCoreException.class) - public final void Typeが関係登録依頼でRequestRelationTargetがない場合にPersoniumCoreExceptionが発生すること() { - String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; - String requestRelation = "http://example.com/reqRelation"; - String requestRelationTarget = (String) OProperties.null_( - SentMessage.P_REQUEST_RELATION_TARGET.getName(), - EdmSimpleType.STRING).getValue(); - MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); - } - - /** - * Typeが関係登録依頼でRequestRelationTargetがある場合にPersoniumCoreExceptionが発生しないこと. - */ - @Test - public final void Typeが関係登録依頼でRequestRelationTargetがある場合にPersoniumCoreExceptionが発生しないこと() { - String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD; - String requestRelation = "http://example.com/reqRelation"; - String requestRelationTarget = "http://example.com/reqRelation"; - MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); - } - - /** - * Typeが関係削除依頼でRequestRelationTargetがない場合にPersoniumCoreExceptionが発生すること. - */ - @Test(expected = PersoniumCoreException.class) - public final void Typeが関係削除依頼でRequestRelationTargetがない場合にPersoniumCoreExceptionが発生すること() { - String type = ReceivedMessage.TYPE_REQ_RELATION_BREAK; - String requestRelation = "http://example.com/reqRelation"; - String requestRelationTarget = (String) OProperties.null_( - SentMessage.P_REQUEST_RELATION_TARGET.getName(), - EdmSimpleType.STRING).getValue(); - MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); - } - - /** - * Typeが関係削除依頼でRequestRelationTargetがある場合にPersoniumCoreExceptionが発生しないこと. - */ - @Test - public final void Typeが関係削除依頼でRequestRelationTargetがある場合にPersoniumCoreExceptionが発生しないこと() { - String type = ReceivedMessage.TYPE_REQ_RELATION_BREAK; - String requestRelation = "http://example.com/reqRelation"; - String requestRelationTarget = "http://example.com/reqRelation"; - MessageODataResource.validateReqRelation(type, requestRelation, requestRelationTarget); - } - /** * 送信先URLが最大送信許可数を超えている場合にPersoniumCoreExceptionが発生すること. */ diff --git a/src/test/java/io/personium/test/utils/RoleUtils.java b/src/test/java/io/personium/test/utils/RoleUtils.java index 3bc688711..3b0a07912 100644 --- a/src/test/java/io/personium/test/utils/RoleUtils.java +++ b/src/test/java/io/personium/test/utils/RoleUtils.java @@ -202,21 +202,21 @@ public static TResponse listViaNPWithAuthSchema( */ public static TResponse create(final String cellName, final String token, final String roleName, final int code) { - return create(cellName, token, null, roleName, code); + return create(cellName, token, roleName, null, code); } /** * Roleを作成するユーティリティ. * @param cellName セル名 * @param token トークン - * @param boxName ボックス名 * @param roleName ロール名 + * @param boxName ボックス名 * @param code レスポンスコード * @return レスポンス */ @SuppressWarnings("unchecked") public static TResponse create(final String cellName, final String token, - final String boxName, final String roleName, final int code) { + final String roleName, final String boxName, final int code) { JSONObject body = new JSONObject(); body.put("Name", roleName); if (boxName != null) { @@ -231,6 +231,24 @@ public static TResponse create(final String cellName, final String token, .statusCode(code); } + /** + * create role utility. + * @param cellName cell name + * @param token token + * @param body body + * @param code response code + * @return response + */ + public static TResponse create(final String cellName, final String token, + final JSONObject body, final int code) { + return Http.request("role-create.txt") + .with("token", token) + .with("cellPath", cellName) + .with("body", body.toString()) + .returns() + .statusCode(code); + } + /** * NP経由でRoleを作成するユーティリティ. * @param cellName セル名 @@ -413,11 +431,11 @@ public static TResponse update(String token, String cellName, String roleName, * ロールを削除するユーティリティ. * @param cellName セル名 * @param token トークン - * @param boxName ボックス名 * @param roleName ロール名 + * @param boxName ボックス名 */ public static void delete(final String cellName, final String token, - final String boxName, final String roleName) { + final String roleName, final String boxName) { String keyBoxName = null; if (boxName == null) { keyBoxName = "null"; @@ -437,12 +455,12 @@ public static void delete(final String cellName, final String token, * ロールを削除するユーティリティ. * @param cellName セル名 * @param token トークン - * @param boxName ボックス名 * @param roleName ロール名 + * @param boxName ボックス名 * @param code レスポンスコード */ public static void delete(final String cellName, final String token, - final String boxName, final String roleName, final int code) { + final String roleName, final String boxName, final int code) { String keyBoxName = null; if (boxName == null) { keyBoxName = "null"; diff --git a/src/test/resources/davFile/decrypt01.txt b/src/test/resources/davFile/decrypt01.txt new file mode 100644 index 000000000..ded45c619 --- /dev/null +++ b/src/test/resources/davFile/decrypt01.txt @@ -0,0 +1,4 @@ +Personium encrypt UT test. +This is decrypt file. +- key:abcdef0123456789 +- IV:dIlleCtseTmuinos diff --git a/src/test/resources/davFile/encrypt01.txt b/src/test/resources/davFile/encrypt01.txt new file mode 100644 index 000000000..12a080e4f --- /dev/null +++ b/src/test/resources/davFile/encrypt01.txt @@ -0,0 +1 @@ +dnløv^̡kUP(4/q_ň w&_!، BnIcc,5n[ (ev[9e,0!EڪGF( \ No newline at end of file diff --git a/src/test/resources/davFile/file01.txt b/src/test/resources/davFile/file01.txt new file mode 100644 index 000000000..66834152c --- /dev/null +++ b/src/test/resources/davFile/file01.txt @@ -0,0 +1,2 @@ +Hello +Personium \ No newline at end of file diff --git a/src/test/resources/davFile/range01.txt b/src/test/resources/davFile/range01.txt new file mode 100644 index 000000000..7813680ae --- /dev/null +++ b/src/test/resources/davFile/range01.txt @@ -0,0 +1,2 @@ +encrypt UT test. +This is decry \ No newline at end of file