repo_name stringclasses 5 values | pr_number int64 1.52k 15.5k | pr_title stringlengths 8 143 | pr_description stringlengths 0 10.2k | author stringlengths 3 18 | date_created timestamp[ns, tz=UTC] | date_merged timestamp[ns, tz=UTC] | previous_commit stringlengths 40 40 | pr_commit stringlengths 40 40 | query stringlengths 11 10.2k | filepath stringlengths 6 220 | before_content stringlengths 0 597M | after_content stringlengths 0 597M | label int64 -1 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/test/java/com/ctrip/framework/apollo/portal/controller/CommitControllerTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.portal.AbstractIntegrationTest;
import java.util.List;
import org.junit.Test;
import org.springframework.web.client.HttpClientErrorException;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Created by kezhenxu at 2019/1/14 12:49.
*
* @author kezhenxu (kezhenxu at lizhi dot fm)
*/
public class CommitControllerTest extends AbstractIntegrationTest {
@Test
public void shouldFailWhenPageOrSiseIsNegative() {
try {
restTemplate.getForEntity(
url("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/commits?page=-1"),
List.class, "1", "env", "cl", "ns"
);
fail("should throw");
} catch (final HttpClientErrorException e) {
assertThat(
new String(e.getResponseBodyAsByteArray()), containsString("page should be positive or 0")
);
}
try {
restTemplate.getForEntity(
url("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/commits?size=0"),
List.class, "1", "env", "cl", "ns"
);
fail("should throw");
} catch (final HttpClientErrorException e) {
assertThat(
new String(e.getResponseBodyAsByteArray()), containsString("size should be positive number")
);
}
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.portal.AbstractIntegrationTest;
import java.util.List;
import org.junit.Test;
import org.springframework.web.client.HttpClientErrorException;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Created by kezhenxu at 2019/1/14 12:49.
*
* @author kezhenxu (kezhenxu at lizhi dot fm)
*/
public class CommitControllerTest extends AbstractIntegrationTest {
@Test
public void shouldFailWhenPageOrSiseIsNegative() {
try {
restTemplate.getForEntity(
url("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/commits?page=-1"),
List.class, "1", "env", "cl", "ns"
);
fail("should throw");
} catch (final HttpClientErrorException e) {
assertThat(
new String(e.getResponseBodyAsByteArray()), containsString("page should be positive or 0")
);
}
try {
restTemplate.getForEntity(
url("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/commits?size=0"),
List.class, "1", "env", "cl", "ns"
);
fail("should throw");
} catch (final HttpClientErrorException e) {
assertThat(
new String(e.getResponseBodyAsByteArray()), containsString("size should be positive number")
);
}
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/dto/GrayReleaseRuleDTO.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.dto;
import com.google.common.collect.Sets;
import java.util.Set;
public class GrayReleaseRuleDTO extends BaseDTO {
private String appId;
private String clusterName;
private String namespaceName;
private String branchName;
private Set<GrayReleaseRuleItemDTO> ruleItems;
private Long releaseId;
public GrayReleaseRuleDTO(String appId, String clusterName, String namespaceName, String branchName) {
this.appId = appId;
this.clusterName = clusterName;
this.namespaceName = namespaceName;
this.branchName = branchName;
this.ruleItems = Sets.newHashSet();
}
public String getAppId() {
return appId;
}
public String getClusterName() {
return clusterName;
}
public String getNamespaceName() {
return namespaceName;
}
public String getBranchName() {
return branchName;
}
public Set<GrayReleaseRuleItemDTO> getRuleItems() {
return ruleItems;
}
public void setRuleItems(Set<GrayReleaseRuleItemDTO> ruleItems) {
this.ruleItems = ruleItems;
}
public void addRuleItem(GrayReleaseRuleItemDTO ruleItem) {
this.ruleItems.add(ruleItem);
}
public Long getReleaseId() {
return releaseId;
}
public void setReleaseId(Long releaseId) {
this.releaseId = releaseId;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.dto;
import com.google.common.collect.Sets;
import java.util.Set;
public class GrayReleaseRuleDTO extends BaseDTO {
private String appId;
private String clusterName;
private String namespaceName;
private String branchName;
private Set<GrayReleaseRuleItemDTO> ruleItems;
private Long releaseId;
public GrayReleaseRuleDTO(String appId, String clusterName, String namespaceName, String branchName) {
this.appId = appId;
this.clusterName = clusterName;
this.namespaceName = namespaceName;
this.branchName = branchName;
this.ruleItems = Sets.newHashSet();
}
public String getAppId() {
return appId;
}
public String getClusterName() {
return clusterName;
}
public String getNamespaceName() {
return namespaceName;
}
public String getBranchName() {
return branchName;
}
public Set<GrayReleaseRuleItemDTO> getRuleItems() {
return ruleItems;
}
public void setRuleItems(Set<GrayReleaseRuleItemDTO> ruleItems) {
this.ruleItems = ruleItems;
}
public void addRuleItem(GrayReleaseRuleItemDTO ruleItem) {
this.ruleItems.add(ruleItem);
}
public Long getReleaseId() {
return releaseId;
}
public void setReleaseId(Long releaseId) {
this.releaseId = releaseId;
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/resources/static/scripts/directive/namespace-panel-directive.js | /*
* Copyright 2021 Apollo Authors
*
* 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.
*
*/
directive_module.directive('apollonspanel', directive);
function directive($window, $translate, toastr, AppUtil, EventManager, PermissionService, NamespaceLockService,
UserService, CommitService, ReleaseService, InstanceService, NamespaceBranchService, ConfigService) {
return {
restrict: 'E',
templateUrl: AppUtil.prefixPath() + '/views/component/namespace-panel.html',
transclude: true,
replace: true,
scope: {
namespace: '=',
appId: '=',
env: '=',
cluster: '=',
user: '=',
lockCheck: '=',
createItem: '=',
editItem: '=',
preDeleteItem: '=',
preRevokeItem: '=',
showText: '=',
showNoModifyPermissionDialog: '=',
preCreateBranch: '=',
preDeleteBranch: '=',
showMergeAndPublishGrayTips: '=',
showBody: "=?",
lazyLoad: "=?"
},
link: function (scope) {
//constants
var namespace_view_type = {
TEXT: 'text',
TABLE: 'table',
HISTORY: 'history',
INSTANCE: 'instance',
RULE: 'rule'
};
var namespace_instance_view_type = {
LATEST_RELEASE: 'latest_release',
NOT_LATEST_RELEASE: 'not_latest_release',
ALL: 'all'
};
var operate_branch_storage_key = 'OperateBranch';
scope.refreshNamespace = refreshNamespace;
scope.switchView = switchView;
scope.toggleItemSearchInput = toggleItemSearchInput;
scope.searchItems = searchItems;
scope.loadCommitHistory = loadCommitHistory;
scope.toggleTextEditStatus = toggleTextEditStatus;
scope.goToSyncPage = goToSyncPage;
scope.goToDiffPage = goToDiffPage;
scope.modifyByText = modifyByText;
scope.syntaxCheck = syntaxCheck;
scope.goToParentAppConfigPage = goToParentAppConfigPage;
scope.switchInstanceViewType = switchInstanceViewType;
scope.switchBranch = switchBranch;
scope.loadInstanceInfo = loadInstanceInfo;
scope.refreshInstancesInfo = refreshInstancesInfo;
scope.deleteRuleItem = deleteRuleItem;
scope.rollback = rollback;
scope.publish = publish;
scope.mergeAndPublish = mergeAndPublish;
scope.addRuleItem = addRuleItem;
scope.editRuleItem = editRuleItem;
scope.deleteNamespace = deleteNamespace;
var subscriberId = EventManager.subscribe(EventManager.EventType.UPDATE_GRAY_RELEASE_RULES,
function (context) {
useRules(context.branch);
}, scope.namespace.baseInfo.namespaceName);
scope.$on('$destroy', function () {
EventManager.unsubscribe(EventManager.EventType.UPDATE_GRAY_RELEASE_RULES,
subscriberId, scope.namespace.baseInfo.namespaceName);
});
preInit(scope.namespace);
if (!scope.lazyLoad || scope.namespace.initialized) {
init();
}
function preInit(namespace) {
scope.showNamespaceBody = false;
namespace.isLinkedNamespace =
namespace.isPublic ? namespace.parentAppId != namespace.baseInfo.appId : false;
//namespace view name hide suffix
namespace.viewName = namespace.baseInfo.namespaceName.replace(".xml", "").replace(
".properties", "").replace(".json", "").replace(".yml", "")
.replace(".yaml", "").replace(".txt", "");
}
function init() {
initNamespace(scope.namespace);
initOther();
scope.namespace.initialized = true;
}
function refreshNamespace() {
EventManager.emit(EventManager.EventType.REFRESH_NAMESPACE,
{ namespace: scope.namespace });
}
function initNamespace(namespace, viewType) {
namespace.hasBranch = false;
namespace.isBranch = false;
namespace.displayControl = {
currentOperateBranch: 'master',
showSearchInput: false,
show: scope.showBody
};
scope.showNamespaceBody = namespace.showNamespaceBody ? true : scope.showBody;
namespace.viewItems = namespace.items;
namespace.isPropertiesFormat = namespace.format == 'properties';
namespace.isSyntaxCheckable = namespace.format == 'yaml' || namespace.format == 'yml';
namespace.isTextEditing = false;
namespace.instanceViewType = namespace_instance_view_type.LATEST_RELEASE;
namespace.latestReleaseInstancesPage = 0;
namespace.allInstances = [];
namespace.allInstancesPage = 0;
namespace.commitChangeBtnDisabled = false;
generateNamespaceId(namespace);
initNamespaceBranch(namespace);
initNamespaceViewName(namespace);
initNamespaceLock(namespace);
initNamespaceInstancesCount(namespace);
initPermission(namespace);
initLinkedNamespace(namespace);
loadInstanceInfo(namespace);
function initNamespaceBranch(namespace) {
NamespaceBranchService.findNamespaceBranch(scope.appId, scope.env,
namespace.baseInfo.clusterName,
namespace.baseInfo.namespaceName)
.then(function (result) {
if (!result.baseInfo) {
return;
}
//namespace has branch
namespace.hasBranch = true;
namespace.branchName = result.baseInfo.clusterName;
//init branch
namespace.branch = result;
namespace.branch.isBranch = true;
namespace.branch.parentNamespace = namespace;
namespace.branch.viewType = namespace_view_type.TABLE;
namespace.branch.isPropertiesFormat = namespace.format == 'properties';
namespace.branch.allInstances = [];//master namespace all instances
namespace.branch.latestReleaseInstances = [];
namespace.branch.latestReleaseInstancesPage = 0;
namespace.branch.instanceViewType = namespace_instance_view_type.LATEST_RELEASE;
namespace.branch.hasLoadInstances = false;
namespace.branch.displayControl = {
show: true
};
generateNamespaceId(namespace.branch);
initBranchItems(namespace.branch);
initRules(namespace.branch);
loadInstanceInfo(namespace.branch);
initNamespaceLock(namespace.branch);
initPermission(namespace);
initUserOperateBranchScene(namespace);
});
function initBranchItems(branch) {
branch.masterItems = [];
branch.branchItems = [];
var masterItemsMap = {};
branch.parentNamespace.items.forEach(function (item) {
if (item.item.key) {
masterItemsMap[item.item.key] = item;
}
});
var branchItemsMap = {};
var itemModifiedCnt = 0;
branch.items.forEach(function (item) {
var key = item.item.key;
var masterItem = masterItemsMap[key];
//modify master item and set item's masterReleaseValue
if (masterItem) {
item.masterItemExists = true;
if (masterItem.isModified) {
item.masterReleaseValue = masterItem.oldValue;
} else {
item.masterReleaseValue = masterItem.item.value;
}
} else {//delete branch item
item.masterItemExists = false;
}
//delete master item. ignore
if (item.isDeleted && masterItem) {
if (item.masterReleaseValue != item.oldValue) {
itemModifiedCnt++;
branch.branchItems.push(item);
}
} else {//branch's item
branchItemsMap[key] = item;
if (item.isModified) {
itemModifiedCnt++;
}
branch.branchItems.push(item);
}
});
branch.itemModifiedCnt = itemModifiedCnt;
branch.parentNamespace.items.forEach(function (item) {
if (item.item.key) {
if (!branchItemsMap[item.item.key]) {
branch.masterItems.push(item);
} else {
item.hasBranchValue = true;
}
}
})
}
}
function generateNamespaceId(namespace) {
namespace.id = Math.random().toString(36).substr(2);
}
function initPermission(namespace) {
PermissionService.has_modify_namespace_permission(
scope.appId,
namespace.baseInfo.namespaceName)
.then(function (result) {
if (!result.hasPermission) {
PermissionService.has_modify_namespace_env_permission(
scope.appId,
scope.env,
namespace.baseInfo.namespaceName
)
.then(function (result) {
//branch has same permission
namespace.hasModifyPermission = result.hasPermission;
if (namespace.branch) {
namespace.branch.hasModifyPermission = result.hasPermission;
}
});
}
else {
//branch has same permission
namespace.hasModifyPermission = result.hasPermission;
if (namespace.branch) {
namespace.branch.hasModifyPermission = result.hasPermission;
}
}
});
PermissionService.has_release_namespace_permission(
scope.appId,
namespace.baseInfo.namespaceName)
.then(function (result) {
if (!result.hasPermission) {
PermissionService.has_release_namespace_env_permission(
scope.appId,
scope.env,
namespace.baseInfo.namespaceName
)
.then(function (result) {
//branch has same permission
namespace.hasReleasePermission = result.hasPermission;
if (namespace.branch) {
namespace.branch.hasReleasePermission = result.hasPermission;
}
});
}
else {
//branch has same permission
namespace.hasReleasePermission = result.hasPermission;
if (namespace.branch) {
namespace.branch.hasReleasePermission = result.hasPermission;
}
}
});
}
function initLinkedNamespace(namespace) {
if (!namespace.isPublic || !namespace.isLinkedNamespace) {
return;
}
//load public namespace
ConfigService.load_public_namespace_for_associated_namespace(scope.env, scope.appId, scope.cluster,
namespace.baseInfo.namespaceName)
.then(function (result) {
var publicNamespace = result;
namespace.publicNamespace = publicNamespace;
var linkNamespaceItemKeys = [];
namespace.items.forEach(function (item) {
var key = item.item.key;
linkNamespaceItemKeys.push(key);
});
publicNamespace.viewItems = [];
publicNamespace.items.forEach(function (item) {
var key = item.item.key;
if (key) {
publicNamespace.viewItems.push(item);
}
item.covered = linkNamespaceItemKeys.indexOf(key) >= 0;
if (item.isModified || item.isDeleted) {
publicNamespace.isModified = true;
} else if (key) {
publicNamespace.hasPublishedItem = true;
}
});
loadParentNamespaceText(namespace);
});
}
function loadParentNamespaceText(namespace){
namespace.publicNamespaceText = "";
if(namespace.isLinkedNamespace) {
namespace.publicNamespaceText = parseModel2Text(namespace.publicNamespace)
}
}
function initNamespaceViewName(namespace) {
if (!viewType) {
if (namespace.isPropertiesFormat) {
switchView(namespace, namespace_view_type.TABLE);
} else {
switchView(namespace, namespace_view_type.TEXT);
}
} else if (viewType == namespace_view_type.TABLE) {
namespace.viewType = namespace_view_type.TABLE;
}
}
function initNamespaceLock(namespace) {
NamespaceLockService.get_namespace_lock(scope.appId, scope.env,
namespace.baseInfo.clusterName,
namespace.baseInfo.namespaceName)
.then(function (result) {
namespace.lockOwner = result.lockOwner;
namespace.isEmergencyPublishAllowed = result.isEmergencyPublishAllowed;
});
}
function initUserOperateBranchScene(namespace) {
var operateBranchStorage = JSON.parse(localStorage.getItem(operate_branch_storage_key));
var namespaceId = [scope.appId, scope.env, scope.cluster, namespace.baseInfo.namespaceName].join(
"+");
if (!operateBranchStorage) {
operateBranchStorage = {};
}
if (!operateBranchStorage[namespaceId]) {
operateBranchStorage[namespaceId] = namespace.branchName;
}
localStorage.setItem(operate_branch_storage_key, JSON.stringify(operateBranchStorage));
switchBranch(operateBranchStorage[namespaceId], false);
}
}
function initNamespaceInstancesCount(namespace) {
InstanceService.getInstanceCountByNamespace(scope.appId,
scope.env,
scope.cluster,
namespace.baseInfo.namespaceName)
.then(function (result) {
namespace.instancesCount = result.num;
})
}
function initOther() {
UserService.load_user().then(function (result) {
scope.currentUser = result.userId;
});
PermissionService.has_assign_user_permission(scope.appId)
.then(function (result) {
scope.hasAssignUserPermission = result.hasPermission;
}, function (result) {
});
}
function switchBranch(branchName, forceShowBody) {
if (branchName != 'master') {
initRules(scope.namespace.branch);
}
if (forceShowBody) {
scope.showNamespaceBody = true;
}
scope.namespace.displayControl.currentOperateBranch = branchName;
//save to local storage
var operateBranchStorage = JSON.parse(localStorage.getItem(operate_branch_storage_key));
if (!operateBranchStorage) {
return;
}
var namespaceId = [scope.appId, scope.env, scope.cluster, scope.namespace.baseInfo.namespaceName].join(
"+");
operateBranchStorage[namespaceId] = branchName;
localStorage.setItem(operate_branch_storage_key, JSON.stringify(operateBranchStorage));
}
function switchView(namespace, viewType) {
namespace.viewType = viewType;
if (namespace_view_type.TEXT == viewType) {
namespace.text = parseModel2Text(namespace);
} else if (namespace_view_type.TABLE == viewType) {
} else if (namespace_view_type.HISTORY == viewType) {
loadCommitHistory(namespace);
} else if (namespace_view_type.INSTANCE == viewType) {
refreshInstancesInfo(namespace);
}
}
function switchInstanceViewType(namespace, type) {
namespace.instanceViewType = type;
loadInstanceInfo(namespace);
}
function loadCommitHistory(namespace) {
if (!namespace.commits) {
namespace.commits = [];
namespace.commitPage = 0;
}
var size = 10;
CommitService.find_commits(scope.appId,
scope.env,
namespace.baseInfo.clusterName,
namespace.baseInfo.namespaceName,
namespace.commitPage,
size)
.then(function (result) {
if (result.length < size) {
namespace.hasLoadAllCommit = true;
}
for (var i = 0; i < result.length; i++) {
//to json
result[i].changeSets = JSON.parse(result[i].changeSets);
namespace.commits.push(result[i]);
}
namespace.commitPage += 1;
}, function (result) {
toastr.error(AppUtil.errorMsg(result), $translate.instant('ApolloNsPanel.LoadingHistoryError'));
});
}
function loadInstanceInfo(namespace) {
var size = 20;
if (namespace.isBranch) {
size = 2000;
}
var type = namespace.instanceViewType;
if (namespace_instance_view_type.LATEST_RELEASE == type) {
if (!namespace.latestRelease) {
ReleaseService.findLatestActiveRelease(scope.appId,
scope.env,
namespace.baseInfo.clusterName,
namespace.baseInfo.namespaceName)
.then(function (result) {
namespace.isLatestReleaseLoaded = true;
if (!result) {
namespace.latestReleaseInstances = {};
namespace.latestReleaseInstances.total = 0;
return;
}
namespace.latestRelease = result;
InstanceService.findInstancesByRelease(scope.env,
namespace.latestRelease.id,
namespace.latestReleaseInstancesPage,
size)
.then(function (result) {
namespace.latestReleaseInstances = result;
namespace.latestReleaseInstancesPage++;
})
});
} else {
InstanceService.findInstancesByRelease(scope.env,
namespace.latestRelease.id,
namespace.latestReleaseInstancesPage,
size)
.then(function (result) {
if (result && result.content.length) {
namespace.latestReleaseInstancesPage++;
result.content.forEach(function (instance) {
namespace.latestReleaseInstances.content.push(
instance);
})
}
})
}
} else if (namespace_instance_view_type.NOT_LATEST_RELEASE == type) {
if (!namespace.latestRelease) {
return;
}
InstanceService.findByReleasesNotIn(scope.appId,
scope.env,
scope.cluster,
namespace.baseInfo.namespaceName,
namespace.latestRelease.id)
.then(function (result) {
if (!result || result.length == 0) {
return
}
var groupedInstances = {},
notLatestReleases = [];
result.forEach(function (instance) {
var configs = instance.configs;
if (configs && configs.length > 0) {
configs.forEach(function (instanceConfig) {
var release = instanceConfig.release;
//filter dirty data
if (!release) {
return;
}
if (!groupedInstances[release.id]) {
groupedInstances[release.id] = [];
notLatestReleases.push(release);
}
groupedInstances[release.id].push(instance);
})
}
});
namespace.notLatestReleases = notLatestReleases;
namespace.notLatestReleaseInstances = groupedInstances;
})
} else {
InstanceService.findInstancesByNamespace(scope.appId,
scope.env,
scope.cluster,
namespace.baseInfo.namespaceName,
'',
namespace.allInstancesPage)
.then(function (result) {
if (result && result.content.length) {
namespace.allInstancesPage++;
result.content.forEach(function (instance) {
namespace.allInstances.push(instance);
})
}
});
}
}
function refreshInstancesInfo(namespace) {
namespace.instanceViewType = namespace_instance_view_type.LATEST_RELEASE;
namespace.latestReleaseInstancesPage = 0;
namespace.latestReleaseInstances = [];
namespace.latestRelease = undefined;
if (!namespace.isBranch) {
namespace.notLatestReleaseNames = [];
namespace.notLatestReleaseInstances = {};
namespace.allInstancesPage = 0;
namespace.allInstances = [];
}
initNamespaceInstancesCount(namespace);
loadInstanceInfo(namespace);
}
function initRules(branch) {
NamespaceBranchService.findBranchGrayRules(scope.appId,
scope.env,
scope.cluster,
scope.namespace.baseInfo.namespaceName,
branch.baseInfo.clusterName)
.then(function (result) {
if (result.appId) {
branch.rules = result;
}
}, function (result) {
toastr.error(AppUtil.errorMsg(result), $translate.instant('ApolloNsPanel.LoadingGrayscaleError'));
});
}
function addRuleItem(branch) {
var newRuleItem = {
clientAppId: !branch.parentNamespace.isPublic ? branch.baseInfo.appId : '',
clientIpList: [],
draftIpList: [],
isNew: true
};
branch.editingRuleItem = newRuleItem;
EventManager.emit(EventManager.EventType.EDIT_GRAY_RELEASE_RULES, {
branch: branch
});
}
function editRuleItem(branch, ruleItem) {
ruleItem.isNew = false;
ruleItem.draftIpList = _.clone(ruleItem.clientIpList);
branch.editingRuleItem = ruleItem;
EventManager.emit(EventManager.EventType.EDIT_GRAY_RELEASE_RULES, {
branch: branch
});
}
function deleteRuleItem(branch, ruleItem) {
branch.rules.ruleItems.forEach(function (item, index) {
if (item.clientAppId == ruleItem.clientAppId) {
branch.rules.ruleItems.splice(index, 1);
toastr.success($translate.instant('ApolloNsPanel.Deleted'));
}
});
useRules(branch);
}
function useRules(branch) {
NamespaceBranchService.updateBranchGrayRules(scope.appId,
scope.env,
scope.cluster,
scope.namespace.baseInfo.namespaceName,
branch.baseInfo.clusterName,
branch.rules
)
.then(function (result) {
toastr.success($translate.instant('ApolloNsPanel.GrayscaleModified'));
//show tips if branch has not release configs
if (branch.itemModifiedCnt) {
AppUtil.showModal("#updateRuleTips");
}
setTimeout(function () {
refreshInstancesInfo(branch);
}, 1500);
}, function (result) {
AppUtil.showErrorMsg(result, $translate.instant('ApolloNsPanel.GrayscaleModifyFailed'));
})
}
function toggleTextEditStatus(namespace) {
if (!scope.lockCheck(namespace)) {
return;
}
namespace.isTextEditing = !namespace.isTextEditing;
if (namespace.isTextEditing) {//切换为编辑状态
namespace.commited = false;
namespace.backupText = namespace.text;
namespace.editText = parseModel2Text(namespace);
} else {
if (!namespace.commited) {//取消编辑,则复原
namespace.text = namespace.backupText;
}
}
}
function goToSyncPage(namespace) {
if (!scope.lockCheck(namespace)) {
return false;
}
$window.location.href =
AppUtil.prefixPath() + "/config/sync.html?#/appid=" + scope.appId + "&env="
+ scope.env + "&clusterName="
+ scope.cluster
+ "&namespaceName=" + namespace.baseInfo.namespaceName;
}
function goToDiffPage(namespace) {
$window.location.href =
AppUtil.prefixPath() + "/config/diff.html?#/appid=" + scope.appId + "&env="
+ scope.env + "&clusterName="
+ scope.cluster
+ "&namespaceName=" + namespace.baseInfo.namespaceName;
}
function modifyByText(namespace) {
var model = {
configText: namespace.editText,
namespaceId: namespace.baseInfo.id,
format: namespace.format
};
//prevent repeat submit
if (namespace.commitChangeBtnDisabled) {
return;
}
namespace.commitChangeBtnDisabled = true;
ConfigService.modify_items(scope.appId,
scope.env,
scope.cluster,
namespace.baseInfo.namespaceName,
model).then(
function (result) {
toastr.success($translate.instant('ApolloNsPanel.ModifiedTips'));
//refresh all namespace items
EventManager.emit(EventManager.EventType.REFRESH_NAMESPACE,
{
namespace: namespace
});
return true;
}, function (result) {
toastr.error(AppUtil.errorMsg(result), $translate.instant('ApolloNsPanel.ModifyFailed'));
namespace.commitChangeBtnDisabled = false;
return false;
}
);
namespace.commited = true;
}
function syntaxCheck(namespace) {
var model = {
configText: namespace.editText,
namespaceId: namespace.baseInfo.id,
format: namespace.format
};
ConfigService.syntax_check_text(scope.appId,
scope.env,
scope.cluster,
namespace.baseInfo.namespaceName,
model).then(
function (result) {
toastr.success($translate.instant('ApolloNsPanel.GrammarIsRight'));
}, function (result) {
EventManager.emit(EventManager.EventType.SYNTAX_CHECK_TEXT_FAILED, {
syntaxCheckMessage: AppUtil.pureErrorMsg(result)
});
}
);
}
function goToParentAppConfigPage(namespace) {
$window.location.href = AppUtil.prefixPath() + "/config.html?#/appid=" + namespace.parentAppId;
$window.location.reload();
}
function parseModel2Text(namespace) {
if (namespace.items.length == 0) {
namespace.itemCnt = 0;
return "";
}
//文件模式
if (!namespace.isPropertiesFormat) {
return parseNotPropertiesText(namespace);
} else {
return parsePropertiesText(namespace);
}
}
function parseNotPropertiesText(namespace) {
var text = namespace.items[0].item.value;
var lineNum = text.split("\n").length;
namespace.itemCnt = lineNum;
return text;
}
function parsePropertiesText(namespace) {
var result = "";
var itemCnt = 0;
namespace.items.forEach(function (item) {
//deleted key
if (!item.item.dataChangeLastModifiedBy) {
return;
}
if (item.item.key) {
//use string \n to display as new line
var itemValue = item.item.value.replace(/\n/g, "\\n");
result +=
item.item.key + " = " + itemValue + "\n";
} else {
result += item.item.comment + "\n";
}
itemCnt++;
});
namespace.itemCnt = itemCnt;
return result;
}
function toggleItemSearchInput(namespace) {
namespace.displayControl.showSearchInput = !namespace.displayControl.showSearchInput;
}
function searchItems(namespace) {
var searchKey = namespace.searchKey.toLowerCase();
var items = [];
namespace.items.forEach(function (item) {
var key = item.item.key;
if (key && key.toLowerCase().indexOf(searchKey) >= 0) {
items.push(item);
}
});
namespace.viewItems = items;
}
//normal release and gray release
function publish(namespace) {
if (!namespace.hasReleasePermission) {
AppUtil.showModal('#releaseNoPermissionDialog');
return;
} else if (namespace.lockOwner && scope.user == namespace.lockOwner) {
//can not publish if config modified by himself
EventManager.emit(EventManager.EventType.PUBLISH_DENY, {
namespace: namespace,
mergeAndPublish: false
});
return;
}
if (namespace.isBranch) {
namespace.mergeAndPublish = false;
}
EventManager.emit(EventManager.EventType.PUBLISH_NAMESPACE,
{
namespace: namespace
});
}
function mergeAndPublish(branch) {
var parentNamespace = branch.parentNamespace;
if (!parentNamespace.hasReleasePermission) {
AppUtil.showModal('#releaseNoPermissionDialog');
} else if (parentNamespace.itemModifiedCnt > 0) {
AppUtil.showModal('#mergeAndReleaseDenyDialog');
} else if (branch.lockOwner && scope.user == branch.lockOwner) {
EventManager.emit(EventManager.EventType.PUBLISH_DENY, {
namespace: branch,
mergeAndPublish: true
});
} else {
EventManager.emit(EventManager.EventType.MERGE_AND_PUBLISH_NAMESPACE, { branch: branch });
}
}
function rollback(namespace) {
EventManager.emit(EventManager.EventType.PRE_ROLLBACK_NAMESPACE, { namespace: namespace });
}
function deleteNamespace(namespace) {
EventManager.emit(EventManager.EventType.PRE_DELETE_NAMESPACE, { namespace: namespace });
}
//theme: https://github.com/ajaxorg/ace-builds/tree/ba3b91e04a5aa559d56ac70964f9054baa0f4caf/src-min
scope.aceConfig = {
$blockScrolling: Infinity,
showPrintMargin: false,
theme: 'eclipse',
mode: scope.namespace.format === 'yml' ? 'yaml' : (scope.namespace.format === 'txt' ? undefined : scope.namespace.format),
onLoad: function (_editor) {
_editor.$blockScrolling = Infinity;
_editor.setOptions({
fontSize: 13,
minLines: 10,
maxLines: 20
})
}
};
setTimeout(function () {
scope.namespace.show = true;
}, 70);
}
}
}
| /*
* Copyright 2021 Apollo Authors
*
* 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.
*
*/
directive_module.directive('apollonspanel', directive);
function directive($window, $translate, toastr, AppUtil, EventManager, PermissionService, NamespaceLockService,
UserService, CommitService, ReleaseService, InstanceService, NamespaceBranchService, ConfigService) {
return {
restrict: 'E',
templateUrl: AppUtil.prefixPath() + '/views/component/namespace-panel.html',
transclude: true,
replace: true,
scope: {
namespace: '=',
appId: '=',
env: '=',
cluster: '=',
user: '=',
lockCheck: '=',
createItem: '=',
editItem: '=',
preDeleteItem: '=',
preRevokeItem: '=',
showText: '=',
showNoModifyPermissionDialog: '=',
preCreateBranch: '=',
preDeleteBranch: '=',
showMergeAndPublishGrayTips: '=',
showBody: "=?",
lazyLoad: "=?"
},
link: function (scope) {
//constants
var namespace_view_type = {
TEXT: 'text',
TABLE: 'table',
HISTORY: 'history',
INSTANCE: 'instance',
RULE: 'rule'
};
var namespace_instance_view_type = {
LATEST_RELEASE: 'latest_release',
NOT_LATEST_RELEASE: 'not_latest_release',
ALL: 'all'
};
var operate_branch_storage_key = 'OperateBranch';
scope.refreshNamespace = refreshNamespace;
scope.switchView = switchView;
scope.toggleItemSearchInput = toggleItemSearchInput;
scope.searchItems = searchItems;
scope.loadCommitHistory = loadCommitHistory;
scope.toggleTextEditStatus = toggleTextEditStatus;
scope.goToSyncPage = goToSyncPage;
scope.goToDiffPage = goToDiffPage;
scope.modifyByText = modifyByText;
scope.syntaxCheck = syntaxCheck;
scope.goToParentAppConfigPage = goToParentAppConfigPage;
scope.switchInstanceViewType = switchInstanceViewType;
scope.switchBranch = switchBranch;
scope.loadInstanceInfo = loadInstanceInfo;
scope.refreshInstancesInfo = refreshInstancesInfo;
scope.deleteRuleItem = deleteRuleItem;
scope.rollback = rollback;
scope.publish = publish;
scope.mergeAndPublish = mergeAndPublish;
scope.addRuleItem = addRuleItem;
scope.editRuleItem = editRuleItem;
scope.deleteNamespace = deleteNamespace;
var subscriberId = EventManager.subscribe(EventManager.EventType.UPDATE_GRAY_RELEASE_RULES,
function (context) {
useRules(context.branch);
}, scope.namespace.baseInfo.namespaceName);
scope.$on('$destroy', function () {
EventManager.unsubscribe(EventManager.EventType.UPDATE_GRAY_RELEASE_RULES,
subscriberId, scope.namespace.baseInfo.namespaceName);
});
preInit(scope.namespace);
if (!scope.lazyLoad || scope.namespace.initialized) {
init();
}
function preInit(namespace) {
scope.showNamespaceBody = false;
namespace.isLinkedNamespace =
namespace.isPublic ? namespace.parentAppId != namespace.baseInfo.appId : false;
//namespace view name hide suffix
namespace.viewName = namespace.baseInfo.namespaceName.replace(".xml", "").replace(
".properties", "").replace(".json", "").replace(".yml", "")
.replace(".yaml", "").replace(".txt", "");
}
function init() {
initNamespace(scope.namespace);
initOther();
scope.namespace.initialized = true;
}
function refreshNamespace() {
EventManager.emit(EventManager.EventType.REFRESH_NAMESPACE,
{ namespace: scope.namespace });
}
function initNamespace(namespace, viewType) {
namespace.hasBranch = false;
namespace.isBranch = false;
namespace.displayControl = {
currentOperateBranch: 'master',
showSearchInput: false,
show: scope.showBody
};
scope.showNamespaceBody = namespace.showNamespaceBody ? true : scope.showBody;
namespace.viewItems = namespace.items;
namespace.isPropertiesFormat = namespace.format == 'properties';
namespace.isSyntaxCheckable = namespace.format == 'yaml' || namespace.format == 'yml';
namespace.isTextEditing = false;
namespace.instanceViewType = namespace_instance_view_type.LATEST_RELEASE;
namespace.latestReleaseInstancesPage = 0;
namespace.allInstances = [];
namespace.allInstancesPage = 0;
namespace.commitChangeBtnDisabled = false;
generateNamespaceId(namespace);
initNamespaceBranch(namespace);
initNamespaceViewName(namespace);
initNamespaceLock(namespace);
initNamespaceInstancesCount(namespace);
initPermission(namespace);
initLinkedNamespace(namespace);
loadInstanceInfo(namespace);
function initNamespaceBranch(namespace) {
NamespaceBranchService.findNamespaceBranch(scope.appId, scope.env,
namespace.baseInfo.clusterName,
namespace.baseInfo.namespaceName)
.then(function (result) {
if (!result.baseInfo) {
return;
}
//namespace has branch
namespace.hasBranch = true;
namespace.branchName = result.baseInfo.clusterName;
//init branch
namespace.branch = result;
namespace.branch.isBranch = true;
namespace.branch.parentNamespace = namespace;
namespace.branch.viewType = namespace_view_type.TABLE;
namespace.branch.isPropertiesFormat = namespace.format == 'properties';
namespace.branch.allInstances = [];//master namespace all instances
namespace.branch.latestReleaseInstances = [];
namespace.branch.latestReleaseInstancesPage = 0;
namespace.branch.instanceViewType = namespace_instance_view_type.LATEST_RELEASE;
namespace.branch.hasLoadInstances = false;
namespace.branch.displayControl = {
show: true
};
generateNamespaceId(namespace.branch);
initBranchItems(namespace.branch);
initRules(namespace.branch);
loadInstanceInfo(namespace.branch);
initNamespaceLock(namespace.branch);
initPermission(namespace);
initUserOperateBranchScene(namespace);
});
function initBranchItems(branch) {
branch.masterItems = [];
branch.branchItems = [];
var masterItemsMap = {};
branch.parentNamespace.items.forEach(function (item) {
if (item.item.key) {
masterItemsMap[item.item.key] = item;
}
});
var branchItemsMap = {};
var itemModifiedCnt = 0;
branch.items.forEach(function (item) {
var key = item.item.key;
var masterItem = masterItemsMap[key];
//modify master item and set item's masterReleaseValue
if (masterItem) {
item.masterItemExists = true;
if (masterItem.isModified) {
item.masterReleaseValue = masterItem.oldValue;
} else {
item.masterReleaseValue = masterItem.item.value;
}
} else {//delete branch item
item.masterItemExists = false;
}
//delete master item. ignore
if (item.isDeleted && masterItem) {
if (item.masterReleaseValue != item.oldValue) {
itemModifiedCnt++;
branch.branchItems.push(item);
}
} else {//branch's item
branchItemsMap[key] = item;
if (item.isModified) {
itemModifiedCnt++;
}
branch.branchItems.push(item);
}
});
branch.itemModifiedCnt = itemModifiedCnt;
branch.parentNamespace.items.forEach(function (item) {
if (item.item.key) {
if (!branchItemsMap[item.item.key]) {
branch.masterItems.push(item);
} else {
item.hasBranchValue = true;
}
}
})
}
}
function generateNamespaceId(namespace) {
namespace.id = Math.random().toString(36).substr(2);
}
function initPermission(namespace) {
PermissionService.has_modify_namespace_permission(
scope.appId,
namespace.baseInfo.namespaceName)
.then(function (result) {
if (!result.hasPermission) {
PermissionService.has_modify_namespace_env_permission(
scope.appId,
scope.env,
namespace.baseInfo.namespaceName
)
.then(function (result) {
//branch has same permission
namespace.hasModifyPermission = result.hasPermission;
if (namespace.branch) {
namespace.branch.hasModifyPermission = result.hasPermission;
}
});
}
else {
//branch has same permission
namespace.hasModifyPermission = result.hasPermission;
if (namespace.branch) {
namespace.branch.hasModifyPermission = result.hasPermission;
}
}
});
PermissionService.has_release_namespace_permission(
scope.appId,
namespace.baseInfo.namespaceName)
.then(function (result) {
if (!result.hasPermission) {
PermissionService.has_release_namespace_env_permission(
scope.appId,
scope.env,
namespace.baseInfo.namespaceName
)
.then(function (result) {
//branch has same permission
namespace.hasReleasePermission = result.hasPermission;
if (namespace.branch) {
namespace.branch.hasReleasePermission = result.hasPermission;
}
});
}
else {
//branch has same permission
namespace.hasReleasePermission = result.hasPermission;
if (namespace.branch) {
namespace.branch.hasReleasePermission = result.hasPermission;
}
}
});
}
function initLinkedNamespace(namespace) {
if (!namespace.isPublic || !namespace.isLinkedNamespace) {
return;
}
//load public namespace
ConfigService.load_public_namespace_for_associated_namespace(scope.env, scope.appId, scope.cluster,
namespace.baseInfo.namespaceName)
.then(function (result) {
var publicNamespace = result;
namespace.publicNamespace = publicNamespace;
var linkNamespaceItemKeys = [];
namespace.items.forEach(function (item) {
var key = item.item.key;
linkNamespaceItemKeys.push(key);
});
publicNamespace.viewItems = [];
publicNamespace.items.forEach(function (item) {
var key = item.item.key;
if (key) {
publicNamespace.viewItems.push(item);
}
item.covered = linkNamespaceItemKeys.indexOf(key) >= 0;
if (item.isModified || item.isDeleted) {
publicNamespace.isModified = true;
} else if (key) {
publicNamespace.hasPublishedItem = true;
}
});
loadParentNamespaceText(namespace);
});
}
function loadParentNamespaceText(namespace){
namespace.publicNamespaceText = "";
if(namespace.isLinkedNamespace) {
namespace.publicNamespaceText = parseModel2Text(namespace.publicNamespace)
}
}
function initNamespaceViewName(namespace) {
if (!viewType) {
if (namespace.isPropertiesFormat) {
switchView(namespace, namespace_view_type.TABLE);
} else {
switchView(namespace, namespace_view_type.TEXT);
}
} else if (viewType == namespace_view_type.TABLE) {
namespace.viewType = namespace_view_type.TABLE;
}
}
function initNamespaceLock(namespace) {
NamespaceLockService.get_namespace_lock(scope.appId, scope.env,
namespace.baseInfo.clusterName,
namespace.baseInfo.namespaceName)
.then(function (result) {
namespace.lockOwner = result.lockOwner;
namespace.isEmergencyPublishAllowed = result.isEmergencyPublishAllowed;
});
}
function initUserOperateBranchScene(namespace) {
var operateBranchStorage = JSON.parse(localStorage.getItem(operate_branch_storage_key));
var namespaceId = [scope.appId, scope.env, scope.cluster, namespace.baseInfo.namespaceName].join(
"+");
if (!operateBranchStorage) {
operateBranchStorage = {};
}
if (!operateBranchStorage[namespaceId]) {
operateBranchStorage[namespaceId] = namespace.branchName;
}
localStorage.setItem(operate_branch_storage_key, JSON.stringify(operateBranchStorage));
switchBranch(operateBranchStorage[namespaceId], false);
}
}
function initNamespaceInstancesCount(namespace) {
InstanceService.getInstanceCountByNamespace(scope.appId,
scope.env,
scope.cluster,
namespace.baseInfo.namespaceName)
.then(function (result) {
namespace.instancesCount = result.num;
})
}
function initOther() {
UserService.load_user().then(function (result) {
scope.currentUser = result.userId;
});
PermissionService.has_assign_user_permission(scope.appId)
.then(function (result) {
scope.hasAssignUserPermission = result.hasPermission;
}, function (result) {
});
}
function switchBranch(branchName, forceShowBody) {
if (branchName != 'master') {
initRules(scope.namespace.branch);
}
if (forceShowBody) {
scope.showNamespaceBody = true;
}
scope.namespace.displayControl.currentOperateBranch = branchName;
//save to local storage
var operateBranchStorage = JSON.parse(localStorage.getItem(operate_branch_storage_key));
if (!operateBranchStorage) {
return;
}
var namespaceId = [scope.appId, scope.env, scope.cluster, scope.namespace.baseInfo.namespaceName].join(
"+");
operateBranchStorage[namespaceId] = branchName;
localStorage.setItem(operate_branch_storage_key, JSON.stringify(operateBranchStorage));
}
function switchView(namespace, viewType) {
namespace.viewType = viewType;
if (namespace_view_type.TEXT == viewType) {
namespace.text = parseModel2Text(namespace);
} else if (namespace_view_type.TABLE == viewType) {
} else if (namespace_view_type.HISTORY == viewType) {
loadCommitHistory(namespace);
} else if (namespace_view_type.INSTANCE == viewType) {
refreshInstancesInfo(namespace);
}
}
function switchInstanceViewType(namespace, type) {
namespace.instanceViewType = type;
loadInstanceInfo(namespace);
}
function loadCommitHistory(namespace) {
if (!namespace.commits) {
namespace.commits = [];
namespace.commitPage = 0;
}
var size = 10;
CommitService.find_commits(scope.appId,
scope.env,
namespace.baseInfo.clusterName,
namespace.baseInfo.namespaceName,
namespace.commitPage,
size)
.then(function (result) {
if (result.length < size) {
namespace.hasLoadAllCommit = true;
}
for (var i = 0; i < result.length; i++) {
//to json
result[i].changeSets = JSON.parse(result[i].changeSets);
namespace.commits.push(result[i]);
}
namespace.commitPage += 1;
}, function (result) {
toastr.error(AppUtil.errorMsg(result), $translate.instant('ApolloNsPanel.LoadingHistoryError'));
});
}
function loadInstanceInfo(namespace) {
var size = 20;
if (namespace.isBranch) {
size = 2000;
}
var type = namespace.instanceViewType;
if (namespace_instance_view_type.LATEST_RELEASE == type) {
if (!namespace.latestRelease) {
ReleaseService.findLatestActiveRelease(scope.appId,
scope.env,
namespace.baseInfo.clusterName,
namespace.baseInfo.namespaceName)
.then(function (result) {
namespace.isLatestReleaseLoaded = true;
if (!result) {
namespace.latestReleaseInstances = {};
namespace.latestReleaseInstances.total = 0;
return;
}
namespace.latestRelease = result;
InstanceService.findInstancesByRelease(scope.env,
namespace.latestRelease.id,
namespace.latestReleaseInstancesPage,
size)
.then(function (result) {
namespace.latestReleaseInstances = result;
namespace.latestReleaseInstancesPage++;
})
});
} else {
InstanceService.findInstancesByRelease(scope.env,
namespace.latestRelease.id,
namespace.latestReleaseInstancesPage,
size)
.then(function (result) {
if (result && result.content.length) {
namespace.latestReleaseInstancesPage++;
result.content.forEach(function (instance) {
namespace.latestReleaseInstances.content.push(
instance);
})
}
})
}
} else if (namespace_instance_view_type.NOT_LATEST_RELEASE == type) {
if (!namespace.latestRelease) {
return;
}
InstanceService.findByReleasesNotIn(scope.appId,
scope.env,
scope.cluster,
namespace.baseInfo.namespaceName,
namespace.latestRelease.id)
.then(function (result) {
if (!result || result.length == 0) {
return
}
var groupedInstances = {},
notLatestReleases = [];
result.forEach(function (instance) {
var configs = instance.configs;
if (configs && configs.length > 0) {
configs.forEach(function (instanceConfig) {
var release = instanceConfig.release;
//filter dirty data
if (!release) {
return;
}
if (!groupedInstances[release.id]) {
groupedInstances[release.id] = [];
notLatestReleases.push(release);
}
groupedInstances[release.id].push(instance);
})
}
});
namespace.notLatestReleases = notLatestReleases;
namespace.notLatestReleaseInstances = groupedInstances;
})
} else {
InstanceService.findInstancesByNamespace(scope.appId,
scope.env,
scope.cluster,
namespace.baseInfo.namespaceName,
'',
namespace.allInstancesPage)
.then(function (result) {
if (result && result.content.length) {
namespace.allInstancesPage++;
result.content.forEach(function (instance) {
namespace.allInstances.push(instance);
})
}
});
}
}
function refreshInstancesInfo(namespace) {
namespace.instanceViewType = namespace_instance_view_type.LATEST_RELEASE;
namespace.latestReleaseInstancesPage = 0;
namespace.latestReleaseInstances = [];
namespace.latestRelease = undefined;
if (!namespace.isBranch) {
namespace.notLatestReleaseNames = [];
namespace.notLatestReleaseInstances = {};
namespace.allInstancesPage = 0;
namespace.allInstances = [];
}
initNamespaceInstancesCount(namespace);
loadInstanceInfo(namespace);
}
function initRules(branch) {
NamespaceBranchService.findBranchGrayRules(scope.appId,
scope.env,
scope.cluster,
scope.namespace.baseInfo.namespaceName,
branch.baseInfo.clusterName)
.then(function (result) {
if (result.appId) {
branch.rules = result;
}
}, function (result) {
toastr.error(AppUtil.errorMsg(result), $translate.instant('ApolloNsPanel.LoadingGrayscaleError'));
});
}
function addRuleItem(branch) {
var newRuleItem = {
clientAppId: !branch.parentNamespace.isPublic ? branch.baseInfo.appId : '',
clientIpList: [],
draftIpList: [],
isNew: true
};
branch.editingRuleItem = newRuleItem;
EventManager.emit(EventManager.EventType.EDIT_GRAY_RELEASE_RULES, {
branch: branch
});
}
function editRuleItem(branch, ruleItem) {
ruleItem.isNew = false;
ruleItem.draftIpList = _.clone(ruleItem.clientIpList);
branch.editingRuleItem = ruleItem;
EventManager.emit(EventManager.EventType.EDIT_GRAY_RELEASE_RULES, {
branch: branch
});
}
function deleteRuleItem(branch, ruleItem) {
branch.rules.ruleItems.forEach(function (item, index) {
if (item.clientAppId == ruleItem.clientAppId) {
branch.rules.ruleItems.splice(index, 1);
toastr.success($translate.instant('ApolloNsPanel.Deleted'));
}
});
useRules(branch);
}
function useRules(branch) {
NamespaceBranchService.updateBranchGrayRules(scope.appId,
scope.env,
scope.cluster,
scope.namespace.baseInfo.namespaceName,
branch.baseInfo.clusterName,
branch.rules
)
.then(function (result) {
toastr.success($translate.instant('ApolloNsPanel.GrayscaleModified'));
//show tips if branch has not release configs
if (branch.itemModifiedCnt) {
AppUtil.showModal("#updateRuleTips");
}
setTimeout(function () {
refreshInstancesInfo(branch);
}, 1500);
}, function (result) {
AppUtil.showErrorMsg(result, $translate.instant('ApolloNsPanel.GrayscaleModifyFailed'));
})
}
function toggleTextEditStatus(namespace) {
if (!scope.lockCheck(namespace)) {
return;
}
namespace.isTextEditing = !namespace.isTextEditing;
if (namespace.isTextEditing) {//切换为编辑状态
namespace.commited = false;
namespace.backupText = namespace.text;
namespace.editText = parseModel2Text(namespace);
} else {
if (!namespace.commited) {//取消编辑,则复原
namespace.text = namespace.backupText;
}
}
}
function goToSyncPage(namespace) {
if (!scope.lockCheck(namespace)) {
return false;
}
$window.location.href =
AppUtil.prefixPath() + "/config/sync.html?#/appid=" + scope.appId + "&env="
+ scope.env + "&clusterName="
+ scope.cluster
+ "&namespaceName=" + namespace.baseInfo.namespaceName;
}
function goToDiffPage(namespace) {
$window.location.href =
AppUtil.prefixPath() + "/config/diff.html?#/appid=" + scope.appId + "&env="
+ scope.env + "&clusterName="
+ scope.cluster
+ "&namespaceName=" + namespace.baseInfo.namespaceName;
}
function modifyByText(namespace) {
var model = {
configText: namespace.editText,
namespaceId: namespace.baseInfo.id,
format: namespace.format
};
//prevent repeat submit
if (namespace.commitChangeBtnDisabled) {
return;
}
namespace.commitChangeBtnDisabled = true;
ConfigService.modify_items(scope.appId,
scope.env,
scope.cluster,
namespace.baseInfo.namespaceName,
model).then(
function (result) {
toastr.success($translate.instant('ApolloNsPanel.ModifiedTips'));
//refresh all namespace items
EventManager.emit(EventManager.EventType.REFRESH_NAMESPACE,
{
namespace: namespace
});
return true;
}, function (result) {
toastr.error(AppUtil.errorMsg(result), $translate.instant('ApolloNsPanel.ModifyFailed'));
namespace.commitChangeBtnDisabled = false;
return false;
}
);
namespace.commited = true;
}
function syntaxCheck(namespace) {
var model = {
configText: namespace.editText,
namespaceId: namespace.baseInfo.id,
format: namespace.format
};
ConfigService.syntax_check_text(scope.appId,
scope.env,
scope.cluster,
namespace.baseInfo.namespaceName,
model).then(
function (result) {
toastr.success($translate.instant('ApolloNsPanel.GrammarIsRight'));
}, function (result) {
EventManager.emit(EventManager.EventType.SYNTAX_CHECK_TEXT_FAILED, {
syntaxCheckMessage: AppUtil.pureErrorMsg(result)
});
}
);
}
function goToParentAppConfigPage(namespace) {
$window.location.href = AppUtil.prefixPath() + "/config.html?#/appid=" + namespace.parentAppId;
$window.location.reload();
}
function parseModel2Text(namespace) {
if (namespace.items.length == 0) {
namespace.itemCnt = 0;
return "";
}
//文件模式
if (!namespace.isPropertiesFormat) {
return parseNotPropertiesText(namespace);
} else {
return parsePropertiesText(namespace);
}
}
function parseNotPropertiesText(namespace) {
var text = namespace.items[0].item.value;
var lineNum = text.split("\n").length;
namespace.itemCnt = lineNum;
return text;
}
function parsePropertiesText(namespace) {
var result = "";
var itemCnt = 0;
namespace.items.forEach(function (item) {
//deleted key
if (!item.item.dataChangeLastModifiedBy) {
return;
}
if (item.item.key) {
//use string \n to display as new line
var itemValue = item.item.value.replace(/\n/g, "\\n");
result +=
item.item.key + " = " + itemValue + "\n";
} else {
result += item.item.comment + "\n";
}
itemCnt++;
});
namespace.itemCnt = itemCnt;
return result;
}
function toggleItemSearchInput(namespace) {
namespace.displayControl.showSearchInput = !namespace.displayControl.showSearchInput;
}
function searchItems(namespace) {
var searchKey = namespace.searchKey.toLowerCase();
var items = [];
namespace.items.forEach(function (item) {
var key = item.item.key;
if (key && key.toLowerCase().indexOf(searchKey) >= 0) {
items.push(item);
}
});
namespace.viewItems = items;
}
//normal release and gray release
function publish(namespace) {
if (!namespace.hasReleasePermission) {
AppUtil.showModal('#releaseNoPermissionDialog');
return;
} else if (namespace.lockOwner && scope.user == namespace.lockOwner) {
//can not publish if config modified by himself
EventManager.emit(EventManager.EventType.PUBLISH_DENY, {
namespace: namespace,
mergeAndPublish: false
});
return;
}
if (namespace.isBranch) {
namespace.mergeAndPublish = false;
}
EventManager.emit(EventManager.EventType.PUBLISH_NAMESPACE,
{
namespace: namespace
});
}
function mergeAndPublish(branch) {
var parentNamespace = branch.parentNamespace;
if (!parentNamespace.hasReleasePermission) {
AppUtil.showModal('#releaseNoPermissionDialog');
} else if (parentNamespace.itemModifiedCnt > 0) {
AppUtil.showModal('#mergeAndReleaseDenyDialog');
} else if (branch.lockOwner && scope.user == branch.lockOwner) {
EventManager.emit(EventManager.EventType.PUBLISH_DENY, {
namespace: branch,
mergeAndPublish: true
});
} else {
EventManager.emit(EventManager.EventType.MERGE_AND_PUBLISH_NAMESPACE, { branch: branch });
}
}
function rollback(namespace) {
EventManager.emit(EventManager.EventType.PRE_ROLLBACK_NAMESPACE, { namespace: namespace });
}
function deleteNamespace(namespace) {
EventManager.emit(EventManager.EventType.PRE_DELETE_NAMESPACE, { namespace: namespace });
}
//theme: https://github.com/ajaxorg/ace-builds/tree/ba3b91e04a5aa559d56ac70964f9054baa0f4caf/src-min
scope.aceConfig = {
$blockScrolling: Infinity,
showPrintMargin: false,
theme: 'eclipse',
mode: scope.namespace.format === 'yml' ? 'yaml' : (scope.namespace.format === 'txt' ? undefined : scope.namespace.format),
onLoad: function (_editor) {
_editor.$blockScrolling = Infinity;
_editor.setOptions({
fontSize: 13,
minLines: 10,
maxLines: 20
})
}
};
setTimeout(function () {
scope.namespace.show = true;
}, 70);
}
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultUserService.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.spi.defaultimpl;
import com.google.common.collect.Lists;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.spi.UserService;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class DefaultUserService implements UserService {
@Override
public List<UserInfo> searchUsers(String keyword, int offset, int limit) {
return Collections.singletonList(assembleDefaultUser());
}
@Override
public UserInfo findByUserId(String userId) {
if (userId.equals("apollo")) {
return assembleDefaultUser();
}
return null;
}
@Override
public List<UserInfo> findByUserIds(List<String> userIds) {
if (userIds.contains("apollo")) {
return Lists.newArrayList(assembleDefaultUser());
}
return null;
}
private UserInfo assembleDefaultUser() {
UserInfo defaultUser = new UserInfo();
defaultUser.setUserId("apollo");
defaultUser.setName("apollo");
defaultUser.setEmail("apollo@acme.com");
return defaultUser;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.spi.defaultimpl;
import com.google.common.collect.Lists;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.spi.UserService;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class DefaultUserService implements UserService {
@Override
public List<UserInfo> searchUsers(String keyword, int offset, int limit) {
return Collections.singletonList(assembleDefaultUser());
}
@Override
public UserInfo findByUserId(String userId) {
if (userId.equals("apollo")) {
return assembleDefaultUser();
}
return null;
}
@Override
public List<UserInfo> findByUserIds(List<String> userIds) {
if (userIds.contains("apollo")) {
return Lists.newArrayList(assembleDefaultUser());
}
return null;
}
private UserInfo assembleDefaultUser() {
UserInfo defaultUser = new UserInfo();
defaultUser.setUserId("apollo");
defaultUser.setName("apollo");
defaultUser.setEmail("apollo@acme.com");
return defaultUser;
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/EnableApolloConfig.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import com.ctrip.framework.apollo.core.ConfigConsts;
/**
* Use this annotation to register Apollo property sources when using Java Config.
*
* <p>Configuration example with multiple namespaces:</p>
* <pre class="code">
* @Configuration
* @EnableApolloConfig({"someNamespace","anotherNamespace"})
* public class AppConfig {
*
* }
* </pre>
*
* <p>Configuration example with placeholder:</p>
* <pre class="code">
* // The namespace could also be specified as a placeholder, e.g. ${redis.namespace:xxx},
* // which will use the value of the key "redis.namespace" or "xxx" if this key is not configured.
* // Please note that this placeholder could not be configured in Apollo as Apollo is not activated during this phase.
* @Configuration
* @EnableApolloConfig({"${redis.namespace:xxx}"})
* public class AppConfig {
*
* }
* </pre>
*
* @author Jason Song(song_s@ctrip.com)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(ApolloConfigRegistrar.class)
public @interface EnableApolloConfig {
/**
* Apollo namespaces to inject configuration into Spring Property Sources.
*/
String[] value() default {ConfigConsts.NAMESPACE_APPLICATION};
/**
* The order of the apollo config, default is {@link Ordered#LOWEST_PRECEDENCE}, which is Integer.MAX_VALUE.
* If there are properties with the same name in different apollo configs, the apollo config with smaller order wins.
* @return
*/
int order() default Ordered.LOWEST_PRECEDENCE;
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import com.ctrip.framework.apollo.core.ConfigConsts;
/**
* Use this annotation to register Apollo property sources when using Java Config.
*
* <p>Configuration example with multiple namespaces:</p>
* <pre class="code">
* @Configuration
* @EnableApolloConfig({"someNamespace","anotherNamespace"})
* public class AppConfig {
*
* }
* </pre>
*
* <p>Configuration example with placeholder:</p>
* <pre class="code">
* // The namespace could also be specified as a placeholder, e.g. ${redis.namespace:xxx},
* // which will use the value of the key "redis.namespace" or "xxx" if this key is not configured.
* // Please note that this placeholder could not be configured in Apollo as Apollo is not activated during this phase.
* @Configuration
* @EnableApolloConfig({"${redis.namespace:xxx}"})
* public class AppConfig {
*
* }
* </pre>
*
* @author Jason Song(song_s@ctrip.com)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(ApolloConfigRegistrar.class)
public @interface EnableApolloConfig {
/**
* Apollo namespaces to inject configuration into Spring Property Sources.
*/
String[] value() default {ConfigConsts.NAMESPACE_APPLICATION};
/**
* The order of the apollo config, default is {@link Ordered#LOWEST_PRECEDENCE}, which is Integer.MAX_VALUE.
* If there are properties with the same name in different apollo configs, the apollo config with smaller order wins.
* @return
*/
int order() default Ordered.LOWEST_PRECEDENCE;
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloJsonValue.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use this annotation to inject json property from Apollo, support the same format as Spring @Value.
*
* <p>Usage example:</p>
* <pre class="code">
* // Inject the json property value for type SomeObject.
* // Suppose SomeObject has 2 properties, someString and someInt, then the possible config
* // in Apollo is someJsonPropertyKey={"someString":"someValue", "someInt":10}.
* @ApolloJsonValue("${someJsonPropertyKey:someDefaultValue}")
* private SomeObject someObject;
* </pre>
*
* Create by zhangzheng on 2018/3/6
*
* @see org.springframework.beans.factory.annotation.Value
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@Documented
public @interface ApolloJsonValue {
/**
* The actual value expression: e.g. "${someJsonPropertyKey:someDefaultValue}".
*/
String value();
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use this annotation to inject json property from Apollo, support the same format as Spring @Value.
*
* <p>Usage example:</p>
* <pre class="code">
* // Inject the json property value for type SomeObject.
* // Suppose SomeObject has 2 properties, someString and someInt, then the possible config
* // in Apollo is someJsonPropertyKey={"someString":"someValue", "someInt":10}.
* @ApolloJsonValue("${someJsonPropertyKey:someDefaultValue}")
* private SomeObject someObject;
* </pre>
*
* Create by zhangzheng on 2018/3/6
*
* @see org.springframework.beans.factory.annotation.Value
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@Documented
public @interface ApolloJsonValue {
/**
* The actual value expression: e.g. "${someJsonPropertyKey:someDefaultValue}".
*/
String value();
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/test/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepositoryTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.internals;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.io.Files;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Created by Jason on 4/9/16.
*/
public class LocalFileConfigRepositoryTest {
private File someBaseDir;
private String someNamespace;
private ConfigRepository upstreamRepo;
private Properties someProperties;
private static String someAppId = "someApp";
private static String someCluster = "someCluster";
private String defaultKey;
private String defaultValue;
private ConfigSourceType someSourceType;
@Before
public void setUp() throws Exception {
someBaseDir = new File("src/test/resources/config-cache");
someBaseDir.mkdir();
someNamespace = "someName";
someProperties = new Properties();
defaultKey = "defaultKey";
defaultValue = "defaultValue";
someProperties.setProperty(defaultKey, defaultValue);
someSourceType = ConfigSourceType.REMOTE;
upstreamRepo = mock(ConfigRepository.class);
when(upstreamRepo.getConfig()).thenReturn(someProperties);
when(upstreamRepo.getSourceType()).thenReturn(someSourceType);
MockInjector.setInstance(ConfigUtil.class, new MockConfigUtil());
PropertiesFactory propertiesFactory = mock(PropertiesFactory.class);
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new Properties();
}
});
MockInjector.setInstance(PropertiesFactory.class, propertiesFactory);
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
recursiveDelete(someBaseDir);
}
//helper method to clean created files
private void recursiveDelete(File file) {
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
for (File f : file.listFiles()) {
recursiveDelete(f);
}
}
file.delete();
}
private String assembleLocalCacheFileName() {
return String.format("%s.properties", Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
.join(someAppId, someCluster, someNamespace));
}
@Test
public void testLoadConfigWithLocalFile() throws Exception {
String someKey = "someKey";
String someValue = "someValue\nxxx\nyyy";
Properties someProperties = new Properties();
someProperties.setProperty(someKey, someValue);
createLocalCachePropertyFile(someProperties);
LocalFileConfigRepository localRepo = new LocalFileConfigRepository(someNamespace);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties properties = localRepo.getConfig();
assertEquals(someValue, properties.getProperty(someKey));
assertEquals(ConfigSourceType.LOCAL, localRepo.getSourceType());
}
@Test
public void testLoadConfigWithLocalFileAndFallbackRepo() throws Exception {
File file = new File(someBaseDir, assembleLocalCacheFileName());
String someValue = "someValue";
Files.write(defaultKey + "=" + someValue, file, Charsets.UTF_8);
LocalFileConfigRepository localRepo = new LocalFileConfigRepository(someNamespace, upstreamRepo);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties properties = localRepo.getConfig();
assertEquals(defaultValue, properties.getProperty(defaultKey));
assertEquals(someSourceType, localRepo.getSourceType());
}
@Test
public void testLoadConfigWithNoLocalFile() throws Exception {
LocalFileConfigRepository localFileConfigRepository =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
localFileConfigRepository.setLocalCacheDir(someBaseDir, true);
Properties result = localFileConfigRepository.getConfig();
assertEquals(
"LocalFileConfigRepository's properties should be the same as fallback repo's when there is no local cache",
result, someProperties);
assertEquals(someSourceType, localFileConfigRepository.getSourceType());
}
@Test
public void testLoadConfigWithNoLocalFileMultipleTimes() throws Exception {
LocalFileConfigRepository localRepo =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties someProperties = localRepo.getConfig();
LocalFileConfigRepository
anotherLocalRepoWithNoFallback =
new LocalFileConfigRepository(someNamespace);
anotherLocalRepoWithNoFallback.setLocalCacheDir(someBaseDir, true);
Properties anotherProperties = anotherLocalRepoWithNoFallback.getConfig();
assertEquals(
"LocalFileConfigRepository should persist local cache files and return that afterwards",
someProperties, anotherProperties);
assertEquals(someSourceType, localRepo.getSourceType());
}
@Test
public void testOnRepositoryChange() throws Exception {
RepositoryChangeListener someListener = mock(RepositoryChangeListener.class);
LocalFileConfigRepository localFileConfigRepository =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
assertEquals(someSourceType, localFileConfigRepository.getSourceType());
localFileConfigRepository.setLocalCacheDir(someBaseDir, true);
localFileConfigRepository.addChangeListener(someListener);
localFileConfigRepository.getConfig();
Properties anotherProperties = new Properties();
anotherProperties.put("anotherKey", "anotherValue");
ConfigSourceType anotherSourceType = ConfigSourceType.NONE;
when(upstreamRepo.getSourceType()).thenReturn(anotherSourceType);
localFileConfigRepository.onRepositoryChange(someNamespace, anotherProperties);
final ArgumentCaptor<Properties> captor = ArgumentCaptor.forClass(Properties.class);
verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture());
assertEquals(anotherProperties, captor.getValue());
assertEquals(anotherSourceType, localFileConfigRepository.getSourceType());
}
public static class MockConfigUtil extends ConfigUtil {
@Override
public String getAppId() {
return someAppId;
}
@Override
public String getCluster() {
return someCluster;
}
}
private File createLocalCachePropertyFile(Properties properties) throws IOException {
File file = new File(someBaseDir, assembleLocalCacheFileName());
FileOutputStream in = null;
try {
in = new FileOutputStream(file);
properties.store(in, "Persisted by LocalFileConfigRepositoryTest");
} finally {
if (in != null) {
in.close();
}
}
return file;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.internals;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.io.Files;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Created by Jason on 4/9/16.
*/
public class LocalFileConfigRepositoryTest {
private File someBaseDir;
private String someNamespace;
private ConfigRepository upstreamRepo;
private Properties someProperties;
private static String someAppId = "someApp";
private static String someCluster = "someCluster";
private String defaultKey;
private String defaultValue;
private ConfigSourceType someSourceType;
@Before
public void setUp() throws Exception {
someBaseDir = new File("src/test/resources/config-cache");
someBaseDir.mkdir();
someNamespace = "someName";
someProperties = new Properties();
defaultKey = "defaultKey";
defaultValue = "defaultValue";
someProperties.setProperty(defaultKey, defaultValue);
someSourceType = ConfigSourceType.REMOTE;
upstreamRepo = mock(ConfigRepository.class);
when(upstreamRepo.getConfig()).thenReturn(someProperties);
when(upstreamRepo.getSourceType()).thenReturn(someSourceType);
MockInjector.setInstance(ConfigUtil.class, new MockConfigUtil());
PropertiesFactory propertiesFactory = mock(PropertiesFactory.class);
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new Properties();
}
});
MockInjector.setInstance(PropertiesFactory.class, propertiesFactory);
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
recursiveDelete(someBaseDir);
}
//helper method to clean created files
private void recursiveDelete(File file) {
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
for (File f : file.listFiles()) {
recursiveDelete(f);
}
}
file.delete();
}
private String assembleLocalCacheFileName() {
return String.format("%s.properties", Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
.join(someAppId, someCluster, someNamespace));
}
@Test
public void testLoadConfigWithLocalFile() throws Exception {
String someKey = "someKey";
String someValue = "someValue\nxxx\nyyy";
Properties someProperties = new Properties();
someProperties.setProperty(someKey, someValue);
createLocalCachePropertyFile(someProperties);
LocalFileConfigRepository localRepo = new LocalFileConfigRepository(someNamespace);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties properties = localRepo.getConfig();
assertEquals(someValue, properties.getProperty(someKey));
assertEquals(ConfigSourceType.LOCAL, localRepo.getSourceType());
}
@Test
public void testLoadConfigWithLocalFileAndFallbackRepo() throws Exception {
File file = new File(someBaseDir, assembleLocalCacheFileName());
String someValue = "someValue";
Files.write(defaultKey + "=" + someValue, file, Charsets.UTF_8);
LocalFileConfigRepository localRepo = new LocalFileConfigRepository(someNamespace, upstreamRepo);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties properties = localRepo.getConfig();
assertEquals(defaultValue, properties.getProperty(defaultKey));
assertEquals(someSourceType, localRepo.getSourceType());
}
@Test
public void testLoadConfigWithNoLocalFile() throws Exception {
LocalFileConfigRepository localFileConfigRepository =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
localFileConfigRepository.setLocalCacheDir(someBaseDir, true);
Properties result = localFileConfigRepository.getConfig();
assertEquals(
"LocalFileConfigRepository's properties should be the same as fallback repo's when there is no local cache",
result, someProperties);
assertEquals(someSourceType, localFileConfigRepository.getSourceType());
}
@Test
public void testLoadConfigWithNoLocalFileMultipleTimes() throws Exception {
LocalFileConfigRepository localRepo =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties someProperties = localRepo.getConfig();
LocalFileConfigRepository
anotherLocalRepoWithNoFallback =
new LocalFileConfigRepository(someNamespace);
anotherLocalRepoWithNoFallback.setLocalCacheDir(someBaseDir, true);
Properties anotherProperties = anotherLocalRepoWithNoFallback.getConfig();
assertEquals(
"LocalFileConfigRepository should persist local cache files and return that afterwards",
someProperties, anotherProperties);
assertEquals(someSourceType, localRepo.getSourceType());
}
@Test
public void testOnRepositoryChange() throws Exception {
RepositoryChangeListener someListener = mock(RepositoryChangeListener.class);
LocalFileConfigRepository localFileConfigRepository =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
assertEquals(someSourceType, localFileConfigRepository.getSourceType());
localFileConfigRepository.setLocalCacheDir(someBaseDir, true);
localFileConfigRepository.addChangeListener(someListener);
localFileConfigRepository.getConfig();
Properties anotherProperties = new Properties();
anotherProperties.put("anotherKey", "anotherValue");
ConfigSourceType anotherSourceType = ConfigSourceType.NONE;
when(upstreamRepo.getSourceType()).thenReturn(anotherSourceType);
localFileConfigRepository.onRepositoryChange(someNamespace, anotherProperties);
final ArgumentCaptor<Properties> captor = ArgumentCaptor.forClass(Properties.class);
verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture());
assertEquals(anotherProperties, captor.getValue());
assertEquals(anotherSourceType, localFileConfigRepository.getSourceType());
}
public static class MockConfigUtil extends ConfigUtil {
@Override
public String getAppId() {
return someAppId;
}
@Override
public String getCluster() {
return someCluster;
}
}
private File createLocalCachePropertyFile(Properties properties) throws IOException {
File file = new File(someBaseDir, assembleLocalCacheFileName());
FileOutputStream in = null;
try {
in = new FileOutputStream(file);
properties.store(in, "Persisted by LocalFileConfigRepositoryTest");
} finally {
if (in != null) {
in.close();
}
}
return file;
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/ConfigServiceApplication.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.configservice;
import com.ctrip.framework.apollo.biz.ApolloBizConfig;
import com.ctrip.framework.apollo.common.ApolloCommonConfig;
import com.ctrip.framework.apollo.metaservice.ApolloMetaServiceConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Spring boot application entry point
*
* @author Jason Song(song_s@ctrip.com)
*/
@EnableAspectJAutoProxy
@EnableAutoConfiguration
@Configuration
@EnableTransactionManagement
@PropertySource(value = {"classpath:configservice.properties"})
@ComponentScan(basePackageClasses = {ApolloCommonConfig.class,
ApolloBizConfig.class,
ConfigServiceApplication.class,
ApolloMetaServiceConfig.class})
public class ConfigServiceApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(ConfigServiceApplication.class, args);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.configservice;
import com.ctrip.framework.apollo.biz.ApolloBizConfig;
import com.ctrip.framework.apollo.common.ApolloCommonConfig;
import com.ctrip.framework.apollo.metaservice.ApolloMetaServiceConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Spring boot application entry point
*
* @author Jason Song(song_s@ctrip.com)
*/
@EnableAspectJAutoProxy
@EnableAutoConfiguration
@Configuration
@EnableTransactionManagement
@PropertySource(value = {"classpath:configservice.properties"})
@ComponentScan(basePackageClasses = {ApolloCommonConfig.class,
ApolloBizConfig.class,
ConfigServiceApplication.class,
ApolloMetaServiceConfig.class})
public class ConfigServiceApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(ConfigServiceApplication.class, args);
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeprecatedPropertyNotifyUtil.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core.utils;
import org.slf4j.Logger;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class DeprecatedPropertyNotifyUtil {
private static final Logger log = DeferredLoggerFactory
.getLogger(DeprecatedPropertyNotifyUtil.class);
public static void warn(String deprecatedProperty, String insteadProperty) {
log.warn("[{}] is deprecated since 1.9.0 and will be removed in a future version, please use the [{}] instead.", deprecatedProperty, insteadProperty);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core.utils;
import org.slf4j.Logger;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class DeprecatedPropertyNotifyUtil {
private static final Logger log = DeferredLoggerFactory
.getLogger(DeprecatedPropertyNotifyUtil.class);
public static void warn(String deprecatedProperty, String insteadProperty) {
log.warn("[{}] is deprecated since 1.9.0 and will be removed in a future version, please use the [{}] instead.", deprecatedProperty, insteadProperty);
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/dto/PageDTO.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.dto;
import org.springframework.data.domain.Pageable;
import java.util.Collections;
import java.util.List;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class PageDTO<T> {
private final long total;
private final List<T> content;
private final int page;
private final int size;
public PageDTO(List<T> content, Pageable pageable, long total) {
this.total = total;
this.content = content;
this.page = pageable.getPageNumber();
this.size = pageable.getPageSize();
}
public long getTotal() {
return total;
}
public List<T> getContent() {
return Collections.unmodifiableList(content);
}
public int getPage() {
return page;
}
public int getSize() {
return size;
}
public boolean hasContent(){
return content != null && content.size() > 0;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.dto;
import org.springframework.data.domain.Pageable;
import java.util.Collections;
import java.util.List;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class PageDTO<T> {
private final long total;
private final List<T> content;
private final int page;
private final int size;
public PageDTO(List<T> content, Pageable pageable, long total) {
this.total = total;
this.content = content;
this.page = pageable.getPageNumber();
this.size = pageable.getPageSize();
}
public long getTotal() {
return total;
}
public List<T> getContent() {
return Collections.unmodifiableList(content);
}
public int getPage() {
return page;
}
public int getSize() {
return size;
}
public boolean hasContent(){
return content != null && content.size() > 0;
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/resources/static/scripts/directive/delete-namespace-modal-directive.js | /*
* Copyright 2021 Apollo Authors
*
* 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.
*
*/
directive_module.directive('deletenamespacemodal', deleteNamespaceModalDirective);
function deleteNamespaceModalDirective($window, $q, $translate, toastr, AppUtil, EventManager,
PermissionService, UserService, NamespaceService) {
return {
restrict: 'E',
templateUrl: AppUtil.prefixPath() + '/views/component/delete-namespace-modal.html',
transclude: true,
replace: true,
scope: {
env: '='
},
link: function (scope) {
scope.doDeleteNamespace = doDeleteNamespace;
EventManager.subscribe(EventManager.EventType.PRE_DELETE_NAMESPACE, function (context) {
var toDeleteNamespace = context.namespace;
scope.toDeleteNamespace = toDeleteNamespace;
//1. check operator has master permission
checkPermission(toDeleteNamespace).then(function () {
//2. check namespace's master branch has not instances
if (!checkMasterInstance(toDeleteNamespace)) {
return;
}
//3. check namespace's gray branch has not instances
if (!checkBranchInstance(toDeleteNamespace)) {
return;
}
if (!toDeleteNamespace.isPublic || toDeleteNamespace.isLinkedNamespace) {
showDeleteNamespaceConfirmDialog();
} else {
//5. check public namespace has not associated namespace
checkPublicNamespace(toDeleteNamespace).then(function () {
showDeleteNamespaceConfirmDialog();
});
}
})
});
function checkPermission(namespace) {
var d = $q.defer();
UserService.load_user().then(function (currentUser) {
var isAppMasterUser = false;
PermissionService.get_app_role_users(namespace.baseInfo.appId)
.then(function (appRoleUsers) {
var masterUsers = [];
appRoleUsers.masterUsers.forEach(function (user) {
masterUsers.push(_.escape(user.userId));
if (currentUser.userId == user.userId) {
isAppMasterUser = true;
}
});
scope.masterUsers = masterUsers;
scope.isAppMasterUser = isAppMasterUser;
if (!isAppMasterUser) {
toastr.error($translate.instant('Config.DeleteNamespaceNoPermissionFailedTips', {
users: scope.masterUsers.join(", ")
}), $translate.instant('Config.DeleteNamespaceNoPermissionFailedTitle'));
d.reject();
} else {
d.resolve();
}
});
});
return d.promise;
}
function checkMasterInstance(namespace) {
if (namespace.instancesCount > 0) {
EventManager.emit(EventManager.EventType.DELETE_NAMESPACE_FAILED, {
namespace: namespace,
reason: 'master_instance'
});
return false;
}
return true;
}
function checkBranchInstance(namespace) {
if (namespace.hasBranch && namespace.branch.latestReleaseInstances.total > 0) {
EventManager.emit(EventManager.EventType.DELETE_NAMESPACE_FAILED, {
namespace: namespace,
reason: 'branch_instance'
});
return false;
}
return true;
}
function checkPublicNamespace(namespace) {
var d = $q.defer();
var publicAppId = namespace.baseInfo.appId;
NamespaceService.getPublicAppNamespaceAllNamespaces(scope.env,
namespace.baseInfo.namespaceName,
0, 20)
.then(function (associatedNamespaces) {
var otherAppAssociatedNamespaces = [];
associatedNamespaces.forEach(function (associatedNamespace) {
if (associatedNamespace.appId != publicAppId) {
otherAppAssociatedNamespaces.push(associatedNamespace);
}
});
if (otherAppAssociatedNamespaces.length) {
EventManager.emit(EventManager.EventType.DELETE_NAMESPACE_FAILED, {
namespace: namespace,
reason: 'public_namespace',
otherAppAssociatedNamespaces: otherAppAssociatedNamespaces
});
d.reject();
} else {
d.resolve();
}
});
return d.promise;
}
function showDeleteNamespaceConfirmDialog() {
AppUtil.showModal('#deleteNamespaceModal');
}
function doDeleteNamespace() {
var toDeleteNamespace = scope.toDeleteNamespace;
NamespaceService.deleteNamespace(toDeleteNamespace.baseInfo.appId, scope.env,
toDeleteNamespace.baseInfo.clusterName,
toDeleteNamespace.baseInfo.namespaceName)
.then(function () {
toastr.success($translate.instant('Common.Deleted'));
setTimeout(function () {
$window.location.reload();
}, 1000);
}, function (result) {
AppUtil.showErrorMsg(result, $translate.instant('Common.DeleteFailed'));
})
}
}
}
}
| /*
* Copyright 2021 Apollo Authors
*
* 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.
*
*/
directive_module.directive('deletenamespacemodal', deleteNamespaceModalDirective);
function deleteNamespaceModalDirective($window, $q, $translate, toastr, AppUtil, EventManager,
PermissionService, UserService, NamespaceService) {
return {
restrict: 'E',
templateUrl: AppUtil.prefixPath() + '/views/component/delete-namespace-modal.html',
transclude: true,
replace: true,
scope: {
env: '='
},
link: function (scope) {
scope.doDeleteNamespace = doDeleteNamespace;
EventManager.subscribe(EventManager.EventType.PRE_DELETE_NAMESPACE, function (context) {
var toDeleteNamespace = context.namespace;
scope.toDeleteNamespace = toDeleteNamespace;
//1. check operator has master permission
checkPermission(toDeleteNamespace).then(function () {
//2. check namespace's master branch has not instances
if (!checkMasterInstance(toDeleteNamespace)) {
return;
}
//3. check namespace's gray branch has not instances
if (!checkBranchInstance(toDeleteNamespace)) {
return;
}
if (!toDeleteNamespace.isPublic || toDeleteNamespace.isLinkedNamespace) {
showDeleteNamespaceConfirmDialog();
} else {
//5. check public namespace has not associated namespace
checkPublicNamespace(toDeleteNamespace).then(function () {
showDeleteNamespaceConfirmDialog();
});
}
})
});
function checkPermission(namespace) {
var d = $q.defer();
UserService.load_user().then(function (currentUser) {
var isAppMasterUser = false;
PermissionService.get_app_role_users(namespace.baseInfo.appId)
.then(function (appRoleUsers) {
var masterUsers = [];
appRoleUsers.masterUsers.forEach(function (user) {
masterUsers.push(_.escape(user.userId));
if (currentUser.userId == user.userId) {
isAppMasterUser = true;
}
});
scope.masterUsers = masterUsers;
scope.isAppMasterUser = isAppMasterUser;
if (!isAppMasterUser) {
toastr.error($translate.instant('Config.DeleteNamespaceNoPermissionFailedTips', {
users: scope.masterUsers.join(", ")
}), $translate.instant('Config.DeleteNamespaceNoPermissionFailedTitle'));
d.reject();
} else {
d.resolve();
}
});
});
return d.promise;
}
function checkMasterInstance(namespace) {
if (namespace.instancesCount > 0) {
EventManager.emit(EventManager.EventType.DELETE_NAMESPACE_FAILED, {
namespace: namespace,
reason: 'master_instance'
});
return false;
}
return true;
}
function checkBranchInstance(namespace) {
if (namespace.hasBranch && namespace.branch.latestReleaseInstances.total > 0) {
EventManager.emit(EventManager.EventType.DELETE_NAMESPACE_FAILED, {
namespace: namespace,
reason: 'branch_instance'
});
return false;
}
return true;
}
function checkPublicNamespace(namespace) {
var d = $q.defer();
var publicAppId = namespace.baseInfo.appId;
NamespaceService.getPublicAppNamespaceAllNamespaces(scope.env,
namespace.baseInfo.namespaceName,
0, 20)
.then(function (associatedNamespaces) {
var otherAppAssociatedNamespaces = [];
associatedNamespaces.forEach(function (associatedNamespace) {
if (associatedNamespace.appId != publicAppId) {
otherAppAssociatedNamespaces.push(associatedNamespace);
}
});
if (otherAppAssociatedNamespaces.length) {
EventManager.emit(EventManager.EventType.DELETE_NAMESPACE_FAILED, {
namespace: namespace,
reason: 'public_namespace',
otherAppAssociatedNamespaces: otherAppAssociatedNamespaces
});
d.reject();
} else {
d.resolve();
}
});
return d.promise;
}
function showDeleteNamespaceConfirmDialog() {
AppUtil.showModal('#deleteNamespaceModal');
}
function doDeleteNamespace() {
var toDeleteNamespace = scope.toDeleteNamespace;
NamespaceService.deleteNamespace(toDeleteNamespace.baseInfo.appId, scope.env,
toDeleteNamespace.baseInfo.clusterName,
toDeleteNamespace.baseInfo.namespaceName)
.then(function () {
toastr.success($translate.instant('Common.Deleted'));
setTimeout(function () {
$window.location.reload();
}, 1000);
}, function (result) {
AppUtil.showErrorMsg(result, $translate.instant('Common.DeleteFailed'));
})
}
}
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-adminservice/src/test/java/com/ctrip/framework/apollo/adminservice/controller/ControllerIntegrationExceptionTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.adminservice.controller;
import com.google.gson.Gson;
import com.ctrip.framework.apollo.biz.service.AdminService;
import com.ctrip.framework.apollo.biz.service.AppService;
import com.ctrip.framework.apollo.common.dto.AppDTO;
import com.ctrip.framework.apollo.common.entity.App;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.HttpStatusCodeException;
import java.util.Map;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
public class ControllerIntegrationExceptionTest extends AbstractControllerTest {
@Autowired
AppController appController;
@Mock
AdminService adminService;
private Object realAdminService;
@Autowired
AppService appService;
private static final Gson GSON = new Gson();
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
realAdminService = ReflectionTestUtils.getField(appController, "adminService");
ReflectionTestUtils.setField(appController, "adminService", adminService);
}
@After
public void tearDown() throws Exception {
ReflectionTestUtils.setField(appController, "adminService", realAdminService);
}
private String getBaseAppUrl() {
return "http://localhost:" + port + "/apps/";
}
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testCreateFailed() {
AppDTO dto = generateSampleDTOData();
when(adminService.createNewApp(any(App.class))).thenThrow(new RuntimeException("save failed"));
try {
restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class);
} catch (HttpStatusCodeException e) {
@SuppressWarnings("unchecked")
Map<String, String> attr = GSON.fromJson(e.getResponseBodyAsString(), Map.class);
Assert.assertEquals("save failed", attr.get("message"));
}
App savedApp = appService.findOne(dto.getAppId());
Assert.assertNull(savedApp);
}
private AppDTO generateSampleDTOData() {
AppDTO dto = new AppDTO();
dto.setAppId("someAppId");
dto.setName("someName");
dto.setOwnerName("someOwner");
dto.setOwnerEmail("someOwner@ctrip.com");
return dto;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.adminservice.controller;
import com.google.gson.Gson;
import com.ctrip.framework.apollo.biz.service.AdminService;
import com.ctrip.framework.apollo.biz.service.AppService;
import com.ctrip.framework.apollo.common.dto.AppDTO;
import com.ctrip.framework.apollo.common.entity.App;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.HttpStatusCodeException;
import java.util.Map;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
public class ControllerIntegrationExceptionTest extends AbstractControllerTest {
@Autowired
AppController appController;
@Mock
AdminService adminService;
private Object realAdminService;
@Autowired
AppService appService;
private static final Gson GSON = new Gson();
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
realAdminService = ReflectionTestUtils.getField(appController, "adminService");
ReflectionTestUtils.setField(appController, "adminService", adminService);
}
@After
public void tearDown() throws Exception {
ReflectionTestUtils.setField(appController, "adminService", realAdminService);
}
private String getBaseAppUrl() {
return "http://localhost:" + port + "/apps/";
}
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testCreateFailed() {
AppDTO dto = generateSampleDTOData();
when(adminService.createNewApp(any(App.class))).thenThrow(new RuntimeException("save failed"));
try {
restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class);
} catch (HttpStatusCodeException e) {
@SuppressWarnings("unchecked")
Map<String, String> attr = GSON.fromJson(e.getResponseBodyAsString(), Map.class);
Assert.assertEquals("save failed", attr.get("message"));
}
App savedApp = appService.findOne(dto.getAppId());
Assert.assertNull(savedApp);
}
private AppDTO generateSampleDTOData() {
AppDTO dto = new AppDTO();
dto.setAppId("someAppId");
dto.setName("someName");
dto.setOwnerName("someOwner");
dto.setOwnerEmail("someOwner@ctrip.com");
return dto;
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/repository/AccessKeyRepository.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.biz.entity.AccessKey;
import java.util.Date;
import java.util.List;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface AccessKeyRepository extends PagingAndSortingRepository<AccessKey, Long> {
long countByAppId(String appId);
AccessKey findOneByAppIdAndId(String appId, long id);
List<AccessKey> findByAppId(String appId);
List<AccessKey> findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(Date date);
List<AccessKey> findByDataChangeLastModifiedTime(Date date);
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.biz.entity.AccessKey;
import java.util.Date;
import java.util.List;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface AccessKeyRepository extends PagingAndSortingRepository<AccessKey, Long> {
long countByAppId(String appId);
AccessKey findOneByAppIdAndId(String appId, long id);
List<AccessKey> findByAppId(String appId);
List<AccessKey> findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(Date date);
List<AccessKey> findByDataChangeLastModifiedTime(Date date);
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/resources/static/views/component/namespace-panel-header.html | <!--
~ Copyright 2021 Apollo Authors
~
~ 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.
~
-->
<header class="row namespace-attribute-panel">
<div class="row">
<div class="col-md-6" style="padding-bottom:5px;">
<span class="text-center namespace-attribute-public label label-primary no-radius">
<span data-tooltip="tooltip" data-placement="bottom"
title="{{'Component.Namespace.Header.Title.PrivateTips' | translate:this }}"
ng-show="!namespace.isPublic">{{'Component.Namespace.Header.Title.Private' | translate }}</span>
<span data-tooltip="tooltip" data-placement="top"
title="{{'Component.Namespace.Header.Title.PublicTips' | translate:this }}"
ng-show="namespace.isPublic && namespace.parentAppId == namespace.baseInfo.appId">{{'Component.Namespace.Header.Title.Public' | translate }}</span>
<span data-tooltip="tooltip" data-placement="top"
title="{{'Component.Namespace.Header.Title.ExtendTips' | translate:this }}"
ng-show="namespace.isPublic && namespace.isLinkedNamespace"
ng-click="goToParentAppConfigPage(namespace)">{{'Component.Namespace.Header.Title.Extend' | translate }}</span>
</span>
<span class="text-center namespace-attribute-public label label-info no-radius">
<span ng-bind="namespace.format" style="width:30px;"></span>
</span>
</div>
<div class="col-md-6 text-right" style="padding-right:23px;">
<span data-toggle="collapse" data-target="#BODY{{namespace.branch.id}}" aria-expanded="false">
<span class="label no-radius cursor-pointer" data-toggle="collapse" data-target="#BODY{{namespace.id}}"
aria-expanded="false" ng-click="showNamespaceBody = !showNamespaceBody"
ng-show="namespace.initialized">
<a>{{'Component.Namespace.Header.Title.ExpandAndCollapse' | translate }}</a>
</span>
</span>
</div>
</div>
</header>
<!--branch nav-->
<header class="panel-heading second-panel-heading" ng-show="namespace.initialized && namespace.hasBranch">
<div class="row">
<div class="col-md-8 pull-left">
<ul class="nav nav-tabs">
<li role="presentation">
<a ng-class="{'node_active': namespace.displayControl.currentOperateBranch == 'master'}"
ng-click="switchBranch('master', true)">
<img src="img/branch.png">
{{'Component.Namespace.Header.Title.Master' | translate }}
</a>
</li>
<li role="presentation">
<a ng-class="{'node_active': namespace.displayControl.currentOperateBranch != 'master'}"
ng-click="switchBranch(namespace.branchName, true)">
<img src="img/branch.png">
{{'Component.Namespace.Header.Title.Grayscale' | translate }}
</a>
</li>
</ul>
</div>
</div>
</header> | <!--
~ Copyright 2021 Apollo Authors
~
~ 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.
~
-->
<header class="row namespace-attribute-panel">
<div class="row">
<div class="col-md-6" style="padding-bottom:5px;">
<span class="text-center namespace-attribute-public label label-primary no-radius">
<span data-tooltip="tooltip" data-placement="bottom"
title="{{'Component.Namespace.Header.Title.PrivateTips' | translate:this }}"
ng-show="!namespace.isPublic">{{'Component.Namespace.Header.Title.Private' | translate }}</span>
<span data-tooltip="tooltip" data-placement="top"
title="{{'Component.Namespace.Header.Title.PublicTips' | translate:this }}"
ng-show="namespace.isPublic && namespace.parentAppId == namespace.baseInfo.appId">{{'Component.Namespace.Header.Title.Public' | translate }}</span>
<span data-tooltip="tooltip" data-placement="top"
title="{{'Component.Namespace.Header.Title.ExtendTips' | translate:this }}"
ng-show="namespace.isPublic && namespace.isLinkedNamespace"
ng-click="goToParentAppConfigPage(namespace)">{{'Component.Namespace.Header.Title.Extend' | translate }}</span>
</span>
<span class="text-center namespace-attribute-public label label-info no-radius">
<span ng-bind="namespace.format" style="width:30px;"></span>
</span>
</div>
<div class="col-md-6 text-right" style="padding-right:23px;">
<span data-toggle="collapse" data-target="#BODY{{namespace.branch.id}}" aria-expanded="false">
<span class="label no-radius cursor-pointer" data-toggle="collapse" data-target="#BODY{{namespace.id}}"
aria-expanded="false" ng-click="showNamespaceBody = !showNamespaceBody"
ng-show="namespace.initialized">
<a>{{'Component.Namespace.Header.Title.ExpandAndCollapse' | translate }}</a>
</span>
</span>
</div>
</div>
</header>
<!--branch nav-->
<header class="panel-heading second-panel-heading" ng-show="namespace.initialized && namespace.hasBranch">
<div class="row">
<div class="col-md-8 pull-left">
<ul class="nav nav-tabs">
<li role="presentation">
<a ng-class="{'node_active': namespace.displayControl.currentOperateBranch == 'master'}"
ng-click="switchBranch('master', true)">
<img src="img/branch.png">
{{'Component.Namespace.Header.Title.Master' | translate }}
</a>
</li>
<li role="presentation">
<a ng-class="{'node_active': namespace.displayControl.currentOperateBranch != 'master'}"
ng-click="switchBranch(namespace.branchName, true)">
<img src="img/branch.png">
{{'Component.Namespace.Header.Title.Grayscale' | translate }}
</a>
</li>
</ul>
</div>
</div>
</header> | -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/config/application-ldap-activedirectory-sample.yml | #
# Copyright 2021 Apollo Authors
#
# 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.
#
# ldap sample for active directory, need to rename this file to application-ldap.yml to make it effective
spring:
ldap:
base: "dc=example,dc=com"
username: "admin" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(sAMAccountName={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://1.1.1.1:389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "user" # ldap 用户 objectClass 配置
loginId: "sAMAccountName" # ldap 用户惟一 id,用来作为登录的 id
userDisplayName: "cn" # ldap 用户名,用来作为显示名
email: "userPrincipalName" # ldap 邮箱属性
# filter: # 可选项,配置过滤,目前只支持 memberOf
# memberOf: "CN=ServiceDEV,OU=test,DC=example,DC=com|CN=WebDEV,OU=test,DC=example,DC=com" # 只允许 memberOf 属性为 ServiceDEV 和 WebDEV 的用户访问
| #
# Copyright 2021 Apollo Authors
#
# 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.
#
# ldap sample for active directory, need to rename this file to application-ldap.yml to make it effective
spring:
ldap:
base: "dc=example,dc=com"
username: "admin" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(sAMAccountName={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://1.1.1.1:389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "user" # ldap 用户 objectClass 配置
loginId: "sAMAccountName" # ldap 用户惟一 id,用来作为登录的 id
userDisplayName: "cn" # ldap 用户名,用来作为显示名
email: "userPrincipalName" # ldap 邮箱属性
# filter: # 可选项,配置过滤,目前只支持 memberOf
# memberOf: "CN=ServiceDEV,OU=test,DC=example,DC=com|CN=WebDEV,OU=test,DC=example,DC=com" # 只允许 memberOf 属性为 ServiceDEV 和 WebDEV 的用户访问
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/grayReleaseRule/GrayReleaseRulesHolder.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.grayReleaseRule;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.GrayReleaseRule;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.message.ReleaseMessageListener;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.biz.repository.GrayReleaseRuleRepository;
import com.ctrip.framework.apollo.common.constants.NamespaceBranchStatus;
import com.ctrip.framework.apollo.common.dto.GrayReleaseRuleItemDTO;
import com.ctrip.framework.apollo.common.utils.GrayReleaseRuleItemTransformer;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.google.common.collect.TreeMultimap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class GrayReleaseRulesHolder implements ReleaseMessageListener, InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(GrayReleaseRulesHolder.class);
private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
private static final Splitter STRING_SPLITTER =
Splitter.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR).omitEmptyStrings();
@Autowired
private GrayReleaseRuleRepository grayReleaseRuleRepository;
@Autowired
private BizConfig bizConfig;
private int databaseScanInterval;
private ScheduledExecutorService executorService;
//store configAppId+configCluster+configNamespace -> GrayReleaseRuleCache map
private Multimap<String, GrayReleaseRuleCache> grayReleaseRuleCache;
//store clientAppId+clientNamespace+ip -> ruleId map
private Multimap<String, Long> reversedGrayReleaseRuleCache;
//an auto increment version to indicate the age of rules
private AtomicLong loadVersion;
public GrayReleaseRulesHolder() {
loadVersion = new AtomicLong();
grayReleaseRuleCache = Multimaps.synchronizedSetMultimap(
TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, Ordering.natural()));
reversedGrayReleaseRuleCache = Multimaps.synchronizedSetMultimap(
TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, Ordering.natural()));
executorService = Executors.newScheduledThreadPool(1, ApolloThreadFactory
.create("GrayReleaseRulesHolder", true));
}
@Override
public void afterPropertiesSet() throws Exception {
populateDataBaseInterval();
//force sync load for the first time
periodicScanRules();
executorService.scheduleWithFixedDelay(this::periodicScanRules,
getDatabaseScanIntervalSecond(), getDatabaseScanIntervalSecond(), getDatabaseScanTimeUnit()
);
}
@Override
public void handleMessage(ReleaseMessage message, String channel) {
logger.info("message received - channel: {}, message: {}", channel, message);
String releaseMessage = message.getMessage();
if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(releaseMessage)) {
return;
}
List<String> keys = STRING_SPLITTER.splitToList(releaseMessage);
//message should be appId+cluster+namespace
if (keys.size() != 3) {
logger.error("message format invalid - {}", releaseMessage);
return;
}
String appId = keys.get(0);
String cluster = keys.get(1);
String namespace = keys.get(2);
List<GrayReleaseRule> rules = grayReleaseRuleRepository
.findByAppIdAndClusterNameAndNamespaceName(appId, cluster, namespace);
mergeGrayReleaseRules(rules);
}
private void periodicScanRules() {
Transaction transaction = Tracer.newTransaction("Apollo.GrayReleaseRulesScanner",
"scanGrayReleaseRules");
try {
loadVersion.incrementAndGet();
scanGrayReleaseRules();
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Scan gray release rule failed", ex);
} finally {
transaction.complete();
}
}
public Long findReleaseIdFromGrayReleaseRule(String clientAppId, String clientIp, String
configAppId, String configCluster, String configNamespaceName) {
String key = assembleGrayReleaseRuleKey(configAppId, configCluster, configNamespaceName);
if (!grayReleaseRuleCache.containsKey(key)) {
return null;
}
//create a new list to avoid ConcurrentModificationException
List<GrayReleaseRuleCache> rules = Lists.newArrayList(grayReleaseRuleCache.get(key));
for (GrayReleaseRuleCache rule : rules) {
//check branch status
if (rule.getBranchStatus() != NamespaceBranchStatus.ACTIVE) {
continue;
}
if (rule.matches(clientAppId, clientIp)) {
return rule.getReleaseId();
}
}
return null;
}
/**
* Check whether there are gray release rules for the clientAppId, clientIp, namespace
* combination. Please note that even there are gray release rules, it doesn't mean it will always
* load gray releases. Because gray release rules actually apply to one more dimension - cluster.
*/
public boolean hasGrayReleaseRule(String clientAppId, String clientIp, String namespaceName) {
return reversedGrayReleaseRuleCache.containsKey(assembleReversedGrayReleaseRuleKey(clientAppId,
namespaceName, clientIp)) || reversedGrayReleaseRuleCache.containsKey
(assembleReversedGrayReleaseRuleKey(clientAppId, namespaceName, GrayReleaseRuleItemDTO
.ALL_IP));
}
private void scanGrayReleaseRules() {
long maxIdScanned = 0;
boolean hasMore = true;
while (hasMore && !Thread.currentThread().isInterrupted()) {
List<GrayReleaseRule> grayReleaseRules = grayReleaseRuleRepository
.findFirst500ByIdGreaterThanOrderByIdAsc(maxIdScanned);
if (CollectionUtils.isEmpty(grayReleaseRules)) {
break;
}
mergeGrayReleaseRules(grayReleaseRules);
int rulesScanned = grayReleaseRules.size();
maxIdScanned = grayReleaseRules.get(rulesScanned - 1).getId();
//batch is 500
hasMore = rulesScanned == 500;
}
}
private void mergeGrayReleaseRules(List<GrayReleaseRule> grayReleaseRules) {
if (CollectionUtils.isEmpty(grayReleaseRules)) {
return;
}
for (GrayReleaseRule grayReleaseRule : grayReleaseRules) {
if (grayReleaseRule.getReleaseId() == null || grayReleaseRule.getReleaseId() == 0) {
//filter rules with no release id, i.e. never released
continue;
}
String key = assembleGrayReleaseRuleKey(grayReleaseRule.getAppId(), grayReleaseRule
.getClusterName(), grayReleaseRule.getNamespaceName());
//create a new list to avoid ConcurrentModificationException
List<GrayReleaseRuleCache> rules = Lists.newArrayList(grayReleaseRuleCache.get(key));
GrayReleaseRuleCache oldRule = null;
for (GrayReleaseRuleCache ruleCache : rules) {
if (ruleCache.getBranchName().equals(grayReleaseRule.getBranchName())) {
oldRule = ruleCache;
break;
}
}
//if old rule is null and new rule's branch status is not active, ignore
if (oldRule == null && grayReleaseRule.getBranchStatus() != NamespaceBranchStatus.ACTIVE) {
continue;
}
//use id comparison to avoid synchronization
if (oldRule == null || grayReleaseRule.getId() > oldRule.getRuleId()) {
addCache(key, transformRuleToRuleCache(grayReleaseRule));
if (oldRule != null) {
removeCache(key, oldRule);
}
} else {
if (oldRule.getBranchStatus() == NamespaceBranchStatus.ACTIVE) {
//update load version
oldRule.setLoadVersion(loadVersion.get());
} else if ((loadVersion.get() - oldRule.getLoadVersion()) > 1) {
//remove outdated inactive branch rule after 2 update cycles
removeCache(key, oldRule);
}
}
}
}
private void addCache(String key, GrayReleaseRuleCache ruleCache) {
if (ruleCache.getBranchStatus() == NamespaceBranchStatus.ACTIVE) {
for (GrayReleaseRuleItemDTO ruleItemDTO : ruleCache.getRuleItems()) {
for (String clientIp : ruleItemDTO.getClientIpList()) {
reversedGrayReleaseRuleCache.put(assembleReversedGrayReleaseRuleKey(ruleItemDTO
.getClientAppId(), ruleCache.getNamespaceName(), clientIp), ruleCache.getRuleId());
}
}
}
grayReleaseRuleCache.put(key, ruleCache);
}
private void removeCache(String key, GrayReleaseRuleCache ruleCache) {
grayReleaseRuleCache.remove(key, ruleCache);
for (GrayReleaseRuleItemDTO ruleItemDTO : ruleCache.getRuleItems()) {
for (String clientIp : ruleItemDTO.getClientIpList()) {
reversedGrayReleaseRuleCache.remove(assembleReversedGrayReleaseRuleKey(ruleItemDTO
.getClientAppId(), ruleCache.getNamespaceName(), clientIp), ruleCache.getRuleId());
}
}
}
private GrayReleaseRuleCache transformRuleToRuleCache(GrayReleaseRule grayReleaseRule) {
Set<GrayReleaseRuleItemDTO> ruleItems;
try {
ruleItems = GrayReleaseRuleItemTransformer.batchTransformFromJSON(grayReleaseRule.getRules());
} catch (Throwable ex) {
ruleItems = Sets.newHashSet();
Tracer.logError(ex);
logger.error("parse rule for gray release rule {} failed", grayReleaseRule.getId(), ex);
}
GrayReleaseRuleCache ruleCache = new GrayReleaseRuleCache(grayReleaseRule.getId(),
grayReleaseRule.getBranchName(), grayReleaseRule.getNamespaceName(), grayReleaseRule
.getReleaseId(), grayReleaseRule.getBranchStatus(), loadVersion.get(), ruleItems);
return ruleCache;
}
private void populateDataBaseInterval() {
databaseScanInterval = bizConfig.grayReleaseRuleScanInterval();
}
private int getDatabaseScanIntervalSecond() {
return databaseScanInterval;
}
private TimeUnit getDatabaseScanTimeUnit() {
return TimeUnit.SECONDS;
}
private String assembleGrayReleaseRuleKey(String configAppId, String configCluster, String
configNamespaceName) {
return STRING_JOINER.join(configAppId, configCluster, configNamespaceName);
}
private String assembleReversedGrayReleaseRuleKey(String clientAppId, String
clientNamespaceName, String clientIp) {
return STRING_JOINER.join(clientAppId, clientNamespaceName, clientIp);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.grayReleaseRule;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.GrayReleaseRule;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.message.ReleaseMessageListener;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.biz.repository.GrayReleaseRuleRepository;
import com.ctrip.framework.apollo.common.constants.NamespaceBranchStatus;
import com.ctrip.framework.apollo.common.dto.GrayReleaseRuleItemDTO;
import com.ctrip.framework.apollo.common.utils.GrayReleaseRuleItemTransformer;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.google.common.collect.TreeMultimap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class GrayReleaseRulesHolder implements ReleaseMessageListener, InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(GrayReleaseRulesHolder.class);
private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
private static final Splitter STRING_SPLITTER =
Splitter.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR).omitEmptyStrings();
@Autowired
private GrayReleaseRuleRepository grayReleaseRuleRepository;
@Autowired
private BizConfig bizConfig;
private int databaseScanInterval;
private ScheduledExecutorService executorService;
//store configAppId+configCluster+configNamespace -> GrayReleaseRuleCache map
private Multimap<String, GrayReleaseRuleCache> grayReleaseRuleCache;
//store clientAppId+clientNamespace+ip -> ruleId map
private Multimap<String, Long> reversedGrayReleaseRuleCache;
//an auto increment version to indicate the age of rules
private AtomicLong loadVersion;
public GrayReleaseRulesHolder() {
loadVersion = new AtomicLong();
grayReleaseRuleCache = Multimaps.synchronizedSetMultimap(
TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, Ordering.natural()));
reversedGrayReleaseRuleCache = Multimaps.synchronizedSetMultimap(
TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, Ordering.natural()));
executorService = Executors.newScheduledThreadPool(1, ApolloThreadFactory
.create("GrayReleaseRulesHolder", true));
}
@Override
public void afterPropertiesSet() throws Exception {
populateDataBaseInterval();
//force sync load for the first time
periodicScanRules();
executorService.scheduleWithFixedDelay(this::periodicScanRules,
getDatabaseScanIntervalSecond(), getDatabaseScanIntervalSecond(), getDatabaseScanTimeUnit()
);
}
@Override
public void handleMessage(ReleaseMessage message, String channel) {
logger.info("message received - channel: {}, message: {}", channel, message);
String releaseMessage = message.getMessage();
if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(releaseMessage)) {
return;
}
List<String> keys = STRING_SPLITTER.splitToList(releaseMessage);
//message should be appId+cluster+namespace
if (keys.size() != 3) {
logger.error("message format invalid - {}", releaseMessage);
return;
}
String appId = keys.get(0);
String cluster = keys.get(1);
String namespace = keys.get(2);
List<GrayReleaseRule> rules = grayReleaseRuleRepository
.findByAppIdAndClusterNameAndNamespaceName(appId, cluster, namespace);
mergeGrayReleaseRules(rules);
}
private void periodicScanRules() {
Transaction transaction = Tracer.newTransaction("Apollo.GrayReleaseRulesScanner",
"scanGrayReleaseRules");
try {
loadVersion.incrementAndGet();
scanGrayReleaseRules();
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Scan gray release rule failed", ex);
} finally {
transaction.complete();
}
}
public Long findReleaseIdFromGrayReleaseRule(String clientAppId, String clientIp, String
configAppId, String configCluster, String configNamespaceName) {
String key = assembleGrayReleaseRuleKey(configAppId, configCluster, configNamespaceName);
if (!grayReleaseRuleCache.containsKey(key)) {
return null;
}
//create a new list to avoid ConcurrentModificationException
List<GrayReleaseRuleCache> rules = Lists.newArrayList(grayReleaseRuleCache.get(key));
for (GrayReleaseRuleCache rule : rules) {
//check branch status
if (rule.getBranchStatus() != NamespaceBranchStatus.ACTIVE) {
continue;
}
if (rule.matches(clientAppId, clientIp)) {
return rule.getReleaseId();
}
}
return null;
}
/**
* Check whether there are gray release rules for the clientAppId, clientIp, namespace
* combination. Please note that even there are gray release rules, it doesn't mean it will always
* load gray releases. Because gray release rules actually apply to one more dimension - cluster.
*/
public boolean hasGrayReleaseRule(String clientAppId, String clientIp, String namespaceName) {
return reversedGrayReleaseRuleCache.containsKey(assembleReversedGrayReleaseRuleKey(clientAppId,
namespaceName, clientIp)) || reversedGrayReleaseRuleCache.containsKey
(assembleReversedGrayReleaseRuleKey(clientAppId, namespaceName, GrayReleaseRuleItemDTO
.ALL_IP));
}
private void scanGrayReleaseRules() {
long maxIdScanned = 0;
boolean hasMore = true;
while (hasMore && !Thread.currentThread().isInterrupted()) {
List<GrayReleaseRule> grayReleaseRules = grayReleaseRuleRepository
.findFirst500ByIdGreaterThanOrderByIdAsc(maxIdScanned);
if (CollectionUtils.isEmpty(grayReleaseRules)) {
break;
}
mergeGrayReleaseRules(grayReleaseRules);
int rulesScanned = grayReleaseRules.size();
maxIdScanned = grayReleaseRules.get(rulesScanned - 1).getId();
//batch is 500
hasMore = rulesScanned == 500;
}
}
private void mergeGrayReleaseRules(List<GrayReleaseRule> grayReleaseRules) {
if (CollectionUtils.isEmpty(grayReleaseRules)) {
return;
}
for (GrayReleaseRule grayReleaseRule : grayReleaseRules) {
if (grayReleaseRule.getReleaseId() == null || grayReleaseRule.getReleaseId() == 0) {
//filter rules with no release id, i.e. never released
continue;
}
String key = assembleGrayReleaseRuleKey(grayReleaseRule.getAppId(), grayReleaseRule
.getClusterName(), grayReleaseRule.getNamespaceName());
//create a new list to avoid ConcurrentModificationException
List<GrayReleaseRuleCache> rules = Lists.newArrayList(grayReleaseRuleCache.get(key));
GrayReleaseRuleCache oldRule = null;
for (GrayReleaseRuleCache ruleCache : rules) {
if (ruleCache.getBranchName().equals(grayReleaseRule.getBranchName())) {
oldRule = ruleCache;
break;
}
}
//if old rule is null and new rule's branch status is not active, ignore
if (oldRule == null && grayReleaseRule.getBranchStatus() != NamespaceBranchStatus.ACTIVE) {
continue;
}
//use id comparison to avoid synchronization
if (oldRule == null || grayReleaseRule.getId() > oldRule.getRuleId()) {
addCache(key, transformRuleToRuleCache(grayReleaseRule));
if (oldRule != null) {
removeCache(key, oldRule);
}
} else {
if (oldRule.getBranchStatus() == NamespaceBranchStatus.ACTIVE) {
//update load version
oldRule.setLoadVersion(loadVersion.get());
} else if ((loadVersion.get() - oldRule.getLoadVersion()) > 1) {
//remove outdated inactive branch rule after 2 update cycles
removeCache(key, oldRule);
}
}
}
}
private void addCache(String key, GrayReleaseRuleCache ruleCache) {
if (ruleCache.getBranchStatus() == NamespaceBranchStatus.ACTIVE) {
for (GrayReleaseRuleItemDTO ruleItemDTO : ruleCache.getRuleItems()) {
for (String clientIp : ruleItemDTO.getClientIpList()) {
reversedGrayReleaseRuleCache.put(assembleReversedGrayReleaseRuleKey(ruleItemDTO
.getClientAppId(), ruleCache.getNamespaceName(), clientIp), ruleCache.getRuleId());
}
}
}
grayReleaseRuleCache.put(key, ruleCache);
}
private void removeCache(String key, GrayReleaseRuleCache ruleCache) {
grayReleaseRuleCache.remove(key, ruleCache);
for (GrayReleaseRuleItemDTO ruleItemDTO : ruleCache.getRuleItems()) {
for (String clientIp : ruleItemDTO.getClientIpList()) {
reversedGrayReleaseRuleCache.remove(assembleReversedGrayReleaseRuleKey(ruleItemDTO
.getClientAppId(), ruleCache.getNamespaceName(), clientIp), ruleCache.getRuleId());
}
}
}
private GrayReleaseRuleCache transformRuleToRuleCache(GrayReleaseRule grayReleaseRule) {
Set<GrayReleaseRuleItemDTO> ruleItems;
try {
ruleItems = GrayReleaseRuleItemTransformer.batchTransformFromJSON(grayReleaseRule.getRules());
} catch (Throwable ex) {
ruleItems = Sets.newHashSet();
Tracer.logError(ex);
logger.error("parse rule for gray release rule {} failed", grayReleaseRule.getId(), ex);
}
GrayReleaseRuleCache ruleCache = new GrayReleaseRuleCache(grayReleaseRule.getId(),
grayReleaseRule.getBranchName(), grayReleaseRule.getNamespaceName(), grayReleaseRule
.getReleaseId(), grayReleaseRule.getBranchStatus(), loadVersion.get(), ruleItems);
return ruleCache;
}
private void populateDataBaseInterval() {
databaseScanInterval = bizConfig.grayReleaseRuleScanInterval();
}
private int getDatabaseScanIntervalSecond() {
return databaseScanInterval;
}
private TimeUnit getDatabaseScanTimeUnit() {
return TimeUnit.SECONDS;
}
private String assembleGrayReleaseRuleKey(String configAppId, String configCluster, String
configNamespaceName) {
return STRING_JOINER.join(configAppId, configCluster, configNamespaceName);
}
private String assembleReversedGrayReleaseRuleKey(String clientAppId, String
clientNamespaceName, String clientIp) {
return STRING_JOINER.join(clientAppId, clientNamespaceName, clientIp);
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/listener/AppNamespaceDeletionEvent.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.listener;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import com.google.common.base.Preconditions;
import org.springframework.context.ApplicationEvent;
public class AppNamespaceDeletionEvent extends ApplicationEvent {
public AppNamespaceDeletionEvent(Object source) {
super(source);
}
public AppNamespace getAppNamespace() {
Preconditions.checkState(source != null);
return (AppNamespace) this.source;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.listener;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import com.google.common.base.Preconditions;
import org.springframework.context.ApplicationEvent;
public class AppNamespaceDeletionEvent extends ApplicationEvent {
public AppNamespaceDeletionEvent(Object source) {
super(source);
}
public AppNamespace getAppNamespace() {
Preconditions.checkState(source != null);
return (AppNamespace) this.source;
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/resources/static/vendor/valdr/valdr-message.min.js | !function(a,b){"use strict";angular.module("valdr").provider("valdrMessage",function(){var a,b,c={},d="valdr/default-message.html",e='<div class="valdr-message">{{ violation.message }}</div>',f='<div class="valdr-message" ng-show="violation"><span translate="{{ violation.message }}" translate-values="violation"></span></div>';this.setTemplate=function(a){b=a},this.setTemplateUrl=function(b){a=b},this.addMessages=function(a){angular.extend(c,a)};var g=this.addMessages;this.getMessage=function(a,b,d){var e=a+"."+b+"."+d;return c[e]||c[d]||"["+d+"]"};var h=this.getMessage;this.$get=["$templateCache","$injector",function(c,i){function j(){try{return i.get("$translate")}catch(a){return void 0}}function k(){try{return i.get("valdrFieldNameKeyGenerator")}catch(a){return function(a){return a.type+"."+a.field}}}function l(){return angular.isDefined(b)?b:p?f:e}function m(){c.put(d,l()),a&&b&&c.put(a,b)}var n=!1,o=j(),p=angular.isDefined(o),q=k();return m(),{templateUrl:a||d,setTemplate:function(a){b=a,m()},translateAvailable:p,$translate:o,fieldNameKeyGenerator:q,addMessages:g,getMessage:h,angularMessagesEnabled:n}}]});var c=function(a){return["$compile",function(b){return{restrict:a,require:["?^valdrType","?^ngModel","?^valdrFormGroup"],link:function(a,c,d,e){var f=e[0],g=e[1],h=e[2],i=d.valdrNoValidate,j=d.valdrNoMessage,k=d.name;if(f&&h&&g&&!angular.isDefined(i)&&!angular.isDefined(j)){var l=angular.element('<span valdr-message="'+k+'"></span>');b(l)(a),h.addMessageElement(g,l),a.$on("$destroy",function(){h.removeMessageElement(g)})}}}}]},d=c("E"),e=c("A"),f={getType:angular.noop};angular.module("valdr").directive("input",d).directive("select",d).directive("textarea",d).directive("enableValdrMessage",e).directive("valdrMessage",["$rootScope","$injector","valdrMessage","valdrUtil",function(a,b,c,d){return{replace:!0,restrict:"A",scope:{formFieldName:"@valdrMessage"},templateUrl:function(){return c.templateUrl},require:["^form","?^valdrType"],link:function(b,e,g,h){var i=h[0],j=h[1]||f,k=function(){c.translateAvailable&&angular.isArray(b.violations)&&angular.forEach(b.violations,function(a){c.$translate(c.fieldNameKeyGenerator(a)).then(function(b){a.fieldName=b})})},l=function(a){var d=j.getType(),e=b.formFieldName;return{type:d,field:e,validator:a,message:c.getMessage(d,e,a)}},m=function(){b.violations=[],angular.forEach(b.formField.valdrViolations,function(a){b.violations.push(a)}),c.angularMessagesEnabled&&angular.forEach(b.formField.$error,function(a,c){d.startsWith(c,"valdr")||b.violations.push(l(c))}),b.violation=b.violations[0],k()},n=function(){b.violations=void 0,b.violation=void 0},o=function(){return b.formField=i[b.formFieldName],b.formField?{valdr:b.formField.valdrViolations,error:b.formField.$error}:void 0};b.$watch(o,function(){b.formField&&b.formField.$invalid?m():n()},!0),a.$on("$translateChangeSuccess",function(){k()})}}}])}(window,document); | !function(a,b){"use strict";angular.module("valdr").provider("valdrMessage",function(){var a,b,c={},d="valdr/default-message.html",e='<div class="valdr-message">{{ violation.message }}</div>',f='<div class="valdr-message" ng-show="violation"><span translate="{{ violation.message }}" translate-values="violation"></span></div>';this.setTemplate=function(a){b=a},this.setTemplateUrl=function(b){a=b},this.addMessages=function(a){angular.extend(c,a)};var g=this.addMessages;this.getMessage=function(a,b,d){var e=a+"."+b+"."+d;return c[e]||c[d]||"["+d+"]"};var h=this.getMessage;this.$get=["$templateCache","$injector",function(c,i){function j(){try{return i.get("$translate")}catch(a){return void 0}}function k(){try{return i.get("valdrFieldNameKeyGenerator")}catch(a){return function(a){return a.type+"."+a.field}}}function l(){return angular.isDefined(b)?b:p?f:e}function m(){c.put(d,l()),a&&b&&c.put(a,b)}var n=!1,o=j(),p=angular.isDefined(o),q=k();return m(),{templateUrl:a||d,setTemplate:function(a){b=a,m()},translateAvailable:p,$translate:o,fieldNameKeyGenerator:q,addMessages:g,getMessage:h,angularMessagesEnabled:n}}]});var c=function(a){return["$compile",function(b){return{restrict:a,require:["?^valdrType","?^ngModel","?^valdrFormGroup"],link:function(a,c,d,e){var f=e[0],g=e[1],h=e[2],i=d.valdrNoValidate,j=d.valdrNoMessage,k=d.name;if(f&&h&&g&&!angular.isDefined(i)&&!angular.isDefined(j)){var l=angular.element('<span valdr-message="'+k+'"></span>');b(l)(a),h.addMessageElement(g,l),a.$on("$destroy",function(){h.removeMessageElement(g)})}}}}]},d=c("E"),e=c("A"),f={getType:angular.noop};angular.module("valdr").directive("input",d).directive("select",d).directive("textarea",d).directive("enableValdrMessage",e).directive("valdrMessage",["$rootScope","$injector","valdrMessage","valdrUtil",function(a,b,c,d){return{replace:!0,restrict:"A",scope:{formFieldName:"@valdrMessage"},templateUrl:function(){return c.templateUrl},require:["^form","?^valdrType"],link:function(b,e,g,h){var i=h[0],j=h[1]||f,k=function(){c.translateAvailable&&angular.isArray(b.violations)&&angular.forEach(b.violations,function(a){c.$translate(c.fieldNameKeyGenerator(a)).then(function(b){a.fieldName=b})})},l=function(a){var d=j.getType(),e=b.formFieldName;return{type:d,field:e,validator:a,message:c.getMessage(d,e,a)}},m=function(){b.violations=[],angular.forEach(b.formField.valdrViolations,function(a){b.violations.push(a)}),c.angularMessagesEnabled&&angular.forEach(b.formField.$error,function(a,c){d.startsWith(c,"valdr")||b.violations.push(l(c))}),b.violation=b.violations[0],k()},n=function(){b.violations=void 0,b.violation=void 0},o=function(){return b.formField=i[b.formFieldName],b.formField?{valdr:b.formField.valdrViolations,error:b.formField.$error}:void 0};b.$watch(o,function(){b.formField&&b.formField.$invalid?m():n()},!0),a.$on("$translateChangeSuccess",function(){k()})}}}])}(window,document); | -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/repository/AuditRepository.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.biz.entity.Audit;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface AuditRepository extends PagingAndSortingRepository<Audit, Long> {
@Query("SELECT a from Audit a WHERE a.dataChangeCreatedBy = :owner")
List<Audit> findByOwner(@Param("owner") String owner);
@Query("SELECT a from Audit a WHERE a.dataChangeCreatedBy = :owner AND a.entityName =:entity AND a.opName = :op")
List<Audit> findAudits(@Param("owner") String owner, @Param("entity") String entity,
@Param("op") String op);
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.biz.entity.Audit;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface AuditRepository extends PagingAndSortingRepository<Audit, Long> {
@Query("SELECT a from Audit a WHERE a.dataChangeCreatedBy = :owner")
List<Audit> findByOwner(@Param("owner") String owner);
@Query("SELECT a from Audit a WHERE a.dataChangeCreatedBy = :owner AND a.entityName =:entity AND a.opName = :op")
List<Audit> findAudits(@Param("owner") String owner, @Param("entity") String entity,
@Param("op") String op);
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/MetaDomainConsts.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core;
import com.ctrip.framework.apollo.core.enums.Env;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import org.slf4j.Logger;
import com.ctrip.framework.apollo.core.spi.MetaServerProvider;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.core.utils.NetUtil;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* The meta domain will try to load the meta server address from MetaServerProviders, the default
* ones are:
*
* <ul>
* <li>com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider</li>
* </ul>
* <p>
* If no provider could provide the meta server url, the default meta url will be used(http://apollo.meta).
* <br />
* <p>
* 3rd party MetaServerProvider could be injected by typical Java Service Loader pattern.
*
* @see com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider
*/
public class MetaDomainConsts {
public static final String DEFAULT_META_URL = "http://apollo.meta";
// env -> meta server address cache
private static final Map<Env, String> metaServerAddressCache = Maps.newConcurrentMap();
private static volatile List<MetaServerProvider> metaServerProviders = null;
private static final long REFRESH_INTERVAL_IN_SECOND = 60;// 1 min
private static final Logger logger = DeferredLoggerFactory.getLogger(MetaDomainConsts.class);
// comma separated meta server address -> selected single meta server address cache
private static final Map<String, String> selectedMetaServerAddressCache = Maps.newConcurrentMap();
private static final AtomicBoolean periodicRefreshStarted = new AtomicBoolean(false);
private static final Object LOCK = new Object();
/**
* Return one meta server address. If multiple meta server addresses are configured, will select
* one.
*/
public static String getDomain(Env env) {
String metaServerAddress = getMetaServerAddress(env);
// if there is more than one address, need to select one
if (metaServerAddress.contains(",")) {
return selectMetaServerAddress(metaServerAddress);
}
return metaServerAddress;
}
/**
* Return meta server address. If multiple meta server addresses are configured, will return the
* comma separated string.
*/
public static String getMetaServerAddress(Env env) {
if (!metaServerAddressCache.containsKey(env)) {
initMetaServerAddress(env);
}
return metaServerAddressCache.get(env);
}
private static void initMetaServerAddress(Env env) {
if (metaServerProviders == null) {
synchronized (LOCK) {
if (metaServerProviders == null) {
metaServerProviders = initMetaServerProviders();
}
}
}
String metaAddress = null;
for (MetaServerProvider provider : metaServerProviders) {
metaAddress = provider.getMetaServerAddress(env);
if (!Strings.isNullOrEmpty(metaAddress)) {
logger.info("Located meta server address {} for env {} from {}", metaAddress, env,
provider.getClass().getName());
break;
}
}
if (Strings.isNullOrEmpty(metaAddress)) {
// Fallback to default meta address
metaAddress = DEFAULT_META_URL;
logger.warn(
"Meta server address fallback to {} for env {}, because it is not available in all MetaServerProviders",
metaAddress, env);
}
metaServerAddressCache.put(env, metaAddress.trim());
}
private static List<MetaServerProvider> initMetaServerProviders() {
Iterator<MetaServerProvider> metaServerProviderIterator = ServiceBootstrap
.loadAll(MetaServerProvider.class);
List<MetaServerProvider> metaServerProviders = Lists.newArrayList(metaServerProviderIterator);
Collections.sort(metaServerProviders, new Comparator<MetaServerProvider>() {
@Override
public int compare(MetaServerProvider o1, MetaServerProvider o2) {
// the smaller order has higher priority
return Integer.compare(o1.getOrder(), o2.getOrder());
}
});
return metaServerProviders;
}
/**
* Select one available meta server from the comma separated meta server addresses, e.g.
* http://1.2.3.4:8080,http://2.3.4.5:8080
* <p>
* <br />
* <p>
* In production environment, we still suggest using one single domain like
* http://config.xxx.com(backed by software load balancers like nginx) instead of multiple ip
* addresses
*/
private static String selectMetaServerAddress(String metaServerAddresses) {
String metaAddressSelected = selectedMetaServerAddressCache.get(metaServerAddresses);
if (metaAddressSelected == null) {
// initialize
if (periodicRefreshStarted.compareAndSet(false, true)) {
schedulePeriodicRefresh();
}
updateMetaServerAddresses(metaServerAddresses);
metaAddressSelected = selectedMetaServerAddressCache.get(metaServerAddresses);
}
return metaAddressSelected;
}
private static void updateMetaServerAddresses(String metaServerAddresses) {
logger.debug("Selecting meta server address for: {}", metaServerAddresses);
Transaction transaction = Tracer
.newTransaction("Apollo.MetaService", "refreshMetaServerAddress");
transaction.addData("Url", metaServerAddresses);
try {
List<String> metaServers = Lists.newArrayList(metaServerAddresses.split(","));
// random load balancing
Collections.shuffle(metaServers);
boolean serverAvailable = false;
for (String address : metaServers) {
address = address.trim();
//check whether /services/config is accessible
if (NetUtil.pingUrl(address + "/services/config")) {
// select the first available meta server
selectedMetaServerAddressCache.put(metaServerAddresses, address);
serverAvailable = true;
logger.debug("Selected meta server address {} for {}", address, metaServerAddresses);
break;
}
}
// we need to make sure the map is not empty, e.g. the first update might be failed
if (!selectedMetaServerAddressCache.containsKey(metaServerAddresses)) {
selectedMetaServerAddressCache.put(metaServerAddresses, metaServers.get(0).trim());
}
if (!serverAvailable) {
logger.warn(
"Could not find available meta server for configured meta server addresses: {}, fallback to: {}",
metaServerAddresses, selectedMetaServerAddressCache.get(metaServerAddresses));
}
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
throw ex;
} finally {
transaction.complete();
}
}
private static void schedulePeriodicRefresh() {
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(1, ApolloThreadFactory.create("MetaServiceLocator", true));
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
for (String metaServerAddresses : selectedMetaServerAddressCache.keySet()) {
updateMetaServerAddresses(metaServerAddresses);
}
} catch (Throwable ex) {
logger
.warn(String.format("Refreshing meta server address failed, will retry in %d seconds",
REFRESH_INTERVAL_IN_SECOND), ex);
}
}
}, REFRESH_INTERVAL_IN_SECOND, REFRESH_INTERVAL_IN_SECOND, TimeUnit.SECONDS);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core;
import com.ctrip.framework.apollo.core.enums.Env;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import org.slf4j.Logger;
import com.ctrip.framework.apollo.core.spi.MetaServerProvider;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.core.utils.NetUtil;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* The meta domain will try to load the meta server address from MetaServerProviders, the default
* ones are:
*
* <ul>
* <li>com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider</li>
* </ul>
* <p>
* If no provider could provide the meta server url, the default meta url will be used(http://apollo.meta).
* <br />
* <p>
* 3rd party MetaServerProvider could be injected by typical Java Service Loader pattern.
*
* @see com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider
*/
public class MetaDomainConsts {
public static final String DEFAULT_META_URL = "http://apollo.meta";
// env -> meta server address cache
private static final Map<Env, String> metaServerAddressCache = Maps.newConcurrentMap();
private static volatile List<MetaServerProvider> metaServerProviders = null;
private static final long REFRESH_INTERVAL_IN_SECOND = 60;// 1 min
private static final Logger logger = DeferredLoggerFactory.getLogger(MetaDomainConsts.class);
// comma separated meta server address -> selected single meta server address cache
private static final Map<String, String> selectedMetaServerAddressCache = Maps.newConcurrentMap();
private static final AtomicBoolean periodicRefreshStarted = new AtomicBoolean(false);
private static final Object LOCK = new Object();
/**
* Return one meta server address. If multiple meta server addresses are configured, will select
* one.
*/
public static String getDomain(Env env) {
String metaServerAddress = getMetaServerAddress(env);
// if there is more than one address, need to select one
if (metaServerAddress.contains(",")) {
return selectMetaServerAddress(metaServerAddress);
}
return metaServerAddress;
}
/**
* Return meta server address. If multiple meta server addresses are configured, will return the
* comma separated string.
*/
public static String getMetaServerAddress(Env env) {
if (!metaServerAddressCache.containsKey(env)) {
initMetaServerAddress(env);
}
return metaServerAddressCache.get(env);
}
private static void initMetaServerAddress(Env env) {
if (metaServerProviders == null) {
synchronized (LOCK) {
if (metaServerProviders == null) {
metaServerProviders = initMetaServerProviders();
}
}
}
String metaAddress = null;
for (MetaServerProvider provider : metaServerProviders) {
metaAddress = provider.getMetaServerAddress(env);
if (!Strings.isNullOrEmpty(metaAddress)) {
logger.info("Located meta server address {} for env {} from {}", metaAddress, env,
provider.getClass().getName());
break;
}
}
if (Strings.isNullOrEmpty(metaAddress)) {
// Fallback to default meta address
metaAddress = DEFAULT_META_URL;
logger.warn(
"Meta server address fallback to {} for env {}, because it is not available in all MetaServerProviders",
metaAddress, env);
}
metaServerAddressCache.put(env, metaAddress.trim());
}
private static List<MetaServerProvider> initMetaServerProviders() {
Iterator<MetaServerProvider> metaServerProviderIterator = ServiceBootstrap
.loadAll(MetaServerProvider.class);
List<MetaServerProvider> metaServerProviders = Lists.newArrayList(metaServerProviderIterator);
Collections.sort(metaServerProviders, new Comparator<MetaServerProvider>() {
@Override
public int compare(MetaServerProvider o1, MetaServerProvider o2) {
// the smaller order has higher priority
return Integer.compare(o1.getOrder(), o2.getOrder());
}
});
return metaServerProviders;
}
/**
* Select one available meta server from the comma separated meta server addresses, e.g.
* http://1.2.3.4:8080,http://2.3.4.5:8080
* <p>
* <br />
* <p>
* In production environment, we still suggest using one single domain like
* http://config.xxx.com(backed by software load balancers like nginx) instead of multiple ip
* addresses
*/
private static String selectMetaServerAddress(String metaServerAddresses) {
String metaAddressSelected = selectedMetaServerAddressCache.get(metaServerAddresses);
if (metaAddressSelected == null) {
// initialize
if (periodicRefreshStarted.compareAndSet(false, true)) {
schedulePeriodicRefresh();
}
updateMetaServerAddresses(metaServerAddresses);
metaAddressSelected = selectedMetaServerAddressCache.get(metaServerAddresses);
}
return metaAddressSelected;
}
private static void updateMetaServerAddresses(String metaServerAddresses) {
logger.debug("Selecting meta server address for: {}", metaServerAddresses);
Transaction transaction = Tracer
.newTransaction("Apollo.MetaService", "refreshMetaServerAddress");
transaction.addData("Url", metaServerAddresses);
try {
List<String> metaServers = Lists.newArrayList(metaServerAddresses.split(","));
// random load balancing
Collections.shuffle(metaServers);
boolean serverAvailable = false;
for (String address : metaServers) {
address = address.trim();
//check whether /services/config is accessible
if (NetUtil.pingUrl(address + "/services/config")) {
// select the first available meta server
selectedMetaServerAddressCache.put(metaServerAddresses, address);
serverAvailable = true;
logger.debug("Selected meta server address {} for {}", address, metaServerAddresses);
break;
}
}
// we need to make sure the map is not empty, e.g. the first update might be failed
if (!selectedMetaServerAddressCache.containsKey(metaServerAddresses)) {
selectedMetaServerAddressCache.put(metaServerAddresses, metaServers.get(0).trim());
}
if (!serverAvailable) {
logger.warn(
"Could not find available meta server for configured meta server addresses: {}, fallback to: {}",
metaServerAddresses, selectedMetaServerAddressCache.get(metaServerAddresses));
}
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
throw ex;
} finally {
transaction.complete();
}
}
private static void schedulePeriodicRefresh() {
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(1, ApolloThreadFactory.create("MetaServiceLocator", true));
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
for (String metaServerAddresses : selectedMetaServerAddressCache.keySet()) {
updateMetaServerAddresses(metaServerAddresses);
}
} catch (Throwable ex) {
logger
.warn(String.format("Refreshing meta server address failed, will retry in %d seconds",
REFRESH_INTERVAL_IN_SECOND), ex);
}
}
}, REFRESH_INTERVAL_IN_SECOND, REFRESH_INTERVAL_IN_SECOND, TimeUnit.SECONDS);
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./scripts/apollo-on-kubernetes/kubernetes/apollo-env-fat/service-apollo-admin-server-fat.yaml | #
# Copyright 2021 Apollo Authors
#
# 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.
#
---
# configmap for apollo-admin-server-fat
kind: ConfigMap
apiVersion: v1
metadata:
namespace: sre
name: configmap-apollo-admin-server-fat
data:
application-github.properties: |
spring.datasource.url = jdbc:mysql://service-mysql-for-apollo-fat-env.sre:3306/ApolloConfigDB?characterEncoding=utf8
spring.datasource.username = FillInCorrectUser
spring.datasource.password = FillInCorrectPassword
eureka.service.url = http://statefulset-apollo-config-server-fat-0.service-apollo-meta-server-fat:8080/eureka/,http://statefulset-apollo-config-server-fat-1.service-apollo-meta-server-fat:8080/eureka/
---
kind: Service
apiVersion: v1
metadata:
namespace: sre
name: service-apollo-admin-server-fat
labels:
app: service-apollo-admin-server-fat
spec:
ports:
- protocol: TCP
port: 8090
targetPort: 8090
selector:
app: pod-apollo-admin-server-fat
type: ClusterIP
sessionAffinity: ClientIP
---
kind: Deployment
apiVersion: apps/v1
metadata:
namespace: sre
name: deployment-apollo-admin-server-fat
labels:
app: deployment-apollo-admin-server-fat
spec:
replicas: 2
selector:
matchLabels:
app: pod-apollo-admin-server-fat
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
type: RollingUpdate
template:
metadata:
labels:
app: pod-apollo-admin-server-fat
spec:
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- pod-apollo-admin-server-fat
topologyKey: kubernetes.io/hostname
volumes:
- name: volume-configmap-apollo-admin-server-fat
configMap:
name: configmap-apollo-admin-server-fat
items:
- key: application-github.properties
path: application-github.properties
containers:
- image: apolloconfig/apollo-adminservice:1.9.0-SNAPSHOT
securityContext:
privileged: true
imagePullPolicy: IfNotPresent
name: container-apollo-admin-server-fat
ports:
- protocol: TCP
containerPort: 8090
volumeMounts:
- name: volume-configmap-apollo-admin-server-fat
mountPath: /apollo-adminservice/config/application-github.properties
subPath: application-github.properties
env:
- name: APOLLO_ADMIN_SERVICE_NAME
value: "service-apollo-admin-server-fat.sre"
readinessProbe:
tcpSocket:
port: 8090
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
tcpSocket:
port: 8090
initialDelaySeconds: 120
periodSeconds: 10
dnsPolicy: ClusterFirst
restartPolicy: Always | #
# Copyright 2021 Apollo Authors
#
# 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.
#
---
# configmap for apollo-admin-server-fat
kind: ConfigMap
apiVersion: v1
metadata:
namespace: sre
name: configmap-apollo-admin-server-fat
data:
application-github.properties: |
spring.datasource.url = jdbc:mysql://service-mysql-for-apollo-fat-env.sre:3306/ApolloConfigDB?characterEncoding=utf8
spring.datasource.username = FillInCorrectUser
spring.datasource.password = FillInCorrectPassword
eureka.service.url = http://statefulset-apollo-config-server-fat-0.service-apollo-meta-server-fat:8080/eureka/,http://statefulset-apollo-config-server-fat-1.service-apollo-meta-server-fat:8080/eureka/
---
kind: Service
apiVersion: v1
metadata:
namespace: sre
name: service-apollo-admin-server-fat
labels:
app: service-apollo-admin-server-fat
spec:
ports:
- protocol: TCP
port: 8090
targetPort: 8090
selector:
app: pod-apollo-admin-server-fat
type: ClusterIP
sessionAffinity: ClientIP
---
kind: Deployment
apiVersion: apps/v1
metadata:
namespace: sre
name: deployment-apollo-admin-server-fat
labels:
app: deployment-apollo-admin-server-fat
spec:
replicas: 2
selector:
matchLabels:
app: pod-apollo-admin-server-fat
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
type: RollingUpdate
template:
metadata:
labels:
app: pod-apollo-admin-server-fat
spec:
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- pod-apollo-admin-server-fat
topologyKey: kubernetes.io/hostname
volumes:
- name: volume-configmap-apollo-admin-server-fat
configMap:
name: configmap-apollo-admin-server-fat
items:
- key: application-github.properties
path: application-github.properties
containers:
- image: apolloconfig/apollo-adminservice:1.9.0-SNAPSHOT
securityContext:
privileged: true
imagePullPolicy: IfNotPresent
name: container-apollo-admin-server-fat
ports:
- protocol: TCP
containerPort: 8090
volumeMounts:
- name: volume-configmap-apollo-admin-server-fat
mountPath: /apollo-adminservice/config/application-github.properties
subPath: application-github.properties
env:
- name: APOLLO_ADMIN_SERVICE_NAME
value: "service-apollo-admin-server-fat.sre"
readinessProbe:
tcpSocket:
port: 8090
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
tcpSocket:
port: 8090
initialDelaySeconds: 120
periodSeconds: 10
dnsPolicy: ClusterFirst
restartPolicy: Always | -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLoader.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.importer;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.config.data.util.Slf4jLogMessageFormatter;
import com.ctrip.framework.apollo.spring.config.ConfigPropertySource;
import com.ctrip.framework.apollo.spring.config.ConfigPropertySourceFactory;
import com.ctrip.framework.apollo.spring.util.SpringInjector;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.springframework.boot.BootstrapRegistry.InstanceSupplier;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.config.ConfigData;
import org.springframework.boot.context.config.ConfigDataLoader;
import org.springframework.boot.context.config.ConfigDataLoaderContext;
import org.springframework.boot.context.config.ConfigDataResourceNotFoundException;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.Ordered;
import org.springframework.core.env.PropertySource;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class ApolloConfigDataLoader implements ConfigDataLoader<ApolloConfigDataResource>, Ordered {
private final Log log;
public ApolloConfigDataLoader(Log log) {
this.log = log;
}
@Override
public ConfigData load(ConfigDataLoaderContext context, ApolloConfigDataResource resource)
throws IOException, ConfigDataResourceNotFoundException {
ConfigurableBootstrapContext bootstrapContext = context.getBootstrapContext();
Binder binder = bootstrapContext.get(Binder.class);
BindHandler bindHandler = this.getBindHandler(context);
bootstrapContext.registerIfAbsent(ApolloConfigDataLoaderInitializer.class, InstanceSupplier
.from(() -> new ApolloConfigDataLoaderInitializer(this.log, binder, bindHandler,
bootstrapContext)));
ApolloConfigDataLoaderInitializer apolloConfigDataLoaderInitializer = bootstrapContext
.get(ApolloConfigDataLoaderInitializer.class);
// init apollo client
List<PropertySource<?>> initialPropertySourceList = apolloConfigDataLoaderInitializer
.initApolloClient();
// load config
bootstrapContext.registerIfAbsent(ConfigPropertySourceFactory.class,
InstanceSupplier.from(() -> SpringInjector.getInstance(ConfigPropertySourceFactory.class)));
ConfigPropertySourceFactory configPropertySourceFactory = bootstrapContext
.get(ConfigPropertySourceFactory.class);
String namespace = resource.getNamespace();
Config config = ConfigService.getConfig(namespace);
ConfigPropertySource configPropertySource = configPropertySourceFactory
.getConfigPropertySource(namespace, config);
List<PropertySource<?>> propertySourceList = new ArrayList<>();
propertySourceList.add(configPropertySource);
propertySourceList.addAll(initialPropertySourceList);
log.debug(Slf4jLogMessageFormatter
.format("apollo client loaded namespace [{}]", resource.getNamespace()));
return new ConfigData(propertySourceList);
}
private BindHandler getBindHandler(ConfigDataLoaderContext context) {
return context.getBootstrapContext().getOrElse(BindHandler.class, null);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 100;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.importer;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.config.data.util.Slf4jLogMessageFormatter;
import com.ctrip.framework.apollo.spring.config.ConfigPropertySource;
import com.ctrip.framework.apollo.spring.config.ConfigPropertySourceFactory;
import com.ctrip.framework.apollo.spring.util.SpringInjector;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.springframework.boot.BootstrapRegistry.InstanceSupplier;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.config.ConfigData;
import org.springframework.boot.context.config.ConfigDataLoader;
import org.springframework.boot.context.config.ConfigDataLoaderContext;
import org.springframework.boot.context.config.ConfigDataResourceNotFoundException;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.Ordered;
import org.springframework.core.env.PropertySource;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class ApolloConfigDataLoader implements ConfigDataLoader<ApolloConfigDataResource>, Ordered {
private final Log log;
public ApolloConfigDataLoader(Log log) {
this.log = log;
}
@Override
public ConfigData load(ConfigDataLoaderContext context, ApolloConfigDataResource resource)
throws IOException, ConfigDataResourceNotFoundException {
ConfigurableBootstrapContext bootstrapContext = context.getBootstrapContext();
Binder binder = bootstrapContext.get(Binder.class);
BindHandler bindHandler = this.getBindHandler(context);
bootstrapContext.registerIfAbsent(ApolloConfigDataLoaderInitializer.class, InstanceSupplier
.from(() -> new ApolloConfigDataLoaderInitializer(this.log, binder, bindHandler,
bootstrapContext)));
ApolloConfigDataLoaderInitializer apolloConfigDataLoaderInitializer = bootstrapContext
.get(ApolloConfigDataLoaderInitializer.class);
// init apollo client
List<PropertySource<?>> initialPropertySourceList = apolloConfigDataLoaderInitializer
.initApolloClient();
// load config
bootstrapContext.registerIfAbsent(ConfigPropertySourceFactory.class,
InstanceSupplier.from(() -> SpringInjector.getInstance(ConfigPropertySourceFactory.class)));
ConfigPropertySourceFactory configPropertySourceFactory = bootstrapContext
.get(ConfigPropertySourceFactory.class);
String namespace = resource.getNamespace();
Config config = ConfigService.getConfig(namespace);
ConfigPropertySource configPropertySource = configPropertySourceFactory
.getConfigPropertySource(namespace, config);
List<PropertySource<?>> propertySourceList = new ArrayList<>();
propertySourceList.add(configPropertySource);
propertySourceList.addAll(initialPropertySourceList);
log.debug(Slf4jLogMessageFormatter
.format("apollo client loaded namespace [{}]", resource.getNamespace()));
return new ConfigData(propertySourceList);
}
private BindHandler getBindHandler(ConfigDataLoaderContext context) {
return context.getBootstrapContext().getOrElse(BindHandler.class, null);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 100;
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/service/AccessKeyServiceWithCache.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.configservice.service;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.AccessKey;
import com.ctrip.framework.apollo.biz.repository.AccessKeyRepository;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.MultimapBuilder.ListMultimapBuilder;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
/**
* @author nisiyong
*/
@Service
public class AccessKeyServiceWithCache implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(AccessKeyServiceWithCache.class);
private final AccessKeyRepository accessKeyRepository;
private final BizConfig bizConfig;
private int scanInterval;
private TimeUnit scanIntervalTimeUnit;
private int rebuildInterval;
private TimeUnit rebuildIntervalTimeUnit;
private ScheduledExecutorService scheduledExecutorService;
private Date lastTimeScanned;
private ListMultimap<String, AccessKey> accessKeyCache;
private ConcurrentMap<Long, AccessKey> accessKeyIdCache;
@Autowired
public AccessKeyServiceWithCache(AccessKeyRepository accessKeyRepository, BizConfig bizConfig) {
this.accessKeyRepository = accessKeyRepository;
this.bizConfig = bizConfig;
initialize();
}
private void initialize() {
scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
ApolloThreadFactory.create("AccessKeyServiceWithCache", true));
lastTimeScanned = new Date(0L);
ListMultimap<String, AccessKey> multimap = ListMultimapBuilder.treeKeys(String.CASE_INSENSITIVE_ORDER)
.arrayListValues().build();
accessKeyCache = Multimaps.synchronizedListMultimap(multimap);
accessKeyIdCache = Maps.newConcurrentMap();
}
public List<String> getAvailableSecrets(String appId) {
List<AccessKey> accessKeys = accessKeyCache.get(appId);
if (CollectionUtils.isEmpty(accessKeys)) {
return Collections.emptyList();
}
return accessKeys.stream()
.filter(AccessKey::isEnabled)
.map(AccessKey::getSecret)
.collect(Collectors.toList());
}
@Override
public void afterPropertiesSet() throws Exception {
populateDataBaseInterval();
scanNewAndUpdatedAccessKeys(); //block the startup process until load finished
scheduledExecutorService.scheduleWithFixedDelay(this::scanNewAndUpdatedAccessKeys,
scanInterval, scanInterval, scanIntervalTimeUnit);
scheduledExecutorService.scheduleAtFixedRate(this::rebuildAccessKeyCache,
rebuildInterval, rebuildInterval, rebuildIntervalTimeUnit);
}
private void scanNewAndUpdatedAccessKeys() {
Transaction transaction = Tracer.newTransaction("Apollo.AccessKeyServiceWithCache",
"scanNewAndUpdatedAccessKeys");
try {
loadNewAndUpdatedAccessKeys();
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Load new/updated app access keys failed", ex);
} finally {
transaction.complete();
}
}
private void rebuildAccessKeyCache() {
Transaction transaction = Tracer.newTransaction("Apollo.AccessKeyServiceWithCache",
"rebuildCache");
try {
deleteAccessKeyCache();
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Rebuild cache failed", ex);
} finally {
transaction.complete();
}
}
private void loadNewAndUpdatedAccessKeys() {
boolean hasMore = true;
while (hasMore && !Thread.currentThread().isInterrupted()) {
//current batch is 500
List<AccessKey> accessKeys = accessKeyRepository
.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(lastTimeScanned);
if (CollectionUtils.isEmpty(accessKeys)) {
break;
}
int scanned = accessKeys.size();
mergeAccessKeys(accessKeys);
logger.info("Loaded {} new/updated Accesskey from startTime {}", scanned, lastTimeScanned);
hasMore = scanned == 500;
lastTimeScanned = accessKeys.get(scanned - 1).getDataChangeLastModifiedTime();
// In order to avoid missing some records at the last time, we need to scan records at this time individually
if (hasMore) {
List<AccessKey> lastModifiedTimeAccessKeys = accessKeyRepository.findByDataChangeLastModifiedTime(lastTimeScanned);
mergeAccessKeys(lastModifiedTimeAccessKeys);
logger.info("Loaded {} new/updated Accesskey at lastModifiedTime {}", scanned, lastTimeScanned);
}
}
}
private void mergeAccessKeys(List<AccessKey> accessKeys) {
for (AccessKey accessKey : accessKeys) {
AccessKey thatInCache = accessKeyIdCache.get(accessKey.getId());
accessKeyIdCache.put(accessKey.getId(), accessKey);
accessKeyCache.put(accessKey.getAppId(), accessKey);
if (thatInCache != null && accessKey.getDataChangeLastModifiedTime()
.after(thatInCache.getDataChangeLastModifiedTime())) {
accessKeyCache.remove(accessKey.getAppId(), thatInCache);
logger.info("Found Accesskey changes, old: {}, new: {}", thatInCache, accessKey);
}
}
}
private void deleteAccessKeyCache() {
List<Long> ids = Lists.newArrayList(accessKeyIdCache.keySet());
if (CollectionUtils.isEmpty(ids)) {
return;
}
List<List<Long>> partitionIds = Lists.partition(ids, 500);
for (List<Long> toRebuildIds : partitionIds) {
Iterable<AccessKey> accessKeys = accessKeyRepository.findAllById(toRebuildIds);
Set<Long> foundIds = Sets.newHashSet();
for (AccessKey accessKey : accessKeys) {
foundIds.add(accessKey.getId());
}
//handle deleted
SetView<Long> deletedIds = Sets.difference(Sets.newHashSet(toRebuildIds), foundIds);
handleDeletedAccessKeys(deletedIds);
}
}
private void handleDeletedAccessKeys(Set<Long> deletedIds) {
if (CollectionUtils.isEmpty(deletedIds)) {
return;
}
for (Long deletedId : deletedIds) {
AccessKey deleted = accessKeyIdCache.remove(deletedId);
if (deleted == null) {
continue;
}
accessKeyCache.remove(deleted.getAppId(), deleted);
logger.info("Found AccessKey deleted, {}", deleted);
}
}
private void populateDataBaseInterval() {
scanInterval = bizConfig.accessKeyCacheScanInterval();
scanIntervalTimeUnit = bizConfig.accessKeyCacheScanIntervalTimeUnit();
rebuildInterval = bizConfig.accessKeyCacheRebuildInterval();
rebuildIntervalTimeUnit = bizConfig.accessKeyCacheRebuildIntervalTimeUnit();
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.configservice.service;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.AccessKey;
import com.ctrip.framework.apollo.biz.repository.AccessKeyRepository;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.MultimapBuilder.ListMultimapBuilder;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
/**
* @author nisiyong
*/
@Service
public class AccessKeyServiceWithCache implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(AccessKeyServiceWithCache.class);
private final AccessKeyRepository accessKeyRepository;
private final BizConfig bizConfig;
private int scanInterval;
private TimeUnit scanIntervalTimeUnit;
private int rebuildInterval;
private TimeUnit rebuildIntervalTimeUnit;
private ScheduledExecutorService scheduledExecutorService;
private Date lastTimeScanned;
private ListMultimap<String, AccessKey> accessKeyCache;
private ConcurrentMap<Long, AccessKey> accessKeyIdCache;
@Autowired
public AccessKeyServiceWithCache(AccessKeyRepository accessKeyRepository, BizConfig bizConfig) {
this.accessKeyRepository = accessKeyRepository;
this.bizConfig = bizConfig;
initialize();
}
private void initialize() {
scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
ApolloThreadFactory.create("AccessKeyServiceWithCache", true));
lastTimeScanned = new Date(0L);
ListMultimap<String, AccessKey> multimap = ListMultimapBuilder.treeKeys(String.CASE_INSENSITIVE_ORDER)
.arrayListValues().build();
accessKeyCache = Multimaps.synchronizedListMultimap(multimap);
accessKeyIdCache = Maps.newConcurrentMap();
}
public List<String> getAvailableSecrets(String appId) {
List<AccessKey> accessKeys = accessKeyCache.get(appId);
if (CollectionUtils.isEmpty(accessKeys)) {
return Collections.emptyList();
}
return accessKeys.stream()
.filter(AccessKey::isEnabled)
.map(AccessKey::getSecret)
.collect(Collectors.toList());
}
@Override
public void afterPropertiesSet() throws Exception {
populateDataBaseInterval();
scanNewAndUpdatedAccessKeys(); //block the startup process until load finished
scheduledExecutorService.scheduleWithFixedDelay(this::scanNewAndUpdatedAccessKeys,
scanInterval, scanInterval, scanIntervalTimeUnit);
scheduledExecutorService.scheduleAtFixedRate(this::rebuildAccessKeyCache,
rebuildInterval, rebuildInterval, rebuildIntervalTimeUnit);
}
private void scanNewAndUpdatedAccessKeys() {
Transaction transaction = Tracer.newTransaction("Apollo.AccessKeyServiceWithCache",
"scanNewAndUpdatedAccessKeys");
try {
loadNewAndUpdatedAccessKeys();
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Load new/updated app access keys failed", ex);
} finally {
transaction.complete();
}
}
private void rebuildAccessKeyCache() {
Transaction transaction = Tracer.newTransaction("Apollo.AccessKeyServiceWithCache",
"rebuildCache");
try {
deleteAccessKeyCache();
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Rebuild cache failed", ex);
} finally {
transaction.complete();
}
}
private void loadNewAndUpdatedAccessKeys() {
boolean hasMore = true;
while (hasMore && !Thread.currentThread().isInterrupted()) {
//current batch is 500
List<AccessKey> accessKeys = accessKeyRepository
.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(lastTimeScanned);
if (CollectionUtils.isEmpty(accessKeys)) {
break;
}
int scanned = accessKeys.size();
mergeAccessKeys(accessKeys);
logger.info("Loaded {} new/updated Accesskey from startTime {}", scanned, lastTimeScanned);
hasMore = scanned == 500;
lastTimeScanned = accessKeys.get(scanned - 1).getDataChangeLastModifiedTime();
// In order to avoid missing some records at the last time, we need to scan records at this time individually
if (hasMore) {
List<AccessKey> lastModifiedTimeAccessKeys = accessKeyRepository.findByDataChangeLastModifiedTime(lastTimeScanned);
mergeAccessKeys(lastModifiedTimeAccessKeys);
logger.info("Loaded {} new/updated Accesskey at lastModifiedTime {}", scanned, lastTimeScanned);
}
}
}
private void mergeAccessKeys(List<AccessKey> accessKeys) {
for (AccessKey accessKey : accessKeys) {
AccessKey thatInCache = accessKeyIdCache.get(accessKey.getId());
accessKeyIdCache.put(accessKey.getId(), accessKey);
accessKeyCache.put(accessKey.getAppId(), accessKey);
if (thatInCache != null && accessKey.getDataChangeLastModifiedTime()
.after(thatInCache.getDataChangeLastModifiedTime())) {
accessKeyCache.remove(accessKey.getAppId(), thatInCache);
logger.info("Found Accesskey changes, old: {}, new: {}", thatInCache, accessKey);
}
}
}
private void deleteAccessKeyCache() {
List<Long> ids = Lists.newArrayList(accessKeyIdCache.keySet());
if (CollectionUtils.isEmpty(ids)) {
return;
}
List<List<Long>> partitionIds = Lists.partition(ids, 500);
for (List<Long> toRebuildIds : partitionIds) {
Iterable<AccessKey> accessKeys = accessKeyRepository.findAllById(toRebuildIds);
Set<Long> foundIds = Sets.newHashSet();
for (AccessKey accessKey : accessKeys) {
foundIds.add(accessKey.getId());
}
//handle deleted
SetView<Long> deletedIds = Sets.difference(Sets.newHashSet(toRebuildIds), foundIds);
handleDeletedAccessKeys(deletedIds);
}
}
private void handleDeletedAccessKeys(Set<Long> deletedIds) {
if (CollectionUtils.isEmpty(deletedIds)) {
return;
}
for (Long deletedId : deletedIds) {
AccessKey deleted = accessKeyIdCache.remove(deletedId);
if (deleted == null) {
continue;
}
accessKeyCache.remove(deleted.getAppId(), deleted);
logger.info("Found AccessKey deleted, {}", deleted);
}
}
private void populateDataBaseInterval() {
scanInterval = bizConfig.accessKeyCacheScanInterval();
scanIntervalTimeUnit = bizConfig.accessKeyCacheScanIntervalTimeUnit();
rebuildInterval = bizConfig.accessKeyCacheRebuildInterval();
rebuildIntervalTimeUnit = bizConfig.accessKeyCacheRebuildIntervalTimeUnit();
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/message/MessageSender.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.message;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface MessageSender {
void sendMessage(String message, String channel);
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.message;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface MessageSender {
void sendMessage(String message, String channel);
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpRequest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.util.http;
import java.util.Map;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class HttpRequest {
private String m_url;
private Map<String, String> headers;
private int m_connectTimeout;
private int m_readTimeout;
/**
* Create the request for the url.
* @param url the url
*/
public HttpRequest(String url) {
this.m_url = url;
m_connectTimeout = -1;
m_readTimeout = -1;
}
public String getUrl() {
return m_url;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public int getConnectTimeout() {
return m_connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.m_connectTimeout = connectTimeout;
}
public int getReadTimeout() {
return m_readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.m_readTimeout = readTimeout;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.util.http;
import java.util.Map;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class HttpRequest {
private String m_url;
private Map<String, String> headers;
private int m_connectTimeout;
private int m_readTimeout;
/**
* Create the request for the url.
* @param url the url
*/
public HttpRequest(String url) {
this.m_url = url;
m_connectTimeout = -1;
m_readTimeout = -1;
}
public String getUrl() {
return m_url;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public int getConnectTimeout() {
return m_connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.m_connectTimeout = connectTimeout;
}
public int getReadTimeout() {
return m_readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.m_readTimeout = readTimeout;
}
}
| -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./docs/charts/apollo-service-0.2.0.tgz | ) +aHR0cHM6Ly95b3V0dS5iZS96OVV6MWljandyTQo=Helm <ks8_ѫdkgR#WU;QřTmmM %aL St
I)RlgH F$aŜ9;2
_tvGn{!
e&/UdORHD?3}DQs߸]'@))ZJ`sFtV rL)K>8>E&JEtTMfCӎ|.H_RS[֞I>g
*mؙPOE~gJ(|&|~Nǝy[ik*B
9m)ypG? 09J9 3c5Qwy'y2]vI8CcP')o47z,|p ^W0R9`yj9 Z<88; @&چ/٠z#QvZ݈HyE?>g}3JP6PgLL8 k5
P|D!ԜiC&T`\f0 %WYj.Q$zy8r8U%؊J483<۾l`: tJ1#.x3"W0w\Tc0k*?+{MojbjPxYB 0ƕ1҃,K=qvVmh75LB:G⣌*J·k95BAyymAi#;#:NWFZ!|DCZ(y~
Q0T([1B,ŐL
d\Q
.ِ"S`W
:z=<vr;[F2B@Mh~Qf t.$NỈ< jZ*ds*8jvDP-xX)4 X1:t㵣EuBT(ŏ?35+.W(6FF#-Ke~ͬ*?niU
֨XfT~0*ێJW8BPvvp5ISwHnFή?BkDY,@GIh] l.s3LڜRk~<xﴵUcTnIFGX,`QW~iqZڶg7$-[ ?RCgB+$t&sE\X./y9(Pq{JN
R5. =y?,[ Mt^dx~K>+;^'IH
\*;PF/FxSf
eTB"A
wӉ gDvČ1=
mkqsڷ
VBp}yMH
=ۉbZ,@6F @"@aG\.X.[Z1e)qûpIK=-,i*˥'!(
fҸH|u0sNV"Qׇ?qnyzP $L6MP{-J,
v;Fd*(''C7vM-(2q-?q[Wz@Fj3$2U
Y,,K,+\1?_E(AjѶ43zynm/gٕni캮|<0B!]=4\{Xt^ÜN=@/!>n'kOAHJ|Z`&VkA;^<K7GEjRIw>R
̸
l&[m[HO*g,9+&uQ_AhD@"Ƀ^ɫ*<X#,(ǷXfcf&{]g*+bZO0,ebk8]3*y-V[K[,axKaJTcJzŽV6LPыrwe`ĵwvj|\ե k\r\UWIx
Znrr^FVZR7މAˡxf{N#{l1+ ?)zKvnV}md6mdƪe+u#
{3QTn>a5a7N)Jv^DPxq;9ўD38~*?FՆlbQotvte
6vV~7~{aŰk,T]xl`L9kʖՙm\{č-gUoHf?}.@+#zJTiTi&Ϣ*ZnHPAQ%5ڑb(^6ZU̪ԦD^!y+XĹe2V >ҫ4d$Y O~c4M-Ui>؈%)LurLi1>%܈jJy(+L) Y˜)f`cک}oױfy/QH(WluhnlMl6mY =8w4QUYnЪjaM&DV "*.φɛȏNڑ/A!oA\U+ʃISo\>\^yO\\>;x ՜YH6i[f`#7yw?+4El^.#H:+2ckTR~nPSuj6ٮ,+&l6T9R$q *?
/ِUܒVETZy`igIhGLot&HB5yMya߮`n$3";Îe^?U{ 1t3HlF$髏0/M^&{?G~x$eC'k P.))}..c@P6iT#i6Ũtnj
pQJ|0Uׇĩ6DY#U UeXFl
V5V2ՅJ:^UVyw2ZBȪd?4fm)ii*yV[a]p%j7
j4]=Z(xUt'ѫ"W WyOcGSO?})ʦti$e> =ik9\+=vAG q:GqΧ;v9ȐTOφ;TO-7ݛ7QoI&E!?esxO;VG]f6Y*ծ'H=sMG85KMk s2ԖZ5UUZ=o: f!nFZ:Y0٬~]ǐ7ȂەaeItjof;ܾT?Mp}1}/z?g(6] ijػ{7+ 㓒w??ESVl6%u3vk;H*aTQT9p0f-[9nqF_iA~')^\%)6W,9l(S?1:lmNY=!Yc;1"q5U[_
Fb4bWdբdݸ5eٱ6a`A)Sr-gC'!'su2vћP((MH܊ݰ4t?')6Q`yhs2w'Nq:?:(}x)Ksy ጆ7du^ gQ,C|hk) CM<*y &EG6x]x;̴$ABuܷן輄OP!wLU;DM^L'ysYf/ڕ絫7t_%|"˷q#G_9.
tluwܹy}k_e_ J t | ) +aHR0cHM6Ly95b3V0dS5iZS96OVV6MWljandyTQo=Helm <ks8_ѫdkgR#WU;QřTmmM %aL St
I)RlgH F$aŜ9;2
_tvGn{!
e&/UdORHD?3}DQs߸]'@))ZJ`sFtV rL)K>8>E&JEtTMfCӎ|.H_RS[֞I>g
*mؙPOE~gJ(|&|~Nǝy[ik*B
9m)ypG? 09J9 3c5Qwy'y2]vI8CcP')o47z,|p ^W0R9`yj9 Z<88; @&چ/٠z#QvZ݈HyE?>g}3JP6PgLL8 k5
P|D!ԜiC&T`\f0 %WYj.Q$zy8r8U%؊J483<۾l`: tJ1#.x3"W0w\Tc0k*?+{MojbjPxYB 0ƕ1҃,K=qvVmh75LB:G⣌*J·k95BAyymAi#;#:NWFZ!|DCZ(y~
Q0T([1B,ŐL
d\Q
.ِ"S`W
:z=<vr;[F2B@Mh~Qf t.$NỈ< jZ*ds*8jvDP-xX)4 X1:t㵣EuBT(ŏ?35+.W(6FF#-Ke~ͬ*?niU
֨XfT~0*ێJW8BPvvp5ISwHnFή?BkDY,@GIh] l.s3LڜRk~<xﴵUcTnIFGX,`QW~iqZڶg7$-[ ?RCgB+$t&sE\X./y9(Pq{JN
R5. =y?,[ Mt^dx~K>+;^'IH
\*;PF/FxSf
eTB"A
wӉ gDvČ1=
mkqsڷ
VBp}yMH
=ۉbZ,@6F @"@aG\.X.[Z1e)qûpIK=-,i*˥'!(
fҸH|u0sNV"Qׇ?qnyzP $L6MP{-J,
v;Fd*(''C7vM-(2q-?q[Wz@Fj3$2U
Y,,K,+\1?_E(AjѶ43zynm/gٕni캮|<0B!]=4\{Xt^ÜN=@/!>n'kOAHJ|Z`&VkA;^<K7GEjRIw>R
̸
l&[m[HO*g,9+&uQ_AhD@"Ƀ^ɫ*<X#,(ǷXfcf&{]g*+bZO0,ebk8]3*y-V[K[,axKaJTcJzŽV6LPыrwe`ĵwvj|\ե k\r\UWIx
Znrr^FVZR7މAˡxf{N#{l1+ ?)zKvnV}md6mdƪe+u#
{3QTn>a5a7N)Jv^DPxq;9ўD38~*?FՆlbQotvte
6vV~7~{aŰk,T]xl`L9kʖՙm\{č-gUoHf?}.@+#zJTiTi&Ϣ*ZnHPAQ%5ڑb(^6ZU̪ԦD^!y+XĹe2V >ҫ4d$Y O~c4M-Ui>؈%)LurLi1>%܈jJy(+L) Y˜)f`cک}oױfy/QH(WluhnlMl6mY =8w4QUYnЪjaM&DV "*.φɛȏNڑ/A!oA\U+ʃISo\>\^yO\\>;x ՜YH6i[f`#7yw?+4El^.#H:+2ckTR~nPSuj6ٮ,+&l6T9R$q *?
/ِUܒVETZy`igIhGLot&HB5yMya߮`n$3";Îe^?U{ 1t3HlF$髏0/M^&{?G~x$eC'k P.))}..c@P6iT#i6Ũtnj
pQJ|0Uׇĩ6DY#U UeXFl
V5V2ՅJ:^UVyw2ZBȪd?4fm)ii*yV[a]p%j7
j4]=Z(xUt'ѫ"W WyOcGSO?})ʦti$e> =ik9\+=vAG q:GqΧ;v9ȐTOφ;TO-7ݛ7QoI&E!?esxO;VG]f6Y*ծ'H=sMG85KMk s2ԖZ5UUZ=o: f!nFZ:Y0٬~]ǐ7ȂەaeItjof;ܾT?Mp}1}/z?g(6] ijػ{7+ 㓒w??ESVl6%u3vk;H*aTQT9p0f-[9nqF_iA~')^\%)6W,9l(S?1:lmNY=!Yc;1"q5U[_
Fb4bWdբdݸ5eٱ6a`A)Sr-gC'!'su2vћP((MH܊ݰ4t?')6Q`yhs2w'Nq:?:(}x)Ksy ጆ7du^ gQ,C|hk) CM<*y &EG6x]x;̴$ABuܷן輄OP!wLU;DM^L'ysYf/ڕ絫7t_%|"˷q#G_9.
tluwܹy}k_e_ J t | -1 |
apolloconfig/apollo | 3,871 | Summer2021 support more format | ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| lepdou | 2021-08-05T10:06:48Z | 2021-08-05T12:40:42Z | 109c98d2f6417ee39568c0eb0ad33b0bcdf92dff | 278114744e1942df45ca2754f6cdec362dee0481 | Summer2021 support more format. ## What's the purpose of this PR
1. remove useless code
2. add change log
3. fix failed ut
## Which issue(s) this PR fixes:
https://github.com/ctripcorp/apollo/discussions/3815
## Brief changelog
remove useless code and add change log
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/test/java/com/ctrip/framework/apollo/biz/service/NamespaceServiceIntegrationTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.service;
import com.ctrip.framework.apollo.biz.AbstractIntegrationTest;
import com.ctrip.framework.apollo.biz.entity.Cluster;
import com.ctrip.framework.apollo.biz.entity.Commit;
import com.ctrip.framework.apollo.biz.entity.InstanceConfig;
import com.ctrip.framework.apollo.biz.entity.Item;
import com.ctrip.framework.apollo.biz.entity.Namespace;
import com.ctrip.framework.apollo.biz.entity.Release;
import com.ctrip.framework.apollo.biz.entity.ReleaseHistory;
import com.ctrip.framework.apollo.biz.repository.InstanceConfigRepository;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.jdbc.Sql;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class NamespaceServiceIntegrationTest extends AbstractIntegrationTest {
@Autowired
private NamespaceService namespaceService;
@Autowired
private ItemService itemService;
@Autowired
private CommitService commitService;
@Autowired
private AppNamespaceService appNamespaceService;
@Autowired
private ClusterService clusterService;
@Autowired
private ReleaseService releaseService;
@Autowired
private ReleaseHistoryService releaseHistoryService;
@Autowired
private InstanceConfigRepository instanceConfigRepository;
private String testApp = "testApp";
private String testCluster = "default";
private String testChildCluster = "child-cluster";
private String testPrivateNamespace = "application";
private String testUser = "apollo";
private String commitTestApp = "commitTestApp";
@Test
@Sql(scripts = "/sql/namespace-test.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/clean.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testDeleteNamespace() {
Namespace namespace = new Namespace();
namespace.setAppId(testApp);
namespace.setClusterName(testCluster);
namespace.setNamespaceName(testPrivateNamespace);
namespace.setId(1);
namespaceService.deleteNamespace(namespace, testUser);
List<Item> items = itemService.findItemsWithoutOrdered(testApp, testCluster, testPrivateNamespace);
List<Commit> commits = commitService.find(testApp, testCluster, testPrivateNamespace, PageRequest.of(0, 10));
AppNamespace appNamespace = appNamespaceService.findOne(testApp, testPrivateNamespace);
List<Cluster> childClusters = clusterService.findChildClusters(testApp, testCluster);
InstanceConfig instanceConfig = instanceConfigRepository.findById(1L).orElse(null);
List<Release> parentNamespaceReleases = releaseService.findActiveReleases(testApp, testCluster,
testPrivateNamespace,
PageRequest.of(0, 10));
List<Release> childNamespaceReleases = releaseService.findActiveReleases(testApp, testChildCluster,
testPrivateNamespace,
PageRequest.of(0, 10));
Page<ReleaseHistory> releaseHistories =
releaseHistoryService
.findReleaseHistoriesByNamespace(testApp, testCluster, testPrivateNamespace, PageRequest.of(0, 10));
assertEquals(0, items.size());
assertEquals(0, commits.size());
assertNotNull(appNamespace);
assertEquals(0, childClusters.size());
assertEquals(0, parentNamespaceReleases.size());
assertEquals(0, childNamespaceReleases.size());
assertTrue(!releaseHistories.hasContent());
assertNull(instanceConfig);
}
@Test
@Sql(scripts = "/sql/namespace-test.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/clean.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testGetCommitsByModifiedTime() throws ParseException {
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date lastModifiedTime = simpleDateFormat.parse("2020-08-22 09:00:00");
List<Commit> commitsByDate = commitService.find(commitTestApp, testCluster, testPrivateNamespace, lastModifiedTime, null);
Date lastModifiedTimeGreater = simpleDateFormat.parse("2020-08-22 11:00:00");
List<Commit> commitsByDateGreater = commitService.find(commitTestApp, testCluster, testPrivateNamespace, lastModifiedTimeGreater, null);
Date lastModifiedTimePage = simpleDateFormat.parse("2020-08-22 09:30:00");
List<Commit> commitsByDatePage = commitService.find(commitTestApp, testCluster, testPrivateNamespace, lastModifiedTimePage, PageRequest.of(0, 1));
assertEquals(1, commitsByDate.size());
assertEquals(0, commitsByDateGreater.size());
assertEquals(1, commitsByDatePage.size());
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.service;
import com.ctrip.framework.apollo.biz.AbstractIntegrationTest;
import com.ctrip.framework.apollo.biz.entity.Cluster;
import com.ctrip.framework.apollo.biz.entity.Commit;
import com.ctrip.framework.apollo.biz.entity.InstanceConfig;
import com.ctrip.framework.apollo.biz.entity.Item;
import com.ctrip.framework.apollo.biz.entity.Namespace;
import com.ctrip.framework.apollo.biz.entity.Release;
import com.ctrip.framework.apollo.biz.entity.ReleaseHistory;
import com.ctrip.framework.apollo.biz.repository.InstanceConfigRepository;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.jdbc.Sql;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class NamespaceServiceIntegrationTest extends AbstractIntegrationTest {
@Autowired
private NamespaceService namespaceService;
@Autowired
private ItemService itemService;
@Autowired
private CommitService commitService;
@Autowired
private AppNamespaceService appNamespaceService;
@Autowired
private ClusterService clusterService;
@Autowired
private ReleaseService releaseService;
@Autowired
private ReleaseHistoryService releaseHistoryService;
@Autowired
private InstanceConfigRepository instanceConfigRepository;
private String testApp = "testApp";
private String testCluster = "default";
private String testChildCluster = "child-cluster";
private String testPrivateNamespace = "application";
private String testUser = "apollo";
private String commitTestApp = "commitTestApp";
@Test
@Sql(scripts = "/sql/namespace-test.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/clean.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testDeleteNamespace() {
Namespace namespace = new Namespace();
namespace.setAppId(testApp);
namespace.setClusterName(testCluster);
namespace.setNamespaceName(testPrivateNamespace);
namespace.setId(1);
namespaceService.deleteNamespace(namespace, testUser);
List<Item> items = itemService.findItemsWithoutOrdered(testApp, testCluster, testPrivateNamespace);
List<Commit> commits = commitService.find(testApp, testCluster, testPrivateNamespace, PageRequest.of(0, 10));
AppNamespace appNamespace = appNamespaceService.findOne(testApp, testPrivateNamespace);
List<Cluster> childClusters = clusterService.findChildClusters(testApp, testCluster);
InstanceConfig instanceConfig = instanceConfigRepository.findById(1L).orElse(null);
List<Release> parentNamespaceReleases = releaseService.findActiveReleases(testApp, testCluster,
testPrivateNamespace,
PageRequest.of(0, 10));
List<Release> childNamespaceReleases = releaseService.findActiveReleases(testApp, testChildCluster,
testPrivateNamespace,
PageRequest.of(0, 10));
Page<ReleaseHistory> releaseHistories =
releaseHistoryService
.findReleaseHistoriesByNamespace(testApp, testCluster, testPrivateNamespace, PageRequest.of(0, 10));
assertEquals(0, items.size());
assertEquals(0, commits.size());
assertNotNull(appNamespace);
assertEquals(0, childClusters.size());
assertEquals(0, parentNamespaceReleases.size());
assertEquals(0, childNamespaceReleases.size());
assertTrue(!releaseHistories.hasContent());
assertNull(instanceConfig);
}
@Test
@Sql(scripts = "/sql/namespace-test.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/clean.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testGetCommitsByModifiedTime() throws ParseException {
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date lastModifiedTime = simpleDateFormat.parse("2020-08-22 09:00:00");
List<Commit> commitsByDate = commitService.find(commitTestApp, testCluster, testPrivateNamespace, lastModifiedTime, null);
Date lastModifiedTimeGreater = simpleDateFormat.parse("2020-08-22 11:00:00");
List<Commit> commitsByDateGreater = commitService.find(commitTestApp, testCluster, testPrivateNamespace, lastModifiedTimeGreater, null);
Date lastModifiedTimePage = simpleDateFormat.parse("2020-08-22 09:30:00");
List<Commit> commitsByDatePage = commitService.find(commitTestApp, testCluster, testPrivateNamespace, lastModifiedTimePage, PageRequest.of(0, 1));
assertEquals(1, commitsByDate.size());
assertEquals(0, commitsByDateGreater.size());
assertEquals(1, commitsByDatePage.size());
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./CHANGES.md | Changes by Version
==================
Release Notes.
Apollo 1.9.0
------------------
* [extend DataChange_CreatedBy, DataChange_LastModifiedBy from 32 to 64.](https://github.com/ctripcorp/apollo/pull/3552)
* [add spring configuration metadata](https://github.com/ctripcorp/apollo/pull/3553)
* [fix #3551 and optimize ldap samples ](https://github.com/ctripcorp/apollo/pull/3561)
* [update wiki url and refine documentation](https://github.com/ctripcorp/apollo/pull/3563)
* [slim docker images](https://github.com/ctripcorp/apollo/pull/3572)
* [add network strategy guideline to docker quick start](https://github.com/ctripcorp/apollo/pull/3574)
* [Added support for consul service discovery](https://github.com/ctripcorp/apollo/pull/3575)
* [disable consul in apollo-assembly by default ](https://github.com/ctripcorp/apollo/pull/3585)
* [ServiceBootstrap unit test fix](https://github.com/ctripcorp/apollo/pull/3593)
* [replace http client implementation with interface ](https://github.com/ctripcorp/apollo/pull/3594)
* [Allow users to inject customized instance via ApolloInjectorCustomizer](https://github.com/ctripcorp/apollo/pull/3602)
* [Fixes #3606](https://github.com/ctripcorp/apollo/pull/3609)
* [Bump xstream from 1.4.15 to 1.4.16](https://github.com/ctripcorp/apollo/pull/3611)
* [docs: user practices. Alibaba Sentinel Dashboard Push Rules to apollo](https://github.com/ctripcorp/apollo/pull/3617)
* [update known users](https://github.com/ctripcorp/apollo/pull/3619)
* [add maven deploy action](https://github.com/ctripcorp/apollo/pull/3620)
* [fix the issue that access key doesn't work if appid passed is in different case](https://github.com/ctripcorp/apollo/pull/3627)
* [fix oidc logout](https://github.com/ctripcorp/apollo/pull/3628)
* [docs: third party sdk nodejs client](https://github.com/ctripcorp/apollo/pull/3632)
* [update known users](https://github.com/ctripcorp/apollo/pull/3633)
* [docs: use docsify pagination plugin](https://github.com/ctripcorp/apollo/pull/3634)
* [apollo client to support jdk16](https://github.com/ctripcorp/apollo/pull/3646)
* [add English version of readme](https://github.com/ctripcorp/apollo/pull/3656)
* [update known users](https://github.com/ctripcorp/apollo/pull/3657)
* [update apolloconfig.com domain](https://github.com/ctripcorp/apollo/pull/3658)
* [localize css to speed up the loading of google fonts](https://github.com/ctripcorp/apollo/pull/3660)
* [test(apollo-client): use assertEquals instead of assertThat](https://github.com/ctripcorp/apollo/pull/3667)
* [test(apollo-client): make timeout more longer when long poll](https://github.com/ctripcorp/apollo/pull/3668)
* [fix unit test](https://github.com/ctripcorp/apollo/pull/3669)
* [解决日志系统未初始化完成时,apollo 的加载日志没法输出问题](https://github.com/ctripcorp/apollo/pull/3677)
* [fix[apollo-configService]: Solve configService startup exception](https://github.com/ctripcorp/apollo/pull/3679)
* [Community Governance Proposal](https://github.com/ctripcorp/apollo/pull/3670)
* [增加阿波罗client的php库](https://github.com/ctripcorp/apollo/pull/3682)
* [Bump xstream from 1.4.16 to 1.4.17](https://github.com/ctripcorp/apollo/pull/3692)
* [Improve the nacos registry configuration document](https://github.com/ctripcorp/apollo/pull/3695)
* [Remove redundant invoke of trySyncFromUpstream](https://github.com/ctripcorp/apollo/pull/3699)
* [add apollo team introduction and community releated contents](https://github.com/ctripcorp/apollo/pull/3713)
* [fix oidc sql](https://github.com/ctripcorp/apollo/pull/3720)
* [feat(apollo-client): add method interestedChangedKeys to ConfigChangeEvent](https://github.com/ctripcorp/apollo/pull/3666)
* [add More... link for known users](https://github.com/ctripcorp/apollo/pull/3757)
* [update OIDC documentation](https://github.com/ctripcorp/apollo/pull/3766)
* [Improve the item-value length limit configuration document](https://github.com/ctripcorp/apollo/pull/3789)
* [Use queue#take instead of poll](https://github.com/ctripcorp/apollo/pull/3765)
* [feature: add Spring Boot 2.4 config data loader support](https://github.com/ctripcorp/apollo/pull/3754)
* [feat(open-api): get authorized apps](https://github.com/ctripcorp/apollo/pull/3647)
* [feature: shared session for multi apollo portal](https://github.com/ctripcorp/apollo/pull/3786)
* [feature: add email for select user on apollo portal](https://github.com/ctripcorp/apollo/pull/3797)
* [feature: modify item comment valid size](https://github.com/ctripcorp/apollo/pull/3803)
* [set default session store-type](https://github.com/ctripcorp/apollo/pull/3812)
* [speed up the stale issue mark and close phase](https://github.com/ctripcorp/apollo/pull/3808)
* [feature: add the delegating password encoder for apollo-portal simple auth](https://github.com/ctripcorp/apollo/pull/3804)
* [support release apollo-client-config-data](https://github.com/ctripcorp/apollo/pull/3822)
* [Fix possiable NPE](https://github.com/ctripcorp/apollo/pull/3832)
* [Reduce bootstrap time in the situation with large properties](https://github.com/ctripcorp/apollo/pull/3816)
* [docs: English catalog in sidebar](https://github.com/ctripcorp/apollo/pull/3831)
* [fix the issue that release messages might be missed in certain scenarios](https://github.com/ctripcorp/apollo/pull/3819)
* [use official docker images for manual kubernetes deployment](https://github.com/ctripcorp/apollo/pull/3840)
* [fix size of create project button](https://github.com/ctripcorp/apollo/pull/3849)
* [translation of "portal-how-to-enable-webhook-notification.md"](https://github.com/ctripcorp/apollo/pull/3847)
* [feature: add history detail for not key-value type of namespace](https://github.com/ctripcorp/apollo/pull/3856)
* [fix show-text-modal number display](https://github.com/ctripcorp/apollo/pull/3851)
* [Lazy load ConfigUtil](https://github.com/ctripcorp/apollo/pull/3864)
* [make jdbc session enable default](https://github.com/ctripcorp/apollo/pull/3869)
* [support json/yaml/xml format for public namespace](https://github.com/ctripcorp/apollo/pull/3836)
* [Translate application into 应用 not 项目](https://github.com/ctripcorp/apollo/pull/3877)
* [add spring configuration metadata for property names cache](https://github.com/ctripcorp/apollo/pull/3879)
* [Fix Multiple PropertySourcesPlaceholderConfigurer beans registered issue](https://github.com/ctripcorp/apollo/pull/3865)
* [use jdk 8 to publish apollo-client-config-data](https://github.com/ctripcorp/apollo/pull/3880)
------------------
All issues and pull requests are [here](https://github.com/ctripcorp/apollo/milestone/6?closed=1)
| Changes by Version
==================
Release Notes.
Apollo 1.9.0
------------------
* [extend DataChange_CreatedBy, DataChange_LastModifiedBy from 32 to 64.](https://github.com/ctripcorp/apollo/pull/3552)
* [add spring configuration metadata](https://github.com/ctripcorp/apollo/pull/3553)
* [fix #3551 and optimize ldap samples ](https://github.com/ctripcorp/apollo/pull/3561)
* [update wiki url and refine documentation](https://github.com/ctripcorp/apollo/pull/3563)
* [slim docker images](https://github.com/ctripcorp/apollo/pull/3572)
* [add network strategy guideline to docker quick start](https://github.com/ctripcorp/apollo/pull/3574)
* [Added support for consul service discovery](https://github.com/ctripcorp/apollo/pull/3575)
* [disable consul in apollo-assembly by default ](https://github.com/ctripcorp/apollo/pull/3585)
* [ServiceBootstrap unit test fix](https://github.com/ctripcorp/apollo/pull/3593)
* [replace http client implementation with interface ](https://github.com/ctripcorp/apollo/pull/3594)
* [Allow users to inject customized instance via ApolloInjectorCustomizer](https://github.com/ctripcorp/apollo/pull/3602)
* [Fixes #3606](https://github.com/ctripcorp/apollo/pull/3609)
* [Bump xstream from 1.4.15 to 1.4.16](https://github.com/ctripcorp/apollo/pull/3611)
* [docs: user practices. Alibaba Sentinel Dashboard Push Rules to apollo](https://github.com/ctripcorp/apollo/pull/3617)
* [update known users](https://github.com/ctripcorp/apollo/pull/3619)
* [add maven deploy action](https://github.com/ctripcorp/apollo/pull/3620)
* [fix the issue that access key doesn't work if appid passed is in different case](https://github.com/ctripcorp/apollo/pull/3627)
* [fix oidc logout](https://github.com/ctripcorp/apollo/pull/3628)
* [docs: third party sdk nodejs client](https://github.com/ctripcorp/apollo/pull/3632)
* [update known users](https://github.com/ctripcorp/apollo/pull/3633)
* [docs: use docsify pagination plugin](https://github.com/ctripcorp/apollo/pull/3634)
* [apollo client to support jdk16](https://github.com/ctripcorp/apollo/pull/3646)
* [add English version of readme](https://github.com/ctripcorp/apollo/pull/3656)
* [update known users](https://github.com/ctripcorp/apollo/pull/3657)
* [update apolloconfig.com domain](https://github.com/ctripcorp/apollo/pull/3658)
* [localize css to speed up the loading of google fonts](https://github.com/ctripcorp/apollo/pull/3660)
* [test(apollo-client): use assertEquals instead of assertThat](https://github.com/ctripcorp/apollo/pull/3667)
* [test(apollo-client): make timeout more longer when long poll](https://github.com/ctripcorp/apollo/pull/3668)
* [fix unit test](https://github.com/ctripcorp/apollo/pull/3669)
* [解决日志系统未初始化完成时,apollo 的加载日志没法输出问题](https://github.com/ctripcorp/apollo/pull/3677)
* [fix[apollo-configService]: Solve configService startup exception](https://github.com/ctripcorp/apollo/pull/3679)
* [Community Governance Proposal](https://github.com/ctripcorp/apollo/pull/3670)
* [增加阿波罗client的php库](https://github.com/ctripcorp/apollo/pull/3682)
* [Bump xstream from 1.4.16 to 1.4.17](https://github.com/ctripcorp/apollo/pull/3692)
* [Improve the nacos registry configuration document](https://github.com/ctripcorp/apollo/pull/3695)
* [Remove redundant invoke of trySyncFromUpstream](https://github.com/ctripcorp/apollo/pull/3699)
* [add apollo team introduction and community releated contents](https://github.com/ctripcorp/apollo/pull/3713)
* [fix oidc sql](https://github.com/ctripcorp/apollo/pull/3720)
* [feat(apollo-client): add method interestedChangedKeys to ConfigChangeEvent](https://github.com/ctripcorp/apollo/pull/3666)
* [add More... link for known users](https://github.com/ctripcorp/apollo/pull/3757)
* [update OIDC documentation](https://github.com/ctripcorp/apollo/pull/3766)
* [Improve the item-value length limit configuration document](https://github.com/ctripcorp/apollo/pull/3789)
* [Use queue#take instead of poll](https://github.com/ctripcorp/apollo/pull/3765)
* [feature: add Spring Boot 2.4 config data loader support](https://github.com/ctripcorp/apollo/pull/3754)
* [feat(open-api): get authorized apps](https://github.com/ctripcorp/apollo/pull/3647)
* [feature: shared session for multi apollo portal](https://github.com/ctripcorp/apollo/pull/3786)
* [feature: add email for select user on apollo portal](https://github.com/ctripcorp/apollo/pull/3797)
* [feature: modify item comment valid size](https://github.com/ctripcorp/apollo/pull/3803)
* [set default session store-type](https://github.com/ctripcorp/apollo/pull/3812)
* [speed up the stale issue mark and close phase](https://github.com/ctripcorp/apollo/pull/3808)
* [feature: add the delegating password encoder for apollo-portal simple auth](https://github.com/ctripcorp/apollo/pull/3804)
* [support release apollo-client-config-data](https://github.com/ctripcorp/apollo/pull/3822)
* [Fix possiable NPE](https://github.com/ctripcorp/apollo/pull/3832)
* [Reduce bootstrap time in the situation with large properties](https://github.com/ctripcorp/apollo/pull/3816)
* [docs: English catalog in sidebar](https://github.com/ctripcorp/apollo/pull/3831)
* [fix the issue that release messages might be missed in certain scenarios](https://github.com/ctripcorp/apollo/pull/3819)
* [use official docker images for manual kubernetes deployment](https://github.com/ctripcorp/apollo/pull/3840)
* [fix size of create project button](https://github.com/ctripcorp/apollo/pull/3849)
* [translation of "portal-how-to-enable-webhook-notification.md"](https://github.com/ctripcorp/apollo/pull/3847)
* [feature: add history detail for not key-value type of namespace](https://github.com/ctripcorp/apollo/pull/3856)
* [fix show-text-modal number display](https://github.com/ctripcorp/apollo/pull/3851)
* [Lazy load ConfigUtil](https://github.com/ctripcorp/apollo/pull/3864)
* [make jdbc session enable default](https://github.com/ctripcorp/apollo/pull/3869)
* [support json/yaml/xml format for public namespace](https://github.com/ctripcorp/apollo/pull/3836)
* [Translate application into 应用 not 项目](https://github.com/ctripcorp/apollo/pull/3877)
* [add spring configuration metadata for property names cache](https://github.com/ctripcorp/apollo/pull/3879)
* [Fix Multiple PropertySourcesPlaceholderConfigurer beans registered issue](https://github.com/ctripcorp/apollo/pull/3865)
* [use jdk 8 to publish apollo-client-config-data](https://github.com/ctripcorp/apollo/pull/3880)
* [fix apollo config data loader with profiles](https://github.com/ctripcorp/apollo/pull/3870)
------------------
All issues and pull requests are [here](https://github.com/ctripcorp/apollo/milestone/6?closed=1)
| 1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/ApolloClientLongPollingExtensionInitializer.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.extension.webclient;
import com.ctrip.framework.apollo.config.data.extension.initialize.ApolloClientExtensionInitializer;
import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties;
import com.ctrip.framework.apollo.config.data.extension.webclient.customizer.spi.ApolloClientWebClientCustomizerFactory;
import com.ctrip.framework.apollo.config.data.extension.webclient.injector.ApolloClientCustomHttpClientInjectorCustomizer;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
import java.util.List;
import org.apache.commons.logging.Log;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.web.reactive.function.client.WebClientCustomizer;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.client.WebClient;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class ApolloClientLongPollingExtensionInitializer implements
ApolloClientExtensionInitializer {
private final Log log;
private final ConfigurableBootstrapContext bootstrapContext;
public ApolloClientLongPollingExtensionInitializer(Log log,
ConfigurableBootstrapContext bootstrapContext) {
this.log = log;
this.bootstrapContext = bootstrapContext;
}
@Override
public void initialize(ApolloClientProperties apolloClientProperties, Binder binder,
BindHandler bindHandler) {
WebClient.Builder webClientBuilder = WebClient.builder();
List<ApolloClientWebClientCustomizerFactory> factories = ServiceBootstrap
.loadAllOrdered(ApolloClientWebClientCustomizerFactory.class);
if (!CollectionUtils.isEmpty(factories)) {
for (ApolloClientWebClientCustomizerFactory factory : factories) {
WebClientCustomizer webClientCustomizer = factory
.createWebClientCustomizer(apolloClientProperties, binder, bindHandler, this.log,
this.bootstrapContext);
if (webClientCustomizer != null) {
webClientCustomizer.customize(webClientBuilder);
}
}
}
ApolloClientCustomHttpClientInjectorCustomizer.setCustomWebClient(webClientBuilder.build());
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.extension.webclient;
import com.ctrip.framework.apollo.config.data.extension.initialize.ApolloClientExtensionInitializer;
import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties;
import com.ctrip.framework.apollo.config.data.extension.webclient.customizer.spi.ApolloClientWebClientCustomizerFactory;
import com.ctrip.framework.apollo.config.data.injector.ApolloConfigDataInjectorCustomizer;
import com.ctrip.framework.apollo.util.http.HttpClient;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
import java.util.List;
import org.apache.commons.logging.Log;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.web.reactive.function.client.WebClientCustomizer;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.client.WebClient;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class ApolloClientLongPollingExtensionInitializer implements
ApolloClientExtensionInitializer {
private final Log log;
private final ConfigurableBootstrapContext bootstrapContext;
public ApolloClientLongPollingExtensionInitializer(Log log,
ConfigurableBootstrapContext bootstrapContext) {
this.log = log;
this.bootstrapContext = bootstrapContext;
}
@Override
public void initialize(ApolloClientProperties apolloClientProperties, Binder binder,
BindHandler bindHandler) {
WebClient.Builder webClientBuilder = WebClient.builder();
List<ApolloClientWebClientCustomizerFactory> factories = ServiceBootstrap
.loadAllOrdered(ApolloClientWebClientCustomizerFactory.class);
if (!CollectionUtils.isEmpty(factories)) {
for (ApolloClientWebClientCustomizerFactory factory : factories) {
WebClientCustomizer webClientCustomizer = factory
.createWebClientCustomizer(apolloClientProperties, binder, bindHandler, this.log,
this.bootstrapContext);
if (webClientCustomizer != null) {
webClientCustomizer.customize(webClientBuilder);
}
}
}
HttpClient httpClient = new ApolloWebClientHttpClient(webClientBuilder.build());
ApolloConfigDataInjectorCustomizer.registerIfAbsent(HttpClient.class, () -> httpClient);
}
}
| 1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLoader.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.importer;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.config.data.util.Slf4jLogMessageFormatter;
import com.ctrip.framework.apollo.spring.config.ConfigPropertySource;
import com.ctrip.framework.apollo.spring.config.ConfigPropertySourceFactory;
import com.ctrip.framework.apollo.spring.util.SpringInjector;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.springframework.boot.BootstrapRegistry.InstanceSupplier;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.config.ConfigData;
import org.springframework.boot.context.config.ConfigDataLoader;
import org.springframework.boot.context.config.ConfigDataLoaderContext;
import org.springframework.boot.context.config.ConfigDataResourceNotFoundException;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.Ordered;
import org.springframework.core.env.PropertySource;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class ApolloConfigDataLoader implements ConfigDataLoader<ApolloConfigDataResource>, Ordered {
private final Log log;
public ApolloConfigDataLoader(Log log) {
this.log = log;
}
@Override
public ConfigData load(ConfigDataLoaderContext context, ApolloConfigDataResource resource)
throws IOException, ConfigDataResourceNotFoundException {
ConfigurableBootstrapContext bootstrapContext = context.getBootstrapContext();
Binder binder = bootstrapContext.get(Binder.class);
BindHandler bindHandler = this.getBindHandler(context);
bootstrapContext.registerIfAbsent(ApolloConfigDataLoaderInitializer.class, InstanceSupplier
.from(() -> new ApolloConfigDataLoaderInitializer(this.log, binder, bindHandler,
bootstrapContext)));
ApolloConfigDataLoaderInitializer apolloConfigDataLoaderInitializer = bootstrapContext
.get(ApolloConfigDataLoaderInitializer.class);
// init apollo client
List<PropertySource<?>> initialPropertySourceList = apolloConfigDataLoaderInitializer
.initApolloClient();
// load config
bootstrapContext.registerIfAbsent(ConfigPropertySourceFactory.class,
InstanceSupplier.from(() -> SpringInjector.getInstance(ConfigPropertySourceFactory.class)));
ConfigPropertySourceFactory configPropertySourceFactory = bootstrapContext
.get(ConfigPropertySourceFactory.class);
String namespace = resource.getNamespace();
Config config = ConfigService.getConfig(namespace);
ConfigPropertySource configPropertySource = configPropertySourceFactory
.getConfigPropertySource(namespace, config);
List<PropertySource<?>> propertySourceList = new ArrayList<>();
propertySourceList.add(configPropertySource);
propertySourceList.addAll(initialPropertySourceList);
log.debug(Slf4jLogMessageFormatter
.format("apollo client loaded namespace [{}]", resource.getNamespace()));
return new ConfigData(propertySourceList);
}
private BindHandler getBindHandler(ConfigDataLoaderContext context) {
return context.getBootstrapContext().getOrElse(BindHandler.class, null);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 100;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.importer;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.config.data.util.Slf4jLogMessageFormatter;
import com.ctrip.framework.apollo.spring.config.ConfigPropertySource;
import com.ctrip.framework.apollo.spring.config.ConfigPropertySourceFactory;
import com.ctrip.framework.apollo.spring.util.SpringInjector;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.springframework.boot.BootstrapRegistry.InstanceSupplier;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.config.ConfigData;
import org.springframework.boot.context.config.ConfigDataLoader;
import org.springframework.boot.context.config.ConfigDataLoaderContext;
import org.springframework.boot.context.config.ConfigDataResourceNotFoundException;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.Ordered;
import org.springframework.core.env.PropertySource;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class ApolloConfigDataLoader implements ConfigDataLoader<ApolloConfigDataResource>, Ordered {
private final Log log;
public ApolloConfigDataLoader(Log log) {
this.log = log;
}
@Override
public ConfigData load(ConfigDataLoaderContext context, ApolloConfigDataResource resource)
throws IOException, ConfigDataResourceNotFoundException {
ConfigurableBootstrapContext bootstrapContext = context.getBootstrapContext();
Binder binder = bootstrapContext.get(Binder.class);
BindHandler bindHandler = this.getBindHandler(context);
bootstrapContext.registerIfAbsent(ApolloConfigDataLoaderInitializer.class, InstanceSupplier
.from(() -> new ApolloConfigDataLoaderInitializer(this.log, binder, bindHandler,
bootstrapContext)));
ApolloConfigDataLoaderInitializer apolloConfigDataLoaderInitializer = bootstrapContext
.get(ApolloConfigDataLoaderInitializer.class);
// init apollo client
List<PropertySource<?>> initialPropertySourceList = apolloConfigDataLoaderInitializer
.initApolloClient();
// load config
bootstrapContext.registerIfAbsent(ConfigPropertySourceFactory.class,
InstanceSupplier.from(() -> SpringInjector.getInstance(ConfigPropertySourceFactory.class)));
ConfigPropertySourceFactory configPropertySourceFactory = bootstrapContext
.get(ConfigPropertySourceFactory.class);
String namespace = resource.getNamespace();
Config config = ConfigService.getConfig(namespace);
ConfigPropertySource configPropertySource = configPropertySourceFactory
.getConfigPropertySource(namespace, config);
List<PropertySource<?>> propertySourceList = new ArrayList<>();
propertySourceList.add(configPropertySource);
propertySourceList.addAll(initialPropertySourceList);
log.debug(Slf4jLogMessageFormatter.format("apollo client loaded namespace [{}]", namespace));
return new ConfigData(propertySourceList);
}
private BindHandler getBindHandler(ConfigDataLoaderContext context) {
return context.getBootstrapContext().getOrElse(BindHandler.class, null);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 100;
}
}
| 1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLoaderInitializer.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.importer;
import com.ctrip.framework.apollo.config.data.extension.initialize.ApolloClientExtensionInitializeFactory;
import com.ctrip.framework.apollo.config.data.system.ApolloClientSystemPropertyInitializer;
import com.ctrip.framework.apollo.config.data.util.Slf4jLogMessageFormatter;
import com.ctrip.framework.apollo.core.utils.DeferredLogger;
import com.ctrip.framework.apollo.spring.config.PropertySourcesConstants;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
/**
* @author vdisk <vdisk@foxmail.com>
*/
class ApolloConfigDataLoaderInitializer {
private static volatile boolean INITIALIZED = false;
private final Log log;
private final Binder binder;
private final BindHandler bindHandler;
private final ConfigurableBootstrapContext bootstrapContext;
public ApolloConfigDataLoaderInitializer(Log log,
Binder binder, BindHandler bindHandler,
ConfigurableBootstrapContext bootstrapContext) {
this.log = log;
this.binder = binder;
this.bindHandler = bindHandler;
this.bootstrapContext = bootstrapContext;
}
/**
* init apollo client (only once)
*
* @return initial sources as placeholders or empty list if already initialized
*/
public List<PropertySource<?>> initApolloClient() {
if (INITIALIZED) {
return Collections.emptyList();
}
synchronized (ApolloConfigDataLoaderInitializer.class) {
if (INITIALIZED) {
return Collections.emptyList();
}
this.initApolloClientInternal();
INITIALIZED = true;
if (this.forceDisableApolloBootstrap()) {
// force disable apollo bootstrap to avoid conflict
Map<String, Object> map = new HashMap<>();
map.put(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, "false");
map.put(PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, "false");
// provide initial sources as placeholders to avoid duplicate loading
return Arrays.asList(
new ApolloConfigEmptyPropertySource(
PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME),
new MapPropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME,
Collections.unmodifiableMap(map)));
}
// provide initial sources as placeholders to avoid duplicate loading
return Arrays.asList(
new ApolloConfigEmptyPropertySource(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME),
new ApolloConfigEmptyPropertySource(
PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME));
}
}
private void initApolloClientInternal() {
new ApolloClientSystemPropertyInitializer(this.log)
.initializeSystemProperty(this.binder, this.bindHandler);
new ApolloClientExtensionInitializeFactory(this.log,
this.bootstrapContext).initializeExtension(this.binder, this.bindHandler);
DeferredLogger.enable();
}
private boolean forceDisableApolloBootstrap() {
boolean bootstrapEnabled = this.binder
.bind(this.camelCasedToKebabCase(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED),
Bindable.of(Boolean.class),
this.bindHandler)
.orElse(false);
if (bootstrapEnabled) {
this.log.warn(Slf4jLogMessageFormatter.format(
"apollo bootstrap is force disabled. please don't configure the property [{}=true] and [spring.config.import=apollo://...] at the same time",
PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED));
return true;
}
boolean bootstrapEagerLoadEnabled = this.binder
.bind(this.camelCasedToKebabCase(
PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED),
Bindable.of(Boolean.class),
this.bindHandler)
.orElse(false);
if (bootstrapEagerLoadEnabled) {
this.log.warn(Slf4jLogMessageFormatter.format(
"apollo bootstrap eager load is force disabled. please don't configure the property [{}=true] and [spring.config.import=apollo://...] at the same time",
PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED));
return true;
}
return false;
}
/**
* {@link ConfigurationPropertyName#isValid(java.lang.CharSequence)}
*
* @param source origin propertyName
* @return valid propertyName
*/
private String camelCasedToKebabCase(String source) {
if (ConfigurationPropertyName.isValid(source)) {
return source;
}
StringBuilder stringBuilder = new StringBuilder(source.length() * 2);
for (char ch : source.toCharArray()) {
if (Character.isUpperCase(ch)) {
stringBuilder.append("-").append(Character.toLowerCase(ch));
continue;
}
stringBuilder.append(ch);
}
return stringBuilder.toString();
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.importer;
import com.ctrip.framework.apollo.config.data.extension.initialize.ApolloClientExtensionInitializeFactory;
import com.ctrip.framework.apollo.config.data.injector.ApolloConfigDataInjectorCustomizer;
import com.ctrip.framework.apollo.config.data.internals.PureApolloConfigFactory;
import com.ctrip.framework.apollo.config.data.system.ApolloClientSystemPropertyInitializer;
import com.ctrip.framework.apollo.config.data.util.Slf4jLogMessageFormatter;
import com.ctrip.framework.apollo.core.utils.DeferredLogger;
import com.ctrip.framework.apollo.spi.ConfigFactory;
import com.ctrip.framework.apollo.spring.config.PropertySourcesConstants;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
/**
* @author vdisk <vdisk@foxmail.com>
*/
class ApolloConfigDataLoaderInitializer {
private static volatile boolean INITIALIZED = false;
private final Log log;
private final Binder binder;
private final BindHandler bindHandler;
private final ConfigurableBootstrapContext bootstrapContext;
public ApolloConfigDataLoaderInitializer(Log log,
Binder binder, BindHandler bindHandler,
ConfigurableBootstrapContext bootstrapContext) {
this.log = log;
this.binder = binder;
this.bindHandler = bindHandler;
this.bootstrapContext = bootstrapContext;
}
/**
* init apollo client (only once)
*
* @return initial sources as placeholders or empty list if already initialized
*/
public List<PropertySource<?>> initApolloClient() {
if (INITIALIZED) {
return Collections.emptyList();
}
synchronized (ApolloConfigDataLoaderInitializer.class) {
if (INITIALIZED) {
return Collections.emptyList();
}
this.initApolloClientInternal();
INITIALIZED = true;
if (this.forceDisableApolloBootstrap()) {
// force disable apollo bootstrap to avoid conflict
Map<String, Object> map = new HashMap<>();
map.put(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, "false");
map.put(PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, "false");
// provide initial sources as placeholders to avoid duplicate loading
return Arrays.asList(
new ApolloConfigEmptyPropertySource(
PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME),
new MapPropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME,
Collections.unmodifiableMap(map)));
}
// provide initial sources as placeholders to avoid duplicate loading
return Arrays.asList(
new ApolloConfigEmptyPropertySource(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME),
new ApolloConfigEmptyPropertySource(
PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME));
}
}
private void initApolloClientInternal() {
new ApolloClientSystemPropertyInitializer(this.log)
.initializeSystemProperty(this.binder, this.bindHandler);
new ApolloClientExtensionInitializeFactory(this.log,
this.bootstrapContext).initializeExtension(this.binder, this.bindHandler);
DeferredLogger.enable();
ApolloConfigDataInjectorCustomizer.register(ConfigFactory.class,
PureApolloConfigFactory::new);
}
private boolean forceDisableApolloBootstrap() {
boolean bootstrapEnabled = this.binder
.bind(this.camelCasedToKebabCase(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED),
Bindable.of(Boolean.class),
this.bindHandler)
.orElse(false);
if (bootstrapEnabled) {
this.log.warn(Slf4jLogMessageFormatter.format(
"apollo bootstrap is force disabled. please don't configure the property [{}=true] and [spring.config.import=apollo://...] at the same time",
PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED));
return true;
}
boolean bootstrapEagerLoadEnabled = this.binder
.bind(this.camelCasedToKebabCase(
PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED),
Bindable.of(Boolean.class),
this.bindHandler)
.orElse(false);
if (bootstrapEagerLoadEnabled) {
this.log.warn(Slf4jLogMessageFormatter.format(
"apollo bootstrap eager load is force disabled. please don't configure the property [{}=true] and [spring.config.import=apollo://...] at the same time",
PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED));
return true;
}
return false;
}
/**
* {@link ConfigurationPropertyName#isValid(java.lang.CharSequence)}
*
* @param source origin propertyName
* @return valid propertyName
*/
private String camelCasedToKebabCase(String source) {
if (ConfigurationPropertyName.isValid(source)) {
return source;
}
StringBuilder stringBuilder = new StringBuilder(source.length() * 2);
for (char ch : source.toCharArray()) {
if (Character.isUpperCase(ch)) {
stringBuilder.append("-").append(Character.toLowerCase(ch));
continue;
}
stringBuilder.append(ch);
}
return stringBuilder.toString();
}
}
| 1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client-config-data/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer | com.ctrip.framework.apollo.config.data.extension.webclient.injector.ApolloClientCustomHttpClientInjectorCustomizer | com.ctrip.framework.apollo.config.data.injector.ApolloConfigDataInjectorCustomizer | 1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.RateLimiter;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class DefaultConfig extends AbstractConfig implements RepositoryChangeListener {
private static final Logger logger = DeferredLoggerFactory.getLogger(DefaultConfig.class);
private final String m_namespace;
private final Properties m_resourceProperties;
private final AtomicReference<Properties> m_configProperties;
private final ConfigRepository m_configRepository;
private final RateLimiter m_warnLogRateLimiter;
private volatile ConfigSourceType m_sourceType = ConfigSourceType.NONE;
/**
* Constructor.
*
* @param namespace the namespace of this config instance
* @param configRepository the config repository for this config instance
*/
public DefaultConfig(String namespace, ConfigRepository configRepository) {
m_namespace = namespace;
m_resourceProperties = loadFromResource(m_namespace);
m_configRepository = configRepository;
m_configProperties = new AtomicReference<>();
m_warnLogRateLimiter = RateLimiter.create(0.017); // 1 warning log output per minute
initialize();
}
private void initialize() {
try {
updateConfig(m_configRepository.getConfig(), m_configRepository.getSourceType());
} catch (Throwable ex) {
Tracer.logError(ex);
logger.warn("Init Apollo Local Config failed - namespace: {}, reason: {}.",
m_namespace, ExceptionUtil.getDetailMessage(ex));
} finally {
//register the change listener no matter config repository is working or not
//so that whenever config repository is recovered, config could get changed
m_configRepository.addChangeListener(this);
}
}
@Override
public String getProperty(String key, String defaultValue) {
// step 1: check system properties, i.e. -Dkey=value
String value = System.getProperty(key);
// step 2: check local cached properties file
if (value == null && m_configProperties.get() != null) {
value = m_configProperties.get().getProperty(key);
}
/**
* step 3: check env variable, i.e. PATH=...
* normally system environment variables are in UPPERCASE, however there might be exceptions.
* so the caller should provide the key in the right case
*/
if (value == null) {
value = System.getenv(key);
}
// step 4: check properties file from classpath
if (value == null && m_resourceProperties != null) {
value = m_resourceProperties.getProperty(key);
}
if (value == null && m_configProperties.get() == null && m_warnLogRateLimiter.tryAcquire()) {
logger.warn(
"Could not load config for namespace {} from Apollo, please check whether the configs are released in Apollo! Return default value now!",
m_namespace);
}
return value == null ? defaultValue : value;
}
@Override
public Set<String> getPropertyNames() {
Properties properties = m_configProperties.get();
if (properties == null) {
return Collections.emptySet();
}
return stringPropertyNames(properties);
}
@Override
public ConfigSourceType getSourceType() {
return m_sourceType;
}
private Set<String> stringPropertyNames(Properties properties) {
//jdk9以下版本Properties#enumerateStringProperties方法存在性能问题,keys() + get(k) 重复迭代, jdk9之后改为entrySet遍历.
Map<String, String> h = new LinkedHashMap<>();
for (Map.Entry<Object, Object> e : properties.entrySet()) {
Object k = e.getKey();
Object v = e.getValue();
if (k instanceof String && v instanceof String) {
h.put((String) k, (String) v);
}
}
return h.keySet();
}
@Override
public synchronized void onRepositoryChange(String namespace, Properties newProperties) {
if (newProperties.equals(m_configProperties.get())) {
return;
}
ConfigSourceType sourceType = m_configRepository.getSourceType();
Properties newConfigProperties = propertiesFactory.getPropertiesInstance();
newConfigProperties.putAll(newProperties);
Map<String, ConfigChange> actualChanges = updateAndCalcConfigChanges(newConfigProperties,
sourceType);
//check double checked result
if (actualChanges.isEmpty()) {
return;
}
this.fireConfigChange(m_namespace, actualChanges);
Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace);
}
private void updateConfig(Properties newConfigProperties, ConfigSourceType sourceType) {
m_configProperties.set(newConfigProperties);
m_sourceType = sourceType;
}
private Map<String, ConfigChange> updateAndCalcConfigChanges(Properties newConfigProperties,
ConfigSourceType sourceType) {
List<ConfigChange> configChanges =
calcPropertyChanges(m_namespace, m_configProperties.get(), newConfigProperties);
ImmutableMap.Builder<String, ConfigChange> actualChanges =
new ImmutableMap.Builder<>();
/** === Double check since DefaultConfig has multiple config sources ==== **/
//1. use getProperty to update configChanges's old value
for (ConfigChange change : configChanges) {
change.setOldValue(this.getProperty(change.getPropertyName(), change.getOldValue()));
}
//2. update m_configProperties
updateConfig(newConfigProperties, sourceType);
clearConfigCache();
//3. use getProperty to update configChange's new value and calc the final changes
for (ConfigChange change : configChanges) {
change.setNewValue(this.getProperty(change.getPropertyName(), change.getNewValue()));
switch (change.getChangeType()) {
case ADDED:
if (Objects.equals(change.getOldValue(), change.getNewValue())) {
break;
}
if (change.getOldValue() != null) {
change.setChangeType(PropertyChangeType.MODIFIED);
}
actualChanges.put(change.getPropertyName(), change);
break;
case MODIFIED:
if (!Objects.equals(change.getOldValue(), change.getNewValue())) {
actualChanges.put(change.getPropertyName(), change);
}
break;
case DELETED:
if (Objects.equals(change.getOldValue(), change.getNewValue())) {
break;
}
if (change.getNewValue() != null) {
change.setChangeType(PropertyChangeType.MODIFIED);
}
actualChanges.put(change.getPropertyName(), change);
break;
default:
//do nothing
break;
}
}
return actualChanges.build();
}
private Properties loadFromResource(String namespace) {
String name = String.format("META-INF/config/%s.properties", namespace);
InputStream in = ClassLoaderUtil.getLoader().getResourceAsStream(name);
Properties properties = null;
if (in != null) {
properties = propertiesFactory.getPropertiesInstance();
try {
properties.load(in);
} catch (IOException ex) {
Tracer.logError(ex);
logger.error("Load resource config for namespace {} failed", namespace, ex);
} finally {
try {
in.close();
} catch (IOException ex) {
// ignore
}
}
}
return properties;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.util.CollectionUtils;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class DefaultConfig extends AbstractConfig implements RepositoryChangeListener {
private static final Logger logger = DeferredLoggerFactory.getLogger(DefaultConfig.class);
private final String m_namespace;
private final Properties m_resourceProperties;
private final AtomicReference<Properties> m_configProperties;
private final ConfigRepository m_configRepository;
private final RateLimiter m_warnLogRateLimiter;
private volatile ConfigSourceType m_sourceType = ConfigSourceType.NONE;
/**
* Constructor.
*
* @param namespace the namespace of this config instance
* @param configRepository the config repository for this config instance
*/
public DefaultConfig(String namespace, ConfigRepository configRepository) {
m_namespace = namespace;
m_resourceProperties = loadFromResource(m_namespace);
m_configRepository = configRepository;
m_configProperties = new AtomicReference<>();
m_warnLogRateLimiter = RateLimiter.create(0.017); // 1 warning log output per minute
initialize();
}
private void initialize() {
try {
updateConfig(m_configRepository.getConfig(), m_configRepository.getSourceType());
} catch (Throwable ex) {
Tracer.logError(ex);
logger.warn("Init Apollo Local Config failed - namespace: {}, reason: {}.",
m_namespace, ExceptionUtil.getDetailMessage(ex));
} finally {
//register the change listener no matter config repository is working or not
//so that whenever config repository is recovered, config could get changed
m_configRepository.addChangeListener(this);
}
}
/**
* get property from cached repository properties file
*
* @param key property key
* @return value
*/
protected String getPropertyFromRepository(String key) {
Properties properties = m_configProperties.get();
if (properties != null) {
return properties.getProperty(key);
}
return null;
}
/**
* get property from additional properties file on classpath
*
* @param key property key
* @return value
*/
protected String getPropertyFromAdditional(String key) {
Properties properties = this.m_resourceProperties;
if (properties != null) {
return properties.getProperty(key);
}
return null;
}
/**
* try to print a warn log when can not find a property
*
* @param value value
*/
protected void tryWarnLog(String value) {
if (value == null && m_configProperties.get() == null && m_warnLogRateLimiter.tryAcquire()) {
logger.warn(
"Could not load config for namespace {} from Apollo, please check whether the configs are released in Apollo! Return default value now!",
m_namespace);
}
}
/**
* get property names from cached repository properties file
*
* @return property names
*/
protected Set<String> getPropertyNamesFromRepository() {
Properties properties = m_configProperties.get();
if (properties == null) {
return Collections.emptySet();
}
return this.stringPropertyNames(properties);
}
/**
* get property names from additional properties file on classpath
*
* @return property names
*/
protected Set<String> getPropertyNamesFromAdditional() {
Properties properties = m_resourceProperties;
if (properties == null) {
return Collections.emptySet();
}
return this.stringPropertyNames(properties);
}
@Override
public String getProperty(String key, String defaultValue) {
// step 1: check system properties, i.e. -Dkey=value
String value = System.getProperty(key);
// step 2: check local cached properties file
if (value == null) {
value = this.getPropertyFromRepository(key);
}
/*
* step 3: check env variable, i.e. PATH=...
* normally system environment variables are in UPPERCASE, however there might be exceptions.
* so the caller should provide the key in the right case
*/
if (value == null) {
value = System.getenv(key);
}
// step 4: check properties file from classpath
if (value == null) {
value = this.getPropertyFromAdditional(key);
}
this.tryWarnLog(value);
return value == null ? defaultValue : value;
}
@Override
public Set<String> getPropertyNames() {
// propertyNames include system property and system env might cause some compatibility issues, though that looks like the correct implementation.
Set<String> fromRepository = this.getPropertyNamesFromRepository();
Set<String> fromAdditional = this.getPropertyNamesFromAdditional();
if (CollectionUtils.isEmpty(fromRepository)) {
return fromAdditional;
}
if (CollectionUtils.isEmpty(fromAdditional)) {
return fromRepository;
}
Set<String> propertyNames = Sets
.newLinkedHashSetWithExpectedSize(fromRepository.size() + fromAdditional.size());
propertyNames.addAll(fromRepository);
propertyNames.addAll(fromAdditional);
return propertyNames;
}
@Override
public ConfigSourceType getSourceType() {
return m_sourceType;
}
private Set<String> stringPropertyNames(Properties properties) {
//jdk9以下版本Properties#enumerateStringProperties方法存在性能问题,keys() + get(k) 重复迭代, jdk9之后改为entrySet遍历.
Map<String, String> h = Maps.newLinkedHashMapWithExpectedSize(properties.size());
for (Map.Entry<Object, Object> e : properties.entrySet()) {
Object k = e.getKey();
Object v = e.getValue();
if (k instanceof String && v instanceof String) {
h.put((String) k, (String) v);
}
}
return h.keySet();
}
@Override
public synchronized void onRepositoryChange(String namespace, Properties newProperties) {
if (newProperties.equals(m_configProperties.get())) {
return;
}
ConfigSourceType sourceType = m_configRepository.getSourceType();
Properties newConfigProperties = propertiesFactory.getPropertiesInstance();
newConfigProperties.putAll(newProperties);
Map<String, ConfigChange> actualChanges = updateAndCalcConfigChanges(newConfigProperties,
sourceType);
//check double checked result
if (actualChanges.isEmpty()) {
return;
}
this.fireConfigChange(m_namespace, actualChanges);
Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace);
}
private void updateConfig(Properties newConfigProperties, ConfigSourceType sourceType) {
m_configProperties.set(newConfigProperties);
m_sourceType = sourceType;
}
private Map<String, ConfigChange> updateAndCalcConfigChanges(Properties newConfigProperties,
ConfigSourceType sourceType) {
List<ConfigChange> configChanges =
calcPropertyChanges(m_namespace, m_configProperties.get(), newConfigProperties);
ImmutableMap.Builder<String, ConfigChange> actualChanges =
new ImmutableMap.Builder<>();
/** === Double check since DefaultConfig has multiple config sources ==== **/
//1. use getProperty to update configChanges's old value
for (ConfigChange change : configChanges) {
change.setOldValue(this.getProperty(change.getPropertyName(), change.getOldValue()));
}
//2. update m_configProperties
updateConfig(newConfigProperties, sourceType);
clearConfigCache();
//3. use getProperty to update configChange's new value and calc the final changes
for (ConfigChange change : configChanges) {
change.setNewValue(this.getProperty(change.getPropertyName(), change.getNewValue()));
switch (change.getChangeType()) {
case ADDED:
if (Objects.equals(change.getOldValue(), change.getNewValue())) {
break;
}
if (change.getOldValue() != null) {
change.setChangeType(PropertyChangeType.MODIFIED);
}
actualChanges.put(change.getPropertyName(), change);
break;
case MODIFIED:
if (!Objects.equals(change.getOldValue(), change.getNewValue())) {
actualChanges.put(change.getPropertyName(), change);
}
break;
case DELETED:
if (Objects.equals(change.getOldValue(), change.getNewValue())) {
break;
}
if (change.getNewValue() != null) {
change.setChangeType(PropertyChangeType.MODIFIED);
}
actualChanges.put(change.getPropertyName(), change);
break;
default:
//do nothing
break;
}
}
return actualChanges.build();
}
private Properties loadFromResource(String namespace) {
String name = String.format("META-INF/config/%s.properties", namespace);
InputStream in = ClassLoaderUtil.getLoader().getResourceAsStream(name);
Properties properties = null;
if (in != null) {
properties = propertiesFactory.getPropertiesInstance();
try {
properties.load(in);
} catch (IOException ex) {
Tracer.logError(ex);
logger.error("Load resource config for namespace {} failed", namespace, ex);
} finally {
try {
in.close();
} catch (IOException ex) {
// ignore
}
}
}
return properties;
}
}
| 1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/spi/DefaultConfigFactory.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spi;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.PropertiesCompatibleConfigFile;
import com.ctrip.framework.apollo.internals.PropertiesCompatibleFileConfigRepository;
import com.ctrip.framework.apollo.internals.TxtConfigFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.internals.ConfigRepository;
import com.ctrip.framework.apollo.internals.DefaultConfig;
import com.ctrip.framework.apollo.internals.JsonConfigFile;
import com.ctrip.framework.apollo.internals.LocalFileConfigRepository;
import com.ctrip.framework.apollo.internals.PropertiesConfigFile;
import com.ctrip.framework.apollo.internals.RemoteConfigRepository;
import com.ctrip.framework.apollo.internals.XmlConfigFile;
import com.ctrip.framework.apollo.internals.YamlConfigFile;
import com.ctrip.framework.apollo.internals.YmlConfigFile;
import com.ctrip.framework.apollo.util.ConfigUtil;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class DefaultConfigFactory implements ConfigFactory {
private static final Logger logger = LoggerFactory.getLogger(DefaultConfigFactory.class);
private ConfigUtil m_configUtil;
public DefaultConfigFactory() {
m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
}
@Override
public Config create(String namespace) {
ConfigFileFormat format = determineFileFormat(namespace);
if (ConfigFileFormat.isPropertiesCompatible(format)) {
return new DefaultConfig(namespace, createPropertiesCompatibleFileConfigRepository(namespace, format));
}
return new DefaultConfig(namespace, createLocalConfigRepository(namespace));
}
@Override
public ConfigFile createConfigFile(String namespace, ConfigFileFormat configFileFormat) {
ConfigRepository configRepository = createLocalConfigRepository(namespace);
switch (configFileFormat) {
case Properties:
return new PropertiesConfigFile(namespace, configRepository);
case XML:
return new XmlConfigFile(namespace, configRepository);
case JSON:
return new JsonConfigFile(namespace, configRepository);
case YAML:
return new YamlConfigFile(namespace, configRepository);
case YML:
return new YmlConfigFile(namespace, configRepository);
case TXT:
return new TxtConfigFile(namespace, configRepository);
}
return null;
}
LocalFileConfigRepository createLocalConfigRepository(String namespace) {
if (m_configUtil.isInLocalMode()) {
logger.warn(
"==== Apollo is in local mode! Won't pull configs from remote server for namespace {} ! ====",
namespace);
return new LocalFileConfigRepository(namespace);
}
return new LocalFileConfigRepository(namespace, createRemoteConfigRepository(namespace));
}
RemoteConfigRepository createRemoteConfigRepository(String namespace) {
return new RemoteConfigRepository(namespace);
}
PropertiesCompatibleFileConfigRepository createPropertiesCompatibleFileConfigRepository(String namespace,
ConfigFileFormat format) {
String actualNamespaceName = trimNamespaceFormat(namespace, format);
PropertiesCompatibleConfigFile configFile = (PropertiesCompatibleConfigFile) ConfigService
.getConfigFile(actualNamespaceName, format);
return new PropertiesCompatibleFileConfigRepository(configFile);
}
// for namespaces whose format are not properties, the file extension must be present, e.g. application.yaml
ConfigFileFormat determineFileFormat(String namespaceName) {
String lowerCase = namespaceName.toLowerCase();
for (ConfigFileFormat format : ConfigFileFormat.values()) {
if (lowerCase.endsWith("." + format.getValue())) {
return format;
}
}
return ConfigFileFormat.Properties;
}
String trimNamespaceFormat(String namespaceName, ConfigFileFormat format) {
String extension = "." + format.getValue();
if (!namespaceName.toLowerCase().endsWith(extension)) {
return namespaceName;
}
return namespaceName.substring(0, namespaceName.length() - extension.length());
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spi;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.PropertiesCompatibleConfigFile;
import com.ctrip.framework.apollo.internals.PropertiesCompatibleFileConfigRepository;
import com.ctrip.framework.apollo.internals.TxtConfigFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.internals.ConfigRepository;
import com.ctrip.framework.apollo.internals.DefaultConfig;
import com.ctrip.framework.apollo.internals.JsonConfigFile;
import com.ctrip.framework.apollo.internals.LocalFileConfigRepository;
import com.ctrip.framework.apollo.internals.PropertiesConfigFile;
import com.ctrip.framework.apollo.internals.RemoteConfigRepository;
import com.ctrip.framework.apollo.internals.XmlConfigFile;
import com.ctrip.framework.apollo.internals.YamlConfigFile;
import com.ctrip.framework.apollo.internals.YmlConfigFile;
import com.ctrip.framework.apollo.util.ConfigUtil;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class DefaultConfigFactory implements ConfigFactory {
private static final Logger logger = LoggerFactory.getLogger(DefaultConfigFactory.class);
private final ConfigUtil m_configUtil;
public DefaultConfigFactory() {
m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
}
@Override
public Config create(String namespace) {
ConfigFileFormat format = determineFileFormat(namespace);
if (ConfigFileFormat.isPropertiesCompatible(format)) {
return this.createRepositoryConfig(namespace, createPropertiesCompatibleFileConfigRepository(namespace, format));
}
return this.createRepositoryConfig(namespace, createLocalConfigRepository(namespace));
}
protected Config createRepositoryConfig(String namespace, ConfigRepository configRepository) {
return new DefaultConfig(namespace, configRepository);
}
@Override
public ConfigFile createConfigFile(String namespace, ConfigFileFormat configFileFormat) {
ConfigRepository configRepository = createLocalConfigRepository(namespace);
switch (configFileFormat) {
case Properties:
return new PropertiesConfigFile(namespace, configRepository);
case XML:
return new XmlConfigFile(namespace, configRepository);
case JSON:
return new JsonConfigFile(namespace, configRepository);
case YAML:
return new YamlConfigFile(namespace, configRepository);
case YML:
return new YmlConfigFile(namespace, configRepository);
case TXT:
return new TxtConfigFile(namespace, configRepository);
}
return null;
}
LocalFileConfigRepository createLocalConfigRepository(String namespace) {
if (m_configUtil.isInLocalMode()) {
logger.warn(
"==== Apollo is in local mode! Won't pull configs from remote server for namespace {} ! ====",
namespace);
return new LocalFileConfigRepository(namespace);
}
return new LocalFileConfigRepository(namespace, createRemoteConfigRepository(namespace));
}
RemoteConfigRepository createRemoteConfigRepository(String namespace) {
return new RemoteConfigRepository(namespace);
}
PropertiesCompatibleFileConfigRepository createPropertiesCompatibleFileConfigRepository(String namespace,
ConfigFileFormat format) {
String actualNamespaceName = trimNamespaceFormat(namespace, format);
PropertiesCompatibleConfigFile configFile = (PropertiesCompatibleConfigFile) ConfigService
.getConfigFile(actualNamespaceName, format);
return new PropertiesCompatibleFileConfigRepository(configFile);
}
// for namespaces whose format are not properties, the file extension must be present, e.g. application.yaml
ConfigFileFormat determineFileFormat(String namespaceName) {
String lowerCase = namespaceName.toLowerCase();
for (ConfigFileFormat format : ConfigFileFormat.values()) {
if (lowerCase.endsWith("." + format.getValue())) {
return format;
}
}
return ConfigFileFormat.Properties;
}
String trimNamespaceFormat(String namespaceName, ConfigFileFormat format) {
String extension = "." + format.getValue();
if (!namespaceName.toLowerCase().endsWith(extension)) {
return namespaceName;
}
return namespaceName.substring(0, namespaceName.length() - extension.length());
}
}
| 1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/constant/RoleType.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.constant;
public class RoleType {
public static final String MASTER = "Master";
public static final String MODIFY_NAMESPACE = "ModifyNamespace";
public static final String RELEASE_NAMESPACE = "ReleaseNamespace";
public static boolean isValidRoleType(String roleType) {
return MASTER.equals(roleType) || MODIFY_NAMESPACE.equals(roleType) || RELEASE_NAMESPACE.equals(roleType);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.constant;
public class RoleType {
public static final String MASTER = "Master";
public static final String MODIFY_NAMESPACE = "ModifyNamespace";
public static final String RELEASE_NAMESPACE = "ReleaseNamespace";
public static boolean isValidRoleType(String roleType) {
return MASTER.equals(roleType) || MODIFY_NAMESPACE.equals(roleType) || RELEASE_NAMESPACE.equals(roleType);
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/model/ConfigChange.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.model;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
/**
* Holds the information for a config change.
* @author Jason Song(song_s@ctrip.com)
*/
public class ConfigChange {
private final String namespace;
private final String propertyName;
private String oldValue;
private String newValue;
private PropertyChangeType changeType;
/**
* Constructor.
* @param namespace the namespace of the key
* @param propertyName the key whose value is changed
* @param oldValue the value before change
* @param newValue the value after change
* @param changeType the change type
*/
public ConfigChange(String namespace, String propertyName, String oldValue, String newValue,
PropertyChangeType changeType) {
this.namespace = namespace;
this.propertyName = propertyName;
this.oldValue = oldValue;
this.newValue = newValue;
this.changeType = changeType;
}
public String getPropertyName() {
return propertyName;
}
public String getOldValue() {
return oldValue;
}
public String getNewValue() {
return newValue;
}
public PropertyChangeType getChangeType() {
return changeType;
}
public void setOldValue(String oldValue) {
this.oldValue = oldValue;
}
public void setNewValue(String newValue) {
this.newValue = newValue;
}
public void setChangeType(PropertyChangeType changeType) {
this.changeType = changeType;
}
public String getNamespace() {
return namespace;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ConfigChange{");
sb.append("namespace='").append(namespace).append('\'');
sb.append(", propertyName='").append(propertyName).append('\'');
sb.append(", oldValue='").append(oldValue).append('\'');
sb.append(", newValue='").append(newValue).append('\'');
sb.append(", changeType=").append(changeType);
sb.append('}');
return sb.toString();
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.model;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
/**
* Holds the information for a config change.
* @author Jason Song(song_s@ctrip.com)
*/
public class ConfigChange {
private final String namespace;
private final String propertyName;
private String oldValue;
private String newValue;
private PropertyChangeType changeType;
/**
* Constructor.
* @param namespace the namespace of the key
* @param propertyName the key whose value is changed
* @param oldValue the value before change
* @param newValue the value after change
* @param changeType the change type
*/
public ConfigChange(String namespace, String propertyName, String oldValue, String newValue,
PropertyChangeType changeType) {
this.namespace = namespace;
this.propertyName = propertyName;
this.oldValue = oldValue;
this.newValue = newValue;
this.changeType = changeType;
}
public String getPropertyName() {
return propertyName;
}
public String getOldValue() {
return oldValue;
}
public String getNewValue() {
return newValue;
}
public PropertyChangeType getChangeType() {
return changeType;
}
public void setOldValue(String oldValue) {
this.oldValue = oldValue;
}
public void setNewValue(String newValue) {
this.newValue = newValue;
}
public void setChangeType(PropertyChangeType changeType) {
this.changeType = changeType;
}
public String getNamespace() {
return namespace;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ConfigChange{");
sb.append("namespace='").append(namespace).append('\'');
sb.append(", propertyName='").append(propertyName).append('\'');
sb.append(", oldValue='").append(oldValue).append('\'');
sb.append(", newValue='").append(newValue).append('\'');
sb.append(", changeType=").append(changeType);
sb.append('}');
return sb.toString();
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./docs/en/misc/apollo-benchmark.md | TODO
| TODO
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/openapi/repository/ConsumerTokenRepository.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.repository;
import com.ctrip.framework.apollo.openapi.entity.ConsumerToken;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface ConsumerTokenRepository extends PagingAndSortingRepository<ConsumerToken, Long> {
/**
* find consumer token by token
*
* @param token the token
* @param validDate the date when the token is valid
*/
ConsumerToken findTopByTokenAndExpiresAfter(String token, Date validDate);
ConsumerToken findByConsumerId(Long consumerId);
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.repository;
import com.ctrip.framework.apollo.openapi.entity.ConsumerToken;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface ConsumerTokenRepository extends PagingAndSortingRepository<ConsumerToken, Long> {
/**
* find consumer token by token
*
* @param token the token
* @param validDate the date when the token is valid
*/
ConsumerToken findTopByTokenAndExpiresAfter(String token, Date validDate);
ConsumerToken findByConsumerId(Long consumerId);
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/ReleaseHistoryController.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.component.PermissionValidator;
import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO;
import com.ctrip.framework.apollo.portal.service.ReleaseHistoryService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.List;
@RestController
public class ReleaseHistoryController {
private final ReleaseHistoryService releaseHistoryService;
private final PermissionValidator permissionValidator;
public ReleaseHistoryController(final ReleaseHistoryService releaseHistoryService, final PermissionValidator permissionValidator) {
this.releaseHistoryService = releaseHistoryService;
this.permissionValidator = permissionValidator;
}
@GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/releases/histories")
public List<ReleaseHistoryBO> findReleaseHistoriesByNamespace(@PathVariable String appId,
@PathVariable String env,
@PathVariable String clusterName,
@PathVariable String namespaceName,
@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "10") int size) {
if (permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceName)) {
return Collections.emptyList();
}
return releaseHistoryService.findNamespaceReleaseHistory(appId, Env.valueOf(env), clusterName ,namespaceName, page, size);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.component.PermissionValidator;
import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO;
import com.ctrip.framework.apollo.portal.service.ReleaseHistoryService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.List;
@RestController
public class ReleaseHistoryController {
private final ReleaseHistoryService releaseHistoryService;
private final PermissionValidator permissionValidator;
public ReleaseHistoryController(final ReleaseHistoryService releaseHistoryService, final PermissionValidator permissionValidator) {
this.releaseHistoryService = releaseHistoryService;
this.permissionValidator = permissionValidator;
}
@GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/releases/histories")
public List<ReleaseHistoryBO> findReleaseHistoriesByNamespace(@PathVariable String appId,
@PathVariable String env,
@PathVariable String clusterName,
@PathVariable String namespaceName,
@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "10") int size) {
if (permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceName)) {
return Collections.emptyList();
}
return releaseHistoryService.findNamespaceReleaseHistory(appId, Env.valueOf(env), clusterName ,namespaceName, page, size);
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/utils/ExceptionUtils.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.utils;
import com.google.common.base.MoreObjects;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.web.client.HttpStatusCodeException;
import java.lang.reflect.Type;
import java.util.Map;
public final class ExceptionUtils {
private static Gson gson = new Gson();
private static Type mapType = new TypeToken<Map<String, Object>>() {}.getType();
public static String toString(HttpStatusCodeException e) {
Map<String, Object> errorAttributes = gson.fromJson(e.getResponseBodyAsString(), mapType);
if (errorAttributes != null) {
return MoreObjects.toStringHelper(HttpStatusCodeException.class).omitNullValues()
.add("status", errorAttributes.get("status"))
.add("message", errorAttributes.get("message"))
.add("timestamp", errorAttributes.get("timestamp"))
.add("exception", errorAttributes.get("exception"))
.add("errorCode", errorAttributes.get("errorCode"))
.add("stackTrace", errorAttributes.get("stackTrace")).toString();
}
return "";
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.utils;
import com.google.common.base.MoreObjects;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.web.client.HttpStatusCodeException;
import java.lang.reflect.Type;
import java.util.Map;
public final class ExceptionUtils {
private static Gson gson = new Gson();
private static Type mapType = new TypeToken<Map<String, Object>>() {}.getType();
public static String toString(HttpStatusCodeException e) {
Map<String, Object> errorAttributes = gson.fromJson(e.getResponseBodyAsString(), mapType);
if (errorAttributes != null) {
return MoreObjects.toStringHelper(HttpStatusCodeException.class).omitNullValues()
.add("status", errorAttributes.get("status"))
.add("message", errorAttributes.get("message"))
.add("timestamp", errorAttributes.get("timestamp"))
.add("exception", errorAttributes.get("exception"))
.add("errorCode", errorAttributes.get("errorCode"))
.add("stackTrace", errorAttributes.get("stackTrace")).toString();
}
return "";
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/oidc/OidcLocalUserServiceImpl.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.spi.oidc;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.entity.po.UserPO;
import com.ctrip.framework.apollo.portal.repository.UserRepository;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class OidcLocalUserServiceImpl implements OidcLocalUserService {
private final Collection<? extends GrantedAuthority> authorities = Collections
.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
private final PasswordEncoder placeholderDelegatingPasswordEncoder = new DelegatingPasswordEncoder(
PlaceholderPasswordEncoder.ENCODING_ID, Collections
.singletonMap(PlaceholderPasswordEncoder.ENCODING_ID, new PlaceholderPasswordEncoder()));
private final JdbcUserDetailsManager userDetailsManager;
private final UserRepository userRepository;
public OidcLocalUserServiceImpl(
JdbcUserDetailsManager userDetailsManager,
UserRepository userRepository) {
this.userDetailsManager = userDetailsManager;
this.userRepository = userRepository;
}
@Transactional(rollbackFor = Exception.class)
@Override
public void createLocalUser(UserInfo newUserInfo) {
UserDetails user = new User(newUserInfo.getUserId(),
this.placeholderDelegatingPasswordEncoder.encode(""), authorities);
userDetailsManager.createUser(user);
this.updateUserInfoInternal(newUserInfo);
}
private void updateUserInfoInternal(UserInfo newUserInfo) {
UserPO managedUser = userRepository.findByUsername(newUserInfo.getUserId());
if (!StringUtils.isBlank(newUserInfo.getEmail())) {
managedUser.setEmail(newUserInfo.getEmail());
}
if (!StringUtils.isBlank(newUserInfo.getName())) {
managedUser.setUserDisplayName(newUserInfo.getName());
}
userRepository.save(managedUser);
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateUserInfo(UserInfo newUserInfo) {
this.updateUserInfoInternal(newUserInfo);
}
@Override
public List<UserInfo> searchUsers(String keyword, int offset, int limit) {
List<UserPO> users = this.findUsers(keyword);
if (CollectionUtils.isEmpty(users)) {
return Collections.emptyList();
}
return users.stream().map(UserPO::toUserInfo)
.collect(Collectors.toList());
}
private List<UserPO> findUsers(String keyword) {
if (StringUtils.isEmpty(keyword)) {
return userRepository.findFirst20ByEnabled(1);
}
List<UserPO> users = new ArrayList<>();
List<UserPO> byUsername = userRepository
.findByUsernameLikeAndEnabled("%" + keyword + "%", 1);
List<UserPO> byUserDisplayName = userRepository
.findByUserDisplayNameLikeAndEnabled("%" + keyword + "%", 1);
if (!CollectionUtils.isEmpty(byUsername)) {
users.addAll(byUsername);
}
if (!CollectionUtils.isEmpty(byUserDisplayName)) {
users.addAll(byUserDisplayName);
}
return users;
}
@Override
public UserInfo findByUserId(String userId) {
UserPO userPO = userRepository.findByUsername(userId);
return userPO == null ? null : userPO.toUserInfo();
}
@Override
public List<UserInfo> findByUserIds(List<String> userIds) {
List<UserPO> users = userRepository.findByUsernameIn(userIds);
if (CollectionUtils.isEmpty(users)) {
return Collections.emptyList();
}
return users.stream().map(UserPO::toUserInfo)
.collect(Collectors.toList());
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.spi.oidc;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.entity.po.UserPO;
import com.ctrip.framework.apollo.portal.repository.UserRepository;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class OidcLocalUserServiceImpl implements OidcLocalUserService {
private final Collection<? extends GrantedAuthority> authorities = Collections
.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
private final PasswordEncoder placeholderDelegatingPasswordEncoder = new DelegatingPasswordEncoder(
PlaceholderPasswordEncoder.ENCODING_ID, Collections
.singletonMap(PlaceholderPasswordEncoder.ENCODING_ID, new PlaceholderPasswordEncoder()));
private final JdbcUserDetailsManager userDetailsManager;
private final UserRepository userRepository;
public OidcLocalUserServiceImpl(
JdbcUserDetailsManager userDetailsManager,
UserRepository userRepository) {
this.userDetailsManager = userDetailsManager;
this.userRepository = userRepository;
}
@Transactional(rollbackFor = Exception.class)
@Override
public void createLocalUser(UserInfo newUserInfo) {
UserDetails user = new User(newUserInfo.getUserId(),
this.placeholderDelegatingPasswordEncoder.encode(""), authorities);
userDetailsManager.createUser(user);
this.updateUserInfoInternal(newUserInfo);
}
private void updateUserInfoInternal(UserInfo newUserInfo) {
UserPO managedUser = userRepository.findByUsername(newUserInfo.getUserId());
if (!StringUtils.isBlank(newUserInfo.getEmail())) {
managedUser.setEmail(newUserInfo.getEmail());
}
if (!StringUtils.isBlank(newUserInfo.getName())) {
managedUser.setUserDisplayName(newUserInfo.getName());
}
userRepository.save(managedUser);
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateUserInfo(UserInfo newUserInfo) {
this.updateUserInfoInternal(newUserInfo);
}
@Override
public List<UserInfo> searchUsers(String keyword, int offset, int limit) {
List<UserPO> users = this.findUsers(keyword);
if (CollectionUtils.isEmpty(users)) {
return Collections.emptyList();
}
return users.stream().map(UserPO::toUserInfo)
.collect(Collectors.toList());
}
private List<UserPO> findUsers(String keyword) {
if (StringUtils.isEmpty(keyword)) {
return userRepository.findFirst20ByEnabled(1);
}
List<UserPO> users = new ArrayList<>();
List<UserPO> byUsername = userRepository
.findByUsernameLikeAndEnabled("%" + keyword + "%", 1);
List<UserPO> byUserDisplayName = userRepository
.findByUserDisplayNameLikeAndEnabled("%" + keyword + "%", 1);
if (!CollectionUtils.isEmpty(byUsername)) {
users.addAll(byUsername);
}
if (!CollectionUtils.isEmpty(byUserDisplayName)) {
users.addAll(byUserDisplayName);
}
return users;
}
@Override
public UserInfo findByUserId(String userId) {
UserPO userPO = userRepository.findByUsername(userId);
return userPO == null ? null : userPO.toUserInfo();
}
@Override
public List<UserInfo> findByUserIds(List<String> userIds) {
List<UserPO> users = userRepository.findByUsernameIn(userIds);
if (CollectionUtils.isEmpty(users)) {
return Collections.emptyList();
}
return users.stream().map(UserPO::toUserInfo)
.collect(Collectors.toList());
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/DefaultApolloConfigRegistrarHelper.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.spi;
import com.ctrip.framework.apollo.core.spi.Ordered;
import com.ctrip.framework.apollo.spring.annotation.ApolloAnnotationProcessor;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor;
import com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor;
import com.ctrip.framework.apollo.spring.util.BeanRegistrationUtil;
import com.google.common.collect.Lists;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
public class DefaultApolloConfigRegistrarHelper implements ApolloConfigRegistrarHelper {
private Environment environment;
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
final String[] namespaces = attributes.getStringArray("value");
final int order = attributes.getNumber("order");
final String[] resolvedNamespaces = this.resolveNamespaces(namespaces);
PropertySourcesProcessor.addNamespaces(Lists.newArrayList(resolvedNamespaces), order);
Map<String, Object> propertySourcesPlaceholderPropertyValues = new HashMap<>();
// to make sure the default PropertySourcesPlaceholderConfigurer's priority is higher than PropertyPlaceholderConfigurer
propertySourcesPlaceholderPropertyValues.put("order", 0);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(),
PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(),
PropertySourcesProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class.getName(),
ApolloAnnotationProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class.getName(),
SpringValueProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueDefinitionProcessor.class.getName(),
SpringValueDefinitionProcessor.class);
}
private String[] resolveNamespaces(String[] namespaces) {
String[] resolvedNamespaces = new String[namespaces.length];
for (int i = 0; i < namespaces.length; i++) {
// throw IllegalArgumentException if given text is null or if any placeholders are unresolvable
resolvedNamespaces[i] = this.environment.resolveRequiredPlaceholders(namespaces[i]);
}
return resolvedNamespaces;
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.spi;
import com.ctrip.framework.apollo.core.spi.Ordered;
import com.ctrip.framework.apollo.spring.annotation.ApolloAnnotationProcessor;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor;
import com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor;
import com.ctrip.framework.apollo.spring.util.BeanRegistrationUtil;
import com.google.common.collect.Lists;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
public class DefaultApolloConfigRegistrarHelper implements ApolloConfigRegistrarHelper {
private Environment environment;
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
final String[] namespaces = attributes.getStringArray("value");
final int order = attributes.getNumber("order");
final String[] resolvedNamespaces = this.resolveNamespaces(namespaces);
PropertySourcesProcessor.addNamespaces(Lists.newArrayList(resolvedNamespaces), order);
Map<String, Object> propertySourcesPlaceholderPropertyValues = new HashMap<>();
// to make sure the default PropertySourcesPlaceholderConfigurer's priority is higher than PropertyPlaceholderConfigurer
propertySourcesPlaceholderPropertyValues.put("order", 0);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(),
PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(),
PropertySourcesProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class.getName(),
ApolloAnnotationProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class.getName(),
SpringValueProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueDefinitionProcessor.class.getName(),
SpringValueDefinitionProcessor.class);
}
private String[] resolveNamespaces(String[] namespaces) {
String[] resolvedNamespaces = new String[namespaces.length];
for (int i = 0; i < namespaces.length; i++) {
// throw IllegalArgumentException if given text is null or if any placeholders are unresolvable
resolvedNamespaces[i] = this.environment.resolveRequiredPlaceholders(namespaces[i]);
}
return resolvedNamespaces;
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./docs/zh/faq/faq.md | ## 1. Apollo是什么?
Apollo(阿波罗)是携程框架部门研发的配置管理平台,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性。
更多介绍,可以参考[Apollo配置中心介绍](zh/design/apollo-introduction)
## 2. Cluster是什么?
一个应用下不同实例的分组,比如典型的可以按照数据中心分,把A机房的应用实例分为一个集群,把B机房的应用实例分为另一个集群。
## 3. Namespace是什么?
一个应用下不同配置的分组。
请参考[Apollo核心概念之“Namespace”](zh/design/apollo-core-concept-namespace)
## 4. 我想要接入Apollo,该如何操作?
请参考[Apollo使用指南](zh/usage/apollo-user-guide)
## 5. 我的应用需要不同机房的配置不一样,Apollo是否能支持?
Apollo是支持的。请参考[Apollo使用指南](zh/usage/apollo-user-guide)中的`三、集群独立配置说明`
## 6. 我有多个应用需要使用同一份配置,Apollo是否能支持?
Apollo是支持的。请参考[Apollo使用指南](zh/usage/apollo-user-guide)中的`四、多个AppId使用同一份配置`
## 7. Apollo是否支持查看权限控制或者配置加密?
从1.1.0版本开始,apollo-portal增加了查看权限的支持,可以支持配置某个环境只允许项目成员查看私有Namespace的配置。
这里的项目成员是指:
1. 项目的管理员
2. 具备该私有Namespace在该环境下的修改或发布权限
配置方式很简单,用超级管理员账号登录后,进入`管理员工具 - 系统参数`页面新增或修改`configView.memberOnly.envs`配置项即可。

配置加密可以参考[spring-boot-encrypt demo项目](https://github.com/ctripcorp/apollo-use-cases/tree/master/spring-boot-encrypt)
## 8. 如果有多个config server,打包时如何配置meta server地址?
有多台meta server可以通过nginx反向代理,通过一个域名代理多个meta server实现ha。
## 9. Apollo相比于Spring Cloud Config有什么优势?
Spring Cloud Config的精妙之处在于它的配置存储于Git,这就天然的把配置的修改、权限、版本等问题隔离在外。通过这个设计使得Spring Cloud Config整体很简单,不过也带来了一些不便之处。
下面尝试做一个简单的小结:
| 功能点 | Apollo | Spring Cloud Config | 备注 |
|------------------|--------------------------------------------|-------------------------------------------------|----------------------------------------------------------------------------|
| 配置界面 | 一个界面管理不同环境、不同集群配置 | 无,需要通过git操作 | |
| 配置生效时间 | 实时 | 重启生效,或手动refresh生效 | Spring Cloud Config需要通过Git webhook,加上额外的消息队列才能支持实时生效 |
| 版本管理 | 界面上直接提供发布历史和回滚按钮 | 无,需要通过git操作 | |
| 灰度发布 | 支持 | 不支持 | |
| 授权、审核、审计 | 界面上直接支持,而且支持修改、发布权限分离 | 需要通过git仓库设置,且不支持修改、发布权限分离 | |
| 实例配置监控 | 可以方便的看到当前哪些客户端在使用哪些配置 | 不支持 | |
| 配置获取性能 | 快,通过数据库访问,还有缓存支持 | 较慢,需要从git clone repository,然后从文件系统读取 | |
| 客户端支持 | 原生支持所有Java和.Net应用,提供API支持其它语言应用,同时也支持Spring annotation获取配置 | 支持Spring应用,提供annotation获取配置 | Apollo的适用范围更广一些 |
## 10. Apollo和Disconf相比有什么优点?
由于我们自己并非Disconf的资深用户,所以无法主观地给出评价。
不过之前Apollo技术支持群中的热心网友[@Krast](https://github.com/krast)做了一个[开源配置中心对比矩阵](https://github.com/ctripcorp/apollo/files/983064/default.pdf),可以参考一下。 | ## 1. Apollo是什么?
Apollo(阿波罗)是携程框架部门研发的配置管理平台,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性。
更多介绍,可以参考[Apollo配置中心介绍](zh/design/apollo-introduction)
## 2. Cluster是什么?
一个应用下不同实例的分组,比如典型的可以按照数据中心分,把A机房的应用实例分为一个集群,把B机房的应用实例分为另一个集群。
## 3. Namespace是什么?
一个应用下不同配置的分组。
请参考[Apollo核心概念之“Namespace”](zh/design/apollo-core-concept-namespace)
## 4. 我想要接入Apollo,该如何操作?
请参考[Apollo使用指南](zh/usage/apollo-user-guide)
## 5. 我的应用需要不同机房的配置不一样,Apollo是否能支持?
Apollo是支持的。请参考[Apollo使用指南](zh/usage/apollo-user-guide)中的`三、集群独立配置说明`
## 6. 我有多个应用需要使用同一份配置,Apollo是否能支持?
Apollo是支持的。请参考[Apollo使用指南](zh/usage/apollo-user-guide)中的`四、多个AppId使用同一份配置`
## 7. Apollo是否支持查看权限控制或者配置加密?
从1.1.0版本开始,apollo-portal增加了查看权限的支持,可以支持配置某个环境只允许项目成员查看私有Namespace的配置。
这里的项目成员是指:
1. 项目的管理员
2. 具备该私有Namespace在该环境下的修改或发布权限
配置方式很简单,用超级管理员账号登录后,进入`管理员工具 - 系统参数`页面新增或修改`configView.memberOnly.envs`配置项即可。

配置加密可以参考[spring-boot-encrypt demo项目](https://github.com/ctripcorp/apollo-use-cases/tree/master/spring-boot-encrypt)
## 8. 如果有多个config server,打包时如何配置meta server地址?
有多台meta server可以通过nginx反向代理,通过一个域名代理多个meta server实现ha。
## 9. Apollo相比于Spring Cloud Config有什么优势?
Spring Cloud Config的精妙之处在于它的配置存储于Git,这就天然的把配置的修改、权限、版本等问题隔离在外。通过这个设计使得Spring Cloud Config整体很简单,不过也带来了一些不便之处。
下面尝试做一个简单的小结:
| 功能点 | Apollo | Spring Cloud Config | 备注 |
|------------------|--------------------------------------------|-------------------------------------------------|----------------------------------------------------------------------------|
| 配置界面 | 一个界面管理不同环境、不同集群配置 | 无,需要通过git操作 | |
| 配置生效时间 | 实时 | 重启生效,或手动refresh生效 | Spring Cloud Config需要通过Git webhook,加上额外的消息队列才能支持实时生效 |
| 版本管理 | 界面上直接提供发布历史和回滚按钮 | 无,需要通过git操作 | |
| 灰度发布 | 支持 | 不支持 | |
| 授权、审核、审计 | 界面上直接支持,而且支持修改、发布权限分离 | 需要通过git仓库设置,且不支持修改、发布权限分离 | |
| 实例配置监控 | 可以方便的看到当前哪些客户端在使用哪些配置 | 不支持 | |
| 配置获取性能 | 快,通过数据库访问,还有缓存支持 | 较慢,需要从git clone repository,然后从文件系统读取 | |
| 客户端支持 | 原生支持所有Java和.Net应用,提供API支持其它语言应用,同时也支持Spring annotation获取配置 | 支持Spring应用,提供annotation获取配置 | Apollo的适用范围更广一些 |
## 10. Apollo和Disconf相比有什么优点?
由于我们自己并非Disconf的资深用户,所以无法主观地给出评价。
不过之前Apollo技术支持群中的热心网友[@Krast](https://github.com/krast)做了一个[开源配置中心对比矩阵](https://github.com/ctripcorp/apollo/files/983064/default.pdf),可以参考一下。 | -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-adminservice/src/main/java/com/ctrip/framework/apollo/adminservice/AdminServiceAutoConfiguration.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.adminservice;
import com.ctrip.framework.apollo.adminservice.filter.AdminServiceAuthenticationFilter;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AdminServiceAutoConfiguration {
private final BizConfig bizConfig;
public AdminServiceAutoConfiguration(final BizConfig bizConfig) {
this.bizConfig = bizConfig;
}
@Bean
public FilterRegistrationBean<AdminServiceAuthenticationFilter> adminServiceAuthenticationFilter() {
FilterRegistrationBean<AdminServiceAuthenticationFilter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(new AdminServiceAuthenticationFilter(bizConfig));
filterRegistrationBean.addUrlPatterns("/apps/*");
filterRegistrationBean.addUrlPatterns("/appnamespaces/*");
filterRegistrationBean.addUrlPatterns("/instances/*");
filterRegistrationBean.addUrlPatterns("/items/*");
filterRegistrationBean.addUrlPatterns("/namespaces/*");
filterRegistrationBean.addUrlPatterns("/releases/*");
return filterRegistrationBean;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.adminservice;
import com.ctrip.framework.apollo.adminservice.filter.AdminServiceAuthenticationFilter;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AdminServiceAutoConfiguration {
private final BizConfig bizConfig;
public AdminServiceAutoConfiguration(final BizConfig bizConfig) {
this.bizConfig = bizConfig;
}
@Bean
public FilterRegistrationBean<AdminServiceAuthenticationFilter> adminServiceAuthenticationFilter() {
FilterRegistrationBean<AdminServiceAuthenticationFilter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(new AdminServiceAuthenticationFilter(bizConfig));
filterRegistrationBean.addUrlPatterns("/apps/*");
filterRegistrationBean.addUrlPatterns("/appnamespaces/*");
filterRegistrationBean.addUrlPatterns("/instances/*");
filterRegistrationBean.addUrlPatterns("/items/*");
filterRegistrationBean.addUrlPatterns("/namespaces/*");
filterRegistrationBean.addUrlPatterns("/releases/*");
return filterRegistrationBean;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/emailbuilder/NormalPublishEmailBuilder.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.component.emailbuilder;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO;
import org.springframework.stereotype.Component;
@Component
public class NormalPublishEmailBuilder extends ConfigPublishEmailBuilder {
private static final String EMAIL_SUBJECT = "[Apollo] 配置发布";
@Override
protected String subject() {
return EMAIL_SUBJECT;
}
@Override
protected String emailContent(Env env, ReleaseHistoryBO releaseHistory) {
return renderEmailCommonContent(env, releaseHistory);
}
@Override
protected String getTemplateFramework() {
return portalConfig.emailTemplateFramework();
}
@Override
protected String getDiffModuleTemplate() {
return portalConfig.emailReleaseDiffModuleTemplate();
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.component.emailbuilder;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO;
import org.springframework.stereotype.Component;
@Component
public class NormalPublishEmailBuilder extends ConfigPublishEmailBuilder {
private static final String EMAIL_SUBJECT = "[Apollo] 配置发布";
@Override
protected String subject() {
return EMAIL_SUBJECT;
}
@Override
protected String emailContent(Env env, ReleaseHistoryBO releaseHistory) {
return renderEmailCommonContent(env, releaseHistory);
}
@Override
protected String getTemplateFramework() {
return portalConfig.emailTemplateFramework();
}
@Override
protected String getDiffModuleTemplate() {
return portalConfig.emailReleaseDiffModuleTemplate();
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/condition/ConditionalOnProfile.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.condition;
import org.springframework.context.annotation.Conditional;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* {@link Conditional} that only matches when the specified profiles are active.
*
* @author Jason Song(song_s@ctrip.com)
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnProfileCondition.class)
public @interface ConditionalOnProfile {
/**
* The profiles that should be active
* @return
*/
String[] value() default {};
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.condition;
import org.springframework.context.annotation.Conditional;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* {@link Conditional} that only matches when the specified profiles are active.
*
* @author Jason Song(song_s@ctrip.com)
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnProfileCondition.class)
public @interface ConditionalOnProfile {
/**
* The profiles that should be active
* @return
*/
String[] value() default {};
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/utils/UniqueKeyGenerator.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.utils;
import com.google.common.base.Joiner;
import com.ctrip.framework.apollo.core.utils.ByteUtil;
import com.ctrip.framework.apollo.core.utils.MachineUtil;
import org.apache.commons.lang.time.FastDateFormat;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
public class UniqueKeyGenerator {
private static final FastDateFormat TIMESTAMP_FORMAT = FastDateFormat.getInstance("yyyyMMddHHmmss");
private static final AtomicInteger counter = new AtomicInteger(new SecureRandom().nextInt());
private static final Joiner KEY_JOINER = Joiner.on("-");
public static String generate(Object... args){
String hexIdString =
ByteUtil.toHexString(toByteArray(Objects.hash(args), MachineUtil.getMachineIdentifier(),
counter.incrementAndGet()));
return KEY_JOINER.join(TIMESTAMP_FORMAT.format(new Date()), hexIdString);
}
/**
* Concat machine id, counter and key to byte array
* Only retrieve lower 3 bytes of the id and counter and 2 bytes of the keyHashCode
*/
protected static byte[] toByteArray(int keyHashCode, int machineIdentifier, int counter) {
byte[] bytes = new byte[8];
bytes[0] = ByteUtil.int1(keyHashCode);
bytes[1] = ByteUtil.int0(keyHashCode);
bytes[2] = ByteUtil.int2(machineIdentifier);
bytes[3] = ByteUtil.int1(machineIdentifier);
bytes[4] = ByteUtil.int0(machineIdentifier);
bytes[5] = ByteUtil.int2(counter);
bytes[6] = ByteUtil.int1(counter);
bytes[7] = ByteUtil.int0(counter);
return bytes;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.utils;
import com.google.common.base.Joiner;
import com.ctrip.framework.apollo.core.utils.ByteUtil;
import com.ctrip.framework.apollo.core.utils.MachineUtil;
import org.apache.commons.lang.time.FastDateFormat;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
public class UniqueKeyGenerator {
private static final FastDateFormat TIMESTAMP_FORMAT = FastDateFormat.getInstance("yyyyMMddHHmmss");
private static final AtomicInteger counter = new AtomicInteger(new SecureRandom().nextInt());
private static final Joiner KEY_JOINER = Joiner.on("-");
public static String generate(Object... args){
String hexIdString =
ByteUtil.toHexString(toByteArray(Objects.hash(args), MachineUtil.getMachineIdentifier(),
counter.incrementAndGet()));
return KEY_JOINER.join(TIMESTAMP_FORMAT.format(new Date()), hexIdString);
}
/**
* Concat machine id, counter and key to byte array
* Only retrieve lower 3 bytes of the id and counter and 2 bytes of the keyHashCode
*/
protected static byte[] toByteArray(int keyHashCode, int machineIdentifier, int counter) {
byte[] bytes = new byte[8];
bytes[0] = ByteUtil.int1(keyHashCode);
bytes[1] = ByteUtil.int0(keyHashCode);
bytes[2] = ByteUtil.int2(machineIdentifier);
bytes[3] = ByteUtil.int1(machineIdentifier);
bytes[4] = ByteUtil.int0(machineIdentifier);
bytes[5] = ByteUtil.int2(counter);
bytes[6] = ByteUtil.int1(counter);
bytes[7] = ByteUtil.int0(counter);
return bytes;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/ConfigConsts.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core;
public interface ConfigConsts {
String NAMESPACE_APPLICATION = "application";
String CLUSTER_NAME_DEFAULT = "default";
String CLUSTER_NAMESPACE_SEPARATOR = "+";
String APOLLO_CLUSTER_KEY = "apollo.cluster";
String APOLLO_META_KEY = "apollo.meta";
String CONFIG_FILE_CONTENT_KEY = "content";
String NO_APPID_PLACEHOLDER = "ApolloNoAppIdPlaceHolder";
long NOTIFICATION_ID_PLACEHOLDER = -1;
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core;
public interface ConfigConsts {
String NAMESPACE_APPLICATION = "application";
String CLUSTER_NAME_DEFAULT = "default";
String CLUSTER_NAMESPACE_SEPARATOR = "+";
String APOLLO_CLUSTER_KEY = "apollo.cluster";
String APOLLO_META_KEY = "apollo.meta";
String CONFIG_FILE_CONTENT_KEY = "content";
String NO_APPID_PLACEHOLDER = "ApolloNoAppIdPlaceHolder";
long NOTIFICATION_ID_PLACEHOLDER = -1;
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-core/src/test/java/com/ctrip/framework/test/tools/AloneRunner.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.test.tools;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.JUnit4;
import org.junit.runners.model.InitializationError;
/**
* @author kl (http://kailing.pub)
* @since 2021/5/21
*/
public class AloneRunner extends Runner {
private static final String CONSTRUCTOR_ERROR_FORMAT = "Custom runner class %s should have a public constructor with signature %s(Class testClass)";
private final Runner realRunner;
private final ClassLoader testCaseClassloader;
public AloneRunner(Class<?> clazz) throws InitializationError {
AloneWith annotation = clazz.getAnnotation(
AloneWith.class);
Class<? extends Runner> realClassRunnerClass =
annotation == null ? JUnit4.class : annotation.value();
if (AloneRunner.class.isAssignableFrom(realClassRunnerClass)) {
throw new InitializationError("Dead-loop code");
}
testCaseClassloader = new AloneClassLoader();
ClassLoader backupClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(testCaseClassloader);
try {
Class<?> newTestCaseClass = testCaseClassloader.loadClass(clazz.getName());
Class<? extends Runner> realRunnerClass = (Class<? extends Runner>) testCaseClassloader
.loadClass(realClassRunnerClass.getName());
realRunner = buildRunner(realRunnerClass, newTestCaseClass);
} catch (ReflectiveOperationException e) {
throw new InitializationError(e);
} finally {
Thread.currentThread().setContextClassLoader(backupClassLoader);
}
}
public Description getDescription() {
return realRunner.getDescription();
}
public void run(RunNotifier runNotifier) {
ClassLoader backupClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(testCaseClassloader);
realRunner.run(runNotifier);
Thread.currentThread().setContextClassLoader(backupClassLoader);
}
protected Runner buildRunner(Class<? extends Runner> runnerClass,
Class<?> testClass) throws ReflectiveOperationException, InitializationError {
try {
return runnerClass.getConstructor(Class.class).newInstance(testClass);
} catch (NoSuchMethodException e) {
String simpleName = runnerClass.getSimpleName();
throw new InitializationError(String.format(
CONSTRUCTOR_ERROR_FORMAT, simpleName, simpleName));
}
}
} | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.test.tools;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.JUnit4;
import org.junit.runners.model.InitializationError;
/**
* @author kl (http://kailing.pub)
* @since 2021/5/21
*/
public class AloneRunner extends Runner {
private static final String CONSTRUCTOR_ERROR_FORMAT = "Custom runner class %s should have a public constructor with signature %s(Class testClass)";
private final Runner realRunner;
private final ClassLoader testCaseClassloader;
public AloneRunner(Class<?> clazz) throws InitializationError {
AloneWith annotation = clazz.getAnnotation(
AloneWith.class);
Class<? extends Runner> realClassRunnerClass =
annotation == null ? JUnit4.class : annotation.value();
if (AloneRunner.class.isAssignableFrom(realClassRunnerClass)) {
throw new InitializationError("Dead-loop code");
}
testCaseClassloader = new AloneClassLoader();
ClassLoader backupClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(testCaseClassloader);
try {
Class<?> newTestCaseClass = testCaseClassloader.loadClass(clazz.getName());
Class<? extends Runner> realRunnerClass = (Class<? extends Runner>) testCaseClassloader
.loadClass(realClassRunnerClass.getName());
realRunner = buildRunner(realRunnerClass, newTestCaseClass);
} catch (ReflectiveOperationException e) {
throw new InitializationError(e);
} finally {
Thread.currentThread().setContextClassLoader(backupClassLoader);
}
}
public Description getDescription() {
return realRunner.getDescription();
}
public void run(RunNotifier runNotifier) {
ClassLoader backupClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(testCaseClassloader);
realRunner.run(runNotifier);
Thread.currentThread().setContextClassLoader(backupClassLoader);
}
protected Runner buildRunner(Class<? extends Runner> runnerClass,
Class<?> testClass) throws ReflectiveOperationException, InitializationError {
try {
return runnerClass.getConstructor(Class.class).newInstance(testClass);
} catch (NoSuchMethodException e) {
String simpleName = runnerClass.getSimpleName();
throw new InitializationError(String.format(
CONSTRUCTOR_ERROR_FORMAT, simpleName, simpleName));
}
}
} | -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core.internals;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.spi.MetaServerProvider;
import com.ctrip.framework.apollo.core.utils.ResourceUtils;
import com.google.common.base.Strings;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* For legacy meta server configuration use, i.e. apollo-env.properties
*/
public class LegacyMetaServerProvider implements MetaServerProvider {
// make it as lowest as possible, yet not the lowest
public static final int ORDER = MetaServerProvider.LOWEST_PRECEDENCE - 1;
private static final Map<Env, String> domains = new HashMap<>();
public LegacyMetaServerProvider() {
initialize();
}
private void initialize() {
Properties prop = new Properties();
prop = ResourceUtils.readConfigFile("apollo-env.properties", prop);
domains.put(Env.LOCAL, getMetaServerAddress(prop, "local_meta", "local.meta"));
domains.put(Env.DEV, getMetaServerAddress(prop, "dev_meta", "dev.meta"));
domains.put(Env.FAT, getMetaServerAddress(prop, "fat_meta", "fat.meta"));
domains.put(Env.UAT, getMetaServerAddress(prop, "uat_meta", "uat.meta"));
domains.put(Env.LPT, getMetaServerAddress(prop, "lpt_meta", "lpt.meta"));
domains.put(Env.PRO, getMetaServerAddress(prop, "pro_meta", "pro.meta"));
}
private String getMetaServerAddress(Properties prop, String sourceName, String propName) {
// 1. Get from System Property.
String metaAddress = System.getProperty(sourceName);
if (Strings.isNullOrEmpty(metaAddress)) {
// 2. Get from OS environment variable, which could not contain dot and is normally in UPPER case,like DEV_META.
metaAddress = System.getenv(sourceName.toUpperCase());
}
if (Strings.isNullOrEmpty(metaAddress)) {
// 3. Get from properties file.
metaAddress = prop.getProperty(propName);
}
return metaAddress;
}
@Override
public String getMetaServerAddress(Env targetEnv) {
String metaServerAddress = domains.get(targetEnv);
return metaServerAddress == null ? null : metaServerAddress.trim();
}
@Override
public int getOrder() {
return ORDER;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core.internals;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.spi.MetaServerProvider;
import com.ctrip.framework.apollo.core.utils.ResourceUtils;
import com.google.common.base.Strings;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* For legacy meta server configuration use, i.e. apollo-env.properties
*/
public class LegacyMetaServerProvider implements MetaServerProvider {
// make it as lowest as possible, yet not the lowest
public static final int ORDER = MetaServerProvider.LOWEST_PRECEDENCE - 1;
private static final Map<Env, String> domains = new HashMap<>();
public LegacyMetaServerProvider() {
initialize();
}
private void initialize() {
Properties prop = new Properties();
prop = ResourceUtils.readConfigFile("apollo-env.properties", prop);
domains.put(Env.LOCAL, getMetaServerAddress(prop, "local_meta", "local.meta"));
domains.put(Env.DEV, getMetaServerAddress(prop, "dev_meta", "dev.meta"));
domains.put(Env.FAT, getMetaServerAddress(prop, "fat_meta", "fat.meta"));
domains.put(Env.UAT, getMetaServerAddress(prop, "uat_meta", "uat.meta"));
domains.put(Env.LPT, getMetaServerAddress(prop, "lpt_meta", "lpt.meta"));
domains.put(Env.PRO, getMetaServerAddress(prop, "pro_meta", "pro.meta"));
}
private String getMetaServerAddress(Properties prop, String sourceName, String propName) {
// 1. Get from System Property.
String metaAddress = System.getProperty(sourceName);
if (Strings.isNullOrEmpty(metaAddress)) {
// 2. Get from OS environment variable, which could not contain dot and is normally in UPPER case,like DEV_META.
metaAddress = System.getenv(sourceName.toUpperCase());
}
if (Strings.isNullOrEmpty(metaAddress)) {
// 3. Get from properties file.
metaAddress = prop.getProperty(propName);
}
return metaAddress;
}
@Override
public String getMetaServerAddress(Env targetEnv) {
String metaServerAddress = domains.get(targetEnv);
return metaServerAddress == null ? null : metaServerAddress.trim();
}
@Override
public int getOrder() {
return ORDER;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/test/java/com/ctrip/framework/apollo/biz/service/AdminServiceTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.service;
import com.ctrip.framework.apollo.biz.AbstractIntegrationTest;
import com.ctrip.framework.apollo.biz.entity.Audit;
import com.ctrip.framework.apollo.biz.entity.Cluster;
import com.ctrip.framework.apollo.biz.entity.Namespace;
import com.ctrip.framework.apollo.biz.repository.AppRepository;
import com.ctrip.framework.apollo.common.entity.App;
import com.ctrip.framework.apollo.common.exception.ServiceException;
import com.ctrip.framework.apollo.core.ConfigConsts;
import java.util.Date;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class AdminServiceTest extends AbstractIntegrationTest {
@Autowired
private AdminService adminService;
@Autowired
private AuditService auditService;
@Autowired
private AppRepository appRepository;
@Autowired
private ClusterService clusterService;
@Autowired
private NamespaceService namespaceService;
@Autowired
private AppNamespaceService appNamespaceService;
@Test
public void testCreateNewApp() {
String appId = "someAppId";
App app = new App();
app.setAppId(appId);
app.setName("someAppName");
String owner = "someOwnerName";
app.setOwnerName(owner);
app.setOwnerEmail("someOwnerName@ctrip.com");
app.setDataChangeCreatedBy(owner);
app.setDataChangeLastModifiedBy(owner);
app.setDataChangeCreatedTime(new Date());
app = adminService.createNewApp(app);
Assert.assertEquals(appId, app.getAppId());
List<Cluster> clusters = clusterService.findParentClusters(app.getAppId());
Assert.assertEquals(1, clusters.size());
Assert.assertEquals(ConfigConsts.CLUSTER_NAME_DEFAULT, clusters.get(0).getName());
List<Namespace> namespaces = namespaceService.findNamespaces(appId, clusters.get(0).getName());
Assert.assertEquals(1, namespaces.size());
Assert.assertEquals(ConfigConsts.NAMESPACE_APPLICATION, namespaces.get(0).getNamespaceName());
List<Audit> audits = auditService.findByOwner(owner);
Assert.assertEquals(4, audits.size());
}
@Test(expected = ServiceException.class)
public void testCreateDuplicateApp() {
String appId = "someAppId";
App app = new App();
app.setAppId(appId);
app.setName("someAppName");
String owner = "someOwnerName";
app.setOwnerName(owner);
app.setOwnerEmail("someOwnerName@ctrip.com");
app.setDataChangeCreatedBy(owner);
app.setDataChangeLastModifiedBy(owner);
app.setDataChangeCreatedTime(new Date());
appRepository.save(app);
adminService.createNewApp(app);
}
@Test
public void testDeleteApp() {
String appId = "someAppId";
App app = new App();
app.setAppId(appId);
app.setName("someAppName");
String owner = "someOwnerName";
app.setOwnerName(owner);
app.setOwnerEmail("someOwnerName@ctrip.com");
app.setDataChangeCreatedBy(owner);
app.setDataChangeLastModifiedBy(owner);
app.setDataChangeCreatedTime(new Date());
app = adminService.createNewApp(app);
Assert.assertEquals(appId, app.getAppId());
Assert.assertEquals(1, appNamespaceService.findByAppId(appId).size());
Assert.assertEquals(1, clusterService.findClusters(appId).size());
Assert.assertEquals(1, namespaceService.findNamespaces(appId, ConfigConsts.CLUSTER_NAME_DEFAULT).size());
adminService.deleteApp(app, owner);
Assert.assertEquals(0, appNamespaceService.findByAppId(appId).size());
Assert.assertEquals(0, clusterService.findClusters(appId).size());
Assert
.assertEquals(0, namespaceService.findByAppIdAndNamespaceName(appId, ConfigConsts.CLUSTER_NAME_DEFAULT).size());
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.service;
import com.ctrip.framework.apollo.biz.AbstractIntegrationTest;
import com.ctrip.framework.apollo.biz.entity.Audit;
import com.ctrip.framework.apollo.biz.entity.Cluster;
import com.ctrip.framework.apollo.biz.entity.Namespace;
import com.ctrip.framework.apollo.biz.repository.AppRepository;
import com.ctrip.framework.apollo.common.entity.App;
import com.ctrip.framework.apollo.common.exception.ServiceException;
import com.ctrip.framework.apollo.core.ConfigConsts;
import java.util.Date;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class AdminServiceTest extends AbstractIntegrationTest {
@Autowired
private AdminService adminService;
@Autowired
private AuditService auditService;
@Autowired
private AppRepository appRepository;
@Autowired
private ClusterService clusterService;
@Autowired
private NamespaceService namespaceService;
@Autowired
private AppNamespaceService appNamespaceService;
@Test
public void testCreateNewApp() {
String appId = "someAppId";
App app = new App();
app.setAppId(appId);
app.setName("someAppName");
String owner = "someOwnerName";
app.setOwnerName(owner);
app.setOwnerEmail("someOwnerName@ctrip.com");
app.setDataChangeCreatedBy(owner);
app.setDataChangeLastModifiedBy(owner);
app.setDataChangeCreatedTime(new Date());
app = adminService.createNewApp(app);
Assert.assertEquals(appId, app.getAppId());
List<Cluster> clusters = clusterService.findParentClusters(app.getAppId());
Assert.assertEquals(1, clusters.size());
Assert.assertEquals(ConfigConsts.CLUSTER_NAME_DEFAULT, clusters.get(0).getName());
List<Namespace> namespaces = namespaceService.findNamespaces(appId, clusters.get(0).getName());
Assert.assertEquals(1, namespaces.size());
Assert.assertEquals(ConfigConsts.NAMESPACE_APPLICATION, namespaces.get(0).getNamespaceName());
List<Audit> audits = auditService.findByOwner(owner);
Assert.assertEquals(4, audits.size());
}
@Test(expected = ServiceException.class)
public void testCreateDuplicateApp() {
String appId = "someAppId";
App app = new App();
app.setAppId(appId);
app.setName("someAppName");
String owner = "someOwnerName";
app.setOwnerName(owner);
app.setOwnerEmail("someOwnerName@ctrip.com");
app.setDataChangeCreatedBy(owner);
app.setDataChangeLastModifiedBy(owner);
app.setDataChangeCreatedTime(new Date());
appRepository.save(app);
adminService.createNewApp(app);
}
@Test
public void testDeleteApp() {
String appId = "someAppId";
App app = new App();
app.setAppId(appId);
app.setName("someAppName");
String owner = "someOwnerName";
app.setOwnerName(owner);
app.setOwnerEmail("someOwnerName@ctrip.com");
app.setDataChangeCreatedBy(owner);
app.setDataChangeLastModifiedBy(owner);
app.setDataChangeCreatedTime(new Date());
app = adminService.createNewApp(app);
Assert.assertEquals(appId, app.getAppId());
Assert.assertEquals(1, appNamespaceService.findByAppId(appId).size());
Assert.assertEquals(1, clusterService.findClusters(appId).size());
Assert.assertEquals(1, namespaceService.findNamespaces(appId, ConfigConsts.CLUSTER_NAME_DEFAULT).size());
adminService.deleteApp(app, owner);
Assert.assertEquals(0, appNamespaceService.findByAppId(appId).size());
Assert.assertEquals(0, clusterService.findClusters(appId).size());
Assert
.assertEquals(0, namespaceService.findByAppIdAndNamespaceName(appId, ConfigConsts.CLUSTER_NAME_DEFAULT).size());
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/util/Slf4jLogMessageFormatter.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.util;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.core.log.LogMessage;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class Slf4jLogMessageFormatter {
/**
* format log message
*
* @param pattern slf4j log message patten
* @param args log message args
* @return string
*/
public static LogMessage format(String pattern, Object... args) {
return LogMessage.of(() -> MessageFormatter.arrayFormat(pattern, args, null).getMessage());
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.util;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.core.log.LogMessage;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class Slf4jLogMessageFormatter {
/**
* format log message
*
* @param pattern slf4j log message patten
* @param args log message args
* @return string
*/
public static LogMessage format(String pattern, Object... args) {
return LogMessage.of(() -> MessageFormatter.arrayFormat(pattern, args, null).getMessage());
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/repository/ServerConfigRepository.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.repository;
import com.ctrip.framework.apollo.portal.entity.po.ServerConfig;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface ServerConfigRepository extends PagingAndSortingRepository<ServerConfig, Long> {
ServerConfig findByKey(String key);
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.repository;
import com.ctrip.framework.apollo.portal.entity.po.ServerConfig;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface ServerConfigRepository extends PagingAndSortingRepository<ServerConfig, Long> {
ServerConfig findByKey(String key);
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.tracer.spi;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface MessageProducer {
/**
* Log an error.
*
* @param cause root cause exception
*/
void logError(Throwable cause);
/**
* Log an error.
*
* @param cause root cause exception
*/
void logError(String message, Throwable cause);
/**
* Log an event in one shot with SUCCESS status.
*
* @param type event type
* @param name event name
*/
void logEvent(String type, String name);
/**
* Log an event in one shot.
*
* @param type event type
* @param name event name
* @param status "0" means success, otherwise means error code
* @param nameValuePairs name value pairs in the format of "a=1&b=2&..."
*/
void logEvent(String type, String name, String status, String nameValuePairs);
/**
* Create a new transaction with given type and name.
*
* @param type transaction type
* @param name transaction name
*/
Transaction newTransaction(String type, String name);
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.tracer.spi;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface MessageProducer {
/**
* Log an error.
*
* @param cause root cause exception
*/
void logError(Throwable cause);
/**
* Log an error.
*
* @param cause root cause exception
*/
void logError(String message, Throwable cause);
/**
* Log an event in one shot with SUCCESS status.
*
* @param type event type
* @param name event name
*/
void logEvent(String type, String name);
/**
* Log an event in one shot.
*
* @param type event type
* @param name event name
* @param status "0" means success, otherwise means error code
* @param nameValuePairs name value pairs in the format of "a=1&b=2&..."
*/
void logEvent(String type, String name, String status, String nameValuePairs);
/**
* Create a new transaction with given type and name.
*
* @param type transaction type
* @param name transaction name
*/
Transaction newTransaction(String type, String name);
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/springsecurity/ApolloPasswordEncoderFactory.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.spi.springsecurity;
import com.ctrip.framework.apollo.portal.spi.oidc.PlaceholderPasswordEncoder;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public final class ApolloPasswordEncoderFactory {
private ApolloPasswordEncoderFactory() {
}
/**
* Creates a {@link DelegatingPasswordEncoder} with default mappings {@link
* PasswordEncoderFactories#createDelegatingPasswordEncoder()}, and add a placeholder encoder for
* oidc {@link PlaceholderPasswordEncoder}
*
* @return the {@link PasswordEncoder} to use
*/
@SuppressWarnings("deprecation")
public static PasswordEncoder createDelegatingPasswordEncoder() {
// copy from PasswordEncoderFactories, and it's should follow the upgrade of the PasswordEncoderFactories
String encodingId = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put(encodingId, new BCryptPasswordEncoder());
encoders.put("ldap", new org.springframework.security.crypto.password.LdapShaPasswordEncoder());
encoders.put("MD4", new org.springframework.security.crypto.password.Md4PasswordEncoder());
encoders.put("MD5",
new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5"));
encoders.put("noop",
org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance());
encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
encoders.put("SHA-1",
new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-1"));
encoders.put("SHA-256",
new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-256"));
encoders
.put("sha256", new org.springframework.security.crypto.password.StandardPasswordEncoder());
encoders.put("argon2", new Argon2PasswordEncoder());
// placeholder encoder for oidc
encoders.put(PlaceholderPasswordEncoder.ENCODING_ID, new PlaceholderPasswordEncoder());
DelegatingPasswordEncoder delegatingPasswordEncoder = new DelegatingPasswordEncoder(encodingId,
encoders);
// todo: adapt the old password, and it should be removed in the next feature version of the 1.9.x
delegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(new PasswordEncoderAdapter(encoders.get(encodingId)));
return delegatingPasswordEncoder;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.spi.springsecurity;
import com.ctrip.framework.apollo.portal.spi.oidc.PlaceholderPasswordEncoder;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public final class ApolloPasswordEncoderFactory {
private ApolloPasswordEncoderFactory() {
}
/**
* Creates a {@link DelegatingPasswordEncoder} with default mappings {@link
* PasswordEncoderFactories#createDelegatingPasswordEncoder()}, and add a placeholder encoder for
* oidc {@link PlaceholderPasswordEncoder}
*
* @return the {@link PasswordEncoder} to use
*/
@SuppressWarnings("deprecation")
public static PasswordEncoder createDelegatingPasswordEncoder() {
// copy from PasswordEncoderFactories, and it's should follow the upgrade of the PasswordEncoderFactories
String encodingId = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put(encodingId, new BCryptPasswordEncoder());
encoders.put("ldap", new org.springframework.security.crypto.password.LdapShaPasswordEncoder());
encoders.put("MD4", new org.springframework.security.crypto.password.Md4PasswordEncoder());
encoders.put("MD5",
new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5"));
encoders.put("noop",
org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance());
encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
encoders.put("SHA-1",
new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-1"));
encoders.put("SHA-256",
new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-256"));
encoders
.put("sha256", new org.springframework.security.crypto.password.StandardPasswordEncoder());
encoders.put("argon2", new Argon2PasswordEncoder());
// placeholder encoder for oidc
encoders.put(PlaceholderPasswordEncoder.ENCODING_ID, new PlaceholderPasswordEncoder());
DelegatingPasswordEncoder delegatingPasswordEncoder = new DelegatingPasswordEncoder(encodingId,
encoders);
// todo: adapt the old password, and it should be removed in the next feature version of the 1.9.x
delegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(new PasswordEncoderAdapter(encoders.get(encodingId)));
return delegatingPasswordEncoder;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/EnableApolloConfig.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import com.ctrip.framework.apollo.core.ConfigConsts;
/**
* Use this annotation to register Apollo property sources when using Java Config.
*
* <p>Configuration example with multiple namespaces:</p>
* <pre class="code">
* @Configuration
* @EnableApolloConfig({"someNamespace","anotherNamespace"})
* public class AppConfig {
*
* }
* </pre>
*
* <p>Configuration example with placeholder:</p>
* <pre class="code">
* // The namespace could also be specified as a placeholder, e.g. ${redis.namespace:xxx},
* // which will use the value of the key "redis.namespace" or "xxx" if this key is not configured.
* // Please note that this placeholder could not be configured in Apollo as Apollo is not activated during this phase.
* @Configuration
* @EnableApolloConfig({"${redis.namespace:xxx}"})
* public class AppConfig {
*
* }
* </pre>
*
* @author Jason Song(song_s@ctrip.com)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(ApolloConfigRegistrar.class)
public @interface EnableApolloConfig {
/**
* Apollo namespaces to inject configuration into Spring Property Sources.
*/
String[] value() default {ConfigConsts.NAMESPACE_APPLICATION};
/**
* The order of the apollo config, default is {@link Ordered#LOWEST_PRECEDENCE}, which is Integer.MAX_VALUE.
* If there are properties with the same name in different apollo configs, the apollo config with smaller order wins.
* @return
*/
int order() default Ordered.LOWEST_PRECEDENCE;
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import com.ctrip.framework.apollo.core.ConfigConsts;
/**
* Use this annotation to register Apollo property sources when using Java Config.
*
* <p>Configuration example with multiple namespaces:</p>
* <pre class="code">
* @Configuration
* @EnableApolloConfig({"someNamespace","anotherNamespace"})
* public class AppConfig {
*
* }
* </pre>
*
* <p>Configuration example with placeholder:</p>
* <pre class="code">
* // The namespace could also be specified as a placeholder, e.g. ${redis.namespace:xxx},
* // which will use the value of the key "redis.namespace" or "xxx" if this key is not configured.
* // Please note that this placeholder could not be configured in Apollo as Apollo is not activated during this phase.
* @Configuration
* @EnableApolloConfig({"${redis.namespace:xxx}"})
* public class AppConfig {
*
* }
* </pre>
*
* @author Jason Song(song_s@ctrip.com)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(ApolloConfigRegistrar.class)
public @interface EnableApolloConfig {
/**
* Apollo namespaces to inject configuration into Spring Property Sources.
*/
String[] value() default {ConfigConsts.NAMESPACE_APPLICATION};
/**
* The order of the apollo config, default is {@link Ordered#LOWEST_PRECEDENCE}, which is Integer.MAX_VALUE.
* If there are properties with the same name in different apollo configs, the apollo config with smaller order wins.
* @return
*/
int order() default Ordered.LOWEST_PRECEDENCE;
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenGrayReleaseRuleDTO.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.dto;
import java.util.Set;
public class OpenGrayReleaseRuleDTO extends BaseDTO{
private String appId;
private String clusterName;
private String namespaceName;
private String branchName;
private Set<OpenGrayReleaseRuleItemDTO> ruleItems;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public String getNamespaceName() {
return namespaceName;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public String getBranchName() {
return branchName;
}
public void setBranchName(String branchName) {
this.branchName = branchName;
}
public Set<OpenGrayReleaseRuleItemDTO> getRuleItems() {
return ruleItems;
}
public void setRuleItems(Set<OpenGrayReleaseRuleItemDTO> ruleItems) {
this.ruleItems = ruleItems;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.dto;
import java.util.Set;
public class OpenGrayReleaseRuleDTO extends BaseDTO{
private String appId;
private String clusterName;
private String namespaceName;
private String branchName;
private Set<OpenGrayReleaseRuleItemDTO> ruleItems;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public String getNamespaceName() {
return namespaceName;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public String getBranchName() {
return branchName;
}
public void setBranchName(String branchName) {
this.branchName = branchName;
}
public Set<OpenGrayReleaseRuleItemDTO> getRuleItems() {
return ruleItems;
}
public void setRuleItems(Set<OpenGrayReleaseRuleItemDTO> ruleItems) {
this.ruleItems = ruleItems;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/ClusterOpenApiServiceTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.client.service;
import static org.junit.Assert.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.openapi.dto.OpenClusterDTO;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
public class ClusterOpenApiServiceTest extends AbstractOpenApiServiceTest {
private ClusterOpenApiService clusterOpenApiService;
private String someAppId;
private String someEnv;
@Before
public void setUp() throws Exception {
super.setUp();
someAppId = "someAppId";
someEnv = "someEnv";
StringEntity responseEntity = new StringEntity("{}");
when(someHttpResponse.getEntity()).thenReturn(responseEntity);
clusterOpenApiService = new ClusterOpenApiService(httpClient, someBaseUrl, gson);
}
@Test
public void testGetCluster() throws Exception {
String someCluster = "someCluster";
final ArgumentCaptor<HttpGet> request = ArgumentCaptor.forClass(HttpGet.class);
clusterOpenApiService.getCluster(someAppId, someEnv, someCluster);
verify(httpClient, times(1)).execute(request.capture());
HttpGet get = request.getValue();
assertEquals(String
.format("%s/envs/%s/apps/%s/clusters/%s", someBaseUrl, someEnv, someAppId, someCluster),
get.getURI().toString());
}
@Test(expected = RuntimeException.class)
public void testGetClusterWithError() throws Exception {
String someCluster = "someCluster";
when(statusLine.getStatusCode()).thenReturn(404);
clusterOpenApiService.getCluster(someAppId, someEnv, someCluster);
}
@Test
public void testCreateCluster() throws Exception {
String someCluster = "someCluster";
String someCreatedBy = "someCreatedBy";
OpenClusterDTO clusterDTO = new OpenClusterDTO();
clusterDTO.setAppId(someAppId);
clusterDTO.setName(someCluster);
clusterDTO.setDataChangeCreatedBy(someCreatedBy);
final ArgumentCaptor<HttpPost> request = ArgumentCaptor.forClass(HttpPost.class);
clusterOpenApiService.createCluster(someEnv, clusterDTO);
verify(httpClient, times(1)).execute(request.capture());
HttpPost post = request.getValue();
assertEquals(String
.format("%s/envs/%s/apps/%s/clusters", someBaseUrl, someEnv, someAppId), post.getURI().toString());
StringEntity entity = (StringEntity) post.getEntity();
assertEquals(ContentType.APPLICATION_JSON.toString(), entity.getContentType().getValue());
assertEquals(gson.toJson(clusterDTO), EntityUtils.toString(entity));
}
@Test(expected = RuntimeException.class)
public void testCreateClusterWithError() throws Exception {
String someCluster = "someCluster";
String someCreatedBy = "someCreatedBy";
OpenClusterDTO clusterDTO = new OpenClusterDTO();
clusterDTO.setAppId(someAppId);
clusterDTO.setName(someCluster);
clusterDTO.setDataChangeCreatedBy(someCreatedBy);
when(statusLine.getStatusCode()).thenReturn(400);
clusterOpenApiService.createCluster(someEnv, clusterDTO);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.client.service;
import static org.junit.Assert.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.openapi.dto.OpenClusterDTO;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
public class ClusterOpenApiServiceTest extends AbstractOpenApiServiceTest {
private ClusterOpenApiService clusterOpenApiService;
private String someAppId;
private String someEnv;
@Before
public void setUp() throws Exception {
super.setUp();
someAppId = "someAppId";
someEnv = "someEnv";
StringEntity responseEntity = new StringEntity("{}");
when(someHttpResponse.getEntity()).thenReturn(responseEntity);
clusterOpenApiService = new ClusterOpenApiService(httpClient, someBaseUrl, gson);
}
@Test
public void testGetCluster() throws Exception {
String someCluster = "someCluster";
final ArgumentCaptor<HttpGet> request = ArgumentCaptor.forClass(HttpGet.class);
clusterOpenApiService.getCluster(someAppId, someEnv, someCluster);
verify(httpClient, times(1)).execute(request.capture());
HttpGet get = request.getValue();
assertEquals(String
.format("%s/envs/%s/apps/%s/clusters/%s", someBaseUrl, someEnv, someAppId, someCluster),
get.getURI().toString());
}
@Test(expected = RuntimeException.class)
public void testGetClusterWithError() throws Exception {
String someCluster = "someCluster";
when(statusLine.getStatusCode()).thenReturn(404);
clusterOpenApiService.getCluster(someAppId, someEnv, someCluster);
}
@Test
public void testCreateCluster() throws Exception {
String someCluster = "someCluster";
String someCreatedBy = "someCreatedBy";
OpenClusterDTO clusterDTO = new OpenClusterDTO();
clusterDTO.setAppId(someAppId);
clusterDTO.setName(someCluster);
clusterDTO.setDataChangeCreatedBy(someCreatedBy);
final ArgumentCaptor<HttpPost> request = ArgumentCaptor.forClass(HttpPost.class);
clusterOpenApiService.createCluster(someEnv, clusterDTO);
verify(httpClient, times(1)).execute(request.capture());
HttpPost post = request.getValue();
assertEquals(String
.format("%s/envs/%s/apps/%s/clusters", someBaseUrl, someEnv, someAppId), post.getURI().toString());
StringEntity entity = (StringEntity) post.getEntity();
assertEquals(ContentType.APPLICATION_JSON.toString(), entity.getContentType().getValue());
assertEquals(gson.toJson(clusterDTO), EntityUtils.toString(entity));
}
@Test(expected = RuntimeException.class)
public void testCreateClusterWithError() throws Exception {
String someCluster = "someCluster";
String someCreatedBy = "someCreatedBy";
OpenClusterDTO clusterDTO = new OpenClusterDTO();
clusterDTO.setAppId(someAppId);
clusterDTO.setName(someCluster);
clusterDTO.setDataChangeCreatedBy(someCreatedBy);
when(statusLine.getStatusCode()).thenReturn(400);
clusterOpenApiService.createCluster(someEnv, clusterDTO);
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/repository/AppNamespaceRepository.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
import java.util.Set;
public interface AppNamespaceRepository extends PagingAndSortingRepository<AppNamespace, Long>{
AppNamespace findByAppIdAndName(String appId, String namespaceName);
List<AppNamespace> findByAppIdAndNameIn(String appId, Set<String> namespaceNames);
AppNamespace findByNameAndIsPublicTrue(String namespaceName);
List<AppNamespace> findByNameInAndIsPublicTrue(Set<String> namespaceNames);
List<AppNamespace> findByAppIdAndIsPublic(String appId, boolean isPublic);
List<AppNamespace> findByAppId(String appId);
List<AppNamespace> findFirst500ByIdGreaterThanOrderByIdAsc(long id);
@Modifying
@Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?2 WHERE AppId=?1")
int batchDeleteByAppId(String appId, String operator);
@Modifying
@Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?3 WHERE AppId=?1 and Name = ?2")
int delete(String appId, String namespaceName, String operator);
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
import java.util.Set;
public interface AppNamespaceRepository extends PagingAndSortingRepository<AppNamespace, Long>{
AppNamespace findByAppIdAndName(String appId, String namespaceName);
List<AppNamespace> findByAppIdAndNameIn(String appId, Set<String> namespaceNames);
AppNamespace findByNameAndIsPublicTrue(String namespaceName);
List<AppNamespace> findByNameInAndIsPublicTrue(Set<String> namespaceNames);
List<AppNamespace> findByAppIdAndIsPublic(String appId, boolean isPublic);
List<AppNamespace> findByAppId(String appId);
List<AppNamespace> findFirst500ByIdGreaterThanOrderByIdAsc(long id);
@Modifying
@Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?2 WHERE AppId=?1")
int batchDeleteByAppId(String appId, String operator);
@Modifying
@Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?3 WHERE AppId=?1 and Name = ?2")
int delete(String appId, String namespaceName, String operator);
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/dto/InstanceDTO.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.dto;
import java.util.Date;
import java.util.List;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class InstanceDTO {
private long id;
private String appId;
private String clusterName;
private String dataCenter;
private String ip;
private List<InstanceConfigDTO> configs;
private Date dataChangeCreatedTime;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public String getDataCenter() {
return dataCenter;
}
public void setDataCenter(String dataCenter) {
this.dataCenter = dataCenter;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public List<InstanceConfigDTO> getConfigs() {
return configs;
}
public void setConfigs(List<InstanceConfigDTO> configs) {
this.configs = configs;
}
public Date getDataChangeCreatedTime() {
return dataChangeCreatedTime;
}
public void setDataChangeCreatedTime(Date dataChangeCreatedTime) {
this.dataChangeCreatedTime = dataChangeCreatedTime;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.dto;
import java.util.Date;
import java.util.List;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class InstanceDTO {
private long id;
private String appId;
private String clusterName;
private String dataCenter;
private String ip;
private List<InstanceConfigDTO> configs;
private Date dataChangeCreatedTime;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public String getDataCenter() {
return dataCenter;
}
public void setDataCenter(String dataCenter) {
this.dataCenter = dataCenter;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public List<InstanceConfigDTO> getConfigs() {
return configs;
}
public void setConfigs(List<InstanceConfigDTO> configs) {
this.configs = configs;
}
public Date getDataChangeCreatedTime() {
return dataChangeCreatedTime;
}
public void setDataChangeCreatedTime(Date dataChangeCreatedTime) {
this.dataChangeCreatedTime = dataChangeCreatedTime;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/repository/ItemRepository.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.biz.entity.Item;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
import java.util.List;
public interface ItemRepository extends PagingAndSortingRepository<Item, Long> {
Item findByNamespaceIdAndKey(Long namespaceId, String key);
List<Item> findByNamespaceIdOrderByLineNumAsc(Long namespaceId);
List<Item> findByNamespaceId(Long namespaceId);
List<Item> findByNamespaceIdAndDataChangeLastModifiedTimeGreaterThan(Long namespaceId, Date date);
Item findFirst1ByNamespaceIdOrderByLineNumDesc(Long namespaceId);
@Modifying
@Query("update Item set isdeleted=1,DataChange_LastModifiedBy = ?2 where namespaceId = ?1")
int deleteByNamespaceId(long namespaceId, String operator);
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.biz.entity.Item;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
import java.util.List;
public interface ItemRepository extends PagingAndSortingRepository<Item, Long> {
Item findByNamespaceIdAndKey(Long namespaceId, String key);
List<Item> findByNamespaceIdOrderByLineNumAsc(Long namespaceId);
List<Item> findByNamespaceId(Long namespaceId);
List<Item> findByNamespaceIdAndDataChangeLastModifiedTimeGreaterThan(Long namespaceId, Date date);
Item findFirst1ByNamespaceIdOrderByLineNumDesc(Long namespaceId);
@Modifying
@Query("update Item set isdeleted=1,DataChange_LastModifiedBy = ?2 where namespaceId = ?1")
int deleteByNamespaceId(long namespaceId, String operator);
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./docs/zh/design/apollo-core-concept-namespace.md | ### 1. 什么是Namespace?
Namespace是配置项的集合,类似于一个配置文件的概念。
### 2. 什么是“application”的Namespace?
Apollo在创建项目的时候,都会默认创建一个“application”的Namespace。顾名思义,“application”是给应用自身使用的,熟悉Spring Boot的同学都知道,Spring Boot项目都有一个默认配置文件application.yml。在这里application.yml就等同于“application”的Namespace。对于90%的应用来说,“application”的Namespace已经满足日常配置使用场景了。
#### 客户端获取“application” Namespace的代码如下:
``` java
Config config = ConfigService.getAppConfig();
```
#### 客户端获取非“application” Namespace的代码如下:
``` java
Config config = ConfigService.getConfig(namespaceName);
```
### 3. Namespace的格式有哪些?
配置文件有多种格式,例如:properties、xml、yml、yaml、json等。同样Namespace也具有这些格式。在Portal UI中可以看到“application”的Namespace上有一个“properties”标签,表明“application”是properties格式的。
>注1:非properties格式的namespace,在客户端使用时需要调用`ConfigService.getConfigFile(String namespace, ConfigFileFormat configFileFormat)`来获取,如果使用[Http接口直接调用](zh/usage/other-language-client-user-guide#_12-通过带缓存的http接口从apollo读取配置)时,对应的namespace参数需要传入namespace的名字加上后缀名,如datasources.json。
>注2:apollo-client 1.3.0版本开始对yaml/yml做了更好的支持,使用起来和properties格式一致:`Config config = ConfigService.getConfig("application.yml");`,Spring的注入方式也和properties一致。
### 4. Namespace的获取权限分类
Namespace的获取权限分为两种:
* private (私有的)
* public (公共的)
这里的获取权限是相对于Apollo客户端来说的。
#### 4.1 private权限
private权限的Namespace,只能被所属的应用获取到。一个应用尝试获取其它应用private的Namespace,Apollo会报“404”异常。
#### 4.2 public权限
public权限的Namespace,能被任何应用获取。
### 5. Namespace的类型
Namespace类型有三种:
* 私有类型
* 公共类型
* 关联类型(继承类型)
#### 5.1 私有类型
私有类型的Namespace具有private权限。例如上文提到的“application” Namespace就是私有类型。
#### 5.2 公共类型
##### 5.2.1 含义
公共类型的Namespace具有public权限。公共类型的Namespace相当于游离于应用之外的配置,且通过Namespace的名称去标识公共Namespace,所以公共的Namespace的名称必须全局唯一。
##### 5.2.2 使用场景
* 部门级别共享的配置
* 小组级别共享的配置
* 几个项目之间共享的配置
* 中间件客户端的配置
#### 5.3 关联类型
##### 5.3.1 含义
关联类型又可称为继承类型,关联类型具有private权限。关联类型的Namespace继承于公共类型的Namespace,用于覆盖公共Namespace的某些配置。例如公共的Namespace有两个配置项
```
k1 = v1
k2 = v2
```
然后应用A有一个关联类型的Namespace关联了此公共Namespace,且覆盖了配置项k1,新值为v3。那么在应用A实际运行时,获取到的公共Namespace的配置为:
```
k1 = v3
k2 = v2
```
##### 5.3.2 使用场景
举一个实际使用的场景。假设RPC框架的配置(如:timeout)有以下要求:
* 提供一份全公司默认的配置且可动态调整
* RPC客户端项目可以自定义某些配置项且可动态调整
1. 如果把以上两点要求去掉“动态调整”,那么做法很简单。在rpc-client.jar包里有一份配置文件,每次修改配置文件然后重新发一个版本的jar包即可。同理,客户端项目修改配置也是如此。
2. 如果只支持客户端项目可动态调整配置。客户端项目可以在Apollo “application” Namespace上配置一些配置项。在初始化service的时候,从Apollo上读取配置即可。这样做的坏处就是,每个项目都要自定义一些key,不统一。
3. 那么如何完美支持以上需求呢?答案就是结合使用Apollo的公共类型的Namespace和关联类型的Namespace。RPC团队在Apollo上维护一个叫“rpc-client”的公共Namespace,在“rpc-client” Namespace上配置默认的参数值。rpc-client.jar里的代码读取“rpc-client”Namespace的配置即可。如果需要调整默认的配置,只需要修改公共类型“rpc-client” Namespace的配置。如果客户端项目想要自定义或动态修改某些配置项,只需要在Apollo 自己项目下关联“rpc-client”,就能创建关联类型“rpc-client”的Namespace。然后在关联类型“rpc-client”的Namespace下修改配置项即可。这里有一点需要指出的,那就是rpc-client.jar是在应用容器里运行的,所以rpc-client获取到的“rpc-client” Namespace的配置是应用的关联类型的Namespace加上公共类型的Namespace。
#### 5.4 例子
如下图所示,有三个应用:应用A、应用B、应用C。
* 应用A有两个私有类型的Namespace:application和NS-Private,以及一个关联类型的Namespace:NS-Public。
* 应用B有一个私有类型的Namespace:application,以及一个公共类型的Namespace:NS-Public。
* 应用C只有一个私有类型的Namespace:application

##### 5.4.1 应用A获取Apollo配置
```java
//application
Config appConfig = ConfigService.getAppConfig();
appConfig.getProperty("k1", null); // k1 = v11
appConfig.getProperty("k2", null); // k2 = v21
//NS-Private
Config privateConfig = ConfigService.getConfig("NS-Private");
privateConfig.getProperty("k1", null); // k1 = v3
privateConfig.getProperty("k3", null); // k3 = v4
//NS-Public,覆盖公共类型配置的情况,k4被覆盖
Config publicConfig = ConfigService.getConfig("NS-Public");
publicConfig.getProperty("k4", null); // k4 = v6 cover
publicConfig.getProperty("k6", null); // k6 = v6
publicConfig.getProperty("k7", null); // k7 = v7
```
##### 5.4.2 应用B获取Apollo配置
```java
//application
Config appConfig = ConfigService.getAppConfig();
appConfig.getProperty("k1", null); // k1 = v12
appConfig.getProperty("k2", null); // k2 = null
appConfig.getProperty("k3", null); // k3 = v32
//NS-Private,由于没有NS-Private Namespace 所以获取到default value
Config privateConfig = ConfigService.getConfig("NS-Private");
privateConfig.getProperty("k1", "default value");
//NS-Public
Config publicConfig = ConfigService.getConfig("NS-Public");
publicConfig.getProperty("k4", null); // k4 = v5
publicConfig.getProperty("k6", null); // k6 = v6
publicConfig.getProperty("k7", null); // k7 = v7
```
##### 5.4.3 应用C获取Apollo配置
```java
//application
Config appConfig = ConfigService.getAppConfig();
appConfig.getProperty("k1", null); // k1 = v12
appConfig.getProperty("k2", null); // k2 = null
appConfig.getProperty("k3", null); // k3 = v33
//NS-Private,由于没有NS-Private Namespace 所以获取到default value
Config privateConfig = ConfigService.getConfig("NS-Private");
privateConfig.getProperty("k1", "default value");
//NS-Public,公共类型的Namespace,任何项目都可以获取到
Config publicConfig = ConfigService.getConfig("NS-Public");
publicConfig.getProperty("k4", null); // k4 = v5
publicConfig.getProperty("k6", null); // k6 = v6
publicConfig.getProperty("k7", null); // k7 = v7
```
##### 5.4.4 ChangeListener
以上代码例子中可以看到,在客户端Namespace映射成一个Config对象。Namespace配置变更的监听器是注册在Config对象上。
所以在应用A中监听application的Namespace代码如下:
```java
Config appConfig = ConfigService.getAppConfig();
appConfig.addChangeListener(new ConfigChangeListener() {
public void onChange(ConfigChangeEvent changeEvent) {
//do something
}
})
```
在应用A中监听NS-Private的Namespace代码如下:
```java
Config privateConfig = ConfigService.getConfig("NS-Private");
privateConfig.addChangeListener(new ConfigChangeListener() {
public void onChange(ConfigChangeEvent changeEvent) {
//do something
}
})
```
在应用A、应用B、应用C中监听NS-Public的Namespace代码如下:
```java
Config publicConfig = ConfigService.getConfig("NS-Public");
publicConfig.addChangeListener(new ConfigChangeListener() {
public void onChange(ConfigChangeEvent changeEvent) {
//do something
}
})
```
| ### 1. 什么是Namespace?
Namespace是配置项的集合,类似于一个配置文件的概念。
### 2. 什么是“application”的Namespace?
Apollo在创建项目的时候,都会默认创建一个“application”的Namespace。顾名思义,“application”是给应用自身使用的,熟悉Spring Boot的同学都知道,Spring Boot项目都有一个默认配置文件application.yml。在这里application.yml就等同于“application”的Namespace。对于90%的应用来说,“application”的Namespace已经满足日常配置使用场景了。
#### 客户端获取“application” Namespace的代码如下:
``` java
Config config = ConfigService.getAppConfig();
```
#### 客户端获取非“application” Namespace的代码如下:
``` java
Config config = ConfigService.getConfig(namespaceName);
```
### 3. Namespace的格式有哪些?
配置文件有多种格式,例如:properties、xml、yml、yaml、json等。同样Namespace也具有这些格式。在Portal UI中可以看到“application”的Namespace上有一个“properties”标签,表明“application”是properties格式的。
>注1:非properties格式的namespace,在客户端使用时需要调用`ConfigService.getConfigFile(String namespace, ConfigFileFormat configFileFormat)`来获取,如果使用[Http接口直接调用](zh/usage/other-language-client-user-guide#_12-通过带缓存的http接口从apollo读取配置)时,对应的namespace参数需要传入namespace的名字加上后缀名,如datasources.json。
>注2:apollo-client 1.3.0版本开始对yaml/yml做了更好的支持,使用起来和properties格式一致:`Config config = ConfigService.getConfig("application.yml");`,Spring的注入方式也和properties一致。
### 4. Namespace的获取权限分类
Namespace的获取权限分为两种:
* private (私有的)
* public (公共的)
这里的获取权限是相对于Apollo客户端来说的。
#### 4.1 private权限
private权限的Namespace,只能被所属的应用获取到。一个应用尝试获取其它应用private的Namespace,Apollo会报“404”异常。
#### 4.2 public权限
public权限的Namespace,能被任何应用获取。
### 5. Namespace的类型
Namespace类型有三种:
* 私有类型
* 公共类型
* 关联类型(继承类型)
#### 5.1 私有类型
私有类型的Namespace具有private权限。例如上文提到的“application” Namespace就是私有类型。
#### 5.2 公共类型
##### 5.2.1 含义
公共类型的Namespace具有public权限。公共类型的Namespace相当于游离于应用之外的配置,且通过Namespace的名称去标识公共Namespace,所以公共的Namespace的名称必须全局唯一。
##### 5.2.2 使用场景
* 部门级别共享的配置
* 小组级别共享的配置
* 几个项目之间共享的配置
* 中间件客户端的配置
#### 5.3 关联类型
##### 5.3.1 含义
关联类型又可称为继承类型,关联类型具有private权限。关联类型的Namespace继承于公共类型的Namespace,用于覆盖公共Namespace的某些配置。例如公共的Namespace有两个配置项
```
k1 = v1
k2 = v2
```
然后应用A有一个关联类型的Namespace关联了此公共Namespace,且覆盖了配置项k1,新值为v3。那么在应用A实际运行时,获取到的公共Namespace的配置为:
```
k1 = v3
k2 = v2
```
##### 5.3.2 使用场景
举一个实际使用的场景。假设RPC框架的配置(如:timeout)有以下要求:
* 提供一份全公司默认的配置且可动态调整
* RPC客户端项目可以自定义某些配置项且可动态调整
1. 如果把以上两点要求去掉“动态调整”,那么做法很简单。在rpc-client.jar包里有一份配置文件,每次修改配置文件然后重新发一个版本的jar包即可。同理,客户端项目修改配置也是如此。
2. 如果只支持客户端项目可动态调整配置。客户端项目可以在Apollo “application” Namespace上配置一些配置项。在初始化service的时候,从Apollo上读取配置即可。这样做的坏处就是,每个项目都要自定义一些key,不统一。
3. 那么如何完美支持以上需求呢?答案就是结合使用Apollo的公共类型的Namespace和关联类型的Namespace。RPC团队在Apollo上维护一个叫“rpc-client”的公共Namespace,在“rpc-client” Namespace上配置默认的参数值。rpc-client.jar里的代码读取“rpc-client”Namespace的配置即可。如果需要调整默认的配置,只需要修改公共类型“rpc-client” Namespace的配置。如果客户端项目想要自定义或动态修改某些配置项,只需要在Apollo 自己项目下关联“rpc-client”,就能创建关联类型“rpc-client”的Namespace。然后在关联类型“rpc-client”的Namespace下修改配置项即可。这里有一点需要指出的,那就是rpc-client.jar是在应用容器里运行的,所以rpc-client获取到的“rpc-client” Namespace的配置是应用的关联类型的Namespace加上公共类型的Namespace。
#### 5.4 例子
如下图所示,有三个应用:应用A、应用B、应用C。
* 应用A有两个私有类型的Namespace:application和NS-Private,以及一个关联类型的Namespace:NS-Public。
* 应用B有一个私有类型的Namespace:application,以及一个公共类型的Namespace:NS-Public。
* 应用C只有一个私有类型的Namespace:application

##### 5.4.1 应用A获取Apollo配置
```java
//application
Config appConfig = ConfigService.getAppConfig();
appConfig.getProperty("k1", null); // k1 = v11
appConfig.getProperty("k2", null); // k2 = v21
//NS-Private
Config privateConfig = ConfigService.getConfig("NS-Private");
privateConfig.getProperty("k1", null); // k1 = v3
privateConfig.getProperty("k3", null); // k3 = v4
//NS-Public,覆盖公共类型配置的情况,k4被覆盖
Config publicConfig = ConfigService.getConfig("NS-Public");
publicConfig.getProperty("k4", null); // k4 = v6 cover
publicConfig.getProperty("k6", null); // k6 = v6
publicConfig.getProperty("k7", null); // k7 = v7
```
##### 5.4.2 应用B获取Apollo配置
```java
//application
Config appConfig = ConfigService.getAppConfig();
appConfig.getProperty("k1", null); // k1 = v12
appConfig.getProperty("k2", null); // k2 = null
appConfig.getProperty("k3", null); // k3 = v32
//NS-Private,由于没有NS-Private Namespace 所以获取到default value
Config privateConfig = ConfigService.getConfig("NS-Private");
privateConfig.getProperty("k1", "default value");
//NS-Public
Config publicConfig = ConfigService.getConfig("NS-Public");
publicConfig.getProperty("k4", null); // k4 = v5
publicConfig.getProperty("k6", null); // k6 = v6
publicConfig.getProperty("k7", null); // k7 = v7
```
##### 5.4.3 应用C获取Apollo配置
```java
//application
Config appConfig = ConfigService.getAppConfig();
appConfig.getProperty("k1", null); // k1 = v12
appConfig.getProperty("k2", null); // k2 = null
appConfig.getProperty("k3", null); // k3 = v33
//NS-Private,由于没有NS-Private Namespace 所以获取到default value
Config privateConfig = ConfigService.getConfig("NS-Private");
privateConfig.getProperty("k1", "default value");
//NS-Public,公共类型的Namespace,任何项目都可以获取到
Config publicConfig = ConfigService.getConfig("NS-Public");
publicConfig.getProperty("k4", null); // k4 = v5
publicConfig.getProperty("k6", null); // k6 = v6
publicConfig.getProperty("k7", null); // k7 = v7
```
##### 5.4.4 ChangeListener
以上代码例子中可以看到,在客户端Namespace映射成一个Config对象。Namespace配置变更的监听器是注册在Config对象上。
所以在应用A中监听application的Namespace代码如下:
```java
Config appConfig = ConfigService.getAppConfig();
appConfig.addChangeListener(new ConfigChangeListener() {
public void onChange(ConfigChangeEvent changeEvent) {
//do something
}
})
```
在应用A中监听NS-Private的Namespace代码如下:
```java
Config privateConfig = ConfigService.getConfig("NS-Private");
privateConfig.addChangeListener(new ConfigChangeListener() {
public void onChange(ConfigChangeEvent changeEvent) {
//do something
}
})
```
在应用A、应用B、应用C中监听NS-Public的Namespace代码如下:
```java
Config publicConfig = ConfigService.getConfig("NS-Public");
publicConfig.addChangeListener(new ConfigChangeListener() {
public void onChange(ConfigChangeEvent changeEvent) {
//do something
}
})
```
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/filter/ClientAuthenticationFilter.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.configservice.filter;
import com.ctrip.framework.apollo.configservice.util.AccessKeyUtil;
import com.ctrip.framework.apollo.core.signature.Signature;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.google.common.net.HttpHeaders;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
/**
* @author nisiyong
*/
public class ClientAuthenticationFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(ClientAuthenticationFilter.class);
private static final Long TIMESTAMP_INTERVAL = 60 * 1000L;
private final AccessKeyUtil accessKeyUtil;
public ClientAuthenticationFilter(AccessKeyUtil accessKeyUtil) {
this.accessKeyUtil = accessKeyUtil;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//nothing
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String appId = accessKeyUtil.extractAppIdFromRequest(request);
if (StringUtils.isBlank(appId)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidAppId");
return;
}
List<String> availableSecrets = accessKeyUtil.findAvailableSecret(appId);
if (!CollectionUtils.isEmpty(availableSecrets)) {
String timestamp = request.getHeader(Signature.HTTP_HEADER_TIMESTAMP);
String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
// check timestamp, valid within 1 minute
if (!checkTimestamp(timestamp)) {
logger.warn("Invalid timestamp. appId={},timestamp={}", appId, timestamp);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "RequestTimeTooSkewed");
return;
}
// check signature
String uri = request.getRequestURI();
String query = request.getQueryString();
if (!checkAuthorization(authorization, availableSecrets, timestamp, uri, query)) {
logger.warn("Invalid authorization. appId={},authorization={}", appId, authorization);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
return;
}
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
//nothing
}
private boolean checkTimestamp(String timestamp) {
long requestTimeMillis = 0L;
try {
requestTimeMillis = Long.parseLong(timestamp);
} catch (NumberFormatException e) {
// nothing to do
}
long x = System.currentTimeMillis() - requestTimeMillis;
return x >= -TIMESTAMP_INTERVAL && x <= TIMESTAMP_INTERVAL;
}
private boolean checkAuthorization(String authorization, List<String> availableSecrets,
String timestamp, String path, String query) {
String signature = null;
if (authorization != null) {
String[] split = authorization.split(":");
if (split.length > 1) {
signature = split[1];
}
}
for (String secret : availableSecrets) {
String availableSignature = accessKeyUtil.buildSignature(path, query, timestamp, secret);
if (Objects.equals(signature, availableSignature)) {
return true;
}
}
return false;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.configservice.filter;
import com.ctrip.framework.apollo.configservice.util.AccessKeyUtil;
import com.ctrip.framework.apollo.core.signature.Signature;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.google.common.net.HttpHeaders;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
/**
* @author nisiyong
*/
public class ClientAuthenticationFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(ClientAuthenticationFilter.class);
private static final Long TIMESTAMP_INTERVAL = 60 * 1000L;
private final AccessKeyUtil accessKeyUtil;
public ClientAuthenticationFilter(AccessKeyUtil accessKeyUtil) {
this.accessKeyUtil = accessKeyUtil;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//nothing
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String appId = accessKeyUtil.extractAppIdFromRequest(request);
if (StringUtils.isBlank(appId)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidAppId");
return;
}
List<String> availableSecrets = accessKeyUtil.findAvailableSecret(appId);
if (!CollectionUtils.isEmpty(availableSecrets)) {
String timestamp = request.getHeader(Signature.HTTP_HEADER_TIMESTAMP);
String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
// check timestamp, valid within 1 minute
if (!checkTimestamp(timestamp)) {
logger.warn("Invalid timestamp. appId={},timestamp={}", appId, timestamp);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "RequestTimeTooSkewed");
return;
}
// check signature
String uri = request.getRequestURI();
String query = request.getQueryString();
if (!checkAuthorization(authorization, availableSecrets, timestamp, uri, query)) {
logger.warn("Invalid authorization. appId={},authorization={}", appId, authorization);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
return;
}
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
//nothing
}
private boolean checkTimestamp(String timestamp) {
long requestTimeMillis = 0L;
try {
requestTimeMillis = Long.parseLong(timestamp);
} catch (NumberFormatException e) {
// nothing to do
}
long x = System.currentTimeMillis() - requestTimeMillis;
return x >= -TIMESTAMP_INTERVAL && x <= TIMESTAMP_INTERVAL;
}
private boolean checkAuthorization(String authorization, List<String> availableSecrets,
String timestamp, String path, String query) {
String signature = null;
if (authorization != null) {
String[] split = authorization.split(":");
if (split.length > 1) {
signature = split[1];
}
}
for (String secret : availableSecrets) {
String availableSignature = accessKeyUtil.buildSignature(path, query, timestamp, secret);
if (Objects.equals(signature, availableSignature)) {
return true;
}
}
return false;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/SsoHeartbeatController.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.portal.spi.SsoHeartbeatHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Since sso auth information has a limited expiry time, so we need to do sso heartbeat to keep the
* information refreshed when unavailable
*
* @author Jason Song(song_s@ctrip.com)
*/
@Controller
@RequestMapping("/sso_heartbeat")
public class SsoHeartbeatController {
private final SsoHeartbeatHandler handler;
public SsoHeartbeatController(final SsoHeartbeatHandler handler) {
this.handler = handler;
}
@GetMapping
public void heartbeat(HttpServletRequest request, HttpServletResponse response) {
handler.doHeartbeat(request, response);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.portal.spi.SsoHeartbeatHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Since sso auth information has a limited expiry time, so we need to do sso heartbeat to keep the
* information refreshed when unavailable
*
* @author Jason Song(song_s@ctrip.com)
*/
@Controller
@RequestMapping("/sso_heartbeat")
public class SsoHeartbeatController {
private final SsoHeartbeatHandler handler;
public SsoHeartbeatController(final SsoHeartbeatHandler handler) {
this.handler = handler;
}
@GetMapping
public void heartbeat(HttpServletRequest request, HttpServletResponse response) {
handler.doHeartbeat(request, response);
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/TestProcessorHelper.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.spi;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
public class TestProcessorHelper extends DefaultConfigPropertySourcesProcessorHelper {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
throws BeansException {
super.postProcessBeanDefinitionRegistry(registry);
}
@Override
public int getOrder() {
return 0;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.spi;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
public class TestProcessorHelper extends DefaultConfigPropertySourcesProcessorHelper {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
throws BeansException {
super.postProcessBeanDefinitionRegistry(registry);
}
@Override
public int getOrder() {
return 0;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/TracerTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.tracer;
import com.ctrip.framework.apollo.tracer.internals.MockMessageProducerManager;
import com.ctrip.framework.apollo.tracer.internals.NullTransaction;
import com.ctrip.framework.apollo.tracer.spi.MessageProducer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class TracerTest {
private MessageProducer someProducer;
@Before
public void setUp() throws Exception {
someProducer = mock(MessageProducer.class);
MockMessageProducerManager.setProducer(someProducer);
}
@Test
public void testLogError() throws Exception {
String someMessage = "someMessage";
Throwable someCause = mock(Throwable.class);
Tracer.logError(someMessage, someCause);
verify(someProducer, times(1)).logError(someMessage, someCause);
}
@Test
public void testLogErrorWithException() throws Exception {
String someMessage = "someMessage";
Throwable someCause = mock(Throwable.class);
doThrow(RuntimeException.class).when(someProducer).logError(someMessage, someCause);
Tracer.logError(someMessage, someCause);
verify(someProducer, times(1)).logError(someMessage, someCause);
}
@Test
public void testLogErrorWithOnlyCause() throws Exception {
Throwable someCause = mock(Throwable.class);
Tracer.logError(someCause);
verify(someProducer, times(1)).logError(someCause);
}
@Test
public void testLogErrorWithOnlyCauseWithException() throws Exception {
Throwable someCause = mock(Throwable.class);
doThrow(RuntimeException.class).when(someProducer).logError(someCause);
Tracer.logError(someCause);
verify(someProducer, times(1)).logError(someCause);
}
@Test
public void testLogEvent() throws Exception {
String someType = "someType";
String someName = "someName";
Tracer.logEvent(someType, someName);
verify(someProducer, times(1)).logEvent(someType, someName);
}
@Test
public void testLogEventWithException() throws Exception {
String someType = "someType";
String someName = "someName";
doThrow(RuntimeException.class).when(someProducer).logEvent(someType, someName);
Tracer.logEvent(someType, someName);
verify(someProducer, times(1)).logEvent(someType, someName);
}
@Test
public void testLogEventWithStatusAndNameValuePairs() throws Exception {
String someType = "someType";
String someName = "someName";
String someStatus = "someStatus";
String someNameValuePairs = "someNameValuePairs";
Tracer.logEvent(someType, someName, someStatus, someNameValuePairs);
verify(someProducer, times(1)).logEvent(someType, someName, someStatus, someNameValuePairs);
}
@Test
public void testLogEventWithStatusAndNameValuePairsWithException() throws Exception {
String someType = "someType";
String someName = "someName";
String someStatus = "someStatus";
String someNameValuePairs = "someNameValuePairs";
doThrow(RuntimeException.class).when(someProducer).logEvent(someType, someName, someStatus,
someNameValuePairs);
Tracer.logEvent(someType, someName, someStatus, someNameValuePairs);
verify(someProducer, times(1)).logEvent(someType, someName, someStatus, someNameValuePairs);
}
@Test
public void testNewTransaction() throws Exception {
String someType = "someType";
String someName = "someName";
Transaction someTransaction = mock(Transaction.class);
when(someProducer.newTransaction(someType, someName)).thenReturn(someTransaction);
Transaction result = Tracer.newTransaction(someType, someName);
verify(someProducer, times(1)).newTransaction(someType, someName);
assertEquals(someTransaction, result);
}
@Test
public void testNewTransactionWithException() throws Exception {
String someType = "someType";
String someName = "someName";
when(someProducer.newTransaction(someType, someName)).thenThrow(RuntimeException.class);
Transaction result = Tracer.newTransaction(someType, someName);
verify(someProducer, times(1)).newTransaction(someType, someName);
assertTrue(result instanceof NullTransaction);
}
} | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.tracer;
import com.ctrip.framework.apollo.tracer.internals.MockMessageProducerManager;
import com.ctrip.framework.apollo.tracer.internals.NullTransaction;
import com.ctrip.framework.apollo.tracer.spi.MessageProducer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class TracerTest {
private MessageProducer someProducer;
@Before
public void setUp() throws Exception {
someProducer = mock(MessageProducer.class);
MockMessageProducerManager.setProducer(someProducer);
}
@Test
public void testLogError() throws Exception {
String someMessage = "someMessage";
Throwable someCause = mock(Throwable.class);
Tracer.logError(someMessage, someCause);
verify(someProducer, times(1)).logError(someMessage, someCause);
}
@Test
public void testLogErrorWithException() throws Exception {
String someMessage = "someMessage";
Throwable someCause = mock(Throwable.class);
doThrow(RuntimeException.class).when(someProducer).logError(someMessage, someCause);
Tracer.logError(someMessage, someCause);
verify(someProducer, times(1)).logError(someMessage, someCause);
}
@Test
public void testLogErrorWithOnlyCause() throws Exception {
Throwable someCause = mock(Throwable.class);
Tracer.logError(someCause);
verify(someProducer, times(1)).logError(someCause);
}
@Test
public void testLogErrorWithOnlyCauseWithException() throws Exception {
Throwable someCause = mock(Throwable.class);
doThrow(RuntimeException.class).when(someProducer).logError(someCause);
Tracer.logError(someCause);
verify(someProducer, times(1)).logError(someCause);
}
@Test
public void testLogEvent() throws Exception {
String someType = "someType";
String someName = "someName";
Tracer.logEvent(someType, someName);
verify(someProducer, times(1)).logEvent(someType, someName);
}
@Test
public void testLogEventWithException() throws Exception {
String someType = "someType";
String someName = "someName";
doThrow(RuntimeException.class).when(someProducer).logEvent(someType, someName);
Tracer.logEvent(someType, someName);
verify(someProducer, times(1)).logEvent(someType, someName);
}
@Test
public void testLogEventWithStatusAndNameValuePairs() throws Exception {
String someType = "someType";
String someName = "someName";
String someStatus = "someStatus";
String someNameValuePairs = "someNameValuePairs";
Tracer.logEvent(someType, someName, someStatus, someNameValuePairs);
verify(someProducer, times(1)).logEvent(someType, someName, someStatus, someNameValuePairs);
}
@Test
public void testLogEventWithStatusAndNameValuePairsWithException() throws Exception {
String someType = "someType";
String someName = "someName";
String someStatus = "someStatus";
String someNameValuePairs = "someNameValuePairs";
doThrow(RuntimeException.class).when(someProducer).logEvent(someType, someName, someStatus,
someNameValuePairs);
Tracer.logEvent(someType, someName, someStatus, someNameValuePairs);
verify(someProducer, times(1)).logEvent(someType, someName, someStatus, someNameValuePairs);
}
@Test
public void testNewTransaction() throws Exception {
String someType = "someType";
String someName = "someName";
Transaction someTransaction = mock(Transaction.class);
when(someProducer.newTransaction(someType, someName)).thenReturn(someTransaction);
Transaction result = Tracer.newTransaction(someType, someName);
verify(someProducer, times(1)).newTransaction(someType, someName);
assertEquals(someTransaction, result);
}
@Test
public void testNewTransactionWithException() throws Exception {
String someType = "someType";
String someName = "someName";
when(someProducer.newTransaction(someType, someName)).thenThrow(RuntimeException.class);
Transaction result = Tracer.newTransaction(someType, someName);
verify(someProducer, times(1)).newTransaction(someType, someName);
assertTrue(result instanceof NullTransaction);
}
} | -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/test/java/com/ctrip/framework/apollo/openapi/filter/ConsumerAuthenticationFilterTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.filter;
import com.ctrip.framework.apollo.openapi.util.ConsumerAuditUtil;
import com.ctrip.framework.apollo.openapi.util.ConsumerAuthUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@RunWith(MockitoJUnitRunner.class)
public class ConsumerAuthenticationFilterTest {
private ConsumerAuthenticationFilter authenticationFilter;
@Mock
private ConsumerAuthUtil consumerAuthUtil;
@Mock
private ConsumerAuditUtil consumerAuditUtil;
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private FilterChain filterChain;
@Before
public void setUp() throws Exception {
authenticationFilter = new ConsumerAuthenticationFilter(consumerAuthUtil, consumerAuditUtil);
}
@Test
public void testAuthSuccessfully() throws Exception {
String someToken = "someToken";
Long someConsumerId = 1L;
when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someToken);
when(consumerAuthUtil.getConsumerId(someToken)).thenReturn(someConsumerId);
authenticationFilter.doFilter(request, response, filterChain);
verify(consumerAuthUtil, times(1)).storeConsumerId(request, someConsumerId);
verify(consumerAuditUtil, times(1)).audit(request, someConsumerId);
verify(filterChain, times(1)).doFilter(request, response);
}
@Test
public void testAuthFailed() throws Exception {
String someInvalidToken = "someInvalidToken";
when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someInvalidToken);
when(consumerAuthUtil.getConsumerId(someInvalidToken)).thenReturn(null);
authenticationFilter.doFilter(request, response, filterChain);
verify(response, times(1)).sendError(eq(HttpServletResponse.SC_UNAUTHORIZED), anyString());
verify(consumerAuthUtil, never()).storeConsumerId(eq(request), anyLong());
verify(consumerAuditUtil, never()).audit(eq(request), anyLong());
verify(filterChain, never()).doFilter(request, response);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.filter;
import com.ctrip.framework.apollo.openapi.util.ConsumerAuditUtil;
import com.ctrip.framework.apollo.openapi.util.ConsumerAuthUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@RunWith(MockitoJUnitRunner.class)
public class ConsumerAuthenticationFilterTest {
private ConsumerAuthenticationFilter authenticationFilter;
@Mock
private ConsumerAuthUtil consumerAuthUtil;
@Mock
private ConsumerAuditUtil consumerAuditUtil;
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private FilterChain filterChain;
@Before
public void setUp() throws Exception {
authenticationFilter = new ConsumerAuthenticationFilter(consumerAuthUtil, consumerAuditUtil);
}
@Test
public void testAuthSuccessfully() throws Exception {
String someToken = "someToken";
Long someConsumerId = 1L;
when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someToken);
when(consumerAuthUtil.getConsumerId(someToken)).thenReturn(someConsumerId);
authenticationFilter.doFilter(request, response, filterChain);
verify(consumerAuthUtil, times(1)).storeConsumerId(request, someConsumerId);
verify(consumerAuditUtil, times(1)).audit(request, someConsumerId);
verify(filterChain, times(1)).doFilter(request, response);
}
@Test
public void testAuthFailed() throws Exception {
String someInvalidToken = "someInvalidToken";
when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someInvalidToken);
when(consumerAuthUtil.getConsumerId(someInvalidToken)).thenReturn(null);
authenticationFilter.doFilter(request, response, filterChain);
verify(response, times(1)).sendError(eq(HttpServletResponse.SC_UNAUTHORIZED), anyString());
verify(consumerAuthUtil, never()).storeConsumerId(eq(request), anyLong());
verify(consumerAuditUtil, never()).audit(eq(request), anyLong());
verify(filterChain, never()).doFilter(request, response);
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/utils/InputValidator.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.utils;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import java.util.regex.Pattern;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class InputValidator {
public static final String INVALID_CLUSTER_NAMESPACE_MESSAGE = "Only digits, alphabets and symbol - _ . are allowed";
public static final String INVALID_NAMESPACE_NAMESPACE_MESSAGE = "not allowed to end with .json, .yml, .yaml, .xml, .properties";
public static final String CLUSTER_NAMESPACE_VALIDATOR = "[0-9a-zA-Z_.-]+";
private static final String APP_NAMESPACE_VALIDATOR = "[a-zA-Z0-9._-]+(?<!\\.(json|yml|yaml|xml|properties))$";
private static final Pattern CLUSTER_NAMESPACE_PATTERN = Pattern.compile(CLUSTER_NAMESPACE_VALIDATOR);
private static final Pattern APP_NAMESPACE_PATTERN = Pattern.compile(APP_NAMESPACE_VALIDATOR);
public static boolean isValidClusterNamespace(String name) {
if (StringUtils.isEmpty(name)){
return false;
}
return CLUSTER_NAMESPACE_PATTERN.matcher(name).matches();
}
public static boolean isValidAppNamespace(String name){
if (StringUtils.isEmpty(name)){
return false;
}
return APP_NAMESPACE_PATTERN.matcher(name).matches();
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.utils;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import java.util.regex.Pattern;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class InputValidator {
public static final String INVALID_CLUSTER_NAMESPACE_MESSAGE = "Only digits, alphabets and symbol - _ . are allowed";
public static final String INVALID_NAMESPACE_NAMESPACE_MESSAGE = "not allowed to end with .json, .yml, .yaml, .xml, .properties";
public static final String CLUSTER_NAMESPACE_VALIDATOR = "[0-9a-zA-Z_.-]+";
private static final String APP_NAMESPACE_VALIDATOR = "[a-zA-Z0-9._-]+(?<!\\.(json|yml|yaml|xml|properties))$";
private static final Pattern CLUSTER_NAMESPACE_PATTERN = Pattern.compile(CLUSTER_NAMESPACE_VALIDATOR);
private static final Pattern APP_NAMESPACE_PATTERN = Pattern.compile(APP_NAMESPACE_VALIDATOR);
public static boolean isValidClusterNamespace(String name) {
if (StringUtils.isEmpty(name)){
return false;
}
return CLUSTER_NAMESPACE_PATTERN.matcher(name).matches();
}
public static boolean isValidAppNamespace(String name){
if (StringUtils.isEmpty(name)){
return false;
}
return APP_NAMESPACE_PATTERN.matcher(name).matches();
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpResponse.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.util.http;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class HttpResponse<T> {
private final int m_statusCode;
private final T m_body;
public HttpResponse(int statusCode, T body) {
this.m_statusCode = statusCode;
this.m_body = body;
}
public int getStatusCode() {
return m_statusCode;
}
public T getBody() {
return m_body;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.util.http;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class HttpResponse<T> {
private final int m_statusCode;
private final T m_body;
public HttpResponse(int statusCode, T body) {
this.m_statusCode = statusCode;
this.m_body = body;
}
public int getStatusCode() {
return m_statusCode;
}
public T getBody() {
return m_body;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-configservice/src/test/java/com/ctrip/framework/apollo/configservice/util/InstanceConfigAuditUtilTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.configservice.util;
import com.ctrip.framework.apollo.biz.entity.Instance;
import com.ctrip.framework.apollo.biz.entity.InstanceConfig;
import com.ctrip.framework.apollo.biz.service.InstanceService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@RunWith(MockitoJUnitRunner.class)
public class InstanceConfigAuditUtilTest {
private InstanceConfigAuditUtil instanceConfigAuditUtil;
@Mock
private InstanceService instanceService;
private BlockingQueue<InstanceConfigAuditUtil.InstanceConfigAuditModel> audits;
private String someAppId;
private String someConfigClusterName;
private String someClusterName;
private String someDataCenter;
private String someIp;
private String someConfigAppId;
private String someConfigNamespace;
private String someReleaseKey;
private InstanceConfigAuditUtil.InstanceConfigAuditModel someAuditModel;
@Before
public void setUp() throws Exception {
instanceConfigAuditUtil = new InstanceConfigAuditUtil(instanceService);
audits = (BlockingQueue<InstanceConfigAuditUtil.InstanceConfigAuditModel>)
ReflectionTestUtils.getField(instanceConfigAuditUtil, "audits");
someAppId = "someAppId";
someClusterName = "someClusterName";
someDataCenter = "someDataCenter";
someIp = "someIp";
someConfigAppId = "someConfigAppId";
someConfigClusterName = "someConfigClusterName";
someConfigNamespace = "someConfigNamespace";
someReleaseKey = "someReleaseKey";
someAuditModel = new InstanceConfigAuditUtil.InstanceConfigAuditModel(someAppId,
someClusterName, someDataCenter, someIp, someConfigAppId, someConfigClusterName,
someConfigNamespace, someReleaseKey);
}
@Test
public void testAudit() throws Exception {
boolean result = instanceConfigAuditUtil.audit(someAppId, someClusterName, someDataCenter,
someIp, someConfigAppId, someConfigClusterName, someConfigNamespace, someReleaseKey);
InstanceConfigAuditUtil.InstanceConfigAuditModel audit = audits.poll();
assertTrue(result);
assertTrue(Objects.equals(someAuditModel, audit));
}
@Test
public void testDoAudit() throws Exception {
long someInstanceId = 1;
Instance someInstance = mock(Instance.class);
when(someInstance.getId()).thenReturn(someInstanceId);
when(instanceService.createInstance(any(Instance.class))).thenReturn(someInstance);
instanceConfigAuditUtil.doAudit(someAuditModel);
verify(instanceService, times(1)).findInstance(someAppId, someClusterName, someDataCenter,
someIp);
verify(instanceService, times(1)).createInstance(any(Instance.class));
verify(instanceService, times(1)).findInstanceConfig(someInstanceId, someConfigAppId,
someConfigNamespace);
verify(instanceService, times(1)).createInstanceConfig(any(InstanceConfig.class));
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.configservice.util;
import com.ctrip.framework.apollo.biz.entity.Instance;
import com.ctrip.framework.apollo.biz.entity.InstanceConfig;
import com.ctrip.framework.apollo.biz.service.InstanceService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@RunWith(MockitoJUnitRunner.class)
public class InstanceConfigAuditUtilTest {
private InstanceConfigAuditUtil instanceConfigAuditUtil;
@Mock
private InstanceService instanceService;
private BlockingQueue<InstanceConfigAuditUtil.InstanceConfigAuditModel> audits;
private String someAppId;
private String someConfigClusterName;
private String someClusterName;
private String someDataCenter;
private String someIp;
private String someConfigAppId;
private String someConfigNamespace;
private String someReleaseKey;
private InstanceConfigAuditUtil.InstanceConfigAuditModel someAuditModel;
@Before
public void setUp() throws Exception {
instanceConfigAuditUtil = new InstanceConfigAuditUtil(instanceService);
audits = (BlockingQueue<InstanceConfigAuditUtil.InstanceConfigAuditModel>)
ReflectionTestUtils.getField(instanceConfigAuditUtil, "audits");
someAppId = "someAppId";
someClusterName = "someClusterName";
someDataCenter = "someDataCenter";
someIp = "someIp";
someConfigAppId = "someConfigAppId";
someConfigClusterName = "someConfigClusterName";
someConfigNamespace = "someConfigNamespace";
someReleaseKey = "someReleaseKey";
someAuditModel = new InstanceConfigAuditUtil.InstanceConfigAuditModel(someAppId,
someClusterName, someDataCenter, someIp, someConfigAppId, someConfigClusterName,
someConfigNamespace, someReleaseKey);
}
@Test
public void testAudit() throws Exception {
boolean result = instanceConfigAuditUtil.audit(someAppId, someClusterName, someDataCenter,
someIp, someConfigAppId, someConfigClusterName, someConfigNamespace, someReleaseKey);
InstanceConfigAuditUtil.InstanceConfigAuditModel audit = audits.poll();
assertTrue(result);
assertTrue(Objects.equals(someAuditModel, audit));
}
@Test
public void testDoAudit() throws Exception {
long someInstanceId = 1;
Instance someInstance = mock(Instance.class);
when(someInstance.getId()).thenReturn(someInstanceId);
when(instanceService.createInstance(any(Instance.class))).thenReturn(someInstance);
instanceConfigAuditUtil.doAudit(someAuditModel);
verify(instanceService, times(1)).findInstance(someAppId, someClusterName, someDataCenter,
someIp);
verify(instanceService, times(1)).createInstance(any(Instance.class));
verify(instanceService, times(1)).findInstanceConfig(someInstanceId, someConfigAppId,
someConfigNamespace);
verify(instanceService, times(1)).createInstanceConfig(any(InstanceConfig.class));
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/test/java/com/ctrip/framework/apollo/internals/RemoteConfigRepositoryTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.internals;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.doAnswer;
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 static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification;
import com.ctrip.framework.apollo.core.dto.ApolloNotificationMessages;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.core.signature.Signature;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.ctrip.framework.apollo.util.OrderedProperties;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import com.ctrip.framework.apollo.util.http.HttpRequest;
import com.ctrip.framework.apollo.util.http.HttpResponse;
import com.ctrip.framework.apollo.util.http.HttpClient;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.net.HttpHeaders;
import com.google.common.net.UrlEscapers;
import com.google.common.util.concurrent.SettableFuture;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
/**
* Created by Jason on 4/9/16.
*/
@RunWith(MockitoJUnitRunner.class)
public class RemoteConfigRepositoryTest {
@Mock
private ConfigServiceLocator configServiceLocator;
private String someNamespace;
private String someServerUrl;
private ConfigUtil configUtil;
private HttpClient httpClient;
@Mock
private static HttpResponse<ApolloConfig> someResponse;
@Mock
private static HttpResponse<List<ApolloConfigNotification>> pollResponse;
private RemoteConfigLongPollService remoteConfigLongPollService;
@Mock
private PropertiesFactory propertiesFactory;
private static String someAppId;
private static String someCluster;
private static String someSecret;
@Before
public void setUp() throws Exception {
someNamespace = "someName";
when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_NOT_MODIFIED);
configUtil = new MockConfigUtil();
MockInjector.setInstance(ConfigUtil.class, configUtil);
someServerUrl = "http://someServer";
ServiceDTO serviceDTO = mock(ServiceDTO.class);
when(serviceDTO.getHomepageUrl()).thenReturn(someServerUrl);
when(configServiceLocator.getConfigServices()).thenReturn(Lists.newArrayList(serviceDTO));
MockInjector.setInstance(ConfigServiceLocator.class, configServiceLocator);
httpClient = spy(new MockHttpClient());
MockInjector.setInstance(HttpClient.class, httpClient);
remoteConfigLongPollService = new RemoteConfigLongPollService();
MockInjector.setInstance(RemoteConfigLongPollService.class, remoteConfigLongPollService);
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new Properties();
}
});
MockInjector.setInstance(PropertiesFactory.class, propertiesFactory);
someAppId = "someAppId";
someCluster = "someCluster";
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
}
@Test
public void testLoadConfig() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig someApolloConfig = assembleApolloConfig(configurations);
when(someResponse.getStatusCode()).thenReturn(200);
when(someResponse.getBody()).thenReturn(someApolloConfig);
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
Properties config = remoteConfigRepository.getConfig();
assertEquals(configurations, config);
assertEquals(ConfigSourceType.REMOTE, remoteConfigRepository.getSourceType());
remoteConfigLongPollService.stopLongPollingRefresh();
}
@Test
public void testLoadConfigWithOrderedProperties() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
Map<String, String> configurations = Maps.newLinkedHashMap();
configurations.put(someKey, someValue);
configurations.put("someKey2", "someValue2");
ApolloConfig someApolloConfig = assembleApolloConfig(configurations);
when(someResponse.getStatusCode()).thenReturn(200);
when(someResponse.getBody()).thenReturn(someApolloConfig);
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new OrderedProperties();
}
});
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
Properties config = remoteConfigRepository.getConfig();
assertTrue(config instanceof OrderedProperties);
assertEquals(configurations, config);
assertEquals(ConfigSourceType.REMOTE, remoteConfigRepository.getSourceType());
remoteConfigLongPollService.stopLongPollingRefresh();
String[] actualArrays = config.keySet().toArray(new String[]{});
String[] expectedArrays = {"someKey", "someKey2"};
assertArrayEquals(expectedArrays, actualArrays);
}
@Test
public void testLoadConfigWithAccessKeySecret() throws Exception {
someSecret = "someSecret";
String someKey = "someKey";
String someValue = "someValue";
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig someApolloConfig = assembleApolloConfig(configurations);
when(someResponse.getStatusCode()).thenReturn(200);
when(someResponse.getBody()).thenReturn(someApolloConfig);
doAnswer(new Answer<HttpResponse<ApolloConfig>>() {
@Override
public HttpResponse<ApolloConfig> answer(InvocationOnMock invocation) throws Throwable {
HttpRequest request = invocation.getArgumentAt(0, HttpRequest.class);
Map<String, String> headers = request.getHeaders();
assertNotNull(headers);
assertTrue(headers.containsKey(Signature.HTTP_HEADER_TIMESTAMP));
assertTrue(headers.containsKey(HttpHeaders.AUTHORIZATION));
return someResponse;
}
}).when(httpClient).doGet(any(HttpRequest.class), any(Class.class));
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
Properties config = remoteConfigRepository.getConfig();
assertEquals(configurations, config);
assertEquals(ConfigSourceType.REMOTE, remoteConfigRepository.getSourceType());
remoteConfigLongPollService.stopLongPollingRefresh();
}
@Test(expected = ApolloConfigException.class)
public void testGetRemoteConfigWithServerError() throws Exception {
when(someResponse.getStatusCode()).thenReturn(500);
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
//must stop the long polling before exception occurred
remoteConfigLongPollService.stopLongPollingRefresh();
remoteConfigRepository.getConfig();
}
@Test(expected = ApolloConfigException.class)
public void testGetRemoteConfigWithNotFount() throws Exception {
when(someResponse.getStatusCode()).thenReturn(404);
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
//must stop the long polling before exception occurred
remoteConfigLongPollService.stopLongPollingRefresh();
remoteConfigRepository.getConfig();
}
@Test
public void testRepositoryChangeListener() throws Exception {
Map<String, String> configurations = ImmutableMap.of("someKey", "someValue");
ApolloConfig someApolloConfig = assembleApolloConfig(configurations);
when(someResponse.getStatusCode()).thenReturn(200);
when(someResponse.getBody()).thenReturn(someApolloConfig);
RepositoryChangeListener someListener = mock(RepositoryChangeListener.class);
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
remoteConfigRepository.addChangeListener(someListener);
final ArgumentCaptor<Properties> captor = ArgumentCaptor.forClass(Properties.class);
Map<String, String> newConfigurations = ImmutableMap.of("someKey", "anotherValue");
ApolloConfig newApolloConfig = assembleApolloConfig(newConfigurations);
when(someResponse.getBody()).thenReturn(newApolloConfig);
remoteConfigRepository.sync();
verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture());
assertEquals(newConfigurations, captor.getValue());
remoteConfigLongPollService.stopLongPollingRefresh();
}
@Test
public void testLongPollingRefresh() throws Exception {
Map<String, String> configurations = ImmutableMap.of("someKey", "someValue");
ApolloConfig someApolloConfig = assembleApolloConfig(configurations);
when(someResponse.getStatusCode()).thenReturn(200);
when(someResponse.getBody()).thenReturn(someApolloConfig);
final SettableFuture<Boolean> longPollFinished = SettableFuture.create();
RepositoryChangeListener someListener = mock(RepositoryChangeListener.class);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
longPollFinished.set(true);
return null;
}
}).when(someListener).onRepositoryChange(any(String.class), any(Properties.class));
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
remoteConfigRepository.addChangeListener(someListener);
final ArgumentCaptor<Properties> captor = ArgumentCaptor.forClass(Properties.class);
Map<String, String> newConfigurations = ImmutableMap.of("someKey", "anotherValue");
ApolloConfig newApolloConfig = assembleApolloConfig(newConfigurations);
ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages();
String someKey = "someKey";
long someNotificationId = 1;
notificationMessages.put(someKey, someNotificationId);
ApolloConfigNotification someNotification = mock(ApolloConfigNotification.class);
when(someNotification.getNamespaceName()).thenReturn(someNamespace);
when(someNotification.getMessages()).thenReturn(notificationMessages);
when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_OK);
when(pollResponse.getBody()).thenReturn(Lists.newArrayList(someNotification));
when(someResponse.getBody()).thenReturn(newApolloConfig);
longPollFinished.get(30_000, TimeUnit.MILLISECONDS);
remoteConfigLongPollService.stopLongPollingRefresh();
verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture());
assertEquals(newConfigurations, captor.getValue());
final ArgumentCaptor<HttpRequest> httpRequestArgumentCaptor = ArgumentCaptor
.forClass(HttpRequest.class);
verify(httpClient, atLeast(2)).doGet(httpRequestArgumentCaptor.capture(), eq(ApolloConfig.class));
HttpRequest request = httpRequestArgumentCaptor.getValue();
assertTrue(request.getUrl().contains("messages=%7B%22details%22%3A%7B%22someKey%22%3A1%7D%7D"));
}
@Test
public void testAssembleQueryConfigUrl() throws Exception {
Gson gson = new Gson();
String someUri = "http://someServer";
String someAppId = "someAppId";
String someCluster = "someCluster+ &.-_someSign";
String someReleaseKey = "20160705193346-583078ef5716c055+20160705193308-31c471ddf9087c3f";
ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages();
String someKey = "someKey";
long someNotificationId = 1;
String anotherKey = "anotherKey";
long anotherNotificationId = 2;
notificationMessages.put(someKey, someNotificationId);
notificationMessages.put(anotherKey, anotherNotificationId);
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
ApolloConfig someApolloConfig = mock(ApolloConfig.class);
when(someApolloConfig.getReleaseKey()).thenReturn(someReleaseKey);
String queryConfigUrl = remoteConfigRepository
.assembleQueryConfigUrl(someUri, someAppId, someCluster, someNamespace, null,
notificationMessages,
someApolloConfig);
remoteConfigLongPollService.stopLongPollingRefresh();
assertTrue(queryConfigUrl
.contains(
"http://someServer/configs/someAppId/someCluster+%20&.-_someSign/" + someNamespace));
assertTrue(queryConfigUrl
.contains("releaseKey=20160705193346-583078ef5716c055%2B20160705193308-31c471ddf9087c3f"));
assertTrue(queryConfigUrl
.contains("messages=" + UrlEscapers.urlFormParameterEscaper()
.escape(gson.toJson(notificationMessages))));
}
private ApolloConfig assembleApolloConfig(Map<String, String> configurations) {
String someAppId = "appId";
String someClusterName = "cluster";
String someReleaseKey = "1";
ApolloConfig apolloConfig =
new ApolloConfig(someAppId, someClusterName, someNamespace, someReleaseKey);
apolloConfig.setConfigurations(configurations);
return apolloConfig;
}
public static class MockConfigUtil extends ConfigUtil {
@Override
public String getAppId() {
return someAppId;
}
@Override
public String getCluster() {
return someCluster;
}
@Override
public String getAccessKeySecret() {
return someSecret;
}
@Override
public String getDataCenter() {
return null;
}
@Override
public int getLoadConfigQPS() {
return 200;
}
@Override
public int getLongPollQPS() {
return 200;
}
@Override
public long getOnErrorRetryInterval() {
return 10;
}
@Override
public TimeUnit getOnErrorRetryIntervalTimeUnit() {
return TimeUnit.MILLISECONDS;
}
@Override
public long getLongPollingInitialDelayInMills() {
return 0;
}
}
public static class MockHttpClient implements HttpClient {
@Override
public <T> HttpResponse<T> doGet(HttpRequest httpRequest, Class<T> responseType) {
if (someResponse.getStatusCode() == 200 || someResponse.getStatusCode() == 304) {
return (HttpResponse<T>) someResponse;
}
throw new ApolloConfigStatusCodeException(someResponse.getStatusCode(),
String.format("Http request failed due to status code: %d",
someResponse.getStatusCode()));
}
@Override
public <T> HttpResponse<T> doGet(HttpRequest httpRequest, Type responseType) {
try {
TimeUnit.MILLISECONDS.sleep(50);
} catch (InterruptedException e) {
}
return (HttpResponse<T>) pollResponse;
}
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.internals;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.doAnswer;
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 static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification;
import com.ctrip.framework.apollo.core.dto.ApolloNotificationMessages;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.core.signature.Signature;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.ctrip.framework.apollo.util.OrderedProperties;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import com.ctrip.framework.apollo.util.http.HttpRequest;
import com.ctrip.framework.apollo.util.http.HttpResponse;
import com.ctrip.framework.apollo.util.http.HttpClient;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.net.HttpHeaders;
import com.google.common.net.UrlEscapers;
import com.google.common.util.concurrent.SettableFuture;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
/**
* Created by Jason on 4/9/16.
*/
@RunWith(MockitoJUnitRunner.class)
public class RemoteConfigRepositoryTest {
@Mock
private ConfigServiceLocator configServiceLocator;
private String someNamespace;
private String someServerUrl;
private ConfigUtil configUtil;
private HttpClient httpClient;
@Mock
private static HttpResponse<ApolloConfig> someResponse;
@Mock
private static HttpResponse<List<ApolloConfigNotification>> pollResponse;
private RemoteConfigLongPollService remoteConfigLongPollService;
@Mock
private PropertiesFactory propertiesFactory;
private static String someAppId;
private static String someCluster;
private static String someSecret;
@Before
public void setUp() throws Exception {
someNamespace = "someName";
when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_NOT_MODIFIED);
configUtil = new MockConfigUtil();
MockInjector.setInstance(ConfigUtil.class, configUtil);
someServerUrl = "http://someServer";
ServiceDTO serviceDTO = mock(ServiceDTO.class);
when(serviceDTO.getHomepageUrl()).thenReturn(someServerUrl);
when(configServiceLocator.getConfigServices()).thenReturn(Lists.newArrayList(serviceDTO));
MockInjector.setInstance(ConfigServiceLocator.class, configServiceLocator);
httpClient = spy(new MockHttpClient());
MockInjector.setInstance(HttpClient.class, httpClient);
remoteConfigLongPollService = new RemoteConfigLongPollService();
MockInjector.setInstance(RemoteConfigLongPollService.class, remoteConfigLongPollService);
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new Properties();
}
});
MockInjector.setInstance(PropertiesFactory.class, propertiesFactory);
someAppId = "someAppId";
someCluster = "someCluster";
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
}
@Test
public void testLoadConfig() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig someApolloConfig = assembleApolloConfig(configurations);
when(someResponse.getStatusCode()).thenReturn(200);
when(someResponse.getBody()).thenReturn(someApolloConfig);
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
Properties config = remoteConfigRepository.getConfig();
assertEquals(configurations, config);
assertEquals(ConfigSourceType.REMOTE, remoteConfigRepository.getSourceType());
remoteConfigLongPollService.stopLongPollingRefresh();
}
@Test
public void testLoadConfigWithOrderedProperties() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
Map<String, String> configurations = Maps.newLinkedHashMap();
configurations.put(someKey, someValue);
configurations.put("someKey2", "someValue2");
ApolloConfig someApolloConfig = assembleApolloConfig(configurations);
when(someResponse.getStatusCode()).thenReturn(200);
when(someResponse.getBody()).thenReturn(someApolloConfig);
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new OrderedProperties();
}
});
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
Properties config = remoteConfigRepository.getConfig();
assertTrue(config instanceof OrderedProperties);
assertEquals(configurations, config);
assertEquals(ConfigSourceType.REMOTE, remoteConfigRepository.getSourceType());
remoteConfigLongPollService.stopLongPollingRefresh();
String[] actualArrays = config.keySet().toArray(new String[]{});
String[] expectedArrays = {"someKey", "someKey2"};
assertArrayEquals(expectedArrays, actualArrays);
}
@Test
public void testLoadConfigWithAccessKeySecret() throws Exception {
someSecret = "someSecret";
String someKey = "someKey";
String someValue = "someValue";
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig someApolloConfig = assembleApolloConfig(configurations);
when(someResponse.getStatusCode()).thenReturn(200);
when(someResponse.getBody()).thenReturn(someApolloConfig);
doAnswer(new Answer<HttpResponse<ApolloConfig>>() {
@Override
public HttpResponse<ApolloConfig> answer(InvocationOnMock invocation) throws Throwable {
HttpRequest request = invocation.getArgumentAt(0, HttpRequest.class);
Map<String, String> headers = request.getHeaders();
assertNotNull(headers);
assertTrue(headers.containsKey(Signature.HTTP_HEADER_TIMESTAMP));
assertTrue(headers.containsKey(HttpHeaders.AUTHORIZATION));
return someResponse;
}
}).when(httpClient).doGet(any(HttpRequest.class), any(Class.class));
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
Properties config = remoteConfigRepository.getConfig();
assertEquals(configurations, config);
assertEquals(ConfigSourceType.REMOTE, remoteConfigRepository.getSourceType());
remoteConfigLongPollService.stopLongPollingRefresh();
}
@Test(expected = ApolloConfigException.class)
public void testGetRemoteConfigWithServerError() throws Exception {
when(someResponse.getStatusCode()).thenReturn(500);
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
//must stop the long polling before exception occurred
remoteConfigLongPollService.stopLongPollingRefresh();
remoteConfigRepository.getConfig();
}
@Test(expected = ApolloConfigException.class)
public void testGetRemoteConfigWithNotFount() throws Exception {
when(someResponse.getStatusCode()).thenReturn(404);
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
//must stop the long polling before exception occurred
remoteConfigLongPollService.stopLongPollingRefresh();
remoteConfigRepository.getConfig();
}
@Test
public void testRepositoryChangeListener() throws Exception {
Map<String, String> configurations = ImmutableMap.of("someKey", "someValue");
ApolloConfig someApolloConfig = assembleApolloConfig(configurations);
when(someResponse.getStatusCode()).thenReturn(200);
when(someResponse.getBody()).thenReturn(someApolloConfig);
RepositoryChangeListener someListener = mock(RepositoryChangeListener.class);
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
remoteConfigRepository.addChangeListener(someListener);
final ArgumentCaptor<Properties> captor = ArgumentCaptor.forClass(Properties.class);
Map<String, String> newConfigurations = ImmutableMap.of("someKey", "anotherValue");
ApolloConfig newApolloConfig = assembleApolloConfig(newConfigurations);
when(someResponse.getBody()).thenReturn(newApolloConfig);
remoteConfigRepository.sync();
verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture());
assertEquals(newConfigurations, captor.getValue());
remoteConfigLongPollService.stopLongPollingRefresh();
}
@Test
public void testLongPollingRefresh() throws Exception {
Map<String, String> configurations = ImmutableMap.of("someKey", "someValue");
ApolloConfig someApolloConfig = assembleApolloConfig(configurations);
when(someResponse.getStatusCode()).thenReturn(200);
when(someResponse.getBody()).thenReturn(someApolloConfig);
final SettableFuture<Boolean> longPollFinished = SettableFuture.create();
RepositoryChangeListener someListener = mock(RepositoryChangeListener.class);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
longPollFinished.set(true);
return null;
}
}).when(someListener).onRepositoryChange(any(String.class), any(Properties.class));
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
remoteConfigRepository.addChangeListener(someListener);
final ArgumentCaptor<Properties> captor = ArgumentCaptor.forClass(Properties.class);
Map<String, String> newConfigurations = ImmutableMap.of("someKey", "anotherValue");
ApolloConfig newApolloConfig = assembleApolloConfig(newConfigurations);
ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages();
String someKey = "someKey";
long someNotificationId = 1;
notificationMessages.put(someKey, someNotificationId);
ApolloConfigNotification someNotification = mock(ApolloConfigNotification.class);
when(someNotification.getNamespaceName()).thenReturn(someNamespace);
when(someNotification.getMessages()).thenReturn(notificationMessages);
when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_OK);
when(pollResponse.getBody()).thenReturn(Lists.newArrayList(someNotification));
when(someResponse.getBody()).thenReturn(newApolloConfig);
longPollFinished.get(30_000, TimeUnit.MILLISECONDS);
remoteConfigLongPollService.stopLongPollingRefresh();
verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture());
assertEquals(newConfigurations, captor.getValue());
final ArgumentCaptor<HttpRequest> httpRequestArgumentCaptor = ArgumentCaptor
.forClass(HttpRequest.class);
verify(httpClient, atLeast(2)).doGet(httpRequestArgumentCaptor.capture(), eq(ApolloConfig.class));
HttpRequest request = httpRequestArgumentCaptor.getValue();
assertTrue(request.getUrl().contains("messages=%7B%22details%22%3A%7B%22someKey%22%3A1%7D%7D"));
}
@Test
public void testAssembleQueryConfigUrl() throws Exception {
Gson gson = new Gson();
String someUri = "http://someServer";
String someAppId = "someAppId";
String someCluster = "someCluster+ &.-_someSign";
String someReleaseKey = "20160705193346-583078ef5716c055+20160705193308-31c471ddf9087c3f";
ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages();
String someKey = "someKey";
long someNotificationId = 1;
String anotherKey = "anotherKey";
long anotherNotificationId = 2;
notificationMessages.put(someKey, someNotificationId);
notificationMessages.put(anotherKey, anotherNotificationId);
RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace);
ApolloConfig someApolloConfig = mock(ApolloConfig.class);
when(someApolloConfig.getReleaseKey()).thenReturn(someReleaseKey);
String queryConfigUrl = remoteConfigRepository
.assembleQueryConfigUrl(someUri, someAppId, someCluster, someNamespace, null,
notificationMessages,
someApolloConfig);
remoteConfigLongPollService.stopLongPollingRefresh();
assertTrue(queryConfigUrl
.contains(
"http://someServer/configs/someAppId/someCluster+%20&.-_someSign/" + someNamespace));
assertTrue(queryConfigUrl
.contains("releaseKey=20160705193346-583078ef5716c055%2B20160705193308-31c471ddf9087c3f"));
assertTrue(queryConfigUrl
.contains("messages=" + UrlEscapers.urlFormParameterEscaper()
.escape(gson.toJson(notificationMessages))));
}
private ApolloConfig assembleApolloConfig(Map<String, String> configurations) {
String someAppId = "appId";
String someClusterName = "cluster";
String someReleaseKey = "1";
ApolloConfig apolloConfig =
new ApolloConfig(someAppId, someClusterName, someNamespace, someReleaseKey);
apolloConfig.setConfigurations(configurations);
return apolloConfig;
}
public static class MockConfigUtil extends ConfigUtil {
@Override
public String getAppId() {
return someAppId;
}
@Override
public String getCluster() {
return someCluster;
}
@Override
public String getAccessKeySecret() {
return someSecret;
}
@Override
public String getDataCenter() {
return null;
}
@Override
public int getLoadConfigQPS() {
return 200;
}
@Override
public int getLongPollQPS() {
return 200;
}
@Override
public long getOnErrorRetryInterval() {
return 10;
}
@Override
public TimeUnit getOnErrorRetryIntervalTimeUnit() {
return TimeUnit.MILLISECONDS;
}
@Override
public long getLongPollingInitialDelayInMills() {
return 0;
}
}
public static class MockHttpClient implements HttpClient {
@Override
public <T> HttpResponse<T> doGet(HttpRequest httpRequest, Class<T> responseType) {
if (someResponse.getStatusCode() == 200 || someResponse.getStatusCode() == 304) {
return (HttpResponse<T>) someResponse;
}
throw new ApolloConfigStatusCodeException(someResponse.getStatusCode(),
String.format("Http request failed due to status code: %d",
someResponse.getStatusCode()));
}
@Override
public <T> HttpResponse<T> doGet(HttpRequest httpRequest, Type responseType) {
try {
TimeUnit.MILLISECONDS.sleep(50);
} catch (InterruptedException e) {
}
return (HttpResponse<T>) pollResponse;
}
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.core.ApolloClientSystemConsts;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.spi.MetaServerProvider;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import com.ctrip.framework.foundation.Foundation;
import com.google.common.base.Strings;
import org.slf4j.Logger;
public class DefaultMetaServerProvider implements MetaServerProvider {
public static final int ORDER = 0;
private static final Logger logger = DeferredLoggerFactory
.getLogger(DefaultMetaServerProvider.class);
private final String metaServerAddress;
public DefaultMetaServerProvider() {
metaServerAddress = initMetaServerAddress();
}
private String initMetaServerAddress() {
// 1. Get from System Property
String metaAddress = System.getProperty(ConfigConsts.APOLLO_META_KEY);
if (Strings.isNullOrEmpty(metaAddress)) {
// 2. Get from OS environment variable, which could not contain dot and is normally in UPPER case
metaAddress = System.getenv(ApolloClientSystemConsts.APOLLO_META_ENVIRONMENT_VARIABLES);
}
if (Strings.isNullOrEmpty(metaAddress)) {
// 3. Get from server.properties
metaAddress = Foundation.server().getProperty(ConfigConsts.APOLLO_META_KEY, null);
}
if (Strings.isNullOrEmpty(metaAddress)) {
// 4. Get from app.properties
metaAddress = Foundation.app().getProperty(ConfigConsts.APOLLO_META_KEY, null);
}
if (Strings.isNullOrEmpty(metaAddress)) {
logger.warn(
"Could not find meta server address, because it is not available in neither (1) JVM system property 'apollo.meta', (2) OS env variable 'APOLLO_META' (3) property 'apollo.meta' from server.properties nor (4) property 'apollo.meta' from app.properties");
} else {
metaAddress = metaAddress.trim();
logger.info("Located meta services from apollo.meta configuration: {}!", metaAddress);
}
return metaAddress;
}
@Override
public String getMetaServerAddress(Env targetEnv) {
//for default meta server provider, we don't care the actual environment
return metaServerAddress;
}
@Override
public int getOrder() {
return ORDER;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.core.ApolloClientSystemConsts;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.spi.MetaServerProvider;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import com.ctrip.framework.foundation.Foundation;
import com.google.common.base.Strings;
import org.slf4j.Logger;
public class DefaultMetaServerProvider implements MetaServerProvider {
public static final int ORDER = 0;
private static final Logger logger = DeferredLoggerFactory
.getLogger(DefaultMetaServerProvider.class);
private final String metaServerAddress;
public DefaultMetaServerProvider() {
metaServerAddress = initMetaServerAddress();
}
private String initMetaServerAddress() {
// 1. Get from System Property
String metaAddress = System.getProperty(ConfigConsts.APOLLO_META_KEY);
if (Strings.isNullOrEmpty(metaAddress)) {
// 2. Get from OS environment variable, which could not contain dot and is normally in UPPER case
metaAddress = System.getenv(ApolloClientSystemConsts.APOLLO_META_ENVIRONMENT_VARIABLES);
}
if (Strings.isNullOrEmpty(metaAddress)) {
// 3. Get from server.properties
metaAddress = Foundation.server().getProperty(ConfigConsts.APOLLO_META_KEY, null);
}
if (Strings.isNullOrEmpty(metaAddress)) {
// 4. Get from app.properties
metaAddress = Foundation.app().getProperty(ConfigConsts.APOLLO_META_KEY, null);
}
if (Strings.isNullOrEmpty(metaAddress)) {
logger.warn(
"Could not find meta server address, because it is not available in neither (1) JVM system property 'apollo.meta', (2) OS env variable 'APOLLO_META' (3) property 'apollo.meta' from server.properties nor (4) property 'apollo.meta' from app.properties");
} else {
metaAddress = metaAddress.trim();
logger.info("Located meta services from apollo.meta configuration: {}!", metaAddress);
}
return metaAddress;
}
@Override
public String getMetaServerAddress(Env targetEnv) {
//for default meta server provider, we don't care the actual environment
return metaServerAddress;
}
@Override
public int getOrder() {
return ORDER;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/constants/ReleaseOperation.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.constants;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface ReleaseOperation {
int NORMAL_RELEASE = 0;
int ROLLBACK = 1;
int GRAY_RELEASE = 2;
int APPLY_GRAY_RULES = 3;
int GRAY_RELEASE_MERGE_TO_MASTER = 4;
int MASTER_NORMAL_RELEASE_MERGE_TO_GRAY = 5;
int MATER_ROLLBACK_MERGE_TO_GRAY = 6;
int ABANDON_GRAY_RELEASE = 7;
int GRAY_RELEASE_DELETED_AFTER_MERGE = 8;
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.constants;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface ReleaseOperation {
int NORMAL_RELEASE = 0;
int ROLLBACK = 1;
int GRAY_RELEASE = 2;
int APPLY_GRAY_RULES = 3;
int GRAY_RELEASE_MERGE_TO_MASTER = 4;
int MASTER_NORMAL_RELEASE_MERGE_TO_GRAY = 5;
int MATER_ROLLBACK_MERGE_TO_GRAY = 6;
int ABANDON_GRAY_RELEASE = 7;
int GRAY_RELEASE_DELETED_AFTER_MERGE = 8;
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/ClusterController.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.common.dto.ClusterDTO;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.service.ClusterService;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
public class ClusterController {
private final ClusterService clusterService;
private final UserInfoHolder userInfoHolder;
public ClusterController(final ClusterService clusterService, final UserInfoHolder userInfoHolder) {
this.clusterService = clusterService;
this.userInfoHolder = userInfoHolder;
}
@PreAuthorize(value = "@permissionValidator.hasCreateClusterPermission(#appId)")
@PostMapping(value = "apps/{appId}/envs/{env}/clusters")
public ClusterDTO createCluster(@PathVariable String appId, @PathVariable String env,
@Valid @RequestBody ClusterDTO cluster) {
String operator = userInfoHolder.getUser().getUserId();
cluster.setDataChangeLastModifiedBy(operator);
cluster.setDataChangeCreatedBy(operator);
return clusterService.createCluster(Env.valueOf(env), cluster);
}
@PreAuthorize(value = "@permissionValidator.isSuperAdmin()")
@DeleteMapping(value = "apps/{appId}/envs/{env}/clusters/{clusterName:.+}")
public ResponseEntity<Void> deleteCluster(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName){
clusterService.deleteCluster(Env.valueOf(env), appId, clusterName);
return ResponseEntity.ok().build();
}
@GetMapping(value = "apps/{appId}/envs/{env}/clusters/{clusterName:.+}")
public ClusterDTO loadCluster(@PathVariable("appId") String appId, @PathVariable String env, @PathVariable("clusterName") String clusterName) {
return clusterService.loadCluster(appId, Env.valueOf(env), clusterName);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.common.dto.ClusterDTO;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.service.ClusterService;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
public class ClusterController {
private final ClusterService clusterService;
private final UserInfoHolder userInfoHolder;
public ClusterController(final ClusterService clusterService, final UserInfoHolder userInfoHolder) {
this.clusterService = clusterService;
this.userInfoHolder = userInfoHolder;
}
@PreAuthorize(value = "@permissionValidator.hasCreateClusterPermission(#appId)")
@PostMapping(value = "apps/{appId}/envs/{env}/clusters")
public ClusterDTO createCluster(@PathVariable String appId, @PathVariable String env,
@Valid @RequestBody ClusterDTO cluster) {
String operator = userInfoHolder.getUser().getUserId();
cluster.setDataChangeLastModifiedBy(operator);
cluster.setDataChangeCreatedBy(operator);
return clusterService.createCluster(Env.valueOf(env), cluster);
}
@PreAuthorize(value = "@permissionValidator.isSuperAdmin()")
@DeleteMapping(value = "apps/{appId}/envs/{env}/clusters/{clusterName:.+}")
public ResponseEntity<Void> deleteCluster(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName){
clusterService.deleteCluster(Env.valueOf(env), appId, clusterName);
return ResponseEntity.ok().build();
}
@GetMapping(value = "apps/{appId}/envs/{env}/clusters/{clusterName:.+}")
public ClusterDTO loadCluster(@PathVariable("appId") String appId, @PathVariable String env, @PathVariable("clusterName") String clusterName) {
return clusterService.loadCluster(appId, Env.valueOf(env), clusterName);
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-adminservice/src/test/java/com/ctrip/framework/apollo/adminservice/controller/AbstractControllerTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.AdminServiceTestConfiguration;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AdminServiceTestConfiguration.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public abstract class AbstractControllerTest {
@Autowired
private HttpMessageConverters httpMessageConverters;
protected RestTemplate restTemplate = (new TestRestTemplate()).getRestTemplate();
@PostConstruct
private void postConstruct() {
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
restTemplate.setMessageConverters(httpMessageConverters.getConverters());
}
@Value("${local.server.port}")
protected int port;
protected String url(String path) {
return "http://localhost:" + port + path;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.AdminServiceTestConfiguration;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AdminServiceTestConfiguration.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public abstract class AbstractControllerTest {
@Autowired
private HttpMessageConverters httpMessageConverters;
protected RestTemplate restTemplate = (new TestRestTemplate()).getRestTemplate();
@PostConstruct
private void postConstruct() {
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
restTemplate.setMessageConverters(httpMessageConverters.getConverters());
}
@Value("${local.server.port}")
protected int port;
protected String url(String path) {
return "http://localhost:" + port + path;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/test/java/com/ctrip/framework/apollo/biz/BizTestConfiguration.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz;
import com.ctrip.framework.apollo.common.ApolloCommonConfig;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = {ApolloCommonConfig.class, ApolloBizConfig.class})
public class BizTestConfiguration {
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz;
import com.ctrip.framework.apollo.common.ApolloCommonConfig;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = {ApolloCommonConfig.class, ApolloBizConfig.class})
public class BizTestConfiguration {
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataResource.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.importer;
import com.ctrip.framework.apollo.core.ConfigConsts;
import java.util.Objects;
import org.springframework.boot.context.config.ConfigDataResource;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class ApolloConfigDataResource extends ConfigDataResource {
/**
* default resource instance
*/
public static final ApolloConfigDataResource DEFAULT = new ApolloConfigDataResource(
ConfigConsts.NAMESPACE_APPLICATION);
/**
* apollo config namespace
*/
private final String namespace;
public ApolloConfigDataResource(String namespace) {
this.namespace = namespace;
}
public String getNamespace() {
return namespace;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ApolloConfigDataResource that = (ApolloConfigDataResource) o;
return Objects.equals(namespace, that.namespace);
}
@Override
public int hashCode() {
return Objects.hash(namespace);
}
@Override
public String toString() {
return "ApolloConfigDataResource{" +
"namespace='" + namespace + '\'' +
'}';
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.config.data.importer;
import com.ctrip.framework.apollo.core.ConfigConsts;
import java.util.Objects;
import org.springframework.boot.context.config.ConfigDataResource;
/**
* @author vdisk <vdisk@foxmail.com>
*/
public class ApolloConfigDataResource extends ConfigDataResource {
/**
* default resource instance
*/
public static final ApolloConfigDataResource DEFAULT = new ApolloConfigDataResource(
ConfigConsts.NAMESPACE_APPLICATION);
/**
* apollo config namespace
*/
private final String namespace;
public ApolloConfigDataResource(String namespace) {
this.namespace = namespace;
}
public String getNamespace() {
return namespace;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ApolloConfigDataResource that = (ApolloConfigDataResource) o;
return Objects.equals(namespace, that.namespace);
}
@Override
public int hashCode() {
return Objects.hash(namespace);
}
@Override
public String toString() {
return "ApolloConfigDataResource{" +
"namespace='" + namespace + '\'' +
'}';
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/dto/GrayReleaseRuleDTO.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.dto;
import com.google.common.collect.Sets;
import java.util.Set;
public class GrayReleaseRuleDTO extends BaseDTO {
private String appId;
private String clusterName;
private String namespaceName;
private String branchName;
private Set<GrayReleaseRuleItemDTO> ruleItems;
private Long releaseId;
public GrayReleaseRuleDTO(String appId, String clusterName, String namespaceName, String branchName) {
this.appId = appId;
this.clusterName = clusterName;
this.namespaceName = namespaceName;
this.branchName = branchName;
this.ruleItems = Sets.newHashSet();
}
public String getAppId() {
return appId;
}
public String getClusterName() {
return clusterName;
}
public String getNamespaceName() {
return namespaceName;
}
public String getBranchName() {
return branchName;
}
public Set<GrayReleaseRuleItemDTO> getRuleItems() {
return ruleItems;
}
public void setRuleItems(Set<GrayReleaseRuleItemDTO> ruleItems) {
this.ruleItems = ruleItems;
}
public void addRuleItem(GrayReleaseRuleItemDTO ruleItem) {
this.ruleItems.add(ruleItem);
}
public Long getReleaseId() {
return releaseId;
}
public void setReleaseId(Long releaseId) {
this.releaseId = releaseId;
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.common.dto;
import com.google.common.collect.Sets;
import java.util.Set;
public class GrayReleaseRuleDTO extends BaseDTO {
private String appId;
private String clusterName;
private String namespaceName;
private String branchName;
private Set<GrayReleaseRuleItemDTO> ruleItems;
private Long releaseId;
public GrayReleaseRuleDTO(String appId, String clusterName, String namespaceName, String branchName) {
this.appId = appId;
this.clusterName = clusterName;
this.namespaceName = namespaceName;
this.branchName = branchName;
this.ruleItems = Sets.newHashSet();
}
public String getAppId() {
return appId;
}
public String getClusterName() {
return clusterName;
}
public String getNamespaceName() {
return namespaceName;
}
public String getBranchName() {
return branchName;
}
public Set<GrayReleaseRuleItemDTO> getRuleItems() {
return ruleItems;
}
public void setRuleItems(Set<GrayReleaseRuleItemDTO> ruleItems) {
this.ruleItems = ruleItems;
}
public void addRuleItem(GrayReleaseRuleItemDTO ruleItem) {
this.ruleItems.add(ruleItem);
}
public Long getReleaseId() {
return releaseId;
}
public void setReleaseId(Long releaseId) {
this.releaseId = releaseId;
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./scripts/sql/delta/v060-v062/apolloportaldb-v060-v062.sql | --
-- Copyright 2021 Apollo Authors
--
-- 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.
--
# delta schema to upgrade apollo portal db from v0.6.0 to v0.6.2
Use ApolloPortalDB;
ALTER TABLE `App` DROP INDEX `NAME`;
CREATE INDEX `IX_NAME` ON App (`Name`(191));
| --
-- Copyright 2021 Apollo Authors
--
-- 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.
--
# delta schema to upgrade apollo portal db from v0.6.0 to v0.6.2
Use ApolloPortalDB;
ALTER TABLE `App` DROP INDEX `NAME`;
CREATE INDEX `IX_NAME` ON App (`Name`(191));
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/AbstractOpenApiServiceTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.client.service;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.openapi.client.constant.ApolloOpenApiConstants;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
abstract class AbstractOpenApiServiceTest {
@Mock
protected CloseableHttpClient httpClient;
@Mock
protected CloseableHttpResponse someHttpResponse;
@Mock
protected StatusLine statusLine;
protected Gson gson;
protected String someBaseUrl;
@Before
public void setUp() throws Exception {
gson = new GsonBuilder().setDateFormat(ApolloOpenApiConstants.JSON_DATE_FORMAT).create();
someBaseUrl = "http://someBaseUrl";
when(someHttpResponse.getStatusLine()).thenReturn(statusLine);
when(statusLine.getStatusCode()).thenReturn(200);
when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(someHttpResponse);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.client.service;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.openapi.client.constant.ApolloOpenApiConstants;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
abstract class AbstractOpenApiServiceTest {
@Mock
protected CloseableHttpClient httpClient;
@Mock
protected CloseableHttpResponse someHttpResponse;
@Mock
protected StatusLine statusLine;
protected Gson gson;
protected String someBaseUrl;
@Before
public void setUp() throws Exception {
gson = new GsonBuilder().setDateFormat(ApolloOpenApiConstants.JSON_DATE_FORMAT).create();
someBaseUrl = "http://someBaseUrl";
when(someHttpResponse.getStatusLine()).thenReturn(statusLine);
when(statusLine.getStatusCode()).thenReturn(200);
when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(someHttpResponse);
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./scripts/helm/apollo-portal/templates/service-portal.yaml | #
# Copyright 2021 Apollo Authors
#
# 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.
#
kind: Service
apiVersion: v1
metadata:
name: {{ include "apollo.portal.serviceName" . }}
labels:
{{- include "apollo.portal.labels" . | nindent 4 }}
spec:
type: {{ .Values.service.type }}
ports:
- name: http
protocol: TCP
port: {{ .Values.service.port }}
targetPort: {{ .Values.service.targetPort }}
selector:
app: {{ include "apollo.portal.fullName" . }}
sessionAffinity: {{ .Values.service.sessionAffinity }} | #
# Copyright 2021 Apollo Authors
#
# 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.
#
kind: Service
apiVersion: v1
metadata:
name: {{ include "apollo.portal.serviceName" . }}
labels:
{{- include "apollo.portal.labels" . | nindent 4 }}
spec:
type: {{ .Values.service.type }}
ports:
- name: http
protocol: TCP
port: {{ .Values.service.port }}
targetPort: {{ .Values.service.targetPort }}
selector:
app: {{ include "apollo.portal.fullName" . }}
sessionAffinity: {{ .Values.service.sessionAffinity }} | -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloConfigRegistrar.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.annotation;
import com.ctrip.framework.apollo.spring.spi.ApolloConfigRegistrarHelper;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class ApolloConfigRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private final ApolloConfigRegistrarHelper helper = ServiceBootstrap.loadPrimary(ApolloConfigRegistrarHelper.class);
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
helper.registerBeanDefinitions(importingClassMetadata, registry);
}
@Override
public void setEnvironment(Environment environment) {
this.helper.setEnvironment(environment);
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.spring.annotation;
import com.ctrip.framework.apollo.spring.spi.ApolloConfigRegistrarHelper;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class ApolloConfigRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private final ApolloConfigRegistrarHelper helper = ServiceBootstrap.loadPrimary(ApolloConfigRegistrarHelper.class);
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
helper.registerBeanDefinitions(importingClassMetadata, registry);
}
@Override
public void setEnvironment(Environment environment) {
this.helper.setEnvironment(environment);
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-configservice/src/main/resources/application-consul-discovery.properties | #
# Copyright 2021 Apollo Authors
#
# 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.
#
apollo.eureka.server.enabled=false
eureka.client.enabled=false
#consul enabled
spring.cloud.consul.enabled=true
spring.cloud.consul.discovery.enabled=true
spring.cloud.consul.service-registry.enabled=true
spring.cloud.consul.discovery.heartbeat.enabled=true
spring.cloud.consul.discovery.instance-id=apollo-configservice
| #
# Copyright 2021 Apollo Authors
#
# 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.
#
apollo.eureka.server.enabled=false
eureka.client.enabled=false
#consul enabled
spring.cloud.consul.enabled=true
spring.cloud.consul.discovery.enabled=true
spring.cloud.consul.service-registry.enabled=true
spring.cloud.consul.discovery.heartbeat.enabled=true
spring.cloud.consul.discovery.instance-id=apollo-configservice
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-configservice/src/test/resources/data.sql | --
-- Copyright 2021 Apollo Authors
--
-- 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.
--
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003171','apollo-config-service','刘一鸣','liuym@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003172','apollo-admin-service','宋顺','song_s@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003173','apollo-portal','张乐','zhanglea@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('fxhermesproducer','fx-hermes-producer','梁锦华','jhliang@ctrip.com');
INSERT INTO Cluster (AppId, Name) VALUES ('100003171', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003171', 'cluster1');
INSERT INTO Cluster (AppId, Name) VALUES ('100003172', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003172', 'cluster2');
INSERT INTO Cluster (AppId, Name) VALUES ('100003173', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003173', 'cluster3');
INSERT INTO Cluster (AppId, Name) VALUES ('fxhermesproducer', 'default');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003171', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003171', 'fx.apollo.config');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003172', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003172', 'fx.apollo.admin');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003173', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003173', 'fx.apollo.portal');
INSERT INTO AppNamespace (AppID, Name) VALUES ('fxhermesproducer', 'fx.hermes.producer');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (1, '100003171', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (2, 'fxhermesproducer', 'default', 'fx.hermes.producer');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (3, '100003172', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (4, '100003173', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (5, '100003171', 'default', 'application');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (1, 'k1', 'v1', 'comment1');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (1, 'k2', 'v2', 'comment2');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (2, 'k3', 'v3', 'comment3');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (5, 'k3', 'v4', 'comment4');
INSERT INTO RELEASE (ReleaseKey, Name, Comment, AppId, ClusterName, NamespaceName, Configurations) VALUES ('TEST-RELEASE-KEY', 'REV1','First Release','100003171', 'default', 'application', '{"k1":"v1"}');
| --
-- Copyright 2021 Apollo Authors
--
-- 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.
--
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003171','apollo-config-service','刘一鸣','liuym@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003172','apollo-admin-service','宋顺','song_s@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003173','apollo-portal','张乐','zhanglea@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('fxhermesproducer','fx-hermes-producer','梁锦华','jhliang@ctrip.com');
INSERT INTO Cluster (AppId, Name) VALUES ('100003171', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003171', 'cluster1');
INSERT INTO Cluster (AppId, Name) VALUES ('100003172', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003172', 'cluster2');
INSERT INTO Cluster (AppId, Name) VALUES ('100003173', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003173', 'cluster3');
INSERT INTO Cluster (AppId, Name) VALUES ('fxhermesproducer', 'default');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003171', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003171', 'fx.apollo.config');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003172', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003172', 'fx.apollo.admin');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003173', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003173', 'fx.apollo.portal');
INSERT INTO AppNamespace (AppID, Name) VALUES ('fxhermesproducer', 'fx.hermes.producer');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (1, '100003171', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (2, 'fxhermesproducer', 'default', 'fx.hermes.producer');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (3, '100003172', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (4, '100003173', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (5, '100003171', 'default', 'application');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (1, 'k1', 'v1', 'comment1');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (1, 'k2', 'v2', 'comment2');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (2, 'k3', 'v3', 'comment3');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (5, 'k3', 'v4', 'comment4');
INSERT INTO RELEASE (ReleaseKey, Name, Comment, AppId, ClusterName, NamespaceName, Configurations) VALUES ('TEST-RELEASE-KEY', 'REV1','First Release','100003171', 'default', 'application', '{"k1":"v1"}');
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultMQService.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.spi.defaultimpl;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO;
import com.ctrip.framework.apollo.portal.spi.MQService;
public class DefaultMQService implements MQService{
@Override
public void sendPublishMsg(Env env, ReleaseHistoryBO releaseHistory) {
//do nothing
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.portal.spi.defaultimpl;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO;
import com.ctrip.framework.apollo.portal.spi.MQService;
public class DefaultMQService implements MQService{
@Override
public void sendPublishMsg(Env env, ReleaseHistoryBO releaseHistory) {
//do nothing
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-client/src/test/resources/spring/XmlConfigAnnotationTest6.xml | <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo Authors
~
~ 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.
~
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<apollo:config/>
<bean class="com.ctrip.framework.apollo.spring.XMLConfigAnnotationTest.TestApolloConfigChangeListenerWithInterestedKeysBean"/>
</beans>
| <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo Authors
~
~ 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.
~
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<apollo:config/>
<bean class="com.ctrip.framework.apollo.spring.XMLConfigAnnotationTest.TestApolloConfigChangeListenerWithInterestedKeysBean"/>
</beans>
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-configservice/pom.xml | <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo Authors
~
~ 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.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo</artifactId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>apollo-configservice</artifactId>
<name>Apollo ConfigService</name>
<properties>
<github.path>${project.artifactId}</github.path>
</properties>
<dependencies>
<!-- apollo -->
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-biz</artifactId>
</dependency>
<!-- end of apollo -->
<!-- eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-cloud-starter-netflix-archaius</artifactId>
<groupId>org.springframework.cloud</groupId>
</exclusion>
<exclusion>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<groupId>org.springframework.cloud</groupId>
</exclusion>
<exclusion>
<artifactId>ribbon-eureka</artifactId>
<groupId>com.netflix.ribbon</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-core</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-ec2</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-autoscaling</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-sts</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-route53</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<!-- duplicated with spring-security-core -->
<exclusion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-apache-client4</artifactId>
</dependency>
<!-- end of eureka -->
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-api</artifactId>
<version>${nacos-discovery-api.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<!-- JDK 1.8+ -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
</dependency>
<!-- end of JDK 1.8+ -->
<!-- JDK 11+ -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
<!-- end of JDK 11+ -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>${project.artifactId}-${project.version}-${package.environment}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/assembly-descriptor.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>1.2.2</version>
<configuration>
<imageName>apolloconfig/${project.artifactId}</imageName>
<imageTags>
<imageTag>${project.version}</imageTag>
<imageTag>latest</imageTag>
</imageTags>
<dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
<serverId>docker-hub</serverId>
<buildArgs>
<VERSION>${project.version}</VERSION>
</buildArgs>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>*.zip</include>
</resource>
</resources>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>nacos-discovery</id>
<dependencies>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
</project>
| <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo Authors
~
~ 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.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo</artifactId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>apollo-configservice</artifactId>
<name>Apollo ConfigService</name>
<properties>
<github.path>${project.artifactId}</github.path>
</properties>
<dependencies>
<!-- apollo -->
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-biz</artifactId>
</dependency>
<!-- end of apollo -->
<!-- eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-cloud-starter-netflix-archaius</artifactId>
<groupId>org.springframework.cloud</groupId>
</exclusion>
<exclusion>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<groupId>org.springframework.cloud</groupId>
</exclusion>
<exclusion>
<artifactId>ribbon-eureka</artifactId>
<groupId>com.netflix.ribbon</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-core</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-ec2</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-autoscaling</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-sts</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<exclusion>
<artifactId>aws-java-sdk-route53</artifactId>
<groupId>com.amazonaws</groupId>
</exclusion>
<!-- duplicated with spring-security-core -->
<exclusion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-apache-client4</artifactId>
</dependency>
<!-- end of eureka -->
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-api</artifactId>
<version>${nacos-discovery-api.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<!-- JDK 1.8+ -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
</dependency>
<!-- end of JDK 1.8+ -->
<!-- JDK 11+ -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
<!-- end of JDK 11+ -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>${project.artifactId}-${project.version}-${package.environment}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/assembly-descriptor.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>1.2.2</version>
<configuration>
<imageName>apolloconfig/${project.artifactId}</imageName>
<imageTags>
<imageTag>${project.version}</imageTag>
<imageTag>latest</imageTag>
</imageTags>
<dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
<serverId>docker-hub</serverId>
<buildArgs>
<VERSION>${project.version}</VERSION>
</buildArgs>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>*.zip</include>
</resource>
</resources>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>nacos-discovery</id>
<dependencies>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
</project>
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/DeferredLoggerTest.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core.utils;
import com.ctrip.framework.test.tools.AloneRunner;
import com.ctrip.framework.test.tools.AloneWith;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.slf4j.Logger;
/**
* @author kl (http://kailing.pub)
* @since 2021/5/11
*/
@RunWith(AloneRunner.class)
@AloneWith(JUnit4.class)
public class DeferredLoggerTest {
private static ByteArrayOutputStream outContent;
private static Logger logger = null;
private static PrintStream printStream;
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException {
DeferredLoggerTest.outContent = new ByteArrayOutputStream();
DeferredLoggerTest.printStream = new PrintStream(DeferredLoggerTest.outContent);
System.setOut(DeferredLoggerTest.printStream);
DeferredLoggerTest.logger = DeferredLoggerFactory.getLogger("DeferredLoggerTest");
}
@Test
public void testErrorLog() {
DeferredLoggerTest.logger.error("errorLogger");
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("errorLogger"));
}
@Test
public void testInfoLog() {
DeferredLoggerTest.logger.info("inFoLogger");
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("inFoLogger"));
}
@Test
public void testWarnLog() {
DeferredLoggerTest.logger.warn("warnLogger");
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("warnLogger"));
}
@Test
public void testDebugLog() {
DeferredLoggerTest.logger.warn("debugLogger");
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("debugLogger"));
}
@Test
public void testDeferredLog() {
DeferredLogger.enable();
DeferredLoggerTest.logger.error("errorLogger_testDeferredLog");
DeferredLoggerTest.logger.info("inFoLogger_testDeferredLog");
DeferredLoggerTest.logger.warn("warnLogger_testDeferredLog");
DeferredLoggerTest.logger.debug("debugLogger_testDeferredLog");
Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("errorLogger_testDeferredLog"));
Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("inFoLogger_testDeferredLog"));
Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("warnLogger_testDeferredLog"));
Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("debugLogger_testDeferredLog"));
DeferredLogCache.replayTo();
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("errorLogger_testDeferredLog"));
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("inFoLogger_testDeferredLog"));
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("warnLogger_testDeferredLog"));
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("debugLogger_testDeferredLog"));
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core.utils;
import com.ctrip.framework.test.tools.AloneRunner;
import com.ctrip.framework.test.tools.AloneWith;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.slf4j.Logger;
/**
* @author kl (http://kailing.pub)
* @since 2021/5/11
*/
@RunWith(AloneRunner.class)
@AloneWith(JUnit4.class)
public class DeferredLoggerTest {
private static ByteArrayOutputStream outContent;
private static Logger logger = null;
private static PrintStream printStream;
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException {
DeferredLoggerTest.outContent = new ByteArrayOutputStream();
DeferredLoggerTest.printStream = new PrintStream(DeferredLoggerTest.outContent);
System.setOut(DeferredLoggerTest.printStream);
DeferredLoggerTest.logger = DeferredLoggerFactory.getLogger("DeferredLoggerTest");
}
@Test
public void testErrorLog() {
DeferredLoggerTest.logger.error("errorLogger");
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("errorLogger"));
}
@Test
public void testInfoLog() {
DeferredLoggerTest.logger.info("inFoLogger");
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("inFoLogger"));
}
@Test
public void testWarnLog() {
DeferredLoggerTest.logger.warn("warnLogger");
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("warnLogger"));
}
@Test
public void testDebugLog() {
DeferredLoggerTest.logger.warn("debugLogger");
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("debugLogger"));
}
@Test
public void testDeferredLog() {
DeferredLogger.enable();
DeferredLoggerTest.logger.error("errorLogger_testDeferredLog");
DeferredLoggerTest.logger.info("inFoLogger_testDeferredLog");
DeferredLoggerTest.logger.warn("warnLogger_testDeferredLog");
DeferredLoggerTest.logger.debug("debugLogger_testDeferredLog");
Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("errorLogger_testDeferredLog"));
Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("inFoLogger_testDeferredLog"));
Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("warnLogger_testDeferredLog"));
Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("debugLogger_testDeferredLog"));
DeferredLogCache.replayTo();
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("errorLogger_testDeferredLog"));
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("inFoLogger_testDeferredLog"));
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("warnLogger_testDeferredLog"));
Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("debugLogger_testDeferredLog"));
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenEnvClusterDTO.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.dto;
import java.util.Set;
public class OpenEnvClusterDTO {
private String env;
private Set<String> clusters;
public String getEnv() {
return env;
}
public void setEnv(String env) {
this.env = env;
}
public Set<String> getClusters() {
return clusters;
}
public void setClusters(Set<String> clusters) {
this.clusters = clusters;
}
@Override
public String toString() {
return "OpenEnvClusterDTO{" +
"env='" + env + '\'' +
", clusters=" + clusters +
'}';
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.openapi.dto;
import java.util.Set;
public class OpenEnvClusterDTO {
private String env;
private Set<String> clusters;
public String getEnv() {
return env;
}
public void setEnv(String env) {
this.env = env;
}
public Set<String> getClusters() {
return clusters;
}
public void setClusters(Set<String> clusters) {
this.clusters = clusters;
}
@Override
public String toString() {
return "OpenEnvClusterDTO{" +
"env='" + env + '\'' +
", clusters=" + clusters +
'}';
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/service/ItemService.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.service;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.Audit;
import com.ctrip.framework.apollo.biz.entity.Item;
import com.ctrip.framework.apollo.biz.entity.Namespace;
import com.ctrip.framework.apollo.biz.repository.ItemRepository;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.common.exception.NotFoundException;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class ItemService {
private final ItemRepository itemRepository;
private final NamespaceService namespaceService;
private final AuditService auditService;
private final BizConfig bizConfig;
public ItemService(
final ItemRepository itemRepository,
final @Lazy NamespaceService namespaceService,
final AuditService auditService,
final BizConfig bizConfig) {
this.itemRepository = itemRepository;
this.namespaceService = namespaceService;
this.auditService = auditService;
this.bizConfig = bizConfig;
}
@Transactional
public Item delete(long id, String operator) {
Item item = itemRepository.findById(id).orElse(null);
if (item == null) {
throw new IllegalArgumentException("item not exist. ID:" + id);
}
item.setDeleted(true);
item.setDataChangeLastModifiedBy(operator);
Item deletedItem = itemRepository.save(item);
auditService.audit(Item.class.getSimpleName(), id, Audit.OP.DELETE, operator);
return deletedItem;
}
@Transactional
public int batchDelete(long namespaceId, String operator) {
return itemRepository.deleteByNamespaceId(namespaceId, operator);
}
public Item findOne(String appId, String clusterName, String namespaceName, String key) {
Namespace namespace = namespaceService.findOne(appId, clusterName, namespaceName);
if (namespace == null) {
throw new NotFoundException(
String.format("namespace not found for %s %s %s", appId, clusterName, namespaceName));
}
return itemRepository.findByNamespaceIdAndKey(namespace.getId(), key);
}
public Item findLastOne(String appId, String clusterName, String namespaceName) {
Namespace namespace = namespaceService.findOne(appId, clusterName, namespaceName);
if (namespace == null) {
throw new NotFoundException(
String.format("namespace not found for %s %s %s", appId, clusterName, namespaceName));
}
return findLastOne(namespace.getId());
}
public Item findLastOne(long namespaceId) {
return itemRepository.findFirst1ByNamespaceIdOrderByLineNumDesc(namespaceId);
}
public Item findOne(long itemId) {
return itemRepository.findById(itemId).orElse(null);
}
public List<Item> findItemsWithoutOrdered(Long namespaceId) {
List<Item> items = itemRepository.findByNamespaceId(namespaceId);
if (items == null) {
return Collections.emptyList();
}
return items;
}
public List<Item> findItemsWithoutOrdered(String appId, String clusterName, String namespaceName) {
Namespace namespace = namespaceService.findOne(appId, clusterName, namespaceName);
if (namespace != null) {
return findItemsWithoutOrdered(namespace.getId());
}
return Collections.emptyList();
}
public List<Item> findItemsWithOrdered(Long namespaceId) {
List<Item> items = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespaceId);
if (items == null) {
return Collections.emptyList();
}
return items;
}
public List<Item> findItemsWithOrdered(String appId, String clusterName, String namespaceName) {
Namespace namespace = namespaceService.findOne(appId, clusterName, namespaceName);
if (namespace != null) {
return findItemsWithOrdered(namespace.getId());
}
return Collections.emptyList();
}
public List<Item> findItemsModifiedAfterDate(long namespaceId, Date date) {
return itemRepository.findByNamespaceIdAndDataChangeLastModifiedTimeGreaterThan(namespaceId, date);
}
@Transactional
public Item save(Item entity) {
checkItemKeyLength(entity.getKey());
checkItemValueLength(entity.getNamespaceId(), entity.getValue());
entity.setId(0);//protection
if (entity.getLineNum() == 0) {
Item lastItem = findLastOne(entity.getNamespaceId());
int lineNum = lastItem == null ? 1 : lastItem.getLineNum() + 1;
entity.setLineNum(lineNum);
}
Item item = itemRepository.save(entity);
auditService.audit(Item.class.getSimpleName(), item.getId(), Audit.OP.INSERT,
item.getDataChangeCreatedBy());
return item;
}
@Transactional
public Item update(Item item) {
checkItemValueLength(item.getNamespaceId(), item.getValue());
Item managedItem = itemRepository.findById(item.getId()).orElse(null);
BeanUtils.copyEntityProperties(item, managedItem);
managedItem = itemRepository.save(managedItem);
auditService.audit(Item.class.getSimpleName(), managedItem.getId(), Audit.OP.UPDATE,
managedItem.getDataChangeLastModifiedBy());
return managedItem;
}
private boolean checkItemValueLength(long namespaceId, String value) {
int limit = getItemValueLengthLimit(namespaceId);
if (!StringUtils.isEmpty(value) && value.length() > limit) {
throw new BadRequestException("value too long. length limit:" + limit);
}
return true;
}
private boolean checkItemKeyLength(String key) {
if (!StringUtils.isEmpty(key) && key.length() > bizConfig.itemKeyLengthLimit()) {
throw new BadRequestException("key too long. length limit:" + bizConfig.itemKeyLengthLimit());
}
return true;
}
private int getItemValueLengthLimit(long namespaceId) {
Map<Long, Integer> namespaceValueLengthOverride = bizConfig.namespaceValueLengthLimitOverride();
if (namespaceValueLengthOverride != null && namespaceValueLengthOverride.containsKey(namespaceId)) {
return namespaceValueLengthOverride.get(namespaceId);
}
return bizConfig.itemValueLengthLimit();
}
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.service;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.Audit;
import com.ctrip.framework.apollo.biz.entity.Item;
import com.ctrip.framework.apollo.biz.entity.Namespace;
import com.ctrip.framework.apollo.biz.repository.ItemRepository;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.common.exception.NotFoundException;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class ItemService {
private final ItemRepository itemRepository;
private final NamespaceService namespaceService;
private final AuditService auditService;
private final BizConfig bizConfig;
public ItemService(
final ItemRepository itemRepository,
final @Lazy NamespaceService namespaceService,
final AuditService auditService,
final BizConfig bizConfig) {
this.itemRepository = itemRepository;
this.namespaceService = namespaceService;
this.auditService = auditService;
this.bizConfig = bizConfig;
}
@Transactional
public Item delete(long id, String operator) {
Item item = itemRepository.findById(id).orElse(null);
if (item == null) {
throw new IllegalArgumentException("item not exist. ID:" + id);
}
item.setDeleted(true);
item.setDataChangeLastModifiedBy(operator);
Item deletedItem = itemRepository.save(item);
auditService.audit(Item.class.getSimpleName(), id, Audit.OP.DELETE, operator);
return deletedItem;
}
@Transactional
public int batchDelete(long namespaceId, String operator) {
return itemRepository.deleteByNamespaceId(namespaceId, operator);
}
public Item findOne(String appId, String clusterName, String namespaceName, String key) {
Namespace namespace = namespaceService.findOne(appId, clusterName, namespaceName);
if (namespace == null) {
throw new NotFoundException(
String.format("namespace not found for %s %s %s", appId, clusterName, namespaceName));
}
return itemRepository.findByNamespaceIdAndKey(namespace.getId(), key);
}
public Item findLastOne(String appId, String clusterName, String namespaceName) {
Namespace namespace = namespaceService.findOne(appId, clusterName, namespaceName);
if (namespace == null) {
throw new NotFoundException(
String.format("namespace not found for %s %s %s", appId, clusterName, namespaceName));
}
return findLastOne(namespace.getId());
}
public Item findLastOne(long namespaceId) {
return itemRepository.findFirst1ByNamespaceIdOrderByLineNumDesc(namespaceId);
}
public Item findOne(long itemId) {
return itemRepository.findById(itemId).orElse(null);
}
public List<Item> findItemsWithoutOrdered(Long namespaceId) {
List<Item> items = itemRepository.findByNamespaceId(namespaceId);
if (items == null) {
return Collections.emptyList();
}
return items;
}
public List<Item> findItemsWithoutOrdered(String appId, String clusterName, String namespaceName) {
Namespace namespace = namespaceService.findOne(appId, clusterName, namespaceName);
if (namespace != null) {
return findItemsWithoutOrdered(namespace.getId());
}
return Collections.emptyList();
}
public List<Item> findItemsWithOrdered(Long namespaceId) {
List<Item> items = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespaceId);
if (items == null) {
return Collections.emptyList();
}
return items;
}
public List<Item> findItemsWithOrdered(String appId, String clusterName, String namespaceName) {
Namespace namespace = namespaceService.findOne(appId, clusterName, namespaceName);
if (namespace != null) {
return findItemsWithOrdered(namespace.getId());
}
return Collections.emptyList();
}
public List<Item> findItemsModifiedAfterDate(long namespaceId, Date date) {
return itemRepository.findByNamespaceIdAndDataChangeLastModifiedTimeGreaterThan(namespaceId, date);
}
@Transactional
public Item save(Item entity) {
checkItemKeyLength(entity.getKey());
checkItemValueLength(entity.getNamespaceId(), entity.getValue());
entity.setId(0);//protection
if (entity.getLineNum() == 0) {
Item lastItem = findLastOne(entity.getNamespaceId());
int lineNum = lastItem == null ? 1 : lastItem.getLineNum() + 1;
entity.setLineNum(lineNum);
}
Item item = itemRepository.save(entity);
auditService.audit(Item.class.getSimpleName(), item.getId(), Audit.OP.INSERT,
item.getDataChangeCreatedBy());
return item;
}
@Transactional
public Item update(Item item) {
checkItemValueLength(item.getNamespaceId(), item.getValue());
Item managedItem = itemRepository.findById(item.getId()).orElse(null);
BeanUtils.copyEntityProperties(item, managedItem);
managedItem = itemRepository.save(managedItem);
auditService.audit(Item.class.getSimpleName(), managedItem.getId(), Audit.OP.UPDATE,
managedItem.getDataChangeLastModifiedBy());
return managedItem;
}
private boolean checkItemValueLength(long namespaceId, String value) {
int limit = getItemValueLengthLimit(namespaceId);
if (!StringUtils.isEmpty(value) && value.length() > limit) {
throw new BadRequestException("value too long. length limit:" + limit);
}
return true;
}
private boolean checkItemKeyLength(String key) {
if (!StringUtils.isEmpty(key) && key.length() > bizConfig.itemKeyLengthLimit()) {
throw new BadRequestException("key too long. length limit:" + bizConfig.itemKeyLengthLimit());
}
return true;
}
private int getItemValueLengthLimit(long namespaceId) {
Map<Long, Integer> namespaceValueLengthOverride = bizConfig.namespaceValueLengthLimitOverride();
if (namespaceValueLengthOverride != null && namespaceValueLengthOverride.containsKey(namespaceId)) {
return namespaceValueLengthOverride.get(namespaceId);
}
return bizConfig.itemValueLengthLimit();
}
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/message/MessageSender.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.message;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface MessageSender {
void sendMessage(String message, String channel);
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz.message;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface MessageSender {
void sendMessage(String message, String channel);
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/datasource/package-info.java | /*
* Copyright 2021 Apollo Authors
*
* 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.
*
*/
/**
* 携程内部的dal,第三方公司可替换实现
*/
package com.ctrip.framework.apollo.common.datasource;
| /*
* Copyright 2021 Apollo Authors
*
* 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.
*
*/
/**
* 携程内部的dal,第三方公司可替换实现
*/
package com.ctrip.framework.apollo.common.datasource;
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/spi/Ordered.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core.spi;
/**
* {@code Ordered} is an interface that can be implemented by objects that
* should be <em>orderable</em>, for example in a {@code Collection}.
*
* <p>The actual {@link #getOrder() order} can be interpreted as prioritization,
* with the first object (with the lowest order value) having the highest
* priority.
*
* @since 1.0.0
*/
public interface Ordered {
/**
* Useful constant for the highest precedence value.
* @see java.lang.Integer#MIN_VALUE
*/
int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;
/**
* Useful constant for the lowest precedence value.
* @see java.lang.Integer#MAX_VALUE
*/
int LOWEST_PRECEDENCE = Integer.MAX_VALUE;
/**
* Get the order value of this object.
* <p>Higher values are interpreted as lower priority. As a consequence,
* the object with the lowest value has the highest priority (somewhat
* analogous to Servlet {@code load-on-startup} values).
* <p>Same order values will result in arbitrary sort positions for the
* affected objects.
* @return the order value
* @see #HIGHEST_PRECEDENCE
* @see #LOWEST_PRECEDENCE
*/
int getOrder();
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core.spi;
/**
* {@code Ordered} is an interface that can be implemented by objects that
* should be <em>orderable</em>, for example in a {@code Collection}.
*
* <p>The actual {@link #getOrder() order} can be interpreted as prioritization,
* with the first object (with the lowest order value) having the highest
* priority.
*
* @since 1.0.0
*/
public interface Ordered {
/**
* Useful constant for the highest precedence value.
* @see java.lang.Integer#MIN_VALUE
*/
int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;
/**
* Useful constant for the lowest precedence value.
* @see java.lang.Integer#MAX_VALUE
*/
int LOWEST_PRECEDENCE = Integer.MAX_VALUE;
/**
* Get the order value of this object.
* <p>Higher values are interpreted as lower priority. As a consequence,
* the object with the lowest value has the highest priority (somewhat
* analogous to Servlet {@code load-on-startup} values).
* <p>Same order values will result in arbitrary sort positions for the
* affected objects.
* @return the order value
* @see #HIGHEST_PRECEDENCE
* @see #LOWEST_PRECEDENCE
*/
int getOrder();
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/ApolloBizConfig.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@EnableAutoConfiguration
@Configuration
@ComponentScan(basePackageClasses = ApolloBizConfig.class)
public class ApolloBizConfig {
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.biz;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@EnableAutoConfiguration
@Configuration
@ComponentScan(basePackageClasses = ApolloBizConfig.class)
public class ApolloBizConfig {
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/resources/static/app/access_key.html | <!--
~ Copyright 2021 Apollo Authors
~
~ 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.
~
-->
<!doctype html>
<html ng-app="access_key">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="icon" href="../img/config.png">
<!-- styles -->
<link rel="stylesheet" type="text/css" href="../vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../vendor/angular/angular-toastr-1.4.1.min.css">
<link rel="stylesheet" type="text/css" media='all' href="../vendor/angular/loading-bar.min.css">
<link rel="stylesheet" type="text/css" href="../styles/common-style.css">
<link rel="stylesheet" type="text/css" href="../vendor/select2/select2.min.css">
<title>{{'Config.AccessKeyManage' | translate }}</title>
</head>
<body>
<apollonav></apollonav>
<div class="container-fluid apollo-container project-setting" ng-controller="AccessKeyController">
<section class="col-md-10 col-md-offset-1 panel hidden">
<header class="panel-heading">
<div class="row">
<div class="col-md-9">
<h4 class="modal-title">{{'Config.AccessKeyManage' | translate }} (
{{'Common.AppId' | translate }}:<label ng-bind="pageContext.appId"></label> )
</h4>
</div>
<div class="col-md-3 text-right">
<a type="button" class="btn btn-info" data-dismiss="modal"
href="{{ '/config.html' | prefixPath }}?#appid={{pageContext.appId}}">{{'Common.ReturnToIndex' | translate }}
</a>
</div>
</div>
</header>
<div class="panel-body row">
<section class="context" ng-show="hasAssignUserPermission">
<section class="form-horizontal">
<div class="alert alert-info no-radius" role="alert">
<strong>Tips:</strong>
<ul>
<li>{{'AccessKey.Tips.1' | translate }}</li>
<li>{{'AccessKey.Tips.2' | translate }}</li>
<li>{{'AccessKey.Tips.3' | translate }}</li>
<ul>
<li>{{'AccessKey.Tips.3.1' | translate }}</li>
<li>{{'AccessKey.Tips.3.2' | translate }}</li>
<li>{{'AccessKey.Tips.3.3' | translate }}</li>
</ul>
</ul>
</div>
</section>
<section>
<div class="row">
<form class="col-sm-8 form-inline" ng-submit="create()">
<div class="form-group">
<select class="form-control input-sm" style="width: 450px;" ng-model="addAccessKeySelectedEnv">
<option value="">{{'Cluster.PleaseChooseEnvironment' | translate }}</option>
<option ng-repeat="env in envs" ng-value="env">{{env}}</option>
</select>
</div>
<button type="submit" class="btn btn-default" style="margin-left: 20px;"
ng-disabled="addAccessKeySelectedEnv == ''">{{'App.Setting.Add' | translate }}
</button>
</form>
</div>
</section>
<!--application info-->
<section ng-repeat="env in envs" ng-value="env">
<hr>
<h4>{{'Common.Environment' | translate }}: {{env}}
</h4>
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>{{'AccessKey.ConfigAccessKeys.Secret' | translate }}</th>
<th>{{'AccessKey.ConfigAccessKeys.Status' | translate }}</th>
<th>{{'AccessKey.ConfigAccessKeys.LastModify' | translate }}</th>
<th>{{'AccessKey.ConfigAccessKeys.LastModifyTime' | translate }}</th>
<th>{{'AccessKey.ConfigAccessKeys.Operator' | translate }}</th>
</tr>
</thead>
<tbody>
<tr ng-show="(!accessKeys[env] || accessKeys[env].length < 1)">
<td colspan="5" style="text-align: center;">{{'AccessKey.NoAccessKeyServiceTips' | translate }}</td>
</tr>
<tr ng-show="accessKeys[env] && accessKeys[env].length > 0"
ng-repeat="accessKey in accessKeys[env]">
<td style="text-align: center;">{{accessKey.secret}}</td>
<td style="text-align: center;" ng-style="{'color': accessKey.enabled ? '#5cb85c' : '#d20707'}">{{accessKey.enabled ? ('AccessKey.Operator.Enabled' | translate) : ('AccessKey.Operator.Disabled' | translate) }}</td>
<td style="text-align: center;">{{accessKey.dataChangeLastModifiedBy}}</td>
<td style="text-align: center;">{{accessKey.dataChangeLastModifiedTime | date: 'yyyy-MM-dd HH:mm:ss'}}</td>
<td style="text-align: center;">
<a href="javascript:;"
ng-click="enable(accessKey.id, env)" ng-if="!accessKey.enabled">{{'AccessKey.Operator.Enable' | translate}}</a>
<a href="javascript:;"
ng-click="disable(accessKey.id, env)" ng-if="accessKey.enabled">{{'AccessKey.Operator.Disable' | translate}}</a>
<a href="javascript:;"
ng-click="remove(accessKey.id, env)" ng-if="!accessKey.enabled">{{'AccessKey.Operator.Remove' | translate }}</a>
</td>
</tr>
</tbody>
</table>
</section>
</section>
<section class="context" ng-show="!hasAssignUserPermission">
<div class="panel-body text-center">
<h4 translate="App.AccessKey.NoPermissionTips" translate-value-users="{{admins.join(',')}}"></h4>
</div>
</section>
</div>
</section>
</div>
<div ng-include="'../views/common/footer.html'"></div>
<!-- jquery.js -->
<script src="../vendor/jquery.min.js" type="text/javascript"></script>
<!--angular-->
<script src="../vendor/angular/angular.min.js"></script>
<script src="../vendor/angular/angular-route.min.js"></script>
<script src="../vendor/angular/angular-resource.min.js"></script>
<script src="../vendor/angular/angular-toastr-1.4.1.tpls.min.js"></script>
<script src="../vendor/angular/loading-bar.min.js"></script>
<script src="../vendor/angular/angular-cookies.min.js"></script>
<script src="../vendor/angular/angular-translate.2.18.1/angular-translate.min.js"></script>
<script src="../vendor/angular/angular-translate.2.18.1/angular-translate-loader-static-files.min.js"></script>
<script src="../vendor/angular/angular-translate.2.18.1/angular-translate-storage-cookie.min.js"></script>
<!--valdr-->
<script src="../vendor/valdr/valdr.min.js" type="text/javascript"></script>
<script src="../vendor/valdr/valdr-message.min.js" type="text/javascript"></script>
<!-- bootstrap.js -->
<script src="../vendor/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../vendor/lodash.min.js"></script>
<script src="../vendor/select2/select2.min.js" type="text/javascript"></script>
<!--biz-->
<!--must import-->
<script type="application/javascript" src="../scripts/app.js"></script>
<script type="application/javascript" src="../scripts/services/AppService.js"></script>
<script type="application/javascript" src="../scripts/services/EnvService.js"></script>
<script type="application/javascript" src="../scripts/services/UserService.js"></script>
<script type="application/javascript" src="../scripts/services/CommonService.js"></script>
<script type="application/javascript" src="../scripts/services/PermissionService.js"></script>
<script type="application/javascript" src="../scripts/services/OrganizationService.js"></script>
<script type="application/javascript" src="../scripts/services/PermissionService.js"></script>
<script type="application/javascript" src="../scripts/services/AccessKeyService.js"></script>
<script type="application/javascript" src="../scripts/AppUtils.js"></script>
<script type="application/javascript" src="../scripts/PageCommon.js"></script>
<script type="application/javascript" src="../scripts/directive/directive.js"></script>
<script type="application/javascript" src="../scripts/valdr.js"></script>
<script type="application/javascript" src="../scripts/controller/AccessKeyController.js"></script>
</body>
</html> | <!--
~ Copyright 2021 Apollo Authors
~
~ 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.
~
-->
<!doctype html>
<html ng-app="access_key">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="icon" href="../img/config.png">
<!-- styles -->
<link rel="stylesheet" type="text/css" href="../vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../vendor/angular/angular-toastr-1.4.1.min.css">
<link rel="stylesheet" type="text/css" media='all' href="../vendor/angular/loading-bar.min.css">
<link rel="stylesheet" type="text/css" href="../styles/common-style.css">
<link rel="stylesheet" type="text/css" href="../vendor/select2/select2.min.css">
<title>{{'Config.AccessKeyManage' | translate }}</title>
</head>
<body>
<apollonav></apollonav>
<div class="container-fluid apollo-container project-setting" ng-controller="AccessKeyController">
<section class="col-md-10 col-md-offset-1 panel hidden">
<header class="panel-heading">
<div class="row">
<div class="col-md-9">
<h4 class="modal-title">{{'Config.AccessKeyManage' | translate }} (
{{'Common.AppId' | translate }}:<label ng-bind="pageContext.appId"></label> )
</h4>
</div>
<div class="col-md-3 text-right">
<a type="button" class="btn btn-info" data-dismiss="modal"
href="{{ '/config.html' | prefixPath }}?#appid={{pageContext.appId}}">{{'Common.ReturnToIndex' | translate }}
</a>
</div>
</div>
</header>
<div class="panel-body row">
<section class="context" ng-show="hasAssignUserPermission">
<section class="form-horizontal">
<div class="alert alert-info no-radius" role="alert">
<strong>Tips:</strong>
<ul>
<li>{{'AccessKey.Tips.1' | translate }}</li>
<li>{{'AccessKey.Tips.2' | translate }}</li>
<li>{{'AccessKey.Tips.3' | translate }}</li>
<ul>
<li>{{'AccessKey.Tips.3.1' | translate }}</li>
<li>{{'AccessKey.Tips.3.2' | translate }}</li>
<li>{{'AccessKey.Tips.3.3' | translate }}</li>
</ul>
</ul>
</div>
</section>
<section>
<div class="row">
<form class="col-sm-8 form-inline" ng-submit="create()">
<div class="form-group">
<select class="form-control input-sm" style="width: 450px;" ng-model="addAccessKeySelectedEnv">
<option value="">{{'Cluster.PleaseChooseEnvironment' | translate }}</option>
<option ng-repeat="env in envs" ng-value="env">{{env}}</option>
</select>
</div>
<button type="submit" class="btn btn-default" style="margin-left: 20px;"
ng-disabled="addAccessKeySelectedEnv == ''">{{'App.Setting.Add' | translate }}
</button>
</form>
</div>
</section>
<!--application info-->
<section ng-repeat="env in envs" ng-value="env">
<hr>
<h4>{{'Common.Environment' | translate }}: {{env}}
</h4>
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>{{'AccessKey.ConfigAccessKeys.Secret' | translate }}</th>
<th>{{'AccessKey.ConfigAccessKeys.Status' | translate }}</th>
<th>{{'AccessKey.ConfigAccessKeys.LastModify' | translate }}</th>
<th>{{'AccessKey.ConfigAccessKeys.LastModifyTime' | translate }}</th>
<th>{{'AccessKey.ConfigAccessKeys.Operator' | translate }}</th>
</tr>
</thead>
<tbody>
<tr ng-show="(!accessKeys[env] || accessKeys[env].length < 1)">
<td colspan="5" style="text-align: center;">{{'AccessKey.NoAccessKeyServiceTips' | translate }}</td>
</tr>
<tr ng-show="accessKeys[env] && accessKeys[env].length > 0"
ng-repeat="accessKey in accessKeys[env]">
<td style="text-align: center;">{{accessKey.secret}}</td>
<td style="text-align: center;" ng-style="{'color': accessKey.enabled ? '#5cb85c' : '#d20707'}">{{accessKey.enabled ? ('AccessKey.Operator.Enabled' | translate) : ('AccessKey.Operator.Disabled' | translate) }}</td>
<td style="text-align: center;">{{accessKey.dataChangeLastModifiedBy}}</td>
<td style="text-align: center;">{{accessKey.dataChangeLastModifiedTime | date: 'yyyy-MM-dd HH:mm:ss'}}</td>
<td style="text-align: center;">
<a href="javascript:;"
ng-click="enable(accessKey.id, env)" ng-if="!accessKey.enabled">{{'AccessKey.Operator.Enable' | translate}}</a>
<a href="javascript:;"
ng-click="disable(accessKey.id, env)" ng-if="accessKey.enabled">{{'AccessKey.Operator.Disable' | translate}}</a>
<a href="javascript:;"
ng-click="remove(accessKey.id, env)" ng-if="!accessKey.enabled">{{'AccessKey.Operator.Remove' | translate }}</a>
</td>
</tr>
</tbody>
</table>
</section>
</section>
<section class="context" ng-show="!hasAssignUserPermission">
<div class="panel-body text-center">
<h4 translate="App.AccessKey.NoPermissionTips" translate-value-users="{{admins.join(',')}}"></h4>
</div>
</section>
</div>
</section>
</div>
<div ng-include="'../views/common/footer.html'"></div>
<!-- jquery.js -->
<script src="../vendor/jquery.min.js" type="text/javascript"></script>
<!--angular-->
<script src="../vendor/angular/angular.min.js"></script>
<script src="../vendor/angular/angular-route.min.js"></script>
<script src="../vendor/angular/angular-resource.min.js"></script>
<script src="../vendor/angular/angular-toastr-1.4.1.tpls.min.js"></script>
<script src="../vendor/angular/loading-bar.min.js"></script>
<script src="../vendor/angular/angular-cookies.min.js"></script>
<script src="../vendor/angular/angular-translate.2.18.1/angular-translate.min.js"></script>
<script src="../vendor/angular/angular-translate.2.18.1/angular-translate-loader-static-files.min.js"></script>
<script src="../vendor/angular/angular-translate.2.18.1/angular-translate-storage-cookie.min.js"></script>
<!--valdr-->
<script src="../vendor/valdr/valdr.min.js" type="text/javascript"></script>
<script src="../vendor/valdr/valdr-message.min.js" type="text/javascript"></script>
<!-- bootstrap.js -->
<script src="../vendor/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../vendor/lodash.min.js"></script>
<script src="../vendor/select2/select2.min.js" type="text/javascript"></script>
<!--biz-->
<!--must import-->
<script type="application/javascript" src="../scripts/app.js"></script>
<script type="application/javascript" src="../scripts/services/AppService.js"></script>
<script type="application/javascript" src="../scripts/services/EnvService.js"></script>
<script type="application/javascript" src="../scripts/services/UserService.js"></script>
<script type="application/javascript" src="../scripts/services/CommonService.js"></script>
<script type="application/javascript" src="../scripts/services/PermissionService.js"></script>
<script type="application/javascript" src="../scripts/services/OrganizationService.js"></script>
<script type="application/javascript" src="../scripts/services/PermissionService.js"></script>
<script type="application/javascript" src="../scripts/services/AccessKeyService.js"></script>
<script type="application/javascript" src="../scripts/AppUtils.js"></script>
<script type="application/javascript" src="../scripts/PageCommon.js"></script>
<script type="application/javascript" src="../scripts/directive/directive.js"></script>
<script type="application/javascript" src="../scripts/valdr.js"></script>
<script type="application/javascript" src="../scripts/controller/AccessKeyController.js"></script>
</body>
</html> | -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-portal/src/main/resources/static/scripts/controller/NamespaceController.js | /*
* Copyright 2021 Apollo Authors
*
* 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.
*
*/
namespace_module.controller("LinkNamespaceController",
['$scope', '$location', '$window', '$translate', 'toastr', 'AppService', 'AppUtil', 'NamespaceService',
'PermissionService', 'CommonService',
function ($scope, $location, $window, $translate, toastr, AppService, AppUtil, NamespaceService,
PermissionService, CommonService) {
var params = AppUtil.parseParams($location.$$url);
$scope.appId = params.appid;
$scope.type = 'link';
$scope.step = 1;
$scope.submitBtnDisabled = false;
$scope.appendNamespacePrefix = true;
PermissionService.has_root_permission().then(function (result) {
$scope.hasRootPermission = result.hasPermission;
});
CommonService.getPageSetting().then(function (setting) {
$scope.pageSetting = setting;
});
NamespaceService.find_public_namespaces().then(function (result) {
var publicNamespaces = [];
result.forEach(function (item) {
var namespace = {};
namespace.id = item.name;
namespace.text = item.name;
publicNamespaces.push(namespace);
});
$('#namespaces').select2({
placeholder: $translate.instant('Namespace.PleaseChooseNamespace'),
width: '100%',
data: publicNamespaces
});
$(".apollo-container").removeClass("hidden");
}, function (result) {
toastr.error(AppUtil.errorMsg(result), $translate.instant('Namespace.LoadingPublicNamespaceError'));
});
AppService.load($scope.appId).then(function (result) {
$scope.appBaseInfo = result;
$scope.appBaseInfo.namespacePrefix = result.orgId + '.';
}, function (result) {
toastr.error(AppUtil.errorMsg(result), $translate.instant('Namespace.LoadingAppInfoError'));
});
$scope.appNamespace = {
appId: $scope.appId,
name: '',
comment: '',
isPublic: true,
format: 'properties'
};
$scope.switchNSType = function (type) {
$scope.appNamespace.isPublic = type;
};
$scope.concatNamespace = function () {
if (!$scope.appBaseInfo) {
return '';
}
var appNamespaceName = $scope.appNamespace.name ? $scope.appNamespace.name : '';
if (shouldAppendNamespacePrefix()) {
return $scope.appBaseInfo.namespacePrefix + appNamespaceName;
}
return appNamespaceName;
};
function shouldAppendNamespacePrefix() {
return $scope.appendNamespacePrefix;
}
var selectedClusters = [];
$scope.collectSelectedClusters = function (data) {
selectedClusters = data;
};
$scope.createNamespace = function () {
if ($scope.type == 'link') {
if (selectedClusters.length == 0) {
toastr.warning($translate.instant('Namespace.PleaseChooseCluster'));
return;
}
if ($scope.namespaceType == 1) {
var selectedNamespaceName = $('#namespaces').select2('data')[0].id;
if (!selectedNamespaceName) {
toastr.warning($translate.instant('Namespace.PleaseChooseNamespace'));
return;
}
$scope.namespaceName = selectedNamespaceName;
}
var namespaceCreationModels = [];
selectedClusters.forEach(function (cluster) {
namespaceCreationModels.push({
env: cluster.env,
namespace: {
appId: $scope.appId,
clusterName: cluster.clusterName,
namespaceName: $scope.namespaceName
}
});
});
$scope.submitBtnDisabled = true;
NamespaceService.createNamespace($scope.appId, namespaceCreationModels)
.then(function (result) {
toastr.success($translate.instant('Common.Created'));
$scope.step = 2;
setInterval(function () {
$scope.submitBtnDisabled = false;
$window.location.href =
AppUtil.prefixPath() + '/namespace/role.html?#appid=' + $scope.appId
+ "&namespaceName=" + $scope.namespaceName;
}, 1000);
}, function (result) {
$scope.submitBtnDisabled = false;
toastr.error(AppUtil.errorMsg(result));
});
} else {
var namespaceNameLength = $scope.concatNamespace().length;
if (namespaceNameLength > 32) {
var errorTip = $translate.instant('Namespace.CheckNamespaceNameLengthTip', {
departmentLength: namespaceNameLength - $scope.appNamespace.name.length,
namespaceLength: $scope.appNamespace.name.length
});
toastr.error(errorTip);
return;
}
$scope.submitBtnDisabled = true;
//only append namespace prefix for public app namespace
var appendNamespacePrefix = shouldAppendNamespacePrefix();
NamespaceService.createAppNamespace($scope.appId, $scope.appNamespace, appendNamespacePrefix).then(
function (result) {
$scope.step = 2;
setTimeout(function () {
$scope.submitBtnDisabled = false;
$window.location.href =
AppUtil.prefixPath() + "/namespace/role.html?#/appid=" + $scope.appId
+ "&namespaceName=" + result.name;
}, 1000);
}, function (result) {
$scope.submitBtnDisabled = false;
toastr.error(AppUtil.errorMsg(result), $translate.instant('Common.CreateFailed'));
});
}
};
$scope.namespaceType = 1;
$scope.selectNamespaceType = function (type) {
$scope.namespaceType = type;
};
$scope.back = function () {
$window.location.href = AppUtil.prefixPath() + '/config.html?#appid=' + $scope.appId;
};
$scope.switchType = function (type) {
$scope.type = type;
};
}]);
| /*
* Copyright 2021 Apollo Authors
*
* 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.
*
*/
namespace_module.controller("LinkNamespaceController",
['$scope', '$location', '$window', '$translate', 'toastr', 'AppService', 'AppUtil', 'NamespaceService',
'PermissionService', 'CommonService',
function ($scope, $location, $window, $translate, toastr, AppService, AppUtil, NamespaceService,
PermissionService, CommonService) {
var params = AppUtil.parseParams($location.$$url);
$scope.appId = params.appid;
$scope.type = 'link';
$scope.step = 1;
$scope.submitBtnDisabled = false;
$scope.appendNamespacePrefix = true;
PermissionService.has_root_permission().then(function (result) {
$scope.hasRootPermission = result.hasPermission;
});
CommonService.getPageSetting().then(function (setting) {
$scope.pageSetting = setting;
});
NamespaceService.find_public_namespaces().then(function (result) {
var publicNamespaces = [];
result.forEach(function (item) {
var namespace = {};
namespace.id = item.name;
namespace.text = item.name;
publicNamespaces.push(namespace);
});
$('#namespaces').select2({
placeholder: $translate.instant('Namespace.PleaseChooseNamespace'),
width: '100%',
data: publicNamespaces
});
$(".apollo-container").removeClass("hidden");
}, function (result) {
toastr.error(AppUtil.errorMsg(result), $translate.instant('Namespace.LoadingPublicNamespaceError'));
});
AppService.load($scope.appId).then(function (result) {
$scope.appBaseInfo = result;
$scope.appBaseInfo.namespacePrefix = result.orgId + '.';
}, function (result) {
toastr.error(AppUtil.errorMsg(result), $translate.instant('Namespace.LoadingAppInfoError'));
});
$scope.appNamespace = {
appId: $scope.appId,
name: '',
comment: '',
isPublic: true,
format: 'properties'
};
$scope.switchNSType = function (type) {
$scope.appNamespace.isPublic = type;
};
$scope.concatNamespace = function () {
if (!$scope.appBaseInfo) {
return '';
}
var appNamespaceName = $scope.appNamespace.name ? $scope.appNamespace.name : '';
if (shouldAppendNamespacePrefix()) {
return $scope.appBaseInfo.namespacePrefix + appNamespaceName;
}
return appNamespaceName;
};
function shouldAppendNamespacePrefix() {
return $scope.appendNamespacePrefix;
}
var selectedClusters = [];
$scope.collectSelectedClusters = function (data) {
selectedClusters = data;
};
$scope.createNamespace = function () {
if ($scope.type == 'link') {
if (selectedClusters.length == 0) {
toastr.warning($translate.instant('Namespace.PleaseChooseCluster'));
return;
}
if ($scope.namespaceType == 1) {
var selectedNamespaceName = $('#namespaces').select2('data')[0].id;
if (!selectedNamespaceName) {
toastr.warning($translate.instant('Namespace.PleaseChooseNamespace'));
return;
}
$scope.namespaceName = selectedNamespaceName;
}
var namespaceCreationModels = [];
selectedClusters.forEach(function (cluster) {
namespaceCreationModels.push({
env: cluster.env,
namespace: {
appId: $scope.appId,
clusterName: cluster.clusterName,
namespaceName: $scope.namespaceName
}
});
});
$scope.submitBtnDisabled = true;
NamespaceService.createNamespace($scope.appId, namespaceCreationModels)
.then(function (result) {
toastr.success($translate.instant('Common.Created'));
$scope.step = 2;
setInterval(function () {
$scope.submitBtnDisabled = false;
$window.location.href =
AppUtil.prefixPath() + '/namespace/role.html?#appid=' + $scope.appId
+ "&namespaceName=" + $scope.namespaceName;
}, 1000);
}, function (result) {
$scope.submitBtnDisabled = false;
toastr.error(AppUtil.errorMsg(result));
});
} else {
var namespaceNameLength = $scope.concatNamespace().length;
if (namespaceNameLength > 32) {
var errorTip = $translate.instant('Namespace.CheckNamespaceNameLengthTip', {
departmentLength: namespaceNameLength - $scope.appNamespace.name.length,
namespaceLength: $scope.appNamespace.name.length
});
toastr.error(errorTip);
return;
}
$scope.submitBtnDisabled = true;
//only append namespace prefix for public app namespace
var appendNamespacePrefix = shouldAppendNamespacePrefix();
NamespaceService.createAppNamespace($scope.appId, $scope.appNamespace, appendNamespacePrefix).then(
function (result) {
$scope.step = 2;
setTimeout(function () {
$scope.submitBtnDisabled = false;
$window.location.href =
AppUtil.prefixPath() + "/namespace/role.html?#/appid=" + $scope.appId
+ "&namespaceName=" + result.name;
}, 1000);
}, function (result) {
$scope.submitBtnDisabled = false;
toastr.error(AppUtil.errorMsg(result), $translate.instant('Common.CreateFailed'));
});
}
};
$scope.namespaceType = 1;
$scope.selectNamespaceType = function (type) {
$scope.namespaceType = type;
};
$scope.back = function () {
$window.location.href = AppUtil.prefixPath() + '/config.html?#appid=' + $scope.appId;
};
$scope.switchType = function (type) {
$scope.type = type;
};
}]);
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./apollo-configservice/src/main/java/com/ctrip/framework/apollo/metaservice/service/DefaultDiscoveryService.java | /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.metaservice.service;
import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
/**
* Default discovery service for Eureka
*/
@Service
@ConditionalOnMissingProfile({"kubernetes", "nacos-discovery", "consul-discovery"})
public class DefaultDiscoveryService implements DiscoveryService {
private final EurekaClient eurekaClient;
public DefaultDiscoveryService(final EurekaClient eurekaClient) {
this.eurekaClient = eurekaClient;
}
@Override
public List<ServiceDTO> getServiceInstances(String serviceId) {
Application application = eurekaClient.getApplication(serviceId);
if (application == null || CollectionUtils.isEmpty(application.getInstances())) {
Tracer.logEvent("Apollo.Discovery.NotFound", serviceId);
return Collections.emptyList();
}
return application.getInstances().stream().map(instanceInfoToServiceDTOFunc)
.collect(Collectors.toList());
}
private static final Function<InstanceInfo, ServiceDTO> instanceInfoToServiceDTOFunc = instance -> {
ServiceDTO service = new ServiceDTO();
service.setAppName(instance.getAppName());
service.setInstanceId(instance.getInstanceId());
service.setHomepageUrl(instance.getHomePageUrl());
return service;
};
}
| /*
* Copyright 2021 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.metaservice.service;
import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
/**
* Default discovery service for Eureka
*/
@Service
@ConditionalOnMissingProfile({"kubernetes", "nacos-discovery", "consul-discovery"})
public class DefaultDiscoveryService implements DiscoveryService {
private final EurekaClient eurekaClient;
public DefaultDiscoveryService(final EurekaClient eurekaClient) {
this.eurekaClient = eurekaClient;
}
@Override
public List<ServiceDTO> getServiceInstances(String serviceId) {
Application application = eurekaClient.getApplication(serviceId);
if (application == null || CollectionUtils.isEmpty(application.getInstances())) {
Tracer.logEvent("Apollo.Discovery.NotFound", serviceId);
return Collections.emptyList();
}
return application.getInstances().stream().map(instanceInfoToServiceDTOFunc)
.collect(Collectors.toList());
}
private static final Function<InstanceInfo, ServiceDTO> instanceInfoToServiceDTOFunc = instance -> {
ServiceDTO service = new ServiceDTO();
service.setAppName(instance.getAppName());
service.setInstanceId(instance.getInstanceId());
service.setHomepageUrl(instance.getHomePageUrl());
return service;
};
}
| -1 |
apolloconfig/apollo | 3,870 | fix apollo config data loader with profiles | ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| vdiskg | 2021-08-04T14:42:01Z | 2021-08-10T01:11:02Z | 8c0241cbb2041eb3e34cb8c12a7dc1f1e46417ed | 2c9b4dccbcf31012913b270cc356a30ab0cab89f | fix apollo config data loader with profiles. ## What's the purpose of this PR
fix apollo config data loader with profiles
## Which issue(s) this PR fixes:
Fixes #3867
## Brief changelog
add a field `m_pureApolloConfig` for `DefaultConfig` to prevent the `DefaultConfig` return the properties from the `system property` or `environment variables` when work with config data loader.
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
- [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
| ./doc/images/local-development/apollo-demo-vm-options.png | PNG
IHDR
iCCPICC Profile HWXS[R -)wH
H! JbG\*]Qp-@Eee],Pyo9sNΝ lFU |IL#2 Fl('**@.nB[(l$u*' DAqr > @zYy<KpkJp[Kmb f@t $tGIN 'ͅ>99+!6OO|dǰ,l3[rţkFGKby
`*GA|ϕKqp~#9 PeA1C#lt.G#!r*̍Gr?2x!'
I@+
=T ㉞)G@q(+&L>aQ_ĨP-l4a`ƅrҵ`-``\,'J8`\ N
-[%ǪyAѲ<cE1s{. *V
GA8 İ\ -l$kFg$HGhlt
˘ViB,\=pd总nʣ`b bΆMF{NE07n#
BO^V33dʣK>GmpS =!g#alNP=Coq= ,,R~1}#.~Ėa)"vkL֊u`$xH+ath),?jc`o%fH^ܼ9B~zF<fcktw@˶7鞍0.}*ӿF y
7kX8e:v3ԁF `
"A,H3`3@<A)(zl;Apen{.0ށaAH
#Z>bX!+ H4 #%H9RlFv ȯrF H?b(UGuQStah,:MG"]nDkнh3z
@{0E`6+EbX&`eX%V5bmw`Gq&nk39x> _of~
A`Ep' YRB%a70,|oD"hFte18D<I&>&H$-ɓIb
HM>"Y@$'br%y8*yXAED]!R0Ga.6+
}
UœKɤ,l4RRS(***)NQ+.Rܨ_bGՒGFSWRk'woh4)EKViiiJJ!J\JUJJW^*+(((P.RT>|Ey@EATO@J-!Ujj
=ULԸj%j;N=ct#C_BE?KS'gSTPӘ1[JFc2BٌUOt[>qq5k4yeM74?i1hh=Ƶ-hҮ>=0^}xAu,uu
ݤ{Zw@[w\__BӇ<416046433,6l2|`D1r5J3Zgn4ho<xq]W
&Mޛ&.5m1}nibVd`vߜfmo^c~݂hjeբt̰bZ9[Zu[ݬ5ַl6>66
6pbۗ'$OX3vNvv٫ه۷ٿvt8T9\w9:.tlu|5j"obNtNKڝ88]]R\rUwr]zGwgyxdyx>loҮI=
=ٞ;<{^)^۽z
5ޏXF,.k7뙏O^vBþ;6<4Llr
t2&Vn'>d0%t~0jXLGk'ߏ0DDȐȵ̢~B5jhyc13cļ]{/<N?->}BEBOIɤCS7iZ鴛ͦϞ~qf*d<BHIHٓɮanIq6p^pYu~',3"ygʌ3UfpYYY# M9䜔#5AL^<Ҽ|0n".j-Pǜ'qoWaUYV-1r9ϊ~mg0o>w,@.h_hdaߢEu)^lW\QvIݒE%
TTXzkmeeoZ[vܮ
ΊK?瑕i+;W9^M\-X}s
Պk'm^\W/VNܶAgcMƛVo9c*ߪ-:[oyj5qmƴr'qgΧwڻwEםwߣgU n;mo>}6;M~?~M恰]6290pY3<y%5H6ÿV{h1cS9QtbdɁSlw:3St
;{\}ΟyEG.^j|éNtlr˭{RWO]vz7"ntߌyִ[=ɾn{=PyPPa?,sQ̣{9_<=WϏw1y/JTsKb18Jj7ZojN|>5]λe>}txS§gó>>obk#9##yl![z`C x] - (^RAdE) gRq@" 6cY utkr9:|Q
ad. 6 GF|d'"<o
Q k pHYs % %IR$ @ IDATxyP\7@E } Ђfbq|f\[[SuVuzޚfrSI&8v,G-[$k#Z !bmE 5X|sݧ }=</ص;p (@
P (@
P (@
P |*§0
P (@
P (@
P (@
P@`7(@
P (@
P (@
P AE@g (@
P (@
P (@
P` (@
P (@
P (@
P AE@g (@
P (@
P (@
P` (@
P (@
P (@
P AE@g (@
P (@
P (@
P` (@
P (@
P (@
P A`""(LF
P (@
P (ZږbX'
P |$u>f1 (@
P (@
P (@
PG^cVB (@
P (@
P GNr (@LezW^5g)@
P (@
P-0>6| (@
R
(@
P (@
P (@
P |'@Y(@
P (@
P (@
P TT
P (@
P (@
P (@
PwΚ%Q (@
P (@
P (@
P@Xq (@
P (@
P"|wuO-/Vʕֹ,o'&@f5
P (@
P (@
P`ffԤHXњ`j &:+=?3 Y$
Pyߘ%P (@
P (@
POzѽ4V!$$X)zyjy ݻ)<zC}ClE
Ds|R]B
P (@
P (@
<kRof'tX~W~tvvb|̂5aR3 ϛ2G
P`V,~Xe!ˢ$Mɢѳ`
P (@
PXSObVZ%DN
xG.>>\bM.GO¢%BxuuոP$ec]H Vca4w&+܋7!Xibxޒ#Tǝe&_lZ2U[ԊrqKMA4<zVx<f$_3`3ՙ"sQfF
P (@
Pp_@
[bL)Pexgf\'^!5'Eiy82FSq3
BIyOKK÷+V:y,߿KaQY||λ~"
՟}fT*MW|]|/G>?#zf?G}!ͻP ,#=hQom+V.ϐ`Ħ&!BTK6,²g~Key([W.{X%]Z\D/ WO_A`}m>*rjeYu_
y97_Ɩ+a+^_ONt6J$ (@
P (@
,q\tR:o.R P
ֽ`?ʊؘH[e
uu`g R?b[.$1%Y}/MQr>Y;>_R9ꀀUbW`L
ݳjU8UJ0Y! ^So|02蕋%8"{pGE9el\K1rNfLj`8IwyFzԹrqfG*^9mYQdm'?[rbV cAx86V{I@[<" $f䣴 ϝ@qYDŽܦ (@
P (@
, ^fԉtM4V)cJ?e?E/w~h%82 [&!9Pf'>x}>oɣ1Y`d)]9lBoEb ~]H3x=YTB%]YRBQq`]nmL#$"YԞNYp|G.j<7?NE磊=7l'o[d4 N]=
}{{ؖF7֏[&Z LP"ȱ(e#\[ByqHTFp/!D=.LHT!>Wb]la,"6.^)?)@
P (@
P$ [hn}41H)F[1xi]|xS,{qS-}R,B&2(=0աcq.kFZCb+.pG`:BK`G'N5:RBVc[./[p]7q4;sr$uaQ}q EM,g
R3bJEFfތ+aӱT_cb_.ګSwhlۚtJ9rwBQulGPzhGK{Zvp (@
P {[hNJQ9MY.O.*O{b2"P[+O|>?I/.eO-`9<־Z?3-,B7ܾo/LMGFr5bz}j0̂DHwGÐWP`}4ԈZ̢MH^ն{ou><B+R{p?nW7`PvY%DIt8鴦\[=2rY%aш.9>41`8ubJWP?^z0Y9[
Әx8:_+#-Qaw;ñODyH%үI,g&:ӣhmtXhE=eZPH+H]
y@-itl웖Mdg 0a-7@xC<,lt3{STױ>w'+N>o}܇0u`n5)H^uZ{F3-#Gtkw|\='ZIA
"VߌxF,CNV.+L~d2tc.;ua7.Fs_^;Ǣts1Nԩi+iε \ (@
P (@
V 19F_N*q)HԦl
!A+:z)ؐ*F %;}$}Z9k\m}/uh6ݿO(}и-=ʋoq{IĥҠa)Z&XDir-5hґ.GWC6tA6λ<yx!1^څ%LcnRd{P:s="aL:ɱ' ) s>ߕ#/qz4FEJAaMl*Y)n.ܷCOj.އcU$QQs_AA.*ǻ˧6^\
9$SK>ƩtCt#zӖr6Tc1mGT
KNv i`)I3OW-oHAJ2)].7q+0ة" g;36
^!hiV>>o+:A^oS!amQN[/CZ-Oƒ(}ċ+ނZ<g{
%.¶ͅb.S4eطk:ԧ>EyY1.<+g3/KJV}%/!"!H~huOko؊K8ZyS+͵&E0뗌tJ4VzI6i"%EXh=JلXqM"v;{]oҽؓSI.#~\<'J1Y`wEݐ=hv=3_j(. HiiJnc%N;([t;?>Jg7g\~R (@
PPS>^
u5ҽo{2[okpL
]%NUSmj2 _{ԑr#m8sW[Ye.PJ^T[x$_w~}7֊X={(M/CQZ2l/tN^+طPߚhz݁[(7?QipڥmxCBx- R[v@gE|{<Wq(WЈRK_?9HL
_7F7oxvo7R+bOVⓓ״<~oŞrܹRNGrCMx`uWo-1Dox m┸Ml<Ep@NUώ,xo"HgM2
?W; UBuG#O,} eNj?ǫlg^zl/-Ŧ2vݱwz`kzUz7D]i虜ciZ^GV 5I6{A:m8\l}} Hg;%Hg[x1!gF\>5 |sK?b$2ZBİڍn%lڮ_oܼZ\;k},V\!=#G#?
>ݶ Hg4+ۋMOģ-.鄬QΖ:MA:iǔ/]{ҵ{y!sw낁 (@
P |Տ;pߖڌ
-sVMfb
+tI֫d=bq[tRyO{_*q7}dZ}/;]ؽ'Az mpE%߷Rhr}W9㝷_Y,@Uh{P4?yt#o!k5\?)OqNSGOvݾ3^s'$AJ@kwtRQ+StN!%CԹ;杸yԞp9]yKmGnNJbPkt5ɪgk7c<,Ʌ#R@7p 2Jog#Qk`b[8WYֻį(lJv>Ftv:%XM(6vd:0 MzփHEs }}h"nt/\F3"Шls!B.{gP]Ulڳ)9'qbN<eݮ¥r/l[b24}iOOq=6;-MxEvB"SDu;rl)*ۊchV϶$XB҅AуI$qwtI̯]yصW?F;pb-'-)²AmYډ`p{EGjn!oC>W璆puMMx*J7<8%y7M㈜߾@ReګNQ8yNd1mMת1҆Qڏy("~&kVډ]3o9a<|ܿ<{*'(@
P (@
Pk\X+L?pN{P:y,wԈiY:Bqx3) EQs^mޯDllTjaߗ5,ĕx~*j.Nl)#I]7QPQn}%nƩsqb-}kIA3-k}!|#fΟs
&Ѷ(oN[oõY;ġwI<;Ͱ}`w{9_ :SJj[eėV!v7X\krjn7u
A-sΜMZLyVl'2/+aضрۑ+1HIKǥ6Ëi?,]&4αG]&sܘNd,VDwϤMc}ws+Cttus>/53{
q)2^p?m͵gpw_+nƥ#ҵ>+UlZilnKtsTrӻ[Et͂QXƋK-;k{vp5*QI(㯌o =e6.|:\߃J9&8К&6'Cno3rhT\w̓wBA5t4Iۖd%˟=c~ Ì3(S\mRRPd*16tvnEtx2²w]@.|ە&~K`yiƑ?|i
J;[a6؆ 5볦7V0CIZBu&\ƄU?N[OU_Tey8"ϱu{21bJdϼL[K#M⺝PF|#~F_gI7gvCߡpܳU
P (@
PX/gm
*fu`ҏ
0:zŻnW7]u#8{GZw3?ޙ%' s$_O {_,}XcR3*?δ*Gp6L{/W+-÷>CmsT/ďM^b('>sq; Tr)q!]<.b("5::$ $Oi'ňvC=f=f;DP5oj~kYM5ܓ-&?_~/oLM
pU;D:aNd!}T5;!?w6?(zOᓯ/]3`eq|G^|5mcZyI
)#j:{ѤF1"CKS_K"Ղty&|[ʈQ:p//OXܵ?Q_kO!E 9#{gǏxJ4f5Hz0tO~уSNx8{Q˟bx*]N=/zDs ڼq9v+HZNƅuyE"E'-=hQ&-f=gݮ+o\S=bN~E!IP}]*yF-H+K ي{;E:7"Q%ڶ4ܸjxݮabh%|><VO[*=p\<{
(@
P (@
P7Nk4Hw\#U]_x~ӇQkC,v4=~0H'RqCx>qy.HܡtE_#9ξQ{YhQYyM{zuq;WCQa*ӡPɣa#^m@btW\D%!#TiA:bҥKT[*S$eWګ[͗uT +9h[40JMb<%|8;*W냝gw.Χ GaJ,@UCkg_{=XwŬY 8HKK8_«-_.z5.ڙKz_bM\MAFJ"bb[Z(l*ǕMsnHK]]۵ZL.撓:uCz0$lqi]!psZ-y)>J?
oW{og
qI]Vt`ރMhmނDwݝ/~.U<[.JWic(P.e<܍>qIʹEw0>=Ru<{JuB
P (@
Pφ2[^{=bۄtd%#!.1IvHêm}D|N785mx{!Y/O#zNw^<~U*ε>q8=>+@
s0= c!{,ġSthm`dfy z{aj2y[|:dw
1GIԌWuUb(d9rkmօ$~K÷Z>B?y?G|?`hCG>mٴ
.I}Zyw9#Z7LS=1Ks.:u߄kҏ@\j[r0ubn5k;{>5ccOT'S_/9a$ODDGCk[HK|sQ[t% -+
.r.#;uтQ"+"?z.'p<?J^Qw1Bx.Q呚D|xワZ5~җ2{JLϳ׆G)@
P (@
P FUҏ-ČԌSļP
r_UO܇jLc`כWԱvp>qn{;,}q\EgȊzg\=|Z,gnj7Qe;9x9u.ͺGvΩt'S3=CAl8sgnGI`ꇿ{i3Mf5/N}h6/Da1ިrb&L`/\'O~@/&\W+VatY]=UP_G[xMyb(uM*|p<SP扉Yt)GXKx~~6Ț4$k*vQs1mω@4SVV#(S}cxNζc
~öybxb<í2=8"T~_njCqcݬj~CT^ZYK,̖ (@
P*zJPݭ
~[汋GRZԙ\n__ҹ3yo(F7 aMBfbg91ZKP($DX0|0j,|VCM
Ӊ^~s~hqIWU~-F6ݰh4ӳ0.ɳ,9qfNpo4\ąKb-?!koՙ_U@'@r'z%K'誽rʻMIMž\%b7e*D2Tu%Vy?W #3Aiǽq(%ZKHFV"65v(waޡ+S\\vcj(%JP+H+ BU$Z~t9[_\c^?z:%qwuR
P (@
PxJ"M1 ӕk.{6AUFH5<xSWi,}v~ėcA+5{ߘ[k#-Q)HJCZf2l c
Q::撴bZK6WQA,}~|Ũxb98-m!8X](Ns3K-ix\
IFmyhR1BRt\<VуF^"!N/C[8y1H'i*c9 #JcZx$%8%u ];>l-Mvɺf=73RP"쟗%je1P9(}v=%+zڭEҴ.9U"#=O~>f%0鯜2vdxKl&0LB1afBCQ9ɩ'a/[R!+ i[f顩oTKqpvߙlQ|%sO~ٓug^ (@
P (
DʼqJo)o~*mʝwߋRf"@zWR'ļt[0ԝjKq#,Qb uo2};jR=D _`ҝTWj/)pU7R=Sz79ڻK.JBrS?FGC;a\b*ҕmgICIU:soO.>ƄRPDywT!^QyM0{lOq.`k?? ^rX_f~g??
lMqls>#PbRORPzӍbdȸӳoJu-U::aguV1~?'mZ6^NHq|ӒꭞC(ղb+h@9l_^?Ԝ#vÛFݣ[ [5fآ|CW"VXlgdm>W]1nCEqa흚!FpZ9<ܯ9(@
P (@
S!) {V+v-Rzә{:Uwޗ.EJ\Ko~.bjEOz8\jVWڍ6ܼWNph-?%?)珏*$ր3->}J[mnRJwP/0/ߌ&!:ڃ[ׯMWԲ؝GI{y⤊[ZpIim547[w4Xzp$y-aߜH]g;%z |&{{ބHD|ijGo4 W !HG^RaܾibͰG(Lg<[9vTD~sڻ0.X,'aoCRӉ'ཟD@[\]oFܘ }u
h,AɊŞn}!!)=9 /ܹ(맧kCw:ރv,B-"Y"j<|WwS_܋rPڻ:?%HT1Y<Q^WE\HFNrw$Ԋ{8ķVؿ9ТRĐ{8<;ұ-zqwM/@?pND$`+/k_(>: ٌYWzϩ^8i_I(@
P (@
Po¦{t|Mh5cL~\^x楯ޯ.}s=ҒEOfkA)\kDEw/LcpD-czplrͦALCzv*- ksׂ12Kh[95ګQ)wWuyaCzx뚜[ׯ/1OS[ax?Y7#Y :WM;&bﴵbn61[گp*1Bmm=z'aw<a[_ CF>[ݤs0ӯE/"Y-Q`PFǕK$=hҲj5kLP`}KlƩHS|- YEaMǺpy- %4t5ԲtN;s-h:S<n?s/D C^;ZHKV)ChI\BAH¹ZI.ɳX$zHnEAŹ +W-ON~lTm.ײԠҮNv?>uQyvT=7cKeC.G!N
otĭHl5B='aH%4H.\<+NROJ+{O7>+S (@
P3#v/R:?ޓoKR"3 _~yJ{;RNYU|_soR32g1HP%}UGnXc{wWpoq'Ee/}C
WpIVɺЊ;K-_XTq>35_<ֺ8;/>wkYXLm@5IoQiR6tЋODj.-GR78jomPwW]?obd@/ZohNʪSoHeRՙ}$kTSjiW)"ˀp_vhJ7ؓGcoK01!V9.O&.v<(mObⱚ *|۽m[ý8Ňtv| Նul>_=+~IhwZE{e|OQ5xDSef['_'xv7![pMtb#=}]L?rݵYJ= /~}W6;EsZ:XT]]yP)XPuWGp-̢g? /\/q<)tԧWU`&>h;Ӎz<>M>y0'eQ*{lzGsb=ڏsG?3Uh[78ԏf\=il1\,3Ə1wlR=ϝ܍k<W)@
P (@
P?~HAF)w!v\I4tȌ|!])3U5x
,}>֕\'MO}O.<PwKS~sw:z1 Egm\:9V__o7<SݥZl6_ﶭ'qWylݭw>?dض"qɅ6yI%k`eC}y->^p~7Ȯ&mh#*5B7>_رkς4$ taA<U|G^ZL>z@<'^𪸨oNf|
V8Ħ -n=EW`ŊX[>=ψ+>Z{4_o[{ť PVcb]=[XdEab]Wy}9K<ޮPQx[]
rs9"k0-X-?`G1{5<W~mX\bKVS]m (@
P \Ciܸ!fffe}k16>vY HFjM|vxv.L7^tnbOޯ.O
R;7maQiw>~k7*\#`eƮ&g01X訡OSWD-1=swx#~OnؿGp9'~cs(Ud,M҅tCh?߄:ܖyg롨F(~AH=ܩҮۇ`M4tI9dT,_m2jB
P (@
PF&{.J|:44cy+Mė!\+ʛr1ʓr\?=m?z_,%j5z7ǝFK-h҉,00 oQ,?ZDpis9uUQ?^uZy7` |j聺SL
POРC:jT>a nvޛf\ČLehs
v}55 (@
P (@
%drֆ#&&FO[!T
ن4n9;3yrO뾔0B1Rb
F hfHAI67@s;Z7>GtAbQq ၡb,ul@3uc=#ӦN\/=Z
$U%-p鿅oN
P (@
P,0-
}aȐ{I<Hja)+ {1_#CJ_vl2ݓ+gp/N
,kdlRFףGdN$:p$Ĉx(,jvW?>\d&D8%74oo9 P (@
P 5Gܤ`X/x߉Ç0ؓWey.d-Z3[.FQ^RHJpVΝf8sW*<EݙSk˟Wcp^رk6)R?ɂi(@EX0L?+Ej(}1)"7S (@
P*0>6{ Wdih@1G/no^
(㲼xxG#.j-&!!h4-`N3U9Q`rb<Å (@
P (@cixCؘAMnP/.<C- K (@
P (@
P (@
PB[P (@
P (@
P (@
PMdr
P (@
P (@
P (@
,D1
(@
P (@
P (@
P Xfz&_E(ER (@
P (@
P (@
xR=<ɼ(@
P (@
P (@
P (0G#R8M:W(@
P (@
P ,kJ
PW*2yϖ9S (@
P (@
P (@_pK_(
P (@
P (@
P (@
80P M
P (@
P (@
P (@
B:_(
P (@
P (@
P (@
80P M
P (@
P (@
P (@
B:_(
P (@
P (@
P (@
80P M
P (@
P (@
P (@
B:_(
P (@
P (@
P (@
80P M
P (@
P (@
P (@
B:_(
P (@
P (@
P (@
80P M
P (@
P (@
P (@
B:_(
P (@
P (@
P (@
80P M
P (@
P (@
P (@
B:_(
P (@
P (@
P (@
80P M
P (@
P (@
P (@
B:_(
P (@
P (@
P (@
80P M
P (@
P (@
P (@
B:_(
P (@
P (@
P (@
80P M
P (@
P (@
P (@
B:_(
P (@
P (@
P (@
80P M
P (@
P (@
P (@
B`/
q,cdxq)
DDF6> O @ IDAT\in(@
P (@
P (@;(@
P (@
P (@
P |#uJ!~c7,
WK֬ݚS;-kP (@
P (@
<>
)
U~R>췑- (@
P (@
P (@
P`> 鿡 ݼ,s(Q+ .<?|n63]9 (@
P (@
P8G͘ (@
P (@
P (@
Pn0P6!3 (@
P (@
P (@
PSP (@
P (@
P (@
Pm&p!!ZL]L6 (@
P (@
P (|\OICdH3xhw1.۳c]0
ͻr
4ɖ"Ց>>fA (@
P (@
P (@
@`YҋmCXvU[`2:o܈lKKHt (i{v?y/?O
P (@
P (@
PxI.<#|\5옘8mvA `lRe1{tax}k,VAϵz|h,lkϳwP (@
P (@
P (A.^ފdi@H2vw10~A!HLBVn*oC͠`?"Iƃ~|~
φF?Faoh_kl F:5/ ǀ(@
P (@
P (@
PXK>P_kl_Fb6p`[Z5.y4ꮎ^ 9fT]uIk3:9ڶ1yr8L)@Thm?
}GJ13 5'q&\> (@
P (@
P ( hѣ%eis[s_fmI\qɩW] r6+N<zL=4@gC8/=3 QA\!2%0Ւ¢#1hWf8mP3Dřդ@H6D!bu63 1DfO mbL5It՜BQ$grV]UqN8g%12!
ZJ *pY$FQ2bs:fN>F`R |{}HeQi3
G5M\TuHN*>`/mxz^xg":=< (@
P (@
Pt.,;F=@U rVTN1"r1'Jā\$)d* g,4_o]ըLTyL&e0F鹤n|{]oBS"YY:o'ڭ"up>x~Ql,mq.ǶBݨGw@vʩqj2>=
'6_#eιxԹv:CKǸKQl5Fyq?*/T-}6 eiR}Ml}b\_k-(}TRpdn?i858J&j6==eߔrY>aY?ů뵓K\(@
P (@
P (@
x_`I\
XQ;N=l[ѺJ*7.-a~Ra
9n"kc1~!z}|Ůӏn-DvxC4=Ҧ]hfRJߺq~qjΖXe_zt> VrzF=~EwΊs۟^iNlMN+V[QWNEXzs*O,>u}[=a[Ȑҋ7$";I&-PclKgzu_Jx;%1W
P (@
P (@
PV%кmuu٬%`>H` pKQ*u]tЂ|eQ{[8`=
E\[@d}6e1>XjԠ&ojkcc\NV.A{UfD'`SI5+[*/~Lf:͘Z 1<oHv4
Cc[K3/-h:h&zd5[U1礮G-u]'I,mn?:c7Tߥ@b.x;/ǝN-u?(@
P (@
P (@
x@`IE8O,[dtt
m Μvʷżx5"Pcip^!.*tnNVXwҜvQJ313
R7
rnx[Z|%~DYpEiQ
oR{mF7|fR!hnTOkW볨W|߭F _-~IB7S1o߿Zj=?)DԮGMn[ C^i#`P9`
5ha)Z`] '-s:H#)*g`<#cS|V>qM. RP"Z0&%ֹ4=^,
XZqV'' /-k':Q`rRx-zXwxB:ŷ06ҳۮfhgub49ҷ/2 (@
P (@
P T]DI -N֭v5ȥo&@[h B`Z{F@RyFa|%ƟH'j1rKZ5g{& ȹm|xuwF1":ja9"[)^X
/ڈBqN)|
j6b&1 @Ω}0VbO9\G)9}f$c㑝rkwu<Itj];JQy4t9g oS{oe܋b7!>hR[4_rjjULW,@]X^=%ꍤ+fDEY3}}5WoO#Փ,B)_3Θ)(<v*Wgk\#\
2Csp;oVwW)@
P (@
P (@Exu+h#6cU -$JMwi+[ո=Q됚NCL {wcJn<BQ5+/>W!td;|۽6$HMbh%`z2_@FV-H%Akp>C`/N̝oݝN"m^mGb(,ǣ#xEVo-絥3X݆![ͪbHD-&1q ~en)SRVG,+cO1gޞvynj={t!/ain皎w~xb%8X])H.(3B
P (@
P (@
,-%x©=\QGL2\##ܽ/1ދl+A/YwFI:V=& PA:sΜMiC1$[=WKdV^,kǧWt̢Kh/&LƖ(I~,]{*kzBקyCɎh3gi4vsW#53ELv.M^KIwjS1> y.H75)8rێ2$(ޓƳMzGmB>H7܌S.RS/S
.[kXySryqYQ҉gxC!`˷`ڬ
؝Rsb (@
P (@
P
ybDpBֲrk.&88t^>gjy9]DW` B5>[-(ٿ<x3x<+-;Gi1'=HV2Ö(Z&?_~/oXPP"Pm;'osߏhFw~{BIL[_ߨsG|]HɃQXƋmJrKŧNˁ:LOCR,+=NmCk[3.N5L0!:$GnŗgDӰXO0^9к÷z]^[Մϴ1v9r5xWySBqT;TP (@
P (@
Pgh0 5XlZn\)ܶQӴEl$p`D猗@1ziWкA<CffgĘZzdz6}9ñ+-sa1q}QHO>l]%|YNeGLR\RS#hԽ8s憋k|3*jA:59L^qxn]1C[ClDyK~Ұ
j3.댃t7ߋD7k=HNl6ܨlxTV^Sjm<.<_yb2Pɣֿz@
P (@
P (@
~ߒYjƭTplJGYzԄ`DX/ʛo}3O?HIƥA6Fy@ȕs#6p:998l) e.K
zF9{H~8}u~[ȱ?dLvXEA>NǫTbd~11r z]:ϝ+?I/|%?S#
1ߙ6Rwzm]b&4w`R?xy<2G7PX<
Sb B@O2p\_^q8Mg-h=VQ~ {]jvKf=WS<`?硧\oO7LM=9+B
P (@
P (@
ץaƍ;+W/2#?1c4[H4^ڗ0փ;wڻQl
JlF(*;z@nˀ,r9索چQ.v}/η9ppȨvS$1^Ne=Kf.Dn-bxK%5!⁽NDhQ9SZ'
jǞܯStO"*ZxDY
{
EE*aZb+R$F/+5ĜhJ9%.ؕ\P
ébDGzncHUolGI[_j^ZԢ]2yƦ}o`wY_>GD(w)MaB\
˸p%`$f?=f\/+xP (@
P (@
PNK<P'\X1ǎYezTC1V,"cҹmĭdg^ᝈL" dg I
ǖшXۂIebzfuVwqݩH
ێ[}fM?1"rHvD2Ftk#PPB{432*q}^_:@XWߘ9h<`)i7έe7,bF:I>.[ń;$o[f<t>gIB[nD2eՐnavi>.s[x@;(S<)q}'0Yk2aXi>jמhwZsc,/
qQH_pdn@fl>qth(@
P (@
P (|xozxД뢰yq\S7;z.D<<d 6d# 7pko\dyZ\d[DqM8"`0h">BJ- &R)]=?ޝq @C}!p ;)LS-ɲNؾ7ʗᾪT[KիTnRNb+"۲%kgHS$A$b_Ģwg̊!]NOwק{}@>s9'oGӞ,0WnXl:&M Wkha5O19(Okv{86rE$I
(h9.<1:shVbվG!<\ix谒HܨW4S*{Wi3(G<P,HAzV"mLGyuGk˒^N8P<˳k.hVvm=g3LIh H*6aF"eRbwM\:*+JX1[8%^hDzZ2rPcPm;Ц>s (@
P (@
Pj]q/YeE:C]]8vm;~˸ܤX}|y,>57P}Ça$̉FIx#KE;]4̋$1=q؈
g
__?~z65~]j9,qϢkU4eG/s6~w#K:ź>ѐh7p~qi*;hSM9\n)ۨQev/pTڄlCtpvgxdH-/:Sj
3Q)یbTp3M˄/Ȃ\ *k7 Tj#CRj
+vdJݍ8in8gˆ\S㑨αZhi#e=٦Nݸgk8
K\bF^r-I4av-s=uBRb",9hǝWѻoC$q (@
P (@
PXUǮEj'vGvsHZTu
Dֱ
Wphl s֛j>
4_ki(^ƻ4ىwSwH+CwxN:M,4%yYīٹb;!k018>K֑+Cz$!2h^<Am
f'E#-j~_>ixO;E,?nROۿWܺۄC>/mClTÜiG])M--8cjܵ0F;Kt^=r̭p]VCҚ2aGM?^k vc<S"ƍSw7>BK.d@eUӋ{."Gbp_8ѸӥɘX+J-ޯ4tawiᘼɱ|tZ|گOWeS|_PoX)6#=T:+>oqsCq
(@
P (@
P (Mj3ALQQ)6+܉hu&oO67-XOR|bm;Lk{zf:zD~eW*P2SRo
F\ۀiGfDqqUCKlFjXoW~j
Mg od(DەVY+
/-[`]e}9< !qϣ,JW204ҙ-vۢ]fK.=)!a&0T5`hvPs0͓<9n>sn֧=a_fgZ.̺ >Oeq*!.u8[=x0&z!m4c.4E(/L7b
/R (@
P (@
P>:Y,q/K+ ݶAOaHܫdlɴ<->-^?ʔ%(?$^v2x|d|IQdm,߾:k.]ZpӋ{}qG/Fcnñَ?/?y}4wDNm__g:%wcxxQSZގƯ-Xbk ngͽEQr,[ٛ;zv-}ah*m"T[5nO%wd\,U`!Fn`:ɎWnu8q={22s{ƣteᾚEoǰv\B
P (@
P (@
@P1}̴daaaZ/
j)q<Gq9XHD$RӒPDb['t{X6j
,Θ*ǁt<7
E!>= bjŅ.]BF!W-G{ṗ8sSyʚu#:X쳨PSC_q!RܣhhC8փ{>! dHi||IyX2:1f1mM|V_ek^4e@:t7Yԃ&tN#:&a!Dų$EC'A=ll3֚Yѫl4&'1<WH((GNTZ}]4](&玫
ȗzF&cp~n4HaaJ8rM[Z. (@
P (@
P {7fc).>ze#lTlJC^mwqz'g¿H!8Pr'PH
¤h [/kDo4w;X#RPIGD`nl@552:$c6D[݄x '釆bb>ϊY]Ҍ\;+x1
;:1Q~VÁ;7y8!Ϳᢽ*w+{;e.GsJDFѻzVǡhgS˸q(@
P (@
P P6Ƹ0M?Dp:qe
=cX'#˫PdXH*~q;xWai]Ə՜jg"z+J5,ky* (@
P (@
P>.P&#c^(@
@>˳2
%ޟ/GF~YMF*7ӡ7u7(@
P (@
P _
uC
P_eCr^S[t;8s*.\"@% H
P (@
P (@'K
uOfi)@
,|C9ޏ=ۊű>ܮƹnyI?X^ (@
P (@
P
nY (@@W+^щ)HN$#"QԵh7tuR (@
P (@
P1`Cc3Y
P%06ɳt'c (@
P (@
P<orZo"-8ء0܈HZ1=6
8C
8$=x\i5|LA
P (@
P (@CWGR.`uS#q3 +Q2"
P (@
P (@
P@Hr<PC!'d\xx<=ѻ (@
P (@
P (@?PVS?`(@
P (@
P (@
P (X
ܭ,(@
P (@
P (@
P84T (@
P (@
P (@
PqQ^bx
P (@
P (@
P (@
: (@
P (@
P (@
P
]A (@
P (@
P (@
PlsA(@
P (@
P (@
P ( dx
P (@
P (@
P (@
: (@
P (@
P (@
P
]A (@
P (@
P (@
PlsA(@
P (@
P (@
P ( dx
P (@
P (@
P (@
: (@
P (@
P (@
P
u7 (@ f{/rL
P (@
P (@
P '榎G#J܆ (@
P (@
P (@
P`:2:
P*Pe (@
P (@
P#FzꩧX}9R,؆
u~
P (@
P (@
P (8.6&
kIj߃ߓ1 (@
P (@
P (@
PzDc ,^l33zzz_`9CþҊ鳡nE"n@
P (@
P (@
P (['7/p|&&aHLa9}L]P (@
P (@
P (@
8* =NffgNʓԳozfF?
u~s5
P (@
P (@
P (ԓNk)
?
P (@
P (@
P (@
: (@
P (@
P (@
P
]A (@
P (@
P (@
PlsA(@
P (@
P (@
P ( #S LQ%DS |-7ӧ3<N (@
PǼ|/m.eʨb| 6To5UϳPE{abHY/-+Wk.aʊ, 3wqqRg:ڂ#G!"(37pB'b
8y['%6%G`qy-~'$;G#5(ΩaZ&Gѩ+tuB??<_`cbo:Yjĉghbݍp6"_l;N|4)@
P (UnK?RG`t_^hq<
_1t
9q3F:im|a/r@[X#EfFg"K(@
X6fdʍtҒ\'|Azo+^VLJ$ >DD");"f ^={˽G݈c|
uyd;l=rEň[2M.,t$폫rp?fqRm٪>o̽[^j6ƶH?*T6!cJGwa[B0Z
4&{twy#P (@
B`ꀐu7_T4PHS70Ojm|5,ϻ%s#G>^% (@"sv}*.p$iq
:Sl6FI<Ԍ`<% EgHyRW+iLǞ~REeͩODdí5uWeC+,ވ#F$ {ZV)yyjG#D :{.{l7PwQVL10n9,^Ỹ8̶X'!7H=[oڗDMݍ (@
P"
uʅ'tPR|]5+b\V+$ʝ_!b6Ajy2rE
P!CEWM gN#l6_^輱wmNG">V3+*!N
Pp|矷jA{kF&2SBa߇O/~X[0۪$,{{[eo?QmjԔ9ՅfM`Mx"3f?~o'
]-;&քGLr:AXr)Y:bOw[f (@
PP4Ӆ%8Qҳ
U4
7>W~W%aP
PpM`nrIgqAg$D{9ҍY{հn?SO2Jc{~Lpʲʯ>D"S'cQ RECiBU"TiCCsA-U#H%|Ih.`߱0ȁӰ^8}2U8NoRl8-51(=F~Õ/?S (@
<>onl+;e%aChֈ;f1ہk5:1$"8Ś.4w+]4yaqmX[\hnщEQ(ھ ).b0jnMɎQ:W~Ki9%NKBx0(Z+e9We(rpb ]uסtm!.ҩAL'D+˄qQ>vWoܜvH{D>y76&bE{Yʔ;VȄ|$ǮEhE^ķ@5ա+m˕_VHQ5WI
ޣGe@X.}N =2ek±8ރk7m/(PQr,{ō[rXrXuXcG[qV;6~ytoϦjnTV[E#;5kFS}}i.[B6
Wޒ}Y/ɺ.zЯGJS7mQ?a5WO_Wܖ/k[91a(q#xcAGX>Ѭy2Z֯nw>GoΐQ~>nM#
dhj,NAS#'OtK<.
&>Gn.BPc>(swm'Ug@QDD4)Cj9N_Z?9VnZ&DvKWB6*0ߊ*g9{q83_崢[ۨ$ [pTZzs4VF'Wl6: \D
P (
i%3&1W)n"J
:@F-to{oWΝzچ<AH7}59XRq|<_w!۳w4EͰ9]ؽg>w4+z.؍DCڇޙ[W/ŜZ<cQt\Ɨ}ᢍ%Q!sculr+
, O:4LفqKMqO^
@/q+p2y{WI҆O<E~6DqYrY{c
`Ҷ=mϭ'DC1*NSʍ@^5㦆:hvQySL=
e#pM_!!~7n1Z6ϕ܁kg?Z*svޥ(;4n6CO&>zse;q;Vu\,Jawlg(o*eC)]|Gˍ
x#98z@_Ucz?S_aOUSU7}z;=c<Yf5~ct?ZX6oi}"\^J_;;c%Kv߃Ud)!i7?N:>z4tuQ۵X({
i<dg jOk]rljzwb{i w.7)INܽe,IDBpTV{{ޥHeEa&S{M<9NdWڞ_k _':֨HiIyR}I{MEP|
OXn>vi-)@
P V]t3j'+yMMMoR
)FCPjٛ?w4ҙ7O"mpqZJEEi3)zPƽ|gW̱hs+b_u#fHIf˯[
𭗿۷l8KG
P/ൗLD E~X47^oSe|iYr(gm#iDl;SNPtOߤ|t.-Nrˬ餍?=j̡g1XfH'o.7sϱ_stZ\7ˁtvL9K*u&L=
[W®pp_w7YKH4@4kh$[Z7RY+g~SDzHMvnwO+9ܰ~뎛6}G罝qq\ΜA8Gݒf7g)"_nR]zX͢foh̟7M߿]z:jK.PVIכOIS ݕzjGv皟6Uttt7AF}[m<mywҋ:ބ*wi"1<&>}mzYɇU=N#)ҳݎ~Vg~q"Ş^#Fq3NZ0'=z
Sk
!-q[yw;U)!)@
P W7=$vnbq12<%;R|/ݥ9j{w?^%MQRf*ĝyʢQwR}Pjw`^)zT:Ǯ
(17l*|z{xMqj$ZX!: C<ԌS
Z=[M(iLĖ=;PlqNZ%&WAA'٘ zR"(@7`׳b D4ւk/^\LM[EOE^.4JW*c
cMza %;a9\la.oi!%9}ΊÈZ5
&.r^*ke{F4qgA<DZ~B.Ut+<MwS_yG.zHiLWˣLuk|z<d:;՝Í7⢔hq r$(w7?hoK)J3[{M=r
07fxg~9ePޅҋ_}y
lQ>H4;ylKR/{o5: <>[E1כMQҪ!A*Gr6FWiT$#[TsӔrzcCZLؼIt˥F\r:
WsnvbXϣ{X&up16[V3˻^w+gf[:1 7Q/J"~@Xc67MKܯEyv]}g0扛$n:]'u\ޭR~'SsDmMQ4bi Vq/j4
p2UQH>
wGfimR:5Rs9aM&/ǥP؉W_ 5w 989_;=_Sch
P (@nմT4Ih[m(,4.¬mܣ uvϪ
'4
~u7Q(<e|;T @ IDATR4ノ@-8IByVV:{h2-ŝpG^Sय़b)p䊆Jew!ThSJP}3t0Wbg17pEh3Ҿ.6ҩ{3q.*-HOPj\{/
uW`_^TP
>M֤=,^bؽCahoL]h$-T}o}[\VAZ8Glogșu?W+{.㑚Lv\R73"ߟ
k8s|pFrs@tx܀fظDp]]Xi䣥$X&k=oܫϽ۟5ϝlƳ?_柂|\mջPbRĸts$h3R
3Ci\=*>n5%~'gݔ}feo+ԟz/QolGf^1ʲ/&ZKˣ}\ʟ|Ttr"WxBv/,>xkoz;>DS=>ez,9I6֙~ Ѱ]t"-w\>,ͫ-Bȝn>E{ʗ%yD#C枒¤_͓˿GM曖IJwߡ;Y_~{H7M'ܯR;=_q (@
P75>`L߫Fru7=jrCQu4ԣ,v>~O5tJDcELeLeMw5tm"(dPWyHʕ+"zZ\ʆ/ԺZk[V%mg>į~-s5ğYwᄃ߳$9
P!h%[ޫ=OqU;wqoUK(
(HJGrv#1FmSVM
BjQ
EQXjyMXjaI/oHq-M#FER?<W>ܖ~@jLQKbf(Y\4<oiS#Zwf1>=ӫ.hiCKKWrMMN8{ñz P-cHm.=OWgݔvzI/ӽF:e[1.g\x<w|yKzr~~gx??FSΈH݊#8X.<$qsYѪ~ߏ]xFv:owry^[uӳNɳx\iq_Ϭ{.)iFc}ߡo9AQ @x8~U
P (@kZ`\QY24X4K(W.f|{
RPb܈p 4xBBAl<D^s j:rJSzZ9j.p:DVӅxoփ~twݺ9qW˖+)@6`zq<U:j\>SYnnMhk8nyQۦIR?7Q]q.%fyk1ա{I;ɽ8Ĺ%qD#?={u]:[*S642| G]/iR%).Bݵŧy,&j;u\]j07Eol9SZ4N -)ai9u\8pʝTU8>4E2&l9#bHw?p'j7׳nzű^BN(_'1jA6_zU&]Wg{D/^Ǖ|def1#br|
D~.u:-ܯy
=@sAסbܼ Qs%}9˵Zjgc|;XӒ՟ ]bTV%
O܇ód[Ąt_ʃsWg}=(@
PNJ)wbP"Ux.͇<+
u31t*;2*\p^zލɕ՜Ɖh۩4#5S<+BL..h5D\)P X3?x[\TQ%#qxfs1Zg;ogֶ3~浱W>}Ŗz<u<Yg'ԧo9"?#?N>C)PGcq\4bcU0?8Ő=m|-\yk5/7w+wݼcapW<J^XgU=XǗ/݊Dn0ӈ˼!{7"CZxkM5n;}֝q|ir|jk]lF5x)i<ia<n ZθR.5^|ޚ5ړ6j͇SyacKoxÐ8|ӍوSI+"1%C,{R:2<(@
PpUᅮpvU `ճoۀ=(oĝV4j5RӝEcSScCYE#3|Uj+϶@)?^6*BJr"RNbC(Цɫ4QpX
!VJv(xC[FwU2gJ$D?Y.
=Y#]2U60p͈X%/L#]xdaAP:,bʼ~xVW#RϝBO0؆
@ɢyk|gG6?]LͰ6:<_ݪV?»ϢzwZ<ĝ;Y2jH{4$gej$n$L=/Sh"OF28'nBD;VTw1~q[kukr1n
Bߧ.a=Z:,wut/S=@߯Q`, (@
<b'zq26)HQ.ꤿ};9wpf\T=[4u\ƅ+lHm=']/RGϸH4udݻS%M"CҳrPczƏm;жsK
8&`9'uH`)
qmD^ eޟszr.vq)21 @szWa-ǨWw7~Auىj^k<?E~,@w[FC&oGzYrj;
cnPApm]ڋ|1V/>Bo O𝌊?/y6ڒ[}~us4l)=3&;5JUBwaNFH$>Dv
Doړ"E~2NS)Ƭ7PFgN3m'#~s{7u'˥ɿWl̬r{x1[=4$7o|dY=$ċk,cpܟvJ<]蕇3ζvyZ)?)@
PoSrr%\w_A}C6^zqڨ\Wo5M~횉J'Zhi#=Y&/_]Xn7//FZNò$ݮhq|zX\ߨ (@
^@GiAFv2/W8wئJ86OZ3lFQ@"FC-ۚ`h[dCn.5]m,^~F%%s)j2O6q[Ky^&#urggKIA!Cթ
CCOQiH0ݮNFgpR:
byjZZZ#铧0hʘ_^گvvzx0y2_%>U͟*.O|gU*^DšElŵWpuXi/zl=݂"e>K|y;+^f|Bɩ
WDJ=lRZH3W!6I 4VC'Đb}Խ[^dOLwی}8|T]8utypFը: (@
PpX?Dvkk͙FF':Qw[{7NWjH-X+4DZ,CnߋJމg@~H-˟~_3˴JόOj8S]Gc^Fq2'7
Pmv5öCؿY9*b7]i92{;,bg+8xph UjwލK?^}(ͰΗsj}K(Kʟ
$寠4WIW_VA|mQYzN؎[MũmͬU]:m=g?ǫuq=M6$gO7j5s#X"L`KosTf܋giZexl:_Wu,~ϓj"ugܫKcsW|X0l>_HᳶEsvzp
,!sP&H{۠9\6u>-;{Q])bt{ڒsz5x7dDmoxMՠitf'3U6!(>+W%4
Q5wpyukWg}zQ (@R`ٛVPo4^jP=B.DO
q9x~CUf>.
%;7Cj˪y$(?Sf\FS(BSTxEs`ua)u3r{N4v3}MEv~!Ep}sJ1 5h)@.vVlA鱿AT9u 8j#2
6#-> _*IS+!V%G&8<s
nQGCGmǎCRi0vI5"UP/hyXǫxb&XW[͘mF%aQB-=07؊QjY4
k1"gD~YPR4Rjih?"'M)sMxwJj}b&}ݖA%2_UL\eYJ.WO<_vz9
kкYOdhϓaw\iqJѼ[5Qyd֫^>wvqVؿkjP,Ry8jqE#=yF
!H;9{|ˍ43t~mooΧ9щh=Xn:sk͒r^BO}-TEGDa!aHHBnQՍ W/ݜ5O~)WaMgk)0?[H~b,ABoWo鰕'iu#Z'QgVCZ< (@
<P QЎ]F3k,wC$t 7oA^s(?40XI{aZ>O?9מCa2dru:]͉t9G
g(xk|`i1u5֭4(:wv8C
xNg?}FyƸ mSw*gu!N`w!MmeM>%V:J jևˍvǥŮ
/"iݢܚ)Kv9ʧnmՏX8sRQ^b8T>TW\ǫ])~|hO!"EymҪNѫe6i[iZ҇Ѽ Vy0.;|&bczx0.UeU/u֙뮛zcotią:WΓx0
l+vꕛ_=e+:$|'
h57ՂN~fiUnL9>Wy7a2M@;jۈ^d7RD/j7w\n윇zy%ù^!EKo6Z Wܬ!t3+ӥp]G{ĚW_ƶlscxxt{%(M7uKb`,PnTۂ?@M_J~˔[ U (@
P~+fs65kFD/Q׀[5Gs0y~=ĖL}mSP7 S9(!,Mm(Gfհno3?p?obMvў&-wAfՔwW&0P;}kJLﮆh@S'
PYʺՃz\_qҒi=9҇ӗjmωGmC0D=|djWYNwڬ<'#bi3ojy >9^ooQR2:i)߂{EY-=3_UbPҬl*[,4Zs-ߋymL}|xza-dg~1_<Ko]R?
]hFDvM|Ufyv\<oݲՖiuƶnb:2WY}O52JDMV8N\ݯJһKW
Ǖ]nz+8JO|h+i4M>\ol?1'k^B}YgN[o+o;!{Ǽ4oh>em']?s\:>_RNӸ$hպh䴳5Zsol\e8GF.K
Nbomw_\vf6.<7ʽb=Y{h;^#GS.j'.shm`xuz~CLb-yd;Lb Ji3sKVswS (@
S{f
ws#5m7Ҍ\;9q;,:*EbȮIbf>ں]ʝJDF1ϬN#h^9{stD'O 7[.tCtdbarA8)"zӋW."c}hi"e|;UhĉǬ{Q"CkxHH)!;=>q#5dlB^]}g4ρTQ-yjGvzHLJvfzӋG$AqϑRЋ^>wJ|LGFaDWqGКELnqzrs2b%HzdoB\L81jcc7;NʘG[B-L0ȣ(<;,p?^\-*5]{3_)@
P,)7DdUFmdNf=IB8x@x9=pK`-j8p W-=kYқq}ö礏bIvPgj=y`د.vrz?k/Yɨ|Z9>ӈ
^A\./k]2ׇ⥛=fq_L1WxfF: _|s (@
PcPg\A
P (@
P_
`P<S6A]VQ([70aHۄMij<sV]
P (@
jw1 (AAjCVjڜK.1w>Nk۫OVy_ŲAXr![KB
P (@
m1 (p}M{wN<Mpgl'{w?Nk۫OVW-[h1vẝg
P (@
}1 (=7qN8Q Xr|YۅZ.U_yȄt$&barAZ:O" (@
PPiQG
P (@
P[^(@
P (A9f(@
P (@
P (@
P$)S7}P (@
P (@
P (@
P#0? gf}hdʜz
L{4w[!}T)@
P (@
P (@
P
>|EERB<ffgn+F:xf
h
uϴ(@
P (@
P (@
P ,(FF-7Gx9E碗z =۷ܚO
r}. (@
P (@
P ('#!t:]OCt|RM((@
P (@
P (@
PlgL`ǹgCw (@Csr (@
P (@
P X`M Y (@
P (@
P (@
P@
.`w3N
P (@
P (@
P (lǼS (@
P (@
P (@
v1 (@
P (@
P (@
P,@{;(@
P (@
P (@
P@
.`w3N
P (@
P (@
P (lǼS (@
P (@
P (@
v1 (@
P (@
P (@
P,@{;(@
P (@
P (@
P@
.`w3N
P (@
P (@
P (lǼS (@
P (@
P (@
v1 (@
P (@
P (@
P,@{;(@
P (@
P (@
P@
.`w3N
P (@
P (@
P (lǼS (@
P (@
P (@
v1 (@
P (@
P (@
P,@{;(@
P (@
P (@
P@
.`w3N
P (@
P (@
P (lǼS (@
P (@
P (@
v1 (@
P (@
P (@
P,@{;(@
P (@
P (@
P@
3 ',"(@
P (@
P (
-̀#{bf)@
P (@
P (@
P {\$A
<S,(@
P (@
P Z_O=Bko"=ã9f
uZ
Sca8w(@
P (@
P (8
L+X4D!x55IuãcXXXͻ?-?=a^(@
P (@
P (@
P tq1X6,l^}a#$$Xаbl[P (@
P (@
P (@
(ɍt7|I:iXN|1 (@
P (@
P (@
P
HϤYj$웞1
)
u?
P (@
P (@
P (ԓNˣ)
?
P (@
P (@
P (@
: (@
P (@
P (@
P
]A (@
P (@
P (@
PA(@
P (@
P (@
P ('±'ݎß"`:KT"<# (@
P (@
P (@
P {y_J,v
_?颿d (֑M\S}wS>-R<~ro?.~ao{j:= "06)`3 y:t:NrC
P (@
P<"YRxt
Bh<G9aݔ`n>~Y0EGm=KY)Dc~s▃ac4cH'60eQ9yg.)@_ wagZ!88ss3C۽&|]nQ /tĉ2=lr'}?En~a@/{{vr[X/-8$iUW/V
9;X:h}hq\4ZϾN*3@
P (@
PUkh>yƣ(x4,&'oTܦkj3 Yp).1#M4u>.&HgBFw#t<:Ƨ7{lr89=mY6 lxp#L%.J@OaCZ&l/ms'Q}_ˀ[*'͙;(\Yoٍ`t8wh{`?9Z>G[ͪ0SCI~v]aojŴ<W"煗'GAK-W
_|uxm`ֱ`Ĉ^zoaJuE (@
P (wo<?~X:עsӥQy}W#r3S-4cu!5~Jϡf?4f:Cdt,RM%=\;'BlBhۈ(@
,#Sw'f8H'5!ݘ^
X߈S˺a5g_$Ǚ.χu|nZIJV~~ۖn5δT}K߱ߪnw?#F_0YeGs#i6ҍwZLA榭؞(oT<Kzu:}mQ8O
P (@
P7U6ڦNٹ
ucvDrtG
p%8QsNlm4)KтR₸E\wl{nʅ
xKGaON)I7vEҍqQ>>t|nz2qؘєzvttt9SZY3-Yjbζ{U+O}V̔g"gFݴTm;6!I 1ނ~ڐV#Hf#O45)(@
P (@
HgUݾc;wbkim*6]-8RI1=
En}4FwKˊsr[<ʀ~|Ҵ]ȵ5Q(^hH=N4`m5h۱/Eʼn'j0Cs,݂ð0z_߱S;:1X/*-#Ƨ" E">̌u[/C?Jk/"]"2%<n0߁+[-_ZN P]"135JBq(*kMZ]Ez}T|a]0֬'YuV^8$ɞю!/ڈEq~\/Ώ}hYgۀhr$J`#ىt4Txo'.lH#bDxNHi2E2-EW8)SV$F!l}5mv4ř GT`e!ވɅ&#+G%&iun+' \[ tꏣst;S <YW0LFN70^{;Ž\E}3 c鸼qzhp!9 ['x3Z$o^!6VqܻciSC<dgIV)Ys4nJmSy$"ӭh+C\ (@
P (ڿ½;h߅Bi&A'dgˇDۖTy_ISR+gjKQR(
d>&GYzi;__Ļ_,5ͦn?Ԝ2<Ub|_V$ը-o,+T42
u9x?iWTo"Rw!۳w4EwaZckL-KEte.MEGe|y
FKp#BPŵn5rpA`Rul9\lTj(2ϊJ3v[vsCay$ošKSQ"9.7(q 9p@ҢK*|xJx+rf9W
Ĺ?K8+}sCFr䖂lV-WɯX[.{vmUa|l0Yflُ/N:MI8?=Ͼ=`tSRYGvR=Q7a[shxvT%m%\}qڐ؋j$'Uo7n]ٻ|o_e'$ 4$&9IzHtrN{{=wݻκYSrt8(*2H Lg諾kW(
(vL*Hy>~4!1*6 *Ue2ehKp_ğn?9mA*Sb`kF:QE,&&jn뷵{ (@
P (~Um~:`.jeٙklGZ+ [GIsR+CouGe OҀas/a?t>|[?Hg)ƀe/WѪӭ`dlxIS)WdKkI)[G1olTt]:A:Kux:6?xU I
rWvᵷڟ3
P`Z.BOAJuHaל,4{~r:k:A:kD{rg~؝T_?Hg2tR\g}A3tvFcӾwgHۂ˳cR,Nx˾co}]c=xnnN.*<M^4EK,ye/6K:j{]waX-:viȻA:K]-ލZ#GsV{t##߯RyxoR9K+z(oFdv>4JuU:) ScWZG
P (@
P
Z6\݈J/Eґtɲ}nSi RMb!bY[w-FqfW֬O
KA 'O_j ,ݼ[-@T`W=4-jת)K7bok(ml~AΫ>(|:. Qr
;݊*]v
UWqH&ʶ`vUB 6ܴ
.߀J Vܷ3/Q&qq(*߄m;
{^H?)iKY͌JQwrZC
, m}5Zfq`An!'mh6mD<2#"T/1ru&nScb QR^QFؾ2M.ogWFfSLY\r,-VrG4/9k\H.5fan(7ΈhyR*O^ժFd<e[h&|MΖsQ4YĴ{BLqQ˵[_UpGuULn|8vw +7&:m!X('u\Tl*1J8uK4)((GwtZ=Ljkpw9wi˖R[X5&I_T߉Z#;}~18rlp,ޛ%ZNY(OԜ>ԢxoE,jcVD9xl.zV^ynCdMLŮ_i)@
P (@
P`qVN0Vydƹ-yuqgS~}\&44ݤmH) L*7}i8zg!hnzb@[߉@Y{5b)eNvn&po?{u}=)yo->A4(YO+tqEꤏbk۴5Ws?`Ped֗^AxOP퇹Zճ3w|~3}[T?coM
vX_hWVnA:q]փEhBIt0:i=%=uEYEWsSSM.R,`&TRHl~[x-S_u]!:(ymnRCUgPp%@eAAuX_# 孯_|t睍8}`u:u.u3J&[_OduAqr0N+5Yz?h$]#U:Λ?TףfLe+MGUhH`o)5=I9س=z=>lٺ"U_Z5H5<\ֈ2Nmmg]hqHk~~_uw9wٚ,yהk!fuNcȓ.4ٙ"PWQΩ\:GuuANۇHc?soK0u/jJ*ԆYw3t88DZز-px(E[?+G
P (@
Pk2w ^@X*$s[yJ"=PU{OfHGOVL(75eg PhZImġlKK߯E<㐙j&%bi\;Z?MHAi(8 )vHrV4#ՄҎ} Ԍ'mmMVY}s[ ^QqbyIQblc;4At6SҥaY(@~Vi\!w>TRiwk-umi 5A:tg%0딌))bLFFTeySǪ'ur@/. [59w>scSZ2Pm._XJ ) zPzd, .SIcC$'_͝c;e#nihGXWQ"FI+ii}sM'9g)W+Jq4E9Mg_\7벮Jp@~vNj`Mڏ?uǘ5"PwoȆQ}KXsr-a @ IDAT_įWcP
dDY@E8t8;4O)@
P (@
P`?_u.[~=4: Ԓ~I|_.*,51VnHTffZ{K]uN0pV'EbmFf͒µB}lƤu~uSk"M7^aT)sRzطퟚWKhnoߘR/hknGWw7Za3ُe#
M=}
P@fCwNozٖ9z4l:""А (4A!XarƳ>1:lu [E.R?#,Ldb$#j?][m}ݽfZq2"`7uL$
]^i;sgIuLLnQQm3AǭGs<(=u#`:gkCli\`j]DM)ZzϵGj_O:Rǹo{m=@%2?~'{Kg;Z[gNuuzf/{,m;VF%"6$`0<sv:J Y,v-s
P (@
PX|hˣ/㻱՚: Q"H';=߭A}}刊Xh%}*61N`ÍMb2['_-~-
c
76Td`SGEӦ(S:
H_9vɏ,[LT<IҹeR\-&EMJԀ2PՌq9uBf.hl11R˲
=WvQT
KslRgq8:?FG4QI}ѮQj/>֬qqs&5ڔy٦u3:>hN2!1vg=ca:$ܵǓp'OźsR6;O1W/ͯS)]=z?ܽg/u'q,a%+sF#)-S u nKAfWιآ \\ly"/"6EcKY)-n'Կ 1k]~XeFcOabׯT (@
P (@x,?~ӟ`u<Fuz%%wJ~\nC62t1YNQt3oסF;[ߖ[gM(SB@m&۴檼a%InDG͜&IRk>GbArRRbYHq*hǿ>fO+a>
P wSGv*1.<m)3 ց+m@O&HqW[1u2~qs.t}2s}=,
#)fdlmtGάbAŪ lU1:źs1JNE(w7bFji}/Nϡ4'b$dR}Ј5[F>ݔ'3tr%8~V}2Ҥ`vb
2EրlkωrHNGP'c(@
P (@
P/>9b45j'QtsO˾=Xi]jde%c*}øW#FqvEN@6g-"oB2BnUkDcҪ4!CC^!FJo}CBB2"㢡75149Smcsyn'FP-2.]D˓&;볬WPh֬7]NfOlQ
ɝhӸʴ:j/g79G
;kGH:3ʘUjީX?#'>O9r8Ěg~GBQ#u2i-JpAl:{~bfi\LDN^ϥzYgzf[qf֠/qc+W:G<G3V6wGVƤ"%)9(ȰƭCam謱h)~iIbrYL7|f9[߶"F2(tMJ<-T4%bzy (@
P [ (.??XsQhAbv(
hؗP|RmPހ#;`) us,LJvu2EjM5[\"/C%&>Pq2`#*g
6jL)43kwZ[&=߶_Yic8oqI-"&m w(@P^`N{ ץ`vڳ:1HĊufE:2+E5#?'vB}lECHʲriݤ|A[mUmVD$ijQ- X xjzq'ԠYwd9gK{}:I7SΡ ʈ֧s/*œU'zץ3em]/~AX1Up}m5⫃b
D7B
:]5SsU-[T1ۃ.eW<.vp (@
P K@ޖGĢ<OmY $>A1H_]k\~]ѳlDöBd\L=ݩn@EF<i =ޚM7hMM-nQ/ut!9,GIφ,kIOflxvךQ*6Xð}NSq4.VJu͚Y2X/_ww1gt]e/bK^Q}$.vIV`r
Ҡ[ʟǦ 1n7*Zu1n0*tvVL>Y#(߳=M緺dJԜm(ϰ| t3;qQ[XbX˲
77H?(v|QߚbD6+gqU^1D͝S2pվҽ?zVbONXh~S3zq:K,6)s7^L8,eu?uAYקs'Xoy
۲,ˤ2w5}:"¦bdHs-"/`z琈}o>r8yc_t{Yr_z,l{6!W20MMHˑ.{0EgNy6߱j=ŮJ
P (@
PSebeUh2#{_[ܵttaHimQuS45u!:,݅[."8܍5(B2MﭮC:Wor) UhF@pr6"Mw7>Dk!a,.n yjth=S+Ï7PӦuu+qzf11F5oK7QoD*d<ڇ٩XmK&#%`@N:'(@/SWlpƯFtk#>s
W!P|$ }{'B]uŹjlҊ1Rc %yր75YvTFuȗCw'8 #
~ =;7Ecb$ɍE7Mr+oGUpʵ:%b;qkՙMQp?Vðو
cxvRwb|hn:mڟ1[ws}:7i?U^Qҏzfc&'iꛊow7g#Kj;N
rқW!E:RxSSf/=,DKUn
7P٪Nlln֣0gKb5"(Pwy~aܡ (@
P (@Xj'Ӹ!b9ƕ+1xhUXl^7
[@pބ
76,{Dz_-MSgB~Y5y4|q1ك-)ZV݈ƤcM7'!mq֟QX飑:DdIlݮU=9=ր[֗?3vU_4v!a3<\^ufV ͅl+'cd7jU7`:K&c
J*45'E9=* &@3:yC@';;&Gvfdۥ<N7k>9츷m]rl[R
v5{8r,"^نTɈ瑯Izȶ(pKwd!<!5q;`4t3=<KXtsO| Dko)km[֨Y\{яgǵ
w/.]FZk`>ďCiw51ɭ6KP
*?ط:ڈ\-Hmf(:q\.vM4|:=q[yjy\[g (@
P ("lzgj._e+m3 ߖniuwѨ.c1ڻn圚&VsbVm1*MZF666Eڮ[TƁu!Ǯ[*M䙧sT<'MucnSjMI3-ۤBnFo-̙Z4K\mQh6k_=ԉmϧF/(@ۅe}ͨ<-~ %EG1|vZߙŇoȟNԤ;gqmt,ݍo`Y./6w6qPeGv9;.z7ڦ Rtt;W*6*rZ? *apg}7_sL)4tjH!K._)kN ?ggIn:Kj,ӹKk3/.~_4I~:W*>8|ܨoG|_ו-f/R)u?~-F"K_l#}z 1i̭ut<%iS?94(@
P (@
P`O=}WE"!L<v<gLF~j&"A+V`܃1-u^{k8` Hfe"T %1ӊA<'~^=7!;q0&Bbܣ.)r354!,<lI]IRjV>
С\^QRxoetF_Y뤌t1`Xo;ZzG8HDNbZ7&^-04'>O/F8XBB-eɿF7Z*wl֢?w6:Ilcz`}u䣯킼u~/p7Z:]7GKD4Gx䤿zĤ %QW4fH1#Henjs1*$QSJRw\#(@
P (@
-0:2
Rƕ+G~VrG~!?elp'47sJ=i;N8v@;jď[kcgEo5UV]DPSp ^VksfsXuJuksޒNgΛ鍚і-oAݸ>=6ZN[m? _#f؇{C~i`MqG'Y-~<P]5H.v_8sR (@
P Eyae (@
P+[wto!K (@
P (@
P (#KZ5^ۙW`yG(@
<g?IhHw-qi6 (@
P (@
,y[[քk&$lXY(@hƍ;ǡ.n,[GY?߫:O xbGwr)<M
P (@
P |.)h-k(@
8tFB`XSp
$wӹQP (@
P (@
̣ uˢ)@
P (@
P (@
P G~A.C (@
P (@
P (@
PKS`2Kk (@
P (@
P (@
P&'ƄO-Yl-96S_:9(@
P (@
P (@
PSǏ15=@`tliڅ<!D0`rLLNb|g] (@
P (@
P (@
P,0-tX)낂Vss+^ OԗQ7{ E 7;sQe (@
P (@
P ?GwO/BCBdQMLLBtuMX)(@
P (@
P (@
PXȺѥ}zz
Paa>w(@
P (@
P (@
,q@|l
P>/Db(
P (@
P (@
P~ &P (@
P (@
P (@
P``
P (@
P (@
P (@`@
P (@
P (@
P ( 0Pr^0(@
P (@
P (@
P?0Pwm (@
P (@
P (@
Px{n9/ (@
P (@
P (@
P6P (@
P (@
P (@
<s=sL
P (@
P (@
P (]`(@
P (@
P (@
P 9ꞹ[ (@
P (@
P (@
P@h@
Pٙ'x (@
P (@
P54-pOuQc^!(@
P (@
P (@
P
pD6 ( (@
P (@
PB 8kٲe
BPP /_aBx]u^
P#0
P (@
P (@
PVёQ] [eDP`]_SSSmO:l(@
P (@
P (@
P4.:*FG f[M }=}ݤYgnV"& |