Return-Path: X-Original-To: archive-asf-public-internal@cust-asf2.ponee.io Delivered-To: archive-asf-public-internal@cust-asf2.ponee.io Received: from cust-asf.ponee.io (cust-asf.ponee.io [163.172.22.183]) by cust-asf2.ponee.io (Postfix) with ESMTP id 7E0FD200B7D for ; Sat, 10 Sep 2016 19:17:12 +0200 (CEST) Received: by cust-asf.ponee.io (Postfix) id 7CA0B160AA5; Sat, 10 Sep 2016 17:17:12 +0000 (UTC) Delivered-To: archive-asf-public@cust-asf.ponee.io Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by cust-asf.ponee.io (Postfix) with SMTP id 8685B160ABE for ; Sat, 10 Sep 2016 19:17:10 +0200 (CEST) Received: (qmail 25525 invoked by uid 500); 10 Sep 2016 17:17:09 -0000 Mailing-List: contact commits-help@brooklyn.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@brooklyn.apache.org Delivered-To: mailing list commits@brooklyn.apache.org Received: (qmail 25506 invoked by uid 99); 10 Sep 2016 17:17:09 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Sat, 10 Sep 2016 17:17:09 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id 4D902E0667; Sat, 10 Sep 2016 17:17:09 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: andreaturli@apache.org To: commits@brooklyn.apache.org Date: Sat, 10 Sep 2016 17:17:09 -0000 Message-Id: X-Mailer: ASF-Git Admin Mailer Subject: [1/2] brooklyn-server git commit: move rest/rest-client to brooklyn-client submodule archived-at: Sat, 10 Sep 2016 17:17:12 -0000 Repository: brooklyn-server Updated Branches: refs/heads/master 66b9b1c51 -> e947e929a move rest/rest-client to brooklyn-client submodule Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/f63006ba Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/f63006ba Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/f63006ba Branch: refs/heads/master Commit: f63006ba60f37a2448df470d15c2ed231471b72b Parents: 66b9b1c Author: Andrea Turli Authored: Wed Sep 7 17:31:53 2016 +0200 Committer: Andrea Turli Committed: Fri Sep 9 09:35:36 2016 +0200 ---------------------------------------------------------------------- karaf/features/src/main/feature/feature.xml | 3 - karaf/pom.xml | 6 - parent/pom.xml | 17 - pom.xml | 4 +- rest/rest-client/pom.xml | 163 -------- .../brooklyn/rest/client/BrooklynApi.java | 419 ------------------- .../brooklyn/rest/client/BrooklynApiUtil.java | 154 ------- .../util/http/BuiltResponsePreservingError.java | 79 ---- .../ApplicationResourceIntegrationTest.java | 190 --------- .../rest/client/BrooklynApiRestClientTest.java | 163 -------- .../rest/client/BrooklynApiUtilTest.java | 129 ------ .../src/test/resources/catalog/test-catalog.bom | 33 -- .../rest-client/src/test/webapp/WEB-INF/web.xml | 129 ------ 13 files changed, 1 insertion(+), 1488 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/karaf/features/src/main/feature/feature.xml ---------------------------------------------------------------------- diff --git a/karaf/features/src/main/feature/feature.xml b/karaf/features/src/main/feature/feature.xml index d2078d3..bea75a6 100644 --- a/karaf/features/src/main/feature/feature.xml +++ b/karaf/features/src/main/feature/feature.xml @@ -110,9 +110,6 @@ mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.jsr305/${jsr305.bundle.version} mvn:com.google.code.gson/gson/${gson.version} - wrap:mvn:org.jboss.resteasy/resteasy-jaxrs/${resteasy.version} - wrap:mvn:org.jboss.resteasy/resteasy-jackson2-provider/${resteasy.version} - wrap:mvn:org.jboss.resteasy/jaxrs-api/${resteasy.version} wrap:mvn:javax.activation/activation/${javax-activation.version} mvn:commons-io/commons-io/${commons-io.version} mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.jcip-annotations/${jcip-annotations.bundle.version} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/karaf/pom.xml ---------------------------------------------------------------------- diff --git a/karaf/pom.xml b/karaf/pom.xml index 8540ca8..5769029 100644 --- a/karaf/pom.xml +++ b/karaf/pom.xml @@ -48,12 +48,6 @@ 6.0.0 0.9.9_1 - - 1.0.1.Final - 1.1 - 1.0_2 - 2.0.1_1 - ${java.version} ${java.version} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/parent/pom.xml ---------------------------------------------------------------------- diff --git a/parent/pom.xml b/parent/pom.xml index 4efc785..55005bd 100644 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -492,23 +492,6 @@ cxf-rt-rs-client ${cxf.version} - - - org.jboss.resteasy - resteasy-jaxrs - ${resteasy.version} - - - org.jboss.resteasy - resteasy-jackson2-provider - ${resteasy.version} - - - org.jboss.resteasy - jaxrs-api - ${resteasy.version} - - http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/pom.xml ---------------------------------------------------------------------- diff --git a/pom.xml b/pom.xml index a6cff34..caa1d37 100644 --- a/pom.xml +++ b/pom.xml @@ -101,9 +101,8 @@ 1.4.8 1.1.4c_7 2.3.0_3 - + 2.4.5 - 3.0.8.Final 3.1.4 4.4.1 3.3.2 @@ -216,7 +215,6 @@ logging/logback-includes logging/logback-xml rest/rest-api - rest/rest-client rest/rest-resources rest/rest-server test-framework http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/rest/rest-client/pom.xml ---------------------------------------------------------------------- diff --git a/rest/rest-client/pom.xml b/rest/rest-client/pom.xml deleted file mode 100644 index 2984331..0000000 --- a/rest/rest-client/pom.xml +++ /dev/null @@ -1,163 +0,0 @@ - - - - 4.0.0 - brooklyn-rest-client - jar - Brooklyn REST Client - - Client library for Brooklyn REST interface - - - - org.apache.brooklyn - brooklyn-parent - 0.10.0-SNAPSHOT - ../../parent/pom.xml - - - - - org.apache.brooklyn - brooklyn-rest-api - ${project.version} - - - org.apache.brooklyn - brooklyn-api - ${project.version} - - - org.jboss.resteasy - resteasy-jaxrs - - - org.slf4j - slf4j-simple - - - - - org.jboss.resteasy - resteasy-jackson2-provider - - - org.slf4j - slf4j-simple - - - - - org.apache.brooklyn - brooklyn-utils-common - ${project.version} - - - org.apache.httpcomponents - httpclient - - - com.google.code.findbugs - jsr305 - - - com.google.guava - guava - - - org.slf4j - slf4j-api - - - com.google.code.gson - gson - - - org.testng - testng - test - - - org.eclipse.jetty - jetty-server - test - - - org.apache.brooklyn - brooklyn-core - ${project.version} - test - - - org.apache.brooklyn - brooklyn-core - ${project.version} - tests - test - - - org.apache.brooklyn - brooklyn-rest-server - ${project.version} - test - - - org.apache.brooklyn - brooklyn-rest-resources - ${project.version} - tests - test - - - org.apache.brooklyn - brooklyn-rest-server - ${project.version} - tests - test - - - org.apache.brooklyn - brooklyn-test-support - ${project.version} - test - - - com.google.mockwebserver - mockwebserver - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - *,org.jboss.resteasy.client.core.marshallers - - - - - - - http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/BrooklynApi.java ---------------------------------------------------------------------- diff --git a/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/BrooklynApi.java b/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/BrooklynApi.java deleted file mode 100644 index 822e296..0000000 --- a/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/BrooklynApi.java +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.brooklyn.rest.client; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.net.MalformedURLException; -import java.net.URL; - -import javax.annotation.Nullable; -import javax.ws.rs.core.Response; - -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.jboss.resteasy.client.ClientExecutor; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.client.ProxyBuilder; -import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor; -import org.jboss.resteasy.client.core.extractors.DefaultEntityExtractorFactory; -import org.jboss.resteasy.specimpl.BuiltResponse; -import org.jboss.resteasy.spi.ResteasyProviderFactory; -import org.jboss.resteasy.util.GenericType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.gson.Gson; - -import org.apache.brooklyn.rest.api.AccessApi; -import org.apache.brooklyn.rest.api.ActivityApi; -import org.apache.brooklyn.rest.api.ApplicationApi; -import org.apache.brooklyn.rest.api.CatalogApi; -import org.apache.brooklyn.rest.api.EffectorApi; -import org.apache.brooklyn.rest.api.EntityApi; -import org.apache.brooklyn.rest.api.EntityConfigApi; -import org.apache.brooklyn.rest.api.LocationApi; -import org.apache.brooklyn.rest.api.PolicyApi; -import org.apache.brooklyn.rest.api.PolicyConfigApi; -import org.apache.brooklyn.rest.api.ScriptApi; -import org.apache.brooklyn.rest.api.SensorApi; -import org.apache.brooklyn.rest.api.ServerApi; -import org.apache.brooklyn.rest.api.UsageApi; -import org.apache.brooklyn.rest.api.VersionApi; -import org.apache.brooklyn.rest.client.util.http.BuiltResponsePreservingError; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.exceptions.Exceptions; -import org.apache.brooklyn.util.javalang.AggregateClassLoader; -import org.apache.brooklyn.util.net.Urls; - -import io.swagger.annotations.ApiOperation; - -/** - * @author Adam Lowe - */ -@SuppressWarnings("deprecation") -public class BrooklynApi { - - private final String target; - private final ClientExecutor clientExecutor; - private final int maxPoolSize; - private final int timeOutInMillis; - private static final Logger LOG = LoggerFactory.getLogger(BrooklynApi.class); - - /** - * @deprecated since 0.9.0. Use {@link BrooklynApi#newInstance(String)} instead - */ - @Deprecated - public BrooklynApi(URL endpoint) { - this(checkNotNull(endpoint, "endpoint").toString()); - } - - /** - * @deprecated since 0.9.0. Use {@link BrooklynApi#newInstance(String)} instead - */ - @Deprecated - public BrooklynApi(String endpoint) { - // username/password cannot be null, but credentials can - this(endpoint, null); - } - - /** - * @deprecated since 0.9.0. Use {@link BrooklynApi#newInstance(String, String, String)} instead - */ - @Deprecated - public BrooklynApi(URL endpoint, String username, String password) { - this(endpoint.toString(), new UsernamePasswordCredentials(username, password)); - } - - /** - * @deprecated since 0.9.0. Use {@link BrooklynApi#newInstance(String, String, String)} instead - */ - @Deprecated - public BrooklynApi(String endpoint, String username, String password) { - this(endpoint, new UsernamePasswordCredentials(username, password)); - } - - /** - * @deprecated since 0.9.0. Use {@link BrooklynApi#newInstance(String, String, String)} instead - */ - @Deprecated - public BrooklynApi(URL endpoint, @Nullable Credentials credentials) { - this(endpoint.toString(), credentials); - } - - /** - * Creates a BrooklynApi using an HTTP connection pool - * - * @deprecated since 0.9.0. Use {@link BrooklynApi#newInstance(String, String, String)} instead - */ - @Deprecated - public BrooklynApi(String endpoint, @Nullable Credentials credentials) { - this(endpoint, credentials, 20, 5000); - } - - /** - * Creates a BrooklynApi using a custom ClientExecutor - * - * @param endpoint the Brooklyn endpoint - * @param clientExecutor the ClientExecutor - * @see #getClientExecutor(org.apache.http.auth.Credentials) - */ - public BrooklynApi(URL endpoint, ClientExecutor clientExecutor) { - this.target = addV1SuffixIfNeeded(checkNotNull(endpoint, "endpoint").toString()); - this.maxPoolSize = -1; - this.timeOutInMillis = -1; - this.clientExecutor = checkNotNull(clientExecutor, "clientExecutor"); - } - - /** - * Creates a BrooklynApi using an HTTP connection pool - * - * @param endpoint the Brooklyn endpoint - * @param credentials user credentials or null - * @param maxPoolSize maximum pool size - * @param timeOutInMillis connection timeout in milliseconds - */ - public BrooklynApi(String endpoint, @Nullable Credentials credentials, int maxPoolSize, int timeOutInMillis) { - try { - new URL(checkNotNull(endpoint, "endpoint")); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - this.target = addV1SuffixIfNeeded(endpoint); - this.maxPoolSize = maxPoolSize; - this.timeOutInMillis = timeOutInMillis; - this.clientExecutor = getClientExecutor(credentials); - } - - private String addV1SuffixIfNeeded(String endpoint) { - if (!endpoint.endsWith("/v1/") && !endpoint.endsWith("/v1")) { - return Urls.mergePaths(endpoint, "v1"); - } else { - return endpoint; - } - } - - private Supplier connectionManagerSupplier = Suppliers.memoize(new Supplier() { - @Override - public PoolingHttpClientConnectionManager get() { - PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); - connManager.setMaxTotal(maxPoolSize); - connManager.setDefaultMaxPerRoute(maxPoolSize); - return connManager; - } - }); - - private Supplier reqConfSupplier = Suppliers.memoize(new Supplier() { - @Override - public RequestConfig get() { - return RequestConfig.custom() - .setConnectTimeout(timeOutInMillis) - .setConnectionRequestTimeout(timeOutInMillis) - .build(); - } - }); - - /** - * Creates a ClientExecutor for this BrooklynApi - */ - protected ClientExecutor getClientExecutor(Credentials credentials) { - CredentialsProvider provider = new BasicCredentialsProvider(); - if (credentials != null) provider.setCredentials(AuthScope.ANY, credentials); - - CloseableHttpClient httpClient = HttpClients.custom() - .setDefaultCredentialsProvider(provider) - .setDefaultRequestConfig(reqConfSupplier.get()) - .setConnectionManager(connectionManagerSupplier.get()) - .build(); - - return new ApacheHttpClient4Executor(httpClient); - } - - /** - * Creates a BrooklynApi using an HTTP connection pool - * - * @param endpoint the Brooklyn endpoint - * @return a new BrooklynApi instance - */ - public static BrooklynApi newInstance(String endpoint) { - return new BrooklynApi(endpoint, null); - } - - /** - * Creates a BrooklynApi using an HTTP connection pool - * - * @param endpoint the Brooklyn endpoint - * @param maxPoolSize maximum connection pool size - * @param timeOutInMillis connection timeout in millisecond - * @return a new BrooklynApi instance - */ - public static BrooklynApi newInstance(String endpoint, int maxPoolSize, int timeOutInMillis) { - return new BrooklynApi(endpoint, null, maxPoolSize, timeOutInMillis); - } - - /** - * Creates a BrooklynApi using an HTTP connection pool - * - * @param endpoint the Brooklyn endpoint - * @param username for authentication - * @param password for authentication - * @return a new BrooklynApi instance - */ - public static BrooklynApi newInstance(String endpoint, String username, String password) { - return new BrooklynApi(endpoint, new UsernamePasswordCredentials(username, password)); - } - - /** - * Creates a BrooklynApi using an HTTP connection pool - * - * @param endpoint the Brooklyn endpoint - * @param username for authentication - * @param password for authentication - * @param maxPoolSize maximum connection pool size - * @param timeOutInMillis connection timeout in millisecond - * @return a new BrooklynApi instance - */ - public static BrooklynApi newInstance(String endpoint, String username, String password, int maxPoolSize, int timeOutInMillis) { - return new BrooklynApi(endpoint, new UsernamePasswordCredentials(username, password), maxPoolSize, timeOutInMillis); - } - - @SuppressWarnings("unchecked") - private T proxy(Class clazz) { - AggregateClassLoader aggregateClassLoader = AggregateClassLoader.newInstanceWithNoLoaders(); - aggregateClassLoader.addLast(clazz.getClassLoader()); - aggregateClassLoader.addLast(getClass().getClassLoader()); - - final T result0 = ProxyBuilder.build(clazz, target) - .executor(clientExecutor) - .classloader(aggregateClassLoader) - .providerFactory(ResteasyProviderFactory.getInstance()) - .extractorFactory(new DefaultEntityExtractorFactory()) - .requestAttributes(MutableMap.of()) - .now(); - - return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - try { - Object result1 = method.invoke(result0, args); - Class type = String.class; - if (result1 instanceof Response) { - Response resp = (Response)result1; - if(isStatusCodeHealthy(resp.getStatus()) && method.isAnnotationPresent(ApiOperation.class)) { - type = getClassFromMethodAnnotationOrDefault(method, type); - } - // wrap the original response so it self-closes - result1 = BuiltResponsePreservingError.copyResponseAndClose(resp, type); - } - return result1; - } catch (Throwable e) { - if (e instanceof InvocationTargetException) { - // throw the original exception - e = ((InvocationTargetException)e).getTargetException(); - } - throw Exceptions.propagate(e); - } - } - - private boolean isStatusCodeHealthy(int code) { return (code>=200 && code<=299); } - - private Class getClassFromMethodAnnotationOrDefault(Method method, Class def){ - Class type; - try{ - type = method.getAnnotation(ApiOperation.class).response(); - } catch (Exception e) { - type = def; - LOG.debug("Unable to get class from annotation: {}. Defaulting to {}", e.getMessage(), def.getName()); - Exceptions.propagateIfFatal(e); - } - return type; - } - }); - } - - public ActivityApi getActivityApi() { - return proxy(ActivityApi.class); - } - - public ApplicationApi getApplicationApi() { - return proxy(ApplicationApi.class); - } - - public CatalogApi getCatalogApi() { - return proxy(CatalogApi.class); - } - - public EffectorApi getEffectorApi() { - return proxy(EffectorApi.class); - } - - public EntityConfigApi getEntityConfigApi() { - return proxy(EntityConfigApi.class); - } - - public EntityApi getEntityApi() { - return proxy(EntityApi.class); - } - - public LocationApi getLocationApi() { - return proxy(LocationApi.class); - } - - public PolicyConfigApi getPolicyConfigApi() { - return proxy(PolicyConfigApi.class); - } - - public PolicyApi getPolicyApi() { - return proxy(PolicyApi.class); - } - - public ScriptApi getScriptApi() { - return proxy(ScriptApi.class); - } - - public SensorApi getSensorApi() { - return proxy(SensorApi.class); - } - - public ServerApi getServerApi() { - return proxy(ServerApi.class); - } - - public UsageApi getUsageApi() { - return proxy(UsageApi.class); - } - - public VersionApi getVersionApi() { - return proxy(VersionApi.class); - } - - public AccessApi getAccessApi() { - return proxy(AccessApi.class); - } - - public static T getEntity(Response response, Class type) { - if (response instanceof ClientResponse) { - ClientResponse clientResponse = (ClientResponse) response; - return clientResponse.getEntity(type); - } else if (response instanceof BuiltResponse) { - // Handle BuiltResponsePreservingError turning objects into Strings - if (response.getEntity() instanceof String && !type.equals(String.class)) { - return new Gson().fromJson(response.getEntity().toString(), type); - } - } - // Last-gasp attempt. - return type.cast(response.getEntity()); - } - - public static T getEntity(Response response, GenericType type) { - if (response instanceof ClientResponse) { - ClientResponse clientResponse = (ClientResponse) response; - return clientResponse.getEntity(type); - } else if (response instanceof BuiltResponse) { - // Handle BuiltResponsePreservingError turning objects into Strings - if (response.getEntity() instanceof String) { - return new Gson().fromJson(response.getEntity().toString(), type.getGenericType()); - } - } - // Last-gasp attempt. - return type.getType().cast(response.getEntity()); - } - - /** - * @deprecated since 0.8.0-incubating. Use {@link #getEntity(Response, GenericType)} instead. - */ - @Deprecated - public static T getEntityGeneric(Response response, GenericType type) { - return getEntity(response, type); - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/BrooklynApiUtil.java ---------------------------------------------------------------------- diff --git a/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/BrooklynApiUtil.java b/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/BrooklynApiUtil.java deleted file mode 100644 index ce57da5..0000000 --- a/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/BrooklynApiUtil.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.brooklyn.rest.client; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Date; -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicReference; -import javax.ws.rs.core.Response; - -import org.apache.brooklyn.rest.api.EffectorApi; -import org.apache.brooklyn.rest.domain.Status; -import org.apache.brooklyn.rest.domain.TaskSummary; -import org.apache.brooklyn.util.repeat.Repeater; -import org.apache.brooklyn.util.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.ImmutableMap; - -public class BrooklynApiUtil { - - private static final Logger LOG = LoggerFactory.getLogger(BrooklynApiUtil.class); - private static final Duration DEFAULT_POLL_PERIOD = Duration.FIVE_SECONDS; - private static final Duration DEFAULT_TIMEOUT = Duration.FIVE_MINUTES; - - private BrooklynApiUtil() {} - - /** - * Deploys the blueprint and returns the task summary. - * @throws Exception If the response from the server when deploying was {@link #isUnhealthyResponse unhealthy}. - */ - public static TaskSummary deployBlueprint(BrooklynApi api, String blueprint) throws Exception { - Response r = api.getApplicationApi().createFromYaml(blueprint); - if (isUnhealthyResponse(r)) { - throw new Exception("Unexpected response deploying blueprint to server: " + r.getStatus()); - } else { - LOG.debug("Server response to deploy blueprint: " + r.getStatus()); - } - return BrooklynApi.getEntity(r, TaskSummary.class); - } - - /** - * Waits for the application with the given ID to be running. - * - * @throws IllegalStateException If the application was not running after {@link #DEFAULT_TIMEOUT}. - */ - public static void waitForRunningAndThrowOtherwise(BrooklynApi api, String applicationId, String taskId) throws IllegalStateException { - waitForRunningAndThrowOtherwise(api, applicationId, taskId, DEFAULT_TIMEOUT); - } - - /** - * Waits for the application with the given ID to be running. - * - * @throws IllegalStateException If the application was not running after the given timeout. - */ - public static void waitForRunningAndThrowOtherwise(BrooklynApi api, String applicationId, String taskId, Duration timeout) throws IllegalStateException { - Status finalStatus = waitForAppStatus(api, applicationId, Status.RUNNING, timeout, DEFAULT_POLL_PERIOD); - if (!Status.RUNNING.equals(finalStatus)) { - LOG.error("Application is not running. Is: " + finalStatus.name().toLowerCase()); - - StringBuilder message = new StringBuilder(); - message.append("Application ").append(applicationId) - .append(" should be running but is ").append(finalStatus.name().toLowerCase()) - .append(". "); - - if (Status.ERROR.equals(finalStatus) || Status.UNKNOWN.equals(finalStatus)) { - String result = getTaskResult(api, taskId); - message.append("\nThe result of the task on the server was:\n") - .append(result); - } - throw new IllegalStateException(message.toString()); - } - } - - /** - * Polls Brooklyn until the given application has the given status. Quits early if the - * application's status is {@link org.apache.brooklyn.rest.domain.Status#ERROR} or - * {@link org.apache.brooklyn.rest.domain.Status#UNKNOWN} and desiredStatus is something else. - * - * @return The final polled status. - */ - public static Status waitForAppStatus(final BrooklynApi api, final String application, final Status desiredStatus, - Duration timeout, Duration pollPeriod) { - final AtomicReference appStatus = new AtomicReference<>(Status.UNKNOWN); - final boolean shortcutOnError = !Status.ERROR.equals(desiredStatus) && !Status.UNKNOWN.equals(desiredStatus); - LOG.info("Waiting " + timeout + " from " + new Date() + " for application " + application + " to be " + desiredStatus); - boolean finalAppStatusKnown = Repeater.create("Waiting for application " + application + " status to be " + desiredStatus) - .every(pollPeriod) - .limitTimeTo(timeout) - .rethrowExceptionImmediately() - .until(new Callable() { - @Override - public Boolean call() throws Exception { - Status status = api.getApplicationApi().get(application).getStatus(); - LOG.debug("Application " + application + " status is: " + status); - appStatus.set(status); - return desiredStatus.equals(status) || (shortcutOnError && - (Status.ERROR.equals(status) || Status.UNKNOWN.equals(status))); - } - }) - .run(); - if (appStatus.get().equals(desiredStatus)) { - LOG.info("Application " + application + " is " + desiredStatus.name()); - } else { - LOG.warn("Application is not " + desiredStatus.name() + " within " + timeout + - ". Status is: " + appStatus.get()); - } - return appStatus.get(); - } - - /** - * Use the {@link EffectorApi effector API} to invoke the stop effector on the given application. - */ - public static void attemptStop(BrooklynApi api, String application, Duration timeout) { - api.getEffectorApi().invoke(application, application, "stop", String.valueOf(timeout.toMilliseconds()), - ImmutableMap.of()); - } - - /** - * @return The result of the task with the given id, or "unknown" if it could not be found. - */ - public static String getTaskResult(BrooklynApi api, String taskId) { - checkNotNull(taskId, "taskId"); - TaskSummary summary = api.getActivityApi().get(taskId); - return summary == null || summary.getResult() == null ? "unknown" : summary.getResult().toString(); - } - - /** - * @return true if response's status code is not between 200 and 299 inclusive. - */ - public static boolean isUnhealthyResponse(Response response) { - return response.getStatus() < 200 || response.getStatus() >= 300; - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/util/http/BuiltResponsePreservingError.java ---------------------------------------------------------------------- diff --git a/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/util/http/BuiltResponsePreservingError.java b/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/util/http/BuiltResponsePreservingError.java deleted file mode 100644 index d011172..0000000 --- a/rest/rest-client/src/main/java/org/apache/brooklyn/rest/client/util/http/BuiltResponsePreservingError.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.brooklyn.rest.client.util.http; - -import java.lang.annotation.Annotation; - -import javax.ws.rs.core.Response; - -import org.apache.brooklyn.util.exceptions.Exceptions; -import org.jboss.resteasy.client.core.BaseClientResponse; -import org.jboss.resteasy.core.Headers; -import org.jboss.resteasy.specimpl.BuiltResponse; - -/** - * Allows wrapping a {@link Response} with the stream fully read and closed so that the client can be re-used. - *

- * The entity may be stored as a string as type info is not available when it is deserialized, - * and that's a relatively convenient common format. - * - * TODO It would be nice to support other parsing, storing the byte array. - */ -public class BuiltResponsePreservingError extends BuiltResponse { - - private Throwable error; - - public BuiltResponsePreservingError(int status, Headers headers, Object entity, Annotation[] annotations, Throwable error) { - super(status, headers, entity, annotations); - this.error = error; - } - - @SuppressWarnings("deprecation") - public static Response copyResponseAndClose(Response source, Class type) { - int status = -1; - Headers headers = new Headers(); - Object entity = null; - try { - status = source.getStatus(); - if (source instanceof BaseClientResponse) - headers.putAll(((BaseClientResponse)source).getMetadata()); - if (source instanceof org.jboss.resteasy.client.ClientResponse) { - entity = ((org.jboss.resteasy.client.ClientResponse)source).getEntity(type); - } else { - entity = source.getEntity(); - } - return new BuiltResponsePreservingError(status, headers, entity, new Annotation[0], null); - } catch (Exception e) { - Exceptions.propagateIfFatal(e); - return new BuiltResponsePreservingError(status, headers, entity, new Annotation[0], e); - } finally { - if (source instanceof BaseClientResponse) - ((BaseClientResponse)source).close(); - } - } - - @Override - public Object getEntity() { - if (error!=null) { - throw new IllegalStateException("getEntity called on BuiltResponsePreservingError, where an Error had been preserved", error); - } - return super.getEntity(); - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java ---------------------------------------------------------------------- diff --git a/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java b/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java deleted file mode 100644 index 81d789f..0000000 --- a/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/ApplicationResourceIntegrationTest.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.brooklyn.rest.client; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.util.Collection; - -import javax.ws.rs.core.Response; - -import org.apache.brooklyn.api.entity.Application; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.core.entity.StartableApplication; -import org.apache.brooklyn.core.entity.lifecycle.Lifecycle; -import org.apache.brooklyn.core.location.BasicLocationRegistry; -import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext; -import org.apache.brooklyn.rest.BrooklynRestApiLauncher; -import org.apache.brooklyn.rest.BrooklynRestApiLauncherTest; -import org.apache.brooklyn.rest.domain.ApplicationSpec; -import org.apache.brooklyn.rest.domain.ApplicationSummary; -import org.apache.brooklyn.rest.domain.EntitySpec; -import org.apache.brooklyn.rest.domain.EntitySummary; -import org.apache.brooklyn.rest.domain.SensorSummary; -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.util.time.Duration; -import org.eclipse.jetty.server.Server; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import org.eclipse.jetty.server.NetworkConnector; - -@Test(singleThreaded = true) -public class ApplicationResourceIntegrationTest { - - private static final Logger log = LoggerFactory.getLogger(ApplicationResourceIntegrationTest.class); - - private static final Duration LONG_WAIT = Duration.minutes(10); - - private final String redisSpec = "{\"name\": \"redis-app\", \"type\": \"org.apache.brooklyn.entity.nosql.redis.RedisStore\", \"locations\": [ \"localhost\"]}"; - - private final ApplicationSpec legacyRedisSpec = ApplicationSpec.builder().name("redis-legacy-app") - .entities(ImmutableSet.of(new EntitySpec("redis-ent", "org.apache.brooklyn.entity.nosql.redis.RedisStore"))) - .locations(ImmutableSet.of("localhost")) - .build(); - - private ManagementContext manager; - - protected synchronized ManagementContext getManagementContext() throws Exception { - if (manager == null) { - manager = new LocalManagementContext(); - BrooklynRestApiLauncherTest.forceUseOfDefaultCatalogWithJavaClassPath(manager); - BasicLocationRegistry.addNamedLocationLocalhost(manager); - BrooklynRestApiLauncherTest.enableAnyoneLogin(manager); - } - return manager; - } - - BrooklynApi api; - - @BeforeClass(groups = "Integration") - public void setUp() throws Exception { - Server server = BrooklynRestApiLauncher.launcher() - .managementContext(getManagementContext()) - .start(); - - api = BrooklynApi.newInstance("http://localhost:" + ((NetworkConnector)server.getConnectors()[0]).getPort() + "/"); - } - - @AfterClass(alwaysRun = true) - public void tearDown() throws Exception { - for (Application app : getManagementContext().getApplications()) { - try { - ((StartableApplication) app).stop(); - } catch (Exception e) { - log.warn("Error stopping app " + app + " during test teardown: " + e); - } - } - } - - @Test(groups = "Integration") - public void testDeployRedisApplication() throws Exception { - Response response = api.getApplicationApi().createPoly(redisSpec.getBytes()); - assertEquals(response.getStatus(), 201); - assertEquals(getManagementContext().getApplications().size(), 1); - final String entityId = getManagementContext().getApplications().iterator().next().getChildren().iterator().next().getId(); - assertServiceStateEventually("redis-app", entityId, Lifecycle.RUNNING, LONG_WAIT); - } - - @Test(groups = "Integration", dependsOnMethods = "testDeployRedisApplication") - public void testDeployLegacyRedisApplication() throws Exception { - @SuppressWarnings("deprecation") - Response response = api.getApplicationApi().create(legacyRedisSpec); - assertEquals(response.getStatus(), 201); - assertEquals(getManagementContext().getApplications().size(), 2); - assertServiceStateEventually("redis-legacy-app", "redis-ent", Lifecycle.RUNNING, LONG_WAIT); - - // Tear the app down so it doesn't interfere with other tests - Response deleteResponse = api.getApplicationApi().delete("redis-legacy-app"); - assertEquals(deleteResponse.getStatus(), 202); - assertEquals(getManagementContext().getApplications().size(), 1); - } - - @Test(groups = "Integration", dependsOnMethods = "testDeployRedisApplication") - public void testListEntities() { - Collection entities = api.getEntityApi().list("redis-app"); - Assert.assertFalse(entities.isEmpty()); - } - - @Test(groups = "Integration", dependsOnMethods = "testDeployRedisApplication") - public void testListSensorsRedis() throws Exception { - String entityId = getManagementContext().getApplications().iterator().next().getChildren().iterator().next().getId(); - Collection sensors = api.getSensorApi().list("redis-app", entityId); - assertTrue(sensors.size() > 0); - SensorSummary uptime = Iterables.find(sensors, new Predicate() { - @Override - public boolean apply(SensorSummary sensorSummary) { - return sensorSummary.getName().equals("redis.uptime"); - } - }); - assertEquals(uptime.getType(), "java.lang.Integer"); - } - - @Test(groups = "Integration", dependsOnMethods = {"testListSensorsRedis", "testListEntities"}) - public void testTriggerRedisStopEffector() throws Exception { - final String entityId = getManagementContext().getApplications().iterator().next().getChildren().iterator().next().getId(); - Response response = api.getEffectorApi().invoke("redis-app", entityId, "stop", "5000", ImmutableMap.of()); - - assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode()); - assertServiceStateEventually("redis-app", entityId, Lifecycle.STOPPED, LONG_WAIT); - } - - @Test(groups = "Integration", dependsOnMethods = "testTriggerRedisStopEffector") - public void testDeleteRedisApplication() throws Exception { - int size = getManagementContext().getApplications().size(); - Response response = api.getApplicationApi().delete("redis-app"); - Assert.assertNotNull(response); - try { - Asserts.succeedsEventually(ImmutableMap.of("timeout", Duration.minutes(1)), new Runnable() { - public void run() { - try { - ApplicationSummary summary = api.getApplicationApi().get("redis-app"); - fail("Redis app failed to disappear: summary="+summary); - } catch (Exception failure) { - // expected -- it will be a ClientResponseFailure but that class is deprecated so catching all - // and asserting contains the word 404 - Assert.assertTrue(failure.toString().indexOf("404") >= 0, "wrong failure, got: "+failure); - } - }}); - } catch (Exception failure) { - // expected -- as above - Assert.assertTrue(failure.toString().indexOf("404") >= 0, "wrong failure, got: "+failure); - } - - assertEquals(getManagementContext().getApplications().size(), size - 1); - } - - private void assertServiceStateEventually(final String app, final String entity, final Lifecycle state, Duration timeout) { - Asserts.succeedsEventually(ImmutableMap.of("timeout", timeout), new Runnable() { - public void run() { - Object status = api.getSensorApi().get(app, entity, "service.state", false); - assertTrue(state.toString().equalsIgnoreCase(status.toString()), "status="+status); - }}); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java ---------------------------------------------------------------------- diff --git a/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java b/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java deleted file mode 100644 index 96c898e..0000000 --- a/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiRestClientTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.brooklyn.rest.client; - -import static org.testng.Assert.assertEquals; - -import java.net.URL; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.Response; - -import org.apache.brooklyn.api.entity.Application; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.core.BrooklynVersion; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.entity.StartableApplication; -import org.apache.brooklyn.core.location.BasicLocationRegistry; -import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext; -import org.apache.brooklyn.core.test.entity.TestEntity; -import org.apache.brooklyn.rest.BrooklynRestApiLauncher; -import org.apache.brooklyn.rest.BrooklynRestApiLauncherTest; -import org.apache.brooklyn.rest.domain.ApplicationSummary; -import org.apache.brooklyn.rest.domain.CatalogLocationSummary; -import org.apache.brooklyn.rest.security.provider.TestSecurityProvider; -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.util.http.HttpAsserts; -import org.eclipse.jetty.server.NetworkConnector; -import org.eclipse.jetty.server.Server; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -@Test -public class BrooklynApiRestClientTest { - - private static final Logger log = LoggerFactory.getLogger(BrooklynApiRestClientTest.class); - - private ManagementContext manager; - private Server server; - private BrooklynApi api; - - protected synchronized ManagementContext getManagementContext() throws Exception { - if (manager == null) { - manager = new LocalManagementContext(); - BrooklynRestApiLauncherTest.forceUseOfDefaultCatalogWithJavaClassPath(manager); - BasicLocationRegistry.addNamedLocationLocalhost(manager); - BrooklynRestApiLauncherTest.enableAnyoneLogin(manager); - } - return manager; - } - - @BeforeClass - public void setUp() throws Exception { - server = BrooklynRestApiLauncher.launcher() - .managementContext(manager) - .securityProvider(TestSecurityProvider.class) - .start(); - - api = BrooklynApi.newInstance("http://localhost:" + ((NetworkConnector)server.getConnectors()[0]).getPort() + "/v1", - TestSecurityProvider.USER, TestSecurityProvider.PASSWORD); - } - - @AfterClass(alwaysRun = true) - public void tearDown() throws Exception { - for (Application app : getManagementContext().getApplications()) { - try { - ((StartableApplication) app).stop(); - } catch (Exception e) { - log.warn("Error stopping app " + app + " during test teardown: " + e); - } - } - Entities.destroyAll(getManagementContext()); - server.stop(); - } - - public void testNoV1InUrl() { - api = BrooklynApi.newInstance("http://localhost:" + ((NetworkConnector)server.getConnectors()[0]).getPort(), - TestSecurityProvider.USER, TestSecurityProvider.PASSWORD); - - assertEquals(api.getServerApi().getVersion().getVersion(), BrooklynVersion.get()); - } - - public void testLocationApi() throws Exception { - log.info("Testing location API"); - Map> locations = api.getLocationApi().getLocatedLocations(); - log.info("locations located are: "+locations); - } - - public void testCatalogApiLocations() throws Exception { - List locations = api.getCatalogApi().listLocations(".*", null, false); - log.info("locations from catalog are: "+locations); - } - - public void testCatalogCreate()throws Exception { - final Response response = api.getCatalogApi().create(getFileContentsAsString("catalog/test-catalog.bom")); - Asserts.assertEquals(response.getStatus(), 201); - Asserts.assertStringContains(String.valueOf(response.getEntity()), "simple-tomcat:1.0"); - } - - - - public void testApplicationApiList() throws Exception { - List apps = api.getApplicationApi().list(null); - log.info("apps are: "+apps); - } - - public void testApplicationApiCreate() throws Exception { - Response r1 = api.getApplicationApi().createFromYaml("name: test-1234\n" - + "services: [ { type: "+TestEntity.class.getName()+" } ]"); - HttpAsserts.assertHealthyStatusCode(r1.getStatus()); - log.info("creation result: "+r1.getEntity()); - List apps = api.getApplicationApi().list(null); - log.info("apps with test: "+apps); - Asserts.assertStringContains(apps.toString(), "test-1234"); - } - - public void testApplicationApiHandledError() throws Exception { - Response r1 = api.getApplicationApi().createFromYaml("name: test"); - HttpAsserts.assertNotHealthyStatusCode(r1.getStatus()); - // new-style messages first, old-style messages after (during switch to TypePlanTransformer) - Asserts.assertStringContainsAtLeastOne(r1.getEntity().toString().toLowerCase(), - "invalid plan", "no services"); - Asserts.assertStringContainsAtLeastOne(r1.getEntity().toString().toLowerCase(), - "format could not be recognized", "Unrecognized application blueprint format"); - } - - public void testApplicationApiThrownError() throws Exception { - try { - ApplicationSummary summary = api.getApplicationApi().get("test-5678"); - Asserts.shouldHaveFailedPreviously("got "+summary); - } catch (Exception e) { - Asserts.expectedFailureContainsIgnoreCase(e, "404", "not found"); - } - } - - private String getFileContentsAsString(final String filename) throws Exception { - final URL resource = getClass().getClassLoader().getResource(filename); - Asserts.assertNotNull(resource); - return new String(Files.readAllBytes(Paths.get(resource.toURI())), Charset.defaultCharset()); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiUtilTest.java ---------------------------------------------------------------------- diff --git a/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiUtilTest.java b/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiUtilTest.java deleted file mode 100644 index 9cae021..0000000 --- a/rest/rest-client/src/test/java/org/apache/brooklyn/rest/client/BrooklynApiUtilTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.brooklyn.rest.client; - -import static org.apache.brooklyn.test.Asserts.assertEquals; - -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; - -import org.apache.brooklyn.util.collections.Jsonya; -import org.apache.brooklyn.util.core.http.BetterMockWebServer; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.google.common.base.Joiner; -import com.google.mockwebserver.MockResponse; -import com.google.mockwebserver.RecordedRequest; - -public class BrooklynApiUtilTest { - - private static final String APP_ID = "fedcba"; - - private static final String YAML = Joiner.on("\n").join( - "name: test-blueprint", - "location: localhost", - "services:", - "- type: brooklyn.entity.basic.EmptySoftwareProcess"); - - private BetterMockWebServer server; - - @BeforeMethod(alwaysRun = true) - public void newMockWebServer() { - server = BetterMockWebServer.newInstanceLocalhost(); - } - - @AfterMethod(alwaysRun = true) - public void shutDownServer() throws Exception { - if (server != null) server.shutdown(); - } - - @Test - public void testDeployBlueprint() throws Exception { - server.enqueue(taskSummaryResponse()); - server.play(); - - BrooklynApi api = BrooklynApi.newInstance(server.getUrl("/").toString()); - BrooklynApiUtil.deployBlueprint(api, YAML); - - RecordedRequest request = server.takeRequest(); - assertEquals(request.getPath(), "/v1/applications"); - assertEquals(request.getMethod(), "POST"); - assertEquals(new String(request.getBody()), YAML); - } - - @Test - public void testWaitForRunningExitsCleanlyWhenAppRunning() throws Exception { - server.enqueue(applicationStatusResponse("RUNNING")); - server.play(); - - BrooklynApi api = BrooklynApi.newInstance(server.getUrl("/").toString()); - BrooklynApiUtil.waitForRunningAndThrowOtherwise(api, "appId", "taskId"); - // i.e. no exception - } - - @Test(expectedExceptions = {IllegalStateException.class}) - public void testWaitForRunningFailsWhenAppStatusError() throws Exception { - server.enqueue(applicationStatusResponse("ERROR")); - // Method checks for status of task. - server.enqueue(taskSummaryResponse()); - server.play(); - - BrooklynApi api = BrooklynApi.newInstance(server.getUrl("/").toString()); - BrooklynApiUtil.waitForRunningAndThrowOtherwise(api, "appId", "taskId"); - } - - @Test(expectedExceptions = {IllegalStateException.class}) - public void testWaitForRunningFailsWhenAppStatusUnknown() throws Exception { - server.enqueue(applicationStatusResponse("UNKNOWN")); - // Method checks for status of task. - server.enqueue(taskSummaryResponse()); - server.play(); - - BrooklynApi api = BrooklynApi.newInstance(server.getUrl("/").toString()); - BrooklynApiUtil.waitForRunningAndThrowOtherwise(api, "appId", "taskId"); - } - - /** @return a response whose Content-Type header is application/json. */ - private MockResponse newJsonResponse() { - return new MockResponse() - .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - } - - private MockResponse taskSummaryResponse() { - String body = Jsonya.newInstance() - .put("id", "taskid") - .put("entityId", APP_ID) - .toString(); - return newJsonResponse().setBody(body); - } - - private MockResponse applicationStatusResponse(String status) { - String body = Jsonya.newInstance() - .put("status", status) - .at("spec", "locations").list().add("localhost") - .root() - .toString(); - return newJsonResponse() - .setBody(body); - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/rest/rest-client/src/test/resources/catalog/test-catalog.bom ---------------------------------------------------------------------- diff --git a/rest/rest-client/src/test/resources/catalog/test-catalog.bom b/rest/rest-client/src/test/resources/catalog/test-catalog.bom deleted file mode 100644 index 698bcf2..0000000 --- a/rest/rest-client/src/test/resources/catalog/test-catalog.bom +++ /dev/null @@ -1,33 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. -# -brooklyn.catalog: - id: simple-tomcat - version: 1.0 - itemType: template - iconUrl: http://tomcat.apache.org/images/tomcat.png - name: Simple Tomcat - license: Apache-2.0 - item: - brooklyn.config: - simple.confg: someValue - services: - - type: org.apache.brooklyn.entity.webapp.tomcat.TomcatServer - id: tomcat - name: Tomcat - war: https://tomcat.apache.org/tomcat-6.0-doc/appdev/sample/sample.war \ No newline at end of file http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f63006ba/rest/rest-client/src/test/webapp/WEB-INF/web.xml ---------------------------------------------------------------------- diff --git a/rest/rest-client/src/test/webapp/WEB-INF/web.xml b/rest/rest-client/src/test/webapp/WEB-INF/web.xml deleted file mode 100644 index 38b637a..0000000 --- a/rest/rest-client/src/test/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - Brooklyn REST API v1 - - - Brooklyn Request Tagging Filter - org.apache.brooklyn.rest.filter.RequestTaggingFilter - - - Brooklyn Request Tagging Filter - /* - - - - Brooklyn Properties Authentication Filter - org.apache.brooklyn.rest.filter.BrooklynPropertiesSecurityFilter - - - Brooklyn Properties Authentication Filter - /* - - - - Brooklyn Logging Filter - org.apache.brooklyn.rest.filter.LoggingFilter - - - Brooklyn Logging Filter - /* - - - - Brooklyn HA Master Filter - org.apache.brooklyn.rest.filter.HaMasterCheckFilter - - - Brooklyn HA Master Filter - /* - - - - - Brooklyn REST API v1 Filter - com.sun.jersey.spi.container.servlet.ServletContainer - - - - com.sun.jersey.config.property.resourceConfigClass - com.sun.jersey.api.core.ClassNamesResourceConfig - - - com.sun.jersey.config.property.classnames - - org.apache.brooklyn.rest.apidoc.ApidocHelpMessageBodyWriter; - org.apache.brooklyn.rest.util.FormMapProvider; - com.fasterxml.jackson.jaxrs.JacksonJsonProvider; - org.apache.brooklyn.rest.resources.ActivityResource; - org.apache.brooklyn.rest.resources.ApidocResource; - org.apache.brooklyn.rest.resources.ApplicationResource; - org.apache.brooklyn.rest.resources.CatalogResource; - org.apache.brooklyn.rest.resources.EffectorResource; - org.apache.brooklyn.rest.resources.EntityConfigResource; - org.apache.brooklyn.rest.resources.EntityResource; - org.apache.brooklyn.rest.resources.LocationResource; - org.apache.brooklyn.rest.resources.PolicyConfigResource; - org.apache.brooklyn.rest.resources.PolicyResource; - org.apache.brooklyn.rest.resources.ScriptResource; - org.apache.brooklyn.rest.resources.SensorResource; - org.apache.brooklyn.rest.resources.VersionResource; - - - - - com.sun.jersey.api.json.POJOMappingFeature - true - - - - - com.sun.jersey.config.feature.DisableWADL - true - - - - - Brooklyn REST API v1 Filter - /* - - -