Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(openapi): create app #32

Merged
merged 18 commits into from
Aug 30, 2023
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ Release Notes.
Apollo Java 2.2.0

------------------
[refactor(apollo-client): Optimize the exception message when failing to retrieve configuration information.](https://github.com/apolloconfig/apollo-java/pull/22)
[Add JUnit5 extension support for apollo mock server.](https://github.com/apolloconfig/apollo-java/pull/25)
[Support concurrent loading of Config for different namespaces.](https://github.com/apolloconfig/apollo-java/pull/31)
[Fix snakeyaml 2.x compatibility issues](https://github.com/apolloconfig/apollo-java/pull/35)
* [refactor(apollo-client): Optimize the exception message when failing to retrieve configuration information.](https://github.com/apolloconfig/apollo-java/pull/22)
* [Add JUnit5 extension support for apollo mock server.](https://github.com/apolloconfig/apollo-java/pull/25)
* [Support concurrent loading of Config for different namespaces.](https://github.com/apolloconfig/apollo-java/pull/31)
* [Fix snakeyaml 2.x compatibility issues](https://github.com/apolloconfig/apollo-java/pull/35)
* [feat(openapi): create app](https://github.com/apolloconfig/apollo-java/pull/32)

------------------
All issues and pull requests are [here](https://github.com/apolloconfig/apollo-java/milestone/2?closed=1)
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.ctrip.framework.apollo.openapi.api;

import com.ctrip.framework.apollo.openapi.dto.OpenAppDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenCreateAppDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenEnvClusterDTO;
import java.util.List;

Expand All @@ -25,6 +26,10 @@
*/
public interface AppOpenApiService {

default void createApp(OpenCreateAppDTO req) {
throw new UnsupportedOperationException();
}

List<OpenEnvClusterDTO> getEnvClusterInfo(String appId);

List<OpenAppDTO> getAllApps();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ private ApolloOpenApiClient(String portalUrl, String token, RequestConfig reques
releaseService = new ReleaseOpenApiService(client, baseUrl, GSON);
}

public void createApp(OpenCreateAppDTO req) {
appService.createApp(req);
}

/**
* Get the environment and cluster information
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import com.ctrip.framework.apollo.openapi.client.url.OpenApiPathBuilder;
import com.ctrip.framework.apollo.openapi.dto.OpenAppDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenCreateAppDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenEnvClusterDTO;
import com.google.common.base.Joiner;
import com.google.gson.Gson;
Expand All @@ -39,6 +40,22 @@ public AppOpenApiService(CloseableHttpClient client, String baseUrl, Gson gson)
super(client, baseUrl, gson);
}

@Override
public void createApp(OpenCreateAppDTO req) {
checkNotEmpty(req.getAppId(), "App id");
checkNotEmpty(req.getName(), "App name");
OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder()
.customResource("apps");

try (CloseableHttpResponse response = post(pathBuilder, req)) {
gson.fromJson(EntityUtils.toString(response.getEntity()), void.class);
} catch (Throwable ex) {
throw new RuntimeException(
String.format("Create app: %s for appId: %s failed", req.getName(),
req.getAppId()), ex);
}
}

@Override
public List<OpenEnvClusterDTO> getEnvClusterInfo(String appId) {
checkNotEmpty(appId, "App id");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright 2022 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 OpenCreateAppDTO extends OpenAppDTO {

/**
* The application owner has project administrator permission by default.
* <p>
* Administrators can create namespace, cluster, and assign user permissions
*/
private Set<String> admins;

public Set<String> getAdmins() {
return admins;
}

public void setAdmins(Set<String> admins) {
this.admins = admins;
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder("OpenCreateAppDTO{");
sb.append("name='").append(getName()).append('\'');
sb.append(", appId='").append(getAppId()).append('\'');
sb.append(", orgId='").append(getOrgId()).append('\'');
sb.append(", orgName='").append(getOrgName()).append('\'');
sb.append(", ownerName='").append(getOwnerName()).append('\'');
sb.append(", ownerEmail='").append(getOwnerEmail()).append('\'');
sb.append(", admins='").append(admins).append('\'');
sb.append(", dataChangeCreatedBy='").append(dataChangeCreatedBy).append('\'');
sb.append(", dataChangeLastModifiedBy='").append(dataChangeLastModifiedBy).append('\'');
sb.append(", dataChangeCreatedTime=").append(dataChangeCreatedTime);
sb.append(", dataChangeLastModifiedTime=").append(dataChangeLastModifiedTime);
sb.append('}');
return sb.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/*
* Copyright 2022 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;

import static org.junit.jupiter.api.Assertions.assertEquals;

import com.ctrip.framework.apollo.openapi.dto.NamespaceReleaseDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenAppDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenCreateAppDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenReleaseDTO;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Do not run in 'mvn clean test',
* left code here for develop test,
* you can run the method by ide.
*/
class ApolloOpenApiClientIntegrationTest {

private final Logger log = LoggerFactory.getLogger(this.getClass());

private final ApolloOpenApiClient client = newClient();

private final String env = "DEV";
private final String clusterName = "default";

ApolloOpenApiClient newClient() {
String someUrl = "http://localhost:8070";
// String someToken = "0627b87948c30517157e8b2a9565e473b5a97323a50128f584838ed10559d3fd";
String someToken = "9d0a241e9cb2300f302a875b1195340b2b6f56373cf5ca5d006a3f4e1a46b3ef";

return ApolloOpenApiClient.newBuilder()
.withPortalUrl(someUrl)
.withToken(someToken)
.withReadTimeout(2000 * 1000)
.withConnectTimeout(2000 * 1000)
.build();
}

void createApp(String appId, String ownerName, String ... admins) {
{
OpenCreateAppDTO req = new OpenCreateAppDTO();
req.setName("openapi create app 测试名字 " + appId);
req.setAppId(appId);
req.setOwnerName(ownerName);
req.setOwnerEmail(ownerName + "@apollo.apollo");
req.setOrgId("orgIdFromOpenapi");
req.setOrgName("orgNameFromOpenapi");
req.setAdmins(new HashSet<>(Arrays.asList(admins)));
client.createApp(req);
}
}

@Test
@Disabled("only for integration test")
public void testCreateApp() {
final String appId = "openapi-create-app1";
final String ownerName = "user-test-xxx1";
createApp(appId, ownerName, "user-test-xxx2", "user3");

List<OpenAppDTO> list = client.getAppsByIds(Collections.singletonList(appId));
assertEquals(1, list.size());
OpenAppDTO openAppDTO = list.get(0);
log.info("{}", openAppDTO);
assertEquals(appId, openAppDTO.getAppId());
assertEquals(ownerName, openAppDTO.getOwnerName());
}

@Test
@Disabled("only for integration test")
public void testCreateAppThenCreateNamespaceThenRelease() {
// create app
final String appId = "openapi-create-app1";
final String ownerName = "test-create-release1";
createApp(appId, ownerName, "user-test-xxx1", "user-test-xxx2");

{
List<OpenAppDTO> list = client.getAppsByIds(Collections.singletonList(appId));
assertEquals(1, list.size());
OpenAppDTO openAppDTO = list.get(0);
log.info("{}", openAppDTO);
assertEquals(appId, openAppDTO.getAppId());
assertEquals(ownerName, openAppDTO.getOwnerName());
}

// create namespace
final String namespaceName = "openapi-create-namespace";
{
OpenAppNamespaceDTO dto = new OpenAppNamespaceDTO();
dto.setName(namespaceName);
dto.setAppId(appId);
dto.setComment("create from openapi");
dto.setDataChangeCreatedBy(ownerName);
client.createAppNamespace(dto);
}

// modify
// k1=v1
{
OpenItemDTO itemDTO = new OpenItemDTO();
itemDTO.setKey("k1");
itemDTO.setValue("v1");
client.createOrUpdateItem(
appId, env, clusterName, namespaceName, itemDTO
);
}
// k2=v2
{
OpenItemDTO itemDTO = new OpenItemDTO();
itemDTO.setKey("k2");
itemDTO.setValue("v2");
client.createOrUpdateItem(
appId, env, clusterName, namespaceName, itemDTO
);
}

// release namespace
{
NamespaceReleaseDTO dto = new NamespaceReleaseDTO();
dto.setReleaseTitle("openapi-release");
dto.setReleasedBy(ownerName);
dto.setReleaseComment("test openapi release in " + LocalDateTime.now());
client.publishNamespace(appId, env, clusterName, namespaceName, dto);
}

// read then namespace
{
OpenNamespaceDTO namespaceDTO
= client.getNamespace(appId, env, clusterName, namespaceName);
List<OpenItemDTO> items = namespaceDTO.getItems();
Map<String, String> map = new HashMap<>(16);
for (OpenItemDTO item : items) {
map.put(item.getKey(), item.getValue());
}
assertEquals(2, map.size());
assertEquals("v1", map.get("k1"));
assertEquals("v2", map.get("k2"));
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,19 @@
package com.ctrip.framework.apollo.openapi.client.service;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.atLeastOnce;
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.OpenAppDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenCreateAppDTO;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.HashSet;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.StringEntity;
import org.junit.Before;
import org.junit.Test;
Expand Down Expand Up @@ -65,4 +73,60 @@ public void testGetEnvClusterInfoWithError() throws Exception {

appOpenApiService.getEnvClusterInfo(someAppId);
}

@Test(expected = RuntimeException.class)
public void testCreateAppEmptyAppId() throws Exception {
OpenCreateAppDTO req = new OpenCreateAppDTO();
appOpenApiService.createApp(req);
}

@Test(expected = RuntimeException.class)
public void testCreateAppEmptyAppName() throws Exception {
OpenCreateAppDTO req = new OpenCreateAppDTO();
req.setAppId("appId1");
appOpenApiService.createApp(req);
}

@Test(expected = RuntimeException.class)
public void testCreateAppFail() throws Exception {
OpenCreateAppDTO req = new OpenCreateAppDTO();
req.setAppId("appId1");
req.setName("name1");
req.setAdmins(new HashSet<>(Arrays.asList("user1", "user2")));

when(statusLine.getStatusCode()).thenReturn(400);

appOpenApiService.createApp(req);
}


@Test
public void testCreateAppSuccess() throws Exception {
OpenCreateAppDTO req = new OpenCreateAppDTO();
req.setAppId("appId1");
req.setName("name1");
req.setAdmins(new HashSet<>(Arrays.asList("user1", "user2")));

when(statusLine.getStatusCode()).thenReturn(200);
{
BasicHttpEntity httpEntity = new BasicHttpEntity();
httpEntity.setContentLength(0L);
httpEntity.setContent(new ByteArrayInputStream(new byte[0]));
when(someHttpResponse.getEntity()).thenReturn(httpEntity);
}

appOpenApiService.createApp(req);

verify(someHttpResponse, atLeastOnce()).getEntity();
verify(httpClient, atLeastOnce()).execute(argThat(request -> {
if (!"POST".equals(request.getMethod())) {
return false;
}
if (!request.getURI().toString().endsWith("apps")) {
return false;
}
return true;
}));

}
}