You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by sj...@apache.org on 2016/04/07 13:14:07 UTC
[1/9] brooklyn-server git commit: Remove jersey compatibility
Repository: brooklyn-server
Updated Branches:
refs/heads/master dc6a313d7 -> d27d6c72b
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java
deleted file mode 100644
index 3aee845..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/EntityLocationUtilsTest.java
+++ /dev/null
@@ -1,72 +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.util;
-
-import static org.testng.Assert.assertEquals;
-
-import java.util.Arrays;
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.location.AbstractLocation;
-import org.apache.brooklyn.core.location.geo.HostGeoInfo;
-import org.apache.brooklyn.core.location.internal.LocationInternal;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.entity.software.base.SoftwareProcess;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity;
-
-import com.google.common.collect.ImmutableList;
-
-public class EntityLocationUtilsTest extends BrooklynAppUnitTestSupport {
-
- private static final Logger log = LoggerFactory.getLogger(EntityLocationUtilsTest.class);
-
- private Location loc;
-
- @BeforeMethod(alwaysRun=true)
- @Override
- public void setUp() throws Exception {
- super.setUp();
- loc = mgmt.getLocationRegistry().getLocationManaged("localhost");
- ((AbstractLocation)loc).setHostGeoInfo(new HostGeoInfo("localhost", "localhost", 50, 0));
- }
-
- @Test
- public void testCount() {
- @SuppressWarnings("unused")
- SoftwareProcess r1 = app.createAndManageChild(EntitySpec.create(SoftwareProcess.class, RestMockSimpleEntity.class));
- SoftwareProcess r2 = app.createAndManageChild(EntitySpec.create(SoftwareProcess.class, RestMockSimpleEntity.class));
- Entities.start(app, Arrays.<Location>asList(loc));
-
- Entities.dumpInfo(app);
-
- log.info("r2loc: "+r2.getLocations());
- log.info("props: "+((LocationInternal)r2.getLocations().iterator().next()).config().getBag().getAllConfig());
-
- Map<Location, Integer> counts = new EntityLocationUtils(mgmt).countLeafEntitiesByLocatedLocations();
- log.info("count: "+counts);
- assertEquals(ImmutableList.copyOf(counts.values()), ImmutableList.of(2), "counts="+counts);
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NoOpRecordingShutdownHandler.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NoOpRecordingShutdownHandler.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NoOpRecordingShutdownHandler.java
deleted file mode 100644
index a99d3d9..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NoOpRecordingShutdownHandler.java
+++ /dev/null
@@ -1,39 +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.util;
-
-import org.apache.brooklyn.rest.util.ShutdownHandler;
-
-public class NoOpRecordingShutdownHandler implements ShutdownHandler {
- private volatile boolean isRequested;
-
- @Override
- public void onShutdownRequest() {
- isRequested = true;
- }
-
- public boolean isRequested() {
- return isRequested;
- }
-
- public void reset() {
- isRequested = false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NullHttpServletRequestProvider.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NullHttpServletRequestProvider.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NullHttpServletRequestProvider.java
deleted file mode 100644
index 7a24f31..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NullHttpServletRequestProvider.java
+++ /dev/null
@@ -1,46 +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.util;
-
-import java.lang.reflect.Type;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.ext.Provider;
-
-import com.sun.jersey.core.spi.component.ComponentContext;
-import com.sun.jersey.core.spi.component.ComponentScope;
-import com.sun.jersey.spi.inject.Injectable;
-import com.sun.jersey.spi.inject.InjectableProvider;
-
-@Provider
-public class NullHttpServletRequestProvider implements InjectableProvider<Context, Type> {
- public Injectable<HttpServletRequest> getInjectable(ComponentContext ic,
- Context a, Type c) {
- if (HttpServletRequest.class == c) {
- return new Injectable<HttpServletRequest>() {
- public HttpServletRequest getValue() { return null; }
- };
- } else
- return null;
- }
- public ComponentScope getScope() {
- return ComponentScope.Singleton;
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NullServletConfigProvider.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NullServletConfigProvider.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NullServletConfigProvider.java
deleted file mode 100644
index 106780d..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/NullServletConfigProvider.java
+++ /dev/null
@@ -1,51 +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.util;
-
-import java.lang.reflect.Type;
-
-import javax.servlet.ServletContext;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.ext.Provider;
-
-import com.sun.jersey.core.spi.component.ComponentContext;
-import com.sun.jersey.core.spi.component.ComponentScope;
-import com.sun.jersey.spi.container.servlet.WebConfig;
-import com.sun.jersey.spi.inject.Injectable;
-import com.sun.jersey.spi.inject.InjectableProvider;
-
-@Provider
-public class NullServletConfigProvider implements InjectableProvider<Context, Type> {
- public Injectable<ServletContext> getInjectable(ComponentContext ic,
- Context a, Type c) {
- if (ServletContext.class == c) {
- return new Injectable<ServletContext>() {
- public ServletContext getValue() { return null; }
- };
- } else if (WebConfig.class == c) {
- return new Injectable<ServletContext>() {
- public ServletContext getValue() { return null; }
- };
- } else
- return null;
- }
- public ComponentScope getScope() {
- return ComponentScope.Singleton;
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/RestApiTestUtils.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/RestApiTestUtils.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/RestApiTestUtils.java
deleted file mode 100644
index 36ad69c..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/RestApiTestUtils.java
+++ /dev/null
@@ -1,58 +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.util;
-
-import java.io.InputStream;
-
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.stream.Streams;
-
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-public class RestApiTestUtils {
-
- public static <T> T fromJson(String text, Class<T> type) {
- try {
- return new ObjectMapper().readValue(text, type);
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }
- public static String asJson(Object x) {
- try {
- return new ObjectMapper().writeValueAsString(x);
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }
- public static String jsonFixture(String path) {
- InputStream stream = RestApiTestUtils.class.getClassLoader().getResourceAsStream(path);
- if (stream==null) throw new IllegalStateException("Cannot find resource: "+path);
- return asJson(fromJson(Streams.readFullyString(stream), Object.class));
- }
-
- public static <T> T fromJson(String text, TypeReference<T> type) {
- try {
- return new ObjectMapper().readValue(text, type);
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/ServerStoppingShutdownHandler.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/ServerStoppingShutdownHandler.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/ServerStoppingShutdownHandler.java
deleted file mode 100644
index fc3bbc4..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/ServerStoppingShutdownHandler.java
+++ /dev/null
@@ -1,75 +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.util;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.brooklyn.util.time.Time;
-import org.eclipse.jetty.server.Server;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/* not the cleanest way to enforce a clean shutdown, but a simple and effective way;
- * usage is restricted to BrooklynRestApiLauncher and subclasses, to stop it inline.
- * the main app stops the server in a more principled way using callbacks. */
-public class ServerStoppingShutdownHandler implements ShutdownHandler {
-
- private static final Logger log = LoggerFactory.getLogger(ServerStoppingShutdownHandler.class);
-
- private final ManagementContext mgmt;
- private Server server;
-
- public ServerStoppingShutdownHandler(ManagementContext mgmt) {
- this.mgmt = mgmt;
- }
-
- @Override
- public void onShutdownRequest() {
- log.info("Shutting down server (when running in rest-api dev mode, using background thread)");
-
- // essentially same as BrooklynLauncher.terminate() but cut down ...
- // NB: this is only used in dev mode use of BrooklynJavascriptGuiLauncher
- new Thread(new Runnable() {
- public void run() {
- Time.sleep(Duration.millis(250));
- log.debug("Shutting down server in background thread, closing "+server+" and "+mgmt);
- if (server!=null) {
- try {
- server.stop();
- server.join();
- } catch (Exception e) {
- log.debug("Stopping server gave an error (not usually a concern): "+e);
- /* NPE may be thrown e.g. if threadpool not started */
- }
- }
-
- if (mgmt instanceof ManagementContextInternal) {
- ((ManagementContextInternal)mgmt).terminate();
- }
- }
- }).start();
- }
-
- /** Expect this to be injected; typically it is not known when this is created, but we need it to trigger shutdown. */
- public void setServer(Server server) {
- this.server = server;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaHotStateCheckClassResource.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaHotStateCheckClassResource.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaHotStateCheckClassResource.java
deleted file mode 100644
index a0084ef..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaHotStateCheckClassResource.java
+++ /dev/null
@@ -1,38 +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.util;
-
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-
-import org.apache.brooklyn.rest.filter.HaHotStateRequired;
-
-@Path("/ha/class")
-@Produces(MediaType.APPLICATION_JSON)
-@HaHotStateRequired
-public class TestingHaHotStateCheckClassResource {
-
- @GET
- @Path("fail")
- public String fail() {
- return "FAIL";
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaHotStateCheckResource.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaHotStateCheckResource.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaHotStateCheckResource.java
deleted file mode 100644
index 512d725..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaHotStateCheckResource.java
+++ /dev/null
@@ -1,44 +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.util;
-
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-
-import org.apache.brooklyn.rest.filter.HaHotStateRequired;
-
-@Path("/ha/method")
-@Produces(MediaType.APPLICATION_JSON)
-public class TestingHaHotStateCheckResource {
-
- @GET
- @Path("ok")
- public String ok() {
- return "OK";
- }
-
- @GET
- @Path("fail")
- @HaHotStateRequired
- public String fail() {
- return "FAIL";
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaMasterCheckResource.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaMasterCheckResource.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaMasterCheckResource.java
deleted file mode 100644
index 9b125dc..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/TestingHaMasterCheckResource.java
+++ /dev/null
@@ -1,41 +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.util;
-
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-
-@Path("/")
-@Produces(MediaType.APPLICATION_JSON)
-public class TestingHaMasterCheckResource {
-
- @POST
- @Path("/server/shutdown")
- public void shutdown() {
-
- }
-
- @POST
- @Path("/ha/post")
- public void post() {
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/json/BrooklynJacksonSerializerTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/json/BrooklynJacksonSerializerTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/json/BrooklynJacksonSerializerTest.java
deleted file mode 100644
index 9542eda..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/json/BrooklynJacksonSerializerTest.java
+++ /dev/null
@@ -1,399 +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.util.json;
-
-import java.io.NotSerializableException;
-import java.net.URI;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import javax.ws.rs.core.MediaType;
-
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.utils.URIBuilder;
-import org.eclipse.jetty.server.Server;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.entity.Attributes;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.rest.BrooklynRestApiLauncher;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.http.HttpTool;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.text.Strings;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Multimap;
-import com.google.common.collect.MultimapBuilder;
-import com.google.gson.Gson;
-import org.eclipse.jetty.server.NetworkConnector;
-
-public class BrooklynJacksonSerializerTest {
-
- private static final Logger log = LoggerFactory.getLogger(BrooklynJacksonSerializerTest.class);
-
- public static class SillyClassWithManagementContext {
- @JsonProperty
- ManagementContext mgmt;
- @JsonProperty
- String id;
-
- public SillyClassWithManagementContext() { }
-
- public SillyClassWithManagementContext(String id, ManagementContext mgmt) {
- this.id = id;
- this.mgmt = mgmt;
- }
-
- @Override
- public String toString() {
- return super.toString()+"[id="+id+";mgmt="+mgmt+"]";
- }
- }
-
- @Test
- public void testCustomSerializerWithSerializableSillyManagementExample() throws Exception {
- ManagementContext mgmt = LocalManagementContextForTests.newInstance();
- try {
-
- ObjectMapper mapper = BrooklynJacksonJsonProvider.newPrivateObjectMapper(mgmt);
-
- SillyClassWithManagementContext silly = new SillyClassWithManagementContext("123", mgmt);
- log.info("silly is: "+silly);
-
- String sillyS = mapper.writeValueAsString(silly);
-
- log.info("silly json is: "+sillyS);
-
- SillyClassWithManagementContext silly2 = mapper.readValue(sillyS, SillyClassWithManagementContext.class);
- log.info("silly2 is: "+silly2);
-
- Assert.assertEquals(silly.id, silly2.id);
-
- } finally {
- Entities.destroyAll(mgmt);
- }
- }
-
- public static class SelfRefNonSerializableClass {
- @JsonProperty
- Object bogus = this;
- }
-
- @Test
- public void testSelfReferenceFailsWhenStrict() {
- checkNonSerializableWhenStrict(new SelfRefNonSerializableClass());
- }
- @Test
- public void testSelfReferenceGeneratesErrorMapObject() throws Exception {
- checkSerializesAsMapWithErrorAndToString(new SelfRefNonSerializableClass());
- }
- @Test
- public void testNonSerializableInListIsShownInList() throws Exception {
- List<?> result = checkSerializesAs(MutableList.of(1, new SelfRefNonSerializableClass()), List.class);
- Assert.assertEquals( result.get(0), 1 );
- Assert.assertEquals( ((Map<?,?>)result.get(1)).get("errorType"), NotSerializableException.class.getName() );
- }
- @Test
- public void testNonSerializableInMapIsShownInMap() throws Exception {
- Map<?,?> result = checkSerializesAs(MutableMap.of("x", new SelfRefNonSerializableClass()), Map.class);
- Assert.assertEquals( ((Map<?,?>)result.get("x")).get("errorType"), NotSerializableException.class.getName() );
- }
- static class TupleWithNonSerializable {
- String good = "bon";
- SelfRefNonSerializableClass bad = new SelfRefNonSerializableClass();
- }
- @Test
- public void testNonSerializableInObjectIsShownInMap() throws Exception {
- String resultS = checkSerializesAs(new TupleWithNonSerializable(), null);
- log.info("nested non-serializable json is "+resultS);
- Assert.assertTrue(resultS.startsWith("{\"good\":\"bon\",\"bad\":{"), "expected a nested map for the error field, not "+resultS);
-
- Map<?,?> result = checkSerializesAs(new TupleWithNonSerializable(), Map.class);
- Assert.assertEquals( result.get("good"), "bon" );
- Assert.assertTrue( result.containsKey("bad"), "Should have had a key for field 'bad'" );
- Assert.assertEquals( ((Map<?,?>)result.get("bad")).get("errorType"), NotSerializableException.class.getName() );
- }
-
- public static class EmptyClass {
- }
-
- @Test
- public void testEmptySerializesAsEmpty() throws Exception {
- // deliberately, a class with no fields and no annotations serializes as an error,
- // because the alternative, {}, is useless. however if it *is* annotated, as below, then it will serialize fine.
- checkSerializesAsMapWithErrorAndToString(new SelfRefNonSerializableClass());
- }
- @Test
- public void testEmptyNonSerializableFailsWhenStrict() {
- checkNonSerializableWhenStrict(new EmptyClass());
- }
-
- @JsonSerialize
- public static class EmptyClassWithSerialize {
- }
-
- @Test
- public void testEmptyAnnotatedSerializesAsEmptyEvenWhenStrict() throws Exception {
- try {
- BidiSerialization.setStrictSerialization(true);
- testEmptyAnnotatedSerializesAsEmpty();
- } finally {
- BidiSerialization.clearStrictSerialization();
- }
- }
-
- @Test
- public void testEmptyAnnotatedSerializesAsEmpty() throws Exception {
- Map<?, ?> map = checkSerializesAs( new EmptyClassWithSerialize(), Map.class );
- Assert.assertTrue(map.isEmpty(), "Expected an empty map; instead got: "+map);
-
- String result = checkSerializesAs( MutableList.of(new EmptyClassWithSerialize()), null );
- result = result.replaceAll(" ", "").trim();
- Assert.assertEquals(result, "[{}]");
- }
-
- @Test
- public void testSensorFailsWhenStrict() {
- checkNonSerializableWhenStrict(MutableList.of(Attributes.HTTP_PORT));
- }
- @Test
- public void testSensorSensible() throws Exception {
- Map<?,?> result = checkSerializesAs(Attributes.HTTP_PORT, Map.class);
- log.info("SENSOR json is: "+result);
- Assert.assertFalse(result.toString().contains("error"), "Shouldn't have had an error, instead got: "+result);
- }
-
- @Test
- public void testLinkedListSerialization() throws Exception {
- LinkedList<Object> ll = new LinkedList<Object>();
- ll.add(1); ll.add("two");
- String result = checkSerializesAs(ll, null);
- log.info("LLIST json is: "+result);
- Assert.assertFalse(result.contains("error"), "Shouldn't have had an error, instead got: "+result);
- Assert.assertEquals(Strings.collapseWhitespace(result, ""), "[1,\"two\"]");
- }
-
- @Test
- public void testMultiMapSerialization() throws Exception {
- Multimap<String, Integer> m = MultimapBuilder.hashKeys().arrayListValues().build();
- m.put("bob", 24);
- m.put("bob", 25);
- String result = checkSerializesAs(m, null);
- log.info("multimap serialized as: " + result);
- Assert.assertFalse(result.contains("error"), "Shouldn't have had an error, instead got: "+result);
- Assert.assertEquals(Strings.collapseWhitespace(result, ""), "{\"bob\":[24,25]}");
- }
-
- @Test
- public void testSupplierSerialization() throws Exception {
- String result = checkSerializesAs(Strings.toStringSupplier(Streams.byteArrayOfString("x")), null);
- log.info("SUPPLIER json is: "+result);
- Assert.assertFalse(result.contains("error"), "Shouldn't have had an error, instead got: "+result);
- }
-
- @Test
- public void testWrappedStreamSerialization() throws Exception {
- String result = checkSerializesAs(BrooklynTaskTags.tagForStream("TEST", Streams.byteArrayOfString("x")), null);
- log.info("WRAPPED STREAM json is: "+result);
- Assert.assertFalse(result.contains("error"), "Shouldn't have had an error, instead got: "+result);
- }
-
- @SuppressWarnings("unchecked")
- protected <T> T checkSerializesAs(Object x, Class<T> type) {
- ManagementContext mgmt = LocalManagementContextForTests.newInstance();
- try {
- ObjectMapper mapper = BrooklynJacksonJsonProvider.newPrivateObjectMapper(mgmt);
- String tS = mapper.writeValueAsString(x);
- log.debug("serialized "+x+" as "+tS);
- Assert.assertTrue(tS.length() < 1000, "Data too long, size "+tS.length()+" for "+x);
- if (type==null) return (T) tS;
- return mapper.readValue(tS, type);
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- } finally {
- Entities.destroyAll(mgmt);
- }
- }
- protected Map<?,?> checkSerializesAsMapWithErrorAndToString(Object x) {
- Map<?,?> rt = checkSerializesAs(x, Map.class);
- Assert.assertEquals(rt.get("toString"), x.toString());
- Assert.assertEquals(rt.get("error"), Boolean.TRUE);
- return rt;
- }
- protected void checkNonSerializableWhenStrict(Object x) {
- checkNonSerializable(x, true);
- }
- protected void checkNonSerializable(Object x, boolean strict) {
- ManagementContext mgmt = LocalManagementContextForTests.newInstance();
- try {
- ObjectMapper mapper = BrooklynJacksonJsonProvider.newPrivateObjectMapper(mgmt);
- if (strict)
- BidiSerialization.setStrictSerialization(true);
-
- String tS = mapper.writeValueAsString(x);
- Assert.fail("Should not have serialized "+x+"; instead gave: "+tS);
-
- } catch (Exception e) {
- Exceptions.propagateIfFatal(e);
- log.info("Got expected error, when serializing "+x+": "+e);
-
- } finally {
- if (strict)
- BidiSerialization.clearStrictSerialization();
- Entities.destroyAll(mgmt);
- }
- }
-
- // Ensure TEXT_PLAIN just returns toString for ManagementContext instance.
- // Strangely, testWithLauncherSerializingListsContainingEntitiesAndOtherComplexStuff ended up in the
- // EntityConfigResource.getPlain code, throwing a ClassCastException.
- //
- // TODO This tests the fix for that ClassCastException, but does not explain why
- // testWithLauncherSerializingListsContainingEntitiesAndOtherComplexStuff was calling it.
- @Test(groups="Integration") //because of time
- public void testWithAcceptsPlainText() throws Exception {
- ManagementContext mgmt = LocalManagementContextForTests.newInstance();
- Server server = null;
- try {
- server = BrooklynRestApiLauncher.launcher().managementContext(mgmt).start();
- HttpClient client = HttpTool.httpClientBuilder().build();
-
- TestApplication app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
-
- String serverAddress = "http://localhost:"+((NetworkConnector)server.getConnectors()[0]).getLocalPort();
- String appUrl = serverAddress + "/v1/applications/" + app.getId();
- String entityUrl = appUrl + "/entities/" + app.getId();
- URI configUri = new URIBuilder(entityUrl + "/config/" + TestEntity.CONF_OBJECT.getName())
- .addParameter("raw", "true")
- .build();
-
- // assert config here is just mgmt.toString()
- app.config().set(TestEntity.CONF_OBJECT, mgmt);
- String content = get(client, configUri, ImmutableMap.of("Accept", MediaType.TEXT_PLAIN));
- log.info("CONFIG MGMT is:\n"+content);
- Assert.assertEquals(content, mgmt.toString(), "content="+content);
-
- } finally {
- try {
- if (server != null) server.stop();
- } catch (Exception e) {
- log.warn("failed to stop server: "+e);
- }
- Entities.destroyAll(mgmt);
- }
- }
-
- @Test(groups="Integration") //because of time
- public void testWithLauncherSerializingListsContainingEntitiesAndOtherComplexStuff() throws Exception {
- ManagementContext mgmt = LocalManagementContextForTests.newInstance();
- Server server = null;
- try {
- server = BrooklynRestApiLauncher.launcher().managementContext(mgmt).start();
- HttpClient client = HttpTool.httpClientBuilder().build();
-
- TestApplication app = TestApplication.Factory.newManagedInstanceForTests(mgmt);
-
- String serverAddress = "http://localhost:"+((NetworkConnector)server.getConnectors()[0]).getLocalPort();
- String appUrl = serverAddress + "/v1/applications/" + app.getId();
- String entityUrl = appUrl + "/entities/" + app.getId();
- URI configUri = new URIBuilder(entityUrl + "/config/" + TestEntity.CONF_OBJECT.getName())
- .addParameter("raw", "true")
- .build();
-
- // assert config here is just mgmt
- app.config().set(TestEntity.CONF_OBJECT, mgmt);
- String content = get(client, configUri, ImmutableMap.of("Accept", MediaType.APPLICATION_JSON));
- log.info("CONFIG MGMT is:\n"+content);
- @SuppressWarnings("rawtypes")
- Map values = new Gson().fromJson(content, Map.class);
- Assert.assertEquals(values, ImmutableMap.of("type", LocalManagementContextForTests.class.getCanonicalName()), "values="+values);
-
- // assert normal API returns the same, containing links
- content = get(client, entityUrl, ImmutableMap.of("Accept", MediaType.APPLICATION_JSON));
- log.info("ENTITY is: \n"+content);
- values = new Gson().fromJson(content, Map.class);
- Assert.assertTrue(values.size()>=3, "Map is too small: "+values);
- Assert.assertTrue(values.size()<=6, "Map is too big: "+values);
- Assert.assertEquals(values.get("type"), TestApplication.class.getCanonicalName(), "values="+values);
- Assert.assertNotNull(values.get("links"), "Map should have contained links: values="+values);
-
- // but config etc returns our nicely json serialized
- app.config().set(TestEntity.CONF_OBJECT, app);
- content = get(client, configUri, ImmutableMap.of("Accept", MediaType.APPLICATION_JSON));
- log.info("CONFIG ENTITY is:\n"+content);
- values = new Gson().fromJson(content, Map.class);
- Assert.assertEquals(values, ImmutableMap.of("type", Entity.class.getCanonicalName(), "id", app.getId()), "values="+values);
-
- // and self-ref gives error + toString
- SelfRefNonSerializableClass angry = new SelfRefNonSerializableClass();
- app.config().set(TestEntity.CONF_OBJECT, angry);
- content = get(client, configUri, ImmutableMap.of("Accept", MediaType.APPLICATION_JSON));
- log.info("CONFIG ANGRY is:\n"+content);
- assertErrorObjectMatchingToString(content, angry);
-
- // as does Server
- app.config().set(TestEntity.CONF_OBJECT, server);
- content = get(client, configUri, ImmutableMap.of("Accept", MediaType.APPLICATION_JSON));
- // NOTE, if using the default visibility / object mapper, the getters of the object are invoked
- // resulting in an object which is huge, 7+MB -- and it wreaks havoc w eclipse console regex parsing!
- // (but with our custom VisibilityChecker server just gives us the nicer error!)
- log.info("CONFIG SERVER is:\n"+content);
- assertErrorObjectMatchingToString(content, server);
- Assert.assertTrue(content.contains(NotSerializableException.class.getCanonicalName()), "server should have contained things which are not serializable");
- Assert.assertTrue(content.length() < 1024, "content should not have been very long; instead was: "+content.length());
-
- } finally {
- try {
- if (server != null) server.stop();
- } catch (Exception e) {
- log.warn("failed to stop server: "+e);
- }
- Entities.destroyAll(mgmt);
- }
- }
-
- private void assertErrorObjectMatchingToString(String content, Object expected) {
- Object value = new Gson().fromJson(content, Object.class);
- Assert.assertTrue(value instanceof Map, "Expected map, got: "+value);
- Assert.assertEquals(((Map<?,?>)value).get("toString"), expected.toString());
- }
-
- private String get(HttpClient client, String uri, Map<String, String> headers) {
- return get(client, URI.create(uri), headers);
- }
-
- private String get(HttpClient client, URI uri, Map<String, String> headers) {
- return HttpTool.httpGet(client, uri, headers).getContentAsString();
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/brooklyn/scanning.catalog.bom
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/brooklyn/scanning.catalog.bom b/rest/rest-server-jersey/src/test/resources/brooklyn/scanning.catalog.bom
deleted file mode 100644
index cddb832..0000000
--- a/rest/rest-server-jersey/src/test/resources/brooklyn/scanning.catalog.bom
+++ /dev/null
@@ -1,19 +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:
- scanJavaAnnotations: true
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/api-error-basic.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/api-error-basic.json b/rest/rest-server-jersey/src/test/resources/fixtures/api-error-basic.json
deleted file mode 100644
index 7634c50..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/api-error-basic.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "message": "explanatory message",
- "details": "accompanying details"
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/api-error-no-details.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/api-error-no-details.json b/rest/rest-server-jersey/src/test/resources/fixtures/api-error-no-details.json
deleted file mode 100644
index 5762f6f..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/api-error-no-details.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "message": "explanatory message"
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/application-list.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/application-list.json b/rest/rest-server-jersey/src/test/resources/fixtures/application-list.json
deleted file mode 100644
index 029cf68..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/application-list.json
+++ /dev/null
@@ -1,44 +0,0 @@
-[
- {
- "spec":{
- "name":"tesr",
- "entities":[
- {
- "name":"tomcat",
- "type":"org.apache.brooklyn.entity.webapp.tomcat.TomcatServer",
- "config":{ }
- }
- ],
- "locations":[
- "/v1/locations/0"
- ]
- },
- "status":"STARTING",
- "links":{
- "self":"/v1/applications/tesr",
- "entities":"fixtures/entity-summary-list.json"
- }
- },
- {
- "spec":{
- "name":"myapp",
- "entities":[
- {
- "name":"Vanilla Java App",
- "type":"org.apache.brooklyn.entity.java.VanillaJavaApp",
- "config":{
- "initialSize":"1",
- "creationScriptUrl":"http://my.brooklyn.io/storage/foo.sql"
- }
- }
- ],
- "locations":["/v1/locations/1"]
- },
- "status":"STARTING",
- "links":{
- "self":"/v1/applications/myapp",
- "entities":"fixtures/entity-summary-list.json"
- }
- }
-]
-
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/application-spec.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/application-spec.json b/rest/rest-server-jersey/src/test/resources/fixtures/application-spec.json
deleted file mode 100644
index 9f042c6..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/application-spec.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "name":"myapp",
- "entities":[
- {
- "name":"Vanilla Java App",
- "type":"org.apache.brooklyn.entity.java.VanillaJavaApp",
- "config":{
- "initialSize":"1",
- "creationScriptUrl":"http://my.brooklyn.io/storage/foo.sql"
- }
- }
- ],
- "locations":[
- "/v1/locations/1"
- ]
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/application-tree.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/application-tree.json b/rest/rest-server-jersey/src/test/resources/fixtures/application-tree.json
deleted file mode 100644
index e4ce29f..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/application-tree.json
+++ /dev/null
@@ -1,43 +0,0 @@
-[
- {
- "name":"test",
- "id":"riBZUjMq",
- "type":null,
- "children":[
- {
- "name":"tomcat1",
- "id":"fXyyQ7Ap",
- "type":"org.apache.brooklyn.entity.webapp.tomcat.TomcatServer"
- }
- ]
- },
- {
- "name":"test2",
- "id":"app-002",
- "type":null,
- "children":[
- {
- "name":"tomcat1",
- "id":"child-01",
- "type":"org.apache.brooklyn.entity.webapp.tomcat.TomcatServer"
- },
- {
- "name":"tomcat2",
- "id":"child-02",
- "type":"org.apache.brooklyn.entity.webapp.tomcat.TomcatServer",
- "children":[
- {
- "name":"tomcat03",
- "id":"child-03",
- "type":"org.apache.brooklyn.entity.webapp.tomcat.TomcatServer"
- },
- {
- "name":"tomcat04",
- "id":"child-04",
- "type":"org.apache.brooklyn.entity.webapp.tomcat.TomcatServer"
- }
- ]
- }
- ]
- }
-]
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/application.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/application.json b/rest/rest-server-jersey/src/test/resources/fixtures/application.json
deleted file mode 100644
index cd6a21a..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/application.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "id":"myapp_id",
- "spec":{
- "name":"myapp",
- "entities":[
- {
- "name":"Vanilla Java App",
- "type":"org.apache.brooklyn.entity.java.VanillaJavaApp",
- "config":{
- "initialSize":"1",
- "creationScriptUrl":"http://my.brooklyn.io/storage/foo.sql"
- }
- }
- ],
- "locations":["/v1/locations/1"]
- },
- "status":"STARTING",
- "links":{
- "self":"/v1/applications/myapp",
- "entities":"fixtures/entity-summary-list.json"
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/catalog-application-list.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/catalog-application-list.json b/rest/rest-server-jersey/src/test/resources/fixtures/catalog-application-list.json
deleted file mode 100644
index c4757be..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/catalog-application-list.json
+++ /dev/null
@@ -1,29 +0,0 @@
-[
- {
- "id": "com.example.app:1.1",
- "type": "com.example.app",
- "name": "My example application",
- "version": "1.1",
- "description": "My awesome example application, as a catalog item",
- "planYaml": "services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n launch.command: echo \"Launch application\"\n checkRunning.command: echo \"Check running application\"",
- "iconUrl": "http://my.example.com/icon.png"
- },
- {
- "id": "com.example.app:2.0",
- "type": "com.example.app",
- "name": "My example application",
- "version": "2.0",
- "description": "My awesome example application, as a catalog item",
- "planYaml": "services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n launch.command: echo \"Launch application\"\n checkRunning.command: echo \"Check running application\"",
- "iconUrl": "http://my.example.com/icon.png"
- },
- {
- "id": "com.example.other.app:1.0",
- "type": "com.example.other.app",
- "name": "Another example application",
- "version": "1.0",
- "description": "Another awesome example application, as a catalog item",
- "planYaml": "services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n launch.command: echo \"Launch other application\"\n checkRunning.command: echo \"Check running other application\"",
- "iconUrl": "http://my.other.example.com/icon.png"
- }
-]
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/catalog-application.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/catalog-application.json b/rest/rest-server-jersey/src/test/resources/fixtures/catalog-application.json
deleted file mode 100644
index 7c72270..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/catalog-application.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "id": "com.example.app:1.1",
- "type": "com.example.app",
- "name": "My example application",
- "version": "1.1",
- "description": "My awesome example application, as a catalog item",
- "planYaml": "services:\n- type: org.apache.brooklyn.entity.software.base.VanillaSoftwareProcess\n launch.command: echo \"Launch application\"\n checkRunning.command: echo \"Check running application\"",
- "iconUrl": "http://my.example.com/icon.png"
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/effector-summary-list.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/effector-summary-list.json b/rest/rest-server-jersey/src/test/resources/fixtures/effector-summary-list.json
deleted file mode 100644
index fe2828c..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/effector-summary-list.json
+++ /dev/null
@@ -1,47 +0,0 @@
-[
- {
- "name":"start",
- "description":"Start the process/service represented by an entity",
- "returnType":"void",
- "parameters":[
- {
- "name":"locations",
- "type":"java.util.Collection",
- "description":"A list of locations"
- },
- {
- "name":"booleanValue",
- "type":"java.lang.Boolean",
- "description":"True or false",
- "defaultValue": true
- }
- ],
- "links":{
- "self":"/v1/applications/tesr/entities/ZgoDhGQA/effectors/start",
- "entity":"/v1/applications/tesr/entities/ZgoDhGQA",
- "application":"/v1/applications/tesr"
- }
- },
- {
- "name":"restart",
- "description":"Restart the process/service represented by an entity",
- "returnType":"void",
- "parameters":[ ],
- "links":{
- "self":"/v1/applications/tesr/entities/ZgoDhGQA/effectors/restart",
- "entity":"/v1/applications/tesr/entities/ZgoDhGQA",
- "application":"/v1/applications/tesr"
- }
- },
- {
- "name":"stop",
- "description":"Stop the process/service represented by an entity",
- "returnType":"void",
- "parameters":[ ],
- "links":{
- "self":"/v1/applications/tesr/entities/ZgoDhGQA/effectors/stop",
- "entity":"/v1/applications/tesr/entities/ZgoDhGQA",
- "application":"/v1/applications/tesr"
- }
- }
-]
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/effector-summary.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/effector-summary.json b/rest/rest-server-jersey/src/test/resources/fixtures/effector-summary.json
deleted file mode 100644
index eda97dd..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/effector-summary.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "name":"stop",
- "returnType":"void",
- "parameters":[],
- "description":"Effector description",
- "links":{
- "self":"/v1/applications/redis-app/entities/redis-ent/effectors/stop"
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/entity-only-type.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/entity-only-type.json b/rest/rest-server-jersey/src/test/resources/fixtures/entity-only-type.json
deleted file mode 100644
index e932ab1..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/entity-only-type.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "type":"org.apache.brooklyn.entity.java.VanillaJavaApp"
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/entity-summary-list.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/entity-summary-list.json b/rest/rest-server-jersey/src/test/resources/fixtures/entity-summary-list.json
deleted file mode 100644
index 6e2dc4e..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/entity-summary-list.json
+++ /dev/null
@@ -1,14 +0,0 @@
-[
- {
- "type":"org.apache.brooklyn.entity.webapp.tomcat.TomcatServer",
- "links":{
- "self":"/v1/applications/tesr/entities/zQsqdXzi",
- "catalog":"/v1/catalog/entities/org.apache.brooklyn.entity.webapp.tomcat.TomcatServer",
- "application":"/v1/applications/tesr",
- "children":"/v1/applications/tesr/entities/zQsqdXzi/entities",
- "effectors":"fixtures/effector-summary-list.json",
- "sensors":"fixtures/sensor-summary-list.json",
- "activities":"fixtures/task-summary-list.json"
- }
- }
-]
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/entity-summary.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/entity-summary.json b/rest/rest-server-jersey/src/test/resources/fixtures/entity-summary.json
deleted file mode 100644
index 05d2e8f..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/entity-summary.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{"id":"zQsqdXzi",
- "name":"MyTomcat",
- "type":"org.apache.brooklyn.entity.webapp.tomcat.TomcatServer",
- "links":{
- "self":"/v1/applications/tesr/entities/zQsqdXzi",
- "catalog":"/v1/catalog/entities/org.apache.brooklyn.entity.webapp.tomcat.TomcatServer",
- "application":"/v1/applications/tesr",
- "children":"/v1/applications/tesr/entities/zQsqdXzi/children",
- "effectors":"fixtures/effector-summary-list.json",
- "sensors":"fixtures/sensor-summary-list.json",
- "activities":"fixtures/task-summary-list.json"
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/entity.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/entity.json b/rest/rest-server-jersey/src/test/resources/fixtures/entity.json
deleted file mode 100644
index dac0509..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/entity.json
+++ /dev/null
@@ -1,7 +0,0 @@
-[
- {
- "name":"Vanilla Java App",
- "type":"org.apache.brooklyn.entity.java.VanillaJavaApp",
- "config":{}
- }
-]
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/ha-summary.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/ha-summary.json b/rest/rest-server-jersey/src/test/resources/fixtures/ha-summary.json
deleted file mode 100644
index 3c3eb7c..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/ha-summary.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "links": {},
- "masterId": "kDp39gAv",
- "nodes": {
- "kDp39gAv": {
- "nodeId": "kDp39gAv",
- "nodeUri": "http://10.30.40.50:8081/",
- "status": "MASTER",
- "timestampUtc": 1400257858796
- },
- "lHNCTtZ4": {
- "nodeId": "lHNCTtZ4",
- "nodeUri": "http://10.30.40.60:8081/",
- "status": "STANDBY",
- "timestampUtc": 1400257858796
- }
- },
- "ownId": "kDp39gAv"
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/location-list.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/location-list.json b/rest/rest-server-jersey/src/test/resources/fixtures/location-list.json
deleted file mode 100644
index c4e05de..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/location-list.json
+++ /dev/null
@@ -1,10 +0,0 @@
-[
- {
- "id":"123",
- "name":"localhost",
- "spec":"localhost",
- "links":{
- "self":"/v1/locations/123"
- }
- }
-]
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/location-summary.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/location-summary.json b/rest/rest-server-jersey/src/test/resources/fixtures/location-summary.json
deleted file mode 100644
index d1d0573..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/location-summary.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "id":"123",
- "name":"localhost",
- "spec":"localhost",
- "links":{
- "self":"/v1/locations/123"
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/location-without-credential.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/location-without-credential.json b/rest/rest-server-jersey/src/test/resources/fixtures/location-without-credential.json
deleted file mode 100644
index af8051d..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/location-without-credential.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "name":"localhost",
- "spec":"localhost",
- "config":{"identity":"bob"}
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/location.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/location.json b/rest/rest-server-jersey/src/test/resources/fixtures/location.json
deleted file mode 100644
index a2670cd..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/location.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "name":"localhost",
- "spec":"localhost"
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/sensor-current-state.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/sensor-current-state.json b/rest/rest-server-jersey/src/test/resources/fixtures/sensor-current-state.json
deleted file mode 100644
index e8084e0..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/sensor-current-state.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "service.state":"running",
- "jmx.context":"jmx/context",
- "tomcat.shutdownport":"8081",
- "service.isUp":"true"
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/sensor-summary-list.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/sensor-summary-list.json b/rest/rest-server-jersey/src/test/resources/fixtures/sensor-summary-list.json
deleted file mode 100644
index 6ab457b..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/sensor-summary-list.json
+++ /dev/null
@@ -1,42 +0,0 @@
-[
- {
- "name":"service.state",
- "type":"org.apache.brooklyn.entity.lifecycle.Lifecycle",
- "description":"Service lifecycle state",
- "links":{
- "self":"fixtures/service-state.json",
- "application":"/v1/applications/tesr",
- "entity":"/v1/applications/tesr/entities/zQsqdXzi"
- }
- },
- {
- "name":"jmx.context",
- "type":"java.lang.String",
- "description":"JMX context path",
- "links":{
- "self":"fixtures/service-state.json",
- "application":"/v1/applications/tesr",
- "entity":"/v1/applications/tesr/entities/zQsqdXzi"
- }
- },
- {
- "name":"tomcat.shutdownport",
- "type":"java.lang.Integer",
- "description":"Suggested shutdown port",
- "links":{
- "self":"fixtures/service-state.json",
- "application":"/v1/applications/tesr",
- "entity":"/v1/applications/tesr/entities/zQsqdXzi"
- }
- },
- {
- "name":"service.isUp",
- "type":"java.lang.Boolean",
- "description":"Service has been started successfully and is running",
- "links":{
- "self":"fixtures/service-state.json",
- "application":"/v1/applications/tesr",
- "entity":"/v1/applications/tesr/entities/zQsqdXzi"
- }
- }
-]
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/sensor-summary.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/sensor-summary.json b/rest/rest-server-jersey/src/test/resources/fixtures/sensor-summary.json
deleted file mode 100644
index 0803b37..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/sensor-summary.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "name":"redis.uptime",
- "type":"Integer",
- "description":"Description",
- "links":{
- "self":"/v1/applications/redis-app/entities/redis-ent/sensors/redis.uptime"
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/server-version.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/server-version.json b/rest/rest-server-jersey/src/test/resources/fixtures/server-version.json
deleted file mode 100644
index affd707..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/server-version.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "version": "0.7.0-SNAPSHOT",
- "buildSha1": "cb4f0a3af2f5042222dd176edc102bfa64e7e0b5",
- "buildBranch":"versions",
- "features":[
- {
- "name": "Sample Brooklyn Project com.acme.sample:brooklyn-sample v0.1.0-SNAPSHOT",
- "symbolicName":"com.acme.sample.brooklyn-sample",
- "version":"0.1.0.SNAPSHOT",
- "lastModified":"523305000",
- "Brooklyn-Feature-Build-Id":"e0fee1adf795c84eec4735f039503eb18d9c35cc"
- }
- ]
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/service-state.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/service-state.json b/rest/rest-server-jersey/src/test/resources/fixtures/service-state.json
deleted file mode 100644
index 61d5e33..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/service-state.json
+++ /dev/null
@@ -1 +0,0 @@
-running
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/resources/fixtures/task-summary-list.json
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/resources/fixtures/task-summary-list.json b/rest/rest-server-jersey/src/test/resources/fixtures/task-summary-list.json
deleted file mode 100644
index 25b3193..0000000
--- a/rest/rest-server-jersey/src/test/resources/fixtures/task-summary-list.json
+++ /dev/null
@@ -1,15 +0,0 @@
-[
- {
- "entityId":"VzK45RFC",
- "entityDisplayName":"tomcat",
- "displayName":"start",
- "description":"invoking start on tomcat",
- "id":"n24NC63Nsu",
- "rawSubmitTimeUtc":1348663165550,
- "submitTimeUtc":"2012-09-26 12:39:25",
- "startTimeUtc":"2012-09-26 12:39:25",
- "endTimeUtc":"2012-09-26 12:39:33",
- "currentStatus":"Ended normally",
- "detailedStatus":"Ended normally after 7940 ms\nResult: null"
- }
-]
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server/pom.xml
----------------------------------------------------------------------
diff --git a/rest/rest-server/pom.xml b/rest/rest-server/pom.xml
index 873b801..0a0741f 100644
--- a/rest/rest-server/pom.xml
+++ b/rest/rest-server/pom.xml
@@ -244,10 +244,7 @@
<supportedProjectType>jar</supportedProjectType>
</supportedProjectTypes>
<instructions>
- <Import-Package>
- com.sun.jersey.spi.container.servlet;version="[1.18.1,2.0)",
- *
- </Import-Package>
+ <Import-Package>*</Import-Package>
<Export-Package>org.apache.brooklyn.*</Export-Package>
<Web-ContextPath>/</Web-ContextPath>
<_wab>src/main/webapp</_wab>
[5/9] brooklyn-server git commit: Remove jersey compatibility
Posted by sj...@apache.org.
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApiErrorTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApiErrorTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApiErrorTest.java
deleted file mode 100644
index f73bd30..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApiErrorTest.java
+++ /dev/null
@@ -1,71 +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.domain;
-
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.asJson;
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.fromJson;
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.jsonFixture;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-
-import java.io.IOException;
-import java.net.URI;
-
-import org.testng.annotations.Test;
-import org.testng.util.Strings;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-
-public class ApiErrorTest extends AbstractDomainTest {
-
- @Override
- protected String getPath() {
- return "fixtures/api-error-basic.json";
- }
-
- @Override
- protected Object getDomainObject() {
- return ApiError.builder()
- .message("explanatory message")
- .details("accompanying details")
- .build();
- }
-
- @Test
- public void testSerializeApiErrorFromThrowable() throws IOException {
- Exception e = new Exception("error");
- e.setStackTrace(Thread.currentThread().getStackTrace());
-
- ApiError error = ApiError.builderFromThrowable(e).build();
- ApiError deserialised = fromJson(asJson(error), ApiError.class);
-
- assertFalse(Strings.isNullOrEmpty(deserialised.getDetails()), "Expected details to contain exception stack trace");
- assertEquals(deserialised, error);
- }
-
- @Test
- public void testSerializeApiErrorWithoutDetails() throws IOException {
- ApiError error = ApiError.builder()
- .message("explanatory message")
- .build();
- assertEquals(asJson(error), jsonFixture("fixtures/api-error-no-details.json"));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApplicationSpecTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApplicationSpecTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApplicationSpecTest.java
deleted file mode 100644
index b2690d6..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApplicationSpecTest.java
+++ /dev/null
@@ -1,40 +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.domain;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-
-public class ApplicationSpecTest extends AbstractDomainTest {
-
- @Override
- protected String getPath() {
- return "fixtures/application-spec.json";
- }
-
- @Override
- protected Object getDomainObject() {
- EntitySpec entitySpec = new EntitySpec("Vanilla Java App", "org.apache.brooklyn.entity.java.VanillaJavaApp",
- ImmutableMap.of("initialSize", "1", "creationScriptUrl", "http://my.brooklyn.io/storage/foo.sql"));
- return ApplicationSpec.builder().name("myapp")
- .entities(ImmutableSet.of(entitySpec)).locations(ImmutableSet.of("/v1/locations/1"))
- .build();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApplicationTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApplicationTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApplicationTest.java
deleted file mode 100644
index 8708fb1..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/ApplicationTest.java
+++ /dev/null
@@ -1,87 +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.domain;
-
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.asJson;
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.fromJson;
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.jsonFixture;
-import static org.testng.Assert.assertEquals;
-
-import java.io.IOException;
-import java.net.URI;
-import java.util.Map;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.test.Asserts;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-
-public class ApplicationTest {
-
- final EntitySpec entitySpec = new EntitySpec("Vanilla Java App", "org.apache.brooklyn.entity.java.VanillaJavaApp",
- ImmutableMap.of(
- "initialSize", "1",
- "creationScriptUrl", "http://my.brooklyn.io/storage/foo.sql"));
-
- final ApplicationSpec applicationSpec = ApplicationSpec.builder().name("myapp")
- .entities(ImmutableSet.of(entitySpec))
- .locations(ImmutableSet.of("/v1/locations/1"))
- .build();
-
- final Map<String, URI> links = ImmutableMap.of(
- "self", URI.create("/v1/applications/" + applicationSpec.getName()),
- "entities", URI.create("fixtures/entity-summary-list.json"));
- final ApplicationSummary application = new ApplicationSummary("myapp_id", applicationSpec, Status.STARTING, links);
-
- @SuppressWarnings("serial")
- @Test
- public void testSerializeToJSON() throws IOException {
- assertEquals(asJson(application), jsonFixture("fixtures/application.json"));
- }
-
- @Test
- public void testDeserializeFromJSON() throws IOException {
- assertEquals(fromJson(jsonFixture("fixtures/application.json"),
- ApplicationSummary.class), application);
- }
-
- @Test
- public void testTransitionToRunning() {
- ApplicationSummary running = application.transitionTo(Status.RUNNING);
- assertEquals(running.getStatus(), Status.RUNNING);
- }
-
- @Test
- public void testAppInAppTest() throws IOException {
- ManagementContext mgmt = LocalManagementContextForTests.newInstance();
- try {
- TestApplication app = mgmt.getEntityManager().createEntity(org.apache.brooklyn.api.entity.EntitySpec.create(TestApplication.class));
- app.addChild(org.apache.brooklyn.api.entity.EntitySpec.create(TestApplication.class));
- Asserts.assertEqualsIgnoringOrder(mgmt.getApplications(), ImmutableList.of(app));
- } finally {
- Entities.destroyAll(mgmt);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EffectorSummaryTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EffectorSummaryTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EffectorSummaryTest.java
deleted file mode 100644
index 71cb64d..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EffectorSummaryTest.java
+++ /dev/null
@@ -1,44 +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.domain;
-
-import java.net.URI;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-
-public class EffectorSummaryTest extends AbstractDomainTest {
-
- @Override
- protected String getPath() {
- return "fixtures/effector-summary.json";
- }
-
- @Override
- protected Object getDomainObject() {
- return new EffectorSummary(
- "stop",
- "void",
- ImmutableSet.<EffectorSummary.ParameterSummary<?>>of(),
- "Effector description",
- ImmutableMap.of(
- "self", URI.create("/v1/applications/redis-app/entities/redis-ent/effectors/stop")));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EntitySpecTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EntitySpecTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EntitySpecTest.java
deleted file mode 100644
index 1beb078..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EntitySpecTest.java
+++ /dev/null
@@ -1,48 +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.domain;
-
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.fromJson;
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.jsonFixture;
-import static org.testng.Assert.assertEquals;
-
-import java.io.IOException;
-
-import org.testng.annotations.Test;
-
-public class EntitySpecTest extends AbstractDomainTest {
-
- @Override
- protected String getPath() {
- return "fixtures/entity.json";
- }
-
- @Override
- protected Object getDomainObject() {
- EntitySpec entitySpec = new EntitySpec("Vanilla Java App", "org.apache.brooklyn.entity.java.VanillaJavaApp");
- return new EntitySpec[] { entitySpec };
- }
-
- @Test
- public void testDeserializeFromJSONOnlyWithType() throws IOException {
- EntitySpec actual = fromJson(jsonFixture("fixtures/entity-only-type.json"), EntitySpec.class);
- assertEquals(actual.getType(), "org.apache.brooklyn.entity.java.VanillaJavaApp");
- assertEquals(actual.getConfig().size(), 0);
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EntitySummaryTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EntitySummaryTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EntitySummaryTest.java
deleted file mode 100644
index 2d39cc9..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/EntitySummaryTest.java
+++ /dev/null
@@ -1,48 +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.domain;
-
-import java.net.URI;
-import java.util.Map;
-
-import com.google.common.collect.Maps;
-
-public class EntitySummaryTest extends AbstractDomainTest {
-
- @Override
- protected String getPath() {
- return "fixtures/entity-summary.json";
- }
-
- @Override
- protected Object getDomainObject() {
- Map<String, URI> links = Maps.newLinkedHashMap();
- links.put("self", URI.create("/v1/applications/tesr/entities/zQsqdXzi"));
- links.put("catalog", URI.create("/v1/catalog/entities/org.apache.brooklyn.entity.webapp.tomcat.TomcatServer"));
- links.put("application", URI.create("/v1/applications/tesr"));
- links.put("children", URI.create("/v1/applications/tesr/entities/zQsqdXzi/children"));
- links.put("effectors", URI.create("fixtures/effector-summary-list.json"));
- links.put("sensors", URI.create("fixtures/sensor-summary-list.json"));
- links.put("activities", URI.create("fixtures/task-summary-list.json"));
-
- return new EntitySummary("zQsqdXzi", "MyTomcat",
- "org.apache.brooklyn.entity.webapp.tomcat.TomcatServer", null, links);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/LocationSpecTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/LocationSpecTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/LocationSpecTest.java
deleted file mode 100644
index 0e653c5..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/LocationSpecTest.java
+++ /dev/null
@@ -1,58 +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.domain;
-
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.asJson;
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.fromJson;
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.jsonFixture;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNull;
-
-import java.io.IOException;
-
-import org.testng.annotations.Test;
-
-@Deprecated
-public class LocationSpecTest {
-
- // TODO when removing the deprecated class this tests, change the tests here to point at LocationSummary
-
- final LocationSpec locationSpec = LocationSpec.localhost();
-
- @Test
- public void testSerializeToJSON() throws IOException {
- assertEquals(asJson(locationSpec), jsonFixture("fixtures/location.json"));
- }
-
- @Test
- public void testDeserializeFromJSON() throws IOException {
- assertEquals(fromJson(jsonFixture("fixtures/location.json"), LocationSpec.class), locationSpec);
- }
-
- @Test
- public void testDeserializeFromJSONWithNoCredential() throws IOException {
- LocationSpec loaded = fromJson(jsonFixture("fixtures/location-without-credential.json"), LocationSpec.class);
-
- assertEquals(loaded.getSpec(), locationSpec.getSpec());
-
- assertEquals(loaded.getConfig().size(), 1);
- assertEquals(loaded.getConfig().get("identity"), "bob");
- assertNull(loaded.getConfig().get("credential"));
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/LocationSummaryTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/LocationSummaryTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/LocationSummaryTest.java
deleted file mode 100644
index 0f81b48..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/LocationSummaryTest.java
+++ /dev/null
@@ -1,41 +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.domain;
-
-import java.net.URI;
-import java.util.Map;
-
-import com.google.common.collect.Maps;
-
-public class LocationSummaryTest extends AbstractDomainTest {
-
- @Override
- protected String getPath() {
- return "fixtures/location-summary.json";
- }
-
- @Override
- protected Object getDomainObject() {
- Map<String, URI> links = Maps.newLinkedHashMap();
- links.put("self", URI.create("/v1/locations/123"));
-
- return new LocationSummary("123", "localhost", "localhost", null, null, null, links);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/SensorSummaryTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/SensorSummaryTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/SensorSummaryTest.java
deleted file mode 100644
index 106d737..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/SensorSummaryTest.java
+++ /dev/null
@@ -1,103 +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.domain;
-
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.asJson;
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.fromJson;
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.jsonFixture;
-import static org.testng.Assert.assertEquals;
-
-import java.io.IOException;
-import java.net.URI;
-
-import javax.ws.rs.core.UriBuilder;
-
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.api.sensor.Sensor;
-import org.apache.brooklyn.core.config.render.RendererHints;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.sensor.Sensors;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.rest.transform.SensorTransformer;
-
-import com.google.common.collect.ImmutableMap;
-
-public class SensorSummaryTest {
-
- private SensorSummary sensorSummary = new SensorSummary("redis.uptime", "Integer",
- "Description", ImmutableMap.of(
- "self", URI.create("/v1/applications/redis-app/entities/redis-ent/sensors/redis.uptime")));
-
- private TestApplication app;
- private TestEntity entity;
- private ManagementContext mgmt;
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception {
- app = TestApplication.Factory.newManagedInstanceForTests();
- mgmt = app.getManagementContext();
- entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception {
- if (mgmt != null) Entities.destroyAll(mgmt);
- }
-
- @Test
- public void testSerializeToJSON() throws IOException {
- assertEquals(asJson(sensorSummary), jsonFixture("fixtures/sensor-summary.json"));
- }
-
- @Test
- public void testDeserializeFromJSON() throws IOException {
- assertEquals(fromJson(jsonFixture("fixtures/sensor-summary.json"), SensorSummary.class), sensorSummary);
- }
-
- @Test
- public void testEscapesUriForSensorName() throws IOException {
- Sensor<String> sensor = Sensors.newStringSensor("name with space");
- SensorSummary summary = SensorTransformer.sensorSummary(entity, sensor, UriBuilder.fromPath("/v1"));
- URI selfUri = summary.getLinks().get("self");
-
- String expectedUri = "/v1/applications/" + entity.getApplicationId() + "/entities/" + entity.getId() + "/sensors/" + "name%20with%20space";
-
- assertEquals(selfUri, URI.create(expectedUri));
- }
-
- // Previously failed because immutable-map builder threw exception if put same key multiple times,
- // and the NamedActionWithUrl did not have equals/hashCode
- @Test
- public void testSensorWithMultipleOpenUrlActionsRegistered() throws IOException {
- AttributeSensor<String> sensor = Sensors.newStringSensor("sensor1");
- entity.sensors().set(sensor, "http://myval");
- RendererHints.register(sensor, RendererHints.namedActionWithUrl());
- RendererHints.register(sensor, RendererHints.namedActionWithUrl());
-
- SensorSummary summary = SensorTransformer.sensorSummary(entity, sensor, UriBuilder.fromPath("/"));
-
- assertEquals(summary.getLinks().get("action:open"), URI.create("http://myval"));
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/VersionSummaryTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/VersionSummaryTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/VersionSummaryTest.java
deleted file mode 100644
index 7bed51b..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/VersionSummaryTest.java
+++ /dev/null
@@ -1,49 +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.domain;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-public class VersionSummaryTest extends AbstractDomainTest {
-
- @Override
- protected String getPath() {
- return "fixtures/server-version.json";
- }
-
- @Override
- protected Object getDomainObject() {
- BrooklynFeatureSummary features = new BrooklynFeatureSummary(
- "Sample Brooklyn Project com.acme.sample:brooklyn-sample v0.1.0-SNAPSHOT",
- "com.acme.sample.brooklyn-sample",
- "0.1.0.SNAPSHOT",
- "523305000",
- ImmutableMap.of("Brooklyn-Feature-Build-Id", "e0fee1adf795c84eec4735f039503eb18d9c35cc")
- );
- return new VersionSummary(
- "0.7.0-SNAPSHOT",
- "cb4f0a3af2f5042222dd176edc102bfa64e7e0b5",
- "versions",
- ImmutableList.of(features)
- );
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/AbstractRestApiEntitlementsTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/AbstractRestApiEntitlementsTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/AbstractRestApiEntitlementsTest.java
deleted file mode 100644
index 73449ea..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/AbstractRestApiEntitlementsTest.java
+++ /dev/null
@@ -1,111 +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.entitlement;
-
-import static org.apache.brooklyn.util.http.HttpTool.httpClientBuilder;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.net.URI;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.entitlement.Entitlements;
-import org.apache.brooklyn.core.mgmt.entitlement.PerUserEntitlementManager;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.rest.BrooklynRestApiLauncher;
-import org.apache.brooklyn.rest.BrooklynRestApiLauncherTestFixture;
-import org.apache.brooklyn.util.http.HttpAsserts;
-import org.apache.brooklyn.util.http.HttpTool;
-import org.apache.brooklyn.util.http.HttpToolResponse;
-import org.apache.http.auth.UsernamePasswordCredentials;
-import org.apache.http.client.HttpClient;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-
-/**
- * Sets up the REST api with some standard users, ready for testing entitlements.
- */
-public abstract class AbstractRestApiEntitlementsTest extends BrooklynRestApiLauncherTestFixture {
-
- protected ManagementContext mgmt;
- protected TestApplication app;
- protected TestEntity entity;
-
- @BeforeMethod(alwaysRun=true)
- public void setUp() throws Exception {
- BrooklynProperties props = BrooklynProperties.Factory.newEmpty();
- props.put(Entitlements.GLOBAL_ENTITLEMENT_MANAGER.getName(), PerUserEntitlementManager.class.getName());
- props.put(PerUserEntitlementManager.PER_USER_ENTITLEMENTS_CONFIG_PREFIX+".myRoot", "root");
- props.put(PerUserEntitlementManager.PER_USER_ENTITLEMENTS_CONFIG_PREFIX+".myReadonly", "readonly");
- props.put(PerUserEntitlementManager.PER_USER_ENTITLEMENTS_CONFIG_PREFIX+".myMinimal", "minimal");
- props.put(PerUserEntitlementManager.PER_USER_ENTITLEMENTS_CONFIG_PREFIX+".myCustom", StaticDelegatingEntitlementManager.class.getName());
-
- mgmt = LocalManagementContextForTests.builder(true).useProperties(props).build();
- app = mgmt.getEntityManager().createEntity(EntitySpec.create(TestApplication.class)
- .child(EntitySpec.create(TestEntity.class))
- .configure(TestEntity.CONF_NAME, "myname"));
- entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
-
- useServerForTest(BrooklynRestApiLauncher.launcher()
- .managementContext(mgmt)
- .forceUseOfDefaultCatalogWithJavaClassPath(true)
- .securityProvider(AuthenticateAnyoneSecurityProvider.class)
- .start());
- }
-
- @AfterMethod(alwaysRun=true)
- public void tearDown() throws Exception {
- if (mgmt != null) Entities.destroyAll(mgmt);
- }
-
- protected HttpClient newClient(String user) throws Exception {
- return httpClientBuilder()
- .uri(getBaseUri())
- .credentials(new UsernamePasswordCredentials(user, "ignoredPassword"))
- .build();
- }
-
- protected String httpGet(String user, String path) throws Exception {
- HttpToolResponse response = HttpTool.httpGet(newClient(user), URI.create(getBaseUri()).resolve(path), ImmutableMap.<String, String>of());
- assertTrue(HttpAsserts.isHealthyStatusCode(response.getResponseCode()), "code="+response.getResponseCode()+"; reason="+response.getReasonPhrase());
- return response.getContentAsString();
- }
-
- protected String assertPermitted(String user, String path) throws Exception {
- return httpGet(user, path);
- }
-
- protected void assertForbidden(String user, String path) throws Exception {
- HttpToolResponse response = HttpTool.httpGet(newClient(user), URI.create(getBaseUri()).resolve(path), ImmutableMap.<String, String>of());
- assertEquals(response.getResponseCode(), 403, "code="+response.getResponseCode()+"; reason="+response.getReasonPhrase()+"; content="+response.getContentAsString());
- }
-
- protected void assert404(String user, String path) throws Exception {
- HttpToolResponse response = HttpTool.httpGet(newClient(user), URI.create(getBaseUri()).resolve(path), ImmutableMap.<String, String>of());
- assertEquals(response.getResponseCode(), 404, "code="+response.getResponseCode()+"; reason="+response.getReasonPhrase()+"; content="+response.getContentAsString());
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/ActivityApiEntitlementsTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/ActivityApiEntitlementsTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/ActivityApiEntitlementsTest.java
deleted file mode 100644
index 2f1cc7b..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/ActivityApiEntitlementsTest.java
+++ /dev/null
@@ -1,122 +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.entitlement;
-
-import static org.testng.Assert.assertEquals;
-
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementClass;
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementContext;
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementManager;
-import org.apache.brooklyn.core.entity.BrooklynConfigKeys;
-import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
-import org.apache.brooklyn.core.mgmt.entitlement.Entitlements;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.machine.MachineEntity;
-import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessStreamsTest;
-import org.apache.brooklyn.util.core.task.TaskPredicates;
-import org.apache.brooklyn.util.text.StringPredicates;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Maps;
-
-@Test(singleThreaded = true)
-public class ActivityApiEntitlementsTest extends AbstractRestApiEntitlementsTest {
-
- protected MachineEntity machineEntity;
- protected Task<?> subTask;
- protected Map<String, String> streams;
-
- @BeforeMethod(alwaysRun=true)
- @Override
- public void setUp() throws Exception {
- super.setUp();
-
- machineEntity = app.addChild(EntitySpec.create(MachineEntity.class)
- .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true)
- .location(TestApplication.LOCALHOST_PROVISIONER_SPEC));
- machineEntity.start(ImmutableList.<Location>of());
-
- machineEntity.execCommand("echo myval");
-
- Set<Task<?>> tasks = BrooklynTaskTags.getTasksInEntityContext(mgmt.getExecutionManager(), machineEntity);
- String taskNameRegex = "ssh: echo myval";
-
- streams = Maps.newLinkedHashMap();
- subTask = AbstractSoftwareProcessStreamsTest.findTaskOrSubTask(tasks, TaskPredicates.displayNameSatisfies(StringPredicates.matchesRegex(taskNameRegex))).get();
- for (String streamId : ImmutableList.of("stdin", "stdout", "stderr")) {
- streams.put(streamId, AbstractSoftwareProcessStreamsTest.getStreamOrFail(subTask, streamId));
- }
- }
-
- @Test(groups = "Integration")
- public void testGetTask() throws Exception {
- String path = "/v1/activities/"+subTask.getId();
- assertPermitted("myRoot", path);
- assertPermitted("myReadonly", path);
- assertForbidden("myMinimal", path);
- assertForbidden("unrecognisedUser", path);
- }
-
- @Test(groups = "Integration")
- public void testGetStream() throws Exception {
- String pathPrefix = "/v1/activities/"+subTask.getId()+"/stream/";
- for (Map.Entry<String, String> entry : streams.entrySet()) {
- String streamId = entry.getKey();
- String expectedStream = entry.getValue();
-
- assertEquals(httpGet("myRoot", pathPrefix+streamId), expectedStream);
- assertEquals(httpGet("myReadonly", pathPrefix+streamId), expectedStream);
- assertForbidden("myMinimal", pathPrefix+streamId);
- assertForbidden("unrecognisedUser", pathPrefix+streamId);
-
- StaticDelegatingEntitlementManager.setDelegate(new SeeSelectiveStreams(streamId));
- assertEquals(httpGet("myCustom", pathPrefix+streamId), expectedStream);
-
- StaticDelegatingEntitlementManager.setDelegate(new SeeSelectiveStreams("differentStreamId"));
- assertForbidden("myCustom", pathPrefix+streamId);
- }
- }
-
- public static class SeeSelectiveStreams implements EntitlementManager {
- private final String regex;
-
- public SeeSelectiveStreams(String regex) {
- this.regex = regex;
- }
- @Override
- @SuppressWarnings("unchecked")
- public <T> boolean isEntitled(EntitlementContext context, EntitlementClass<T> entitlementClass, T entitlementClassArgument) {
- String type = entitlementClass.entitlementClassIdentifier();
- if (Entitlements.SEE_ACTIVITY_STREAMS.entitlementClassIdentifier().equals(type)) {
- Entitlements.TaskAndItem<String> pair = (Entitlements.TaskAndItem<String>) entitlementClassArgument;
- return pair.getItem().matches(regex);
- } else {
- return true;
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/AuthenticateAnyoneSecurityProvider.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/AuthenticateAnyoneSecurityProvider.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/AuthenticateAnyoneSecurityProvider.java
deleted file mode 100644
index b7264b2..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/AuthenticateAnyoneSecurityProvider.java
+++ /dev/null
@@ -1,41 +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.entitlement;
-
-import javax.servlet.http.HttpSession;
-
-import org.apache.brooklyn.rest.security.provider.SecurityProvider;
-
-public class AuthenticateAnyoneSecurityProvider implements SecurityProvider {
-
- @Override
- public boolean isAuthenticated(HttpSession session) {
- return false;
- }
-
- @Override
- public boolean authenticate(HttpSession session, String user, String password) {
- return user != null;
- }
-
- @Override
- public boolean logout(HttpSession session) {
- return false;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/EntityConfigApiEntitlementsTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/EntityConfigApiEntitlementsTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/EntityConfigApiEntitlementsTest.java
deleted file mode 100644
index cbda515..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/EntityConfigApiEntitlementsTest.java
+++ /dev/null
@@ -1,103 +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.entitlement;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementClass;
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementContext;
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementManager;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.core.config.render.RendererHints;
-import org.apache.brooklyn.core.mgmt.entitlement.Entitlements;
-import org.apache.brooklyn.core.mgmt.entitlement.Entitlements.EntityAndItem;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.rest.api.SensorApi;
-import org.apache.brooklyn.rest.resources.SensorResource;
-import org.apache.brooklyn.test.Asserts;
-import org.testng.annotations.Test;
-
-/**
- * Test the {@link SensorApi} implementation.
- * <p>
- * Check that {@link SensorResource} correctly renders {@link AttributeSensor}
- * values, including {@link RendererHints.DisplayValue} hints.
- */
-@Test(singleThreaded = true)
-public class EntityConfigApiEntitlementsTest extends AbstractRestApiEntitlementsTest {
-
- @Test(groups = "Integration")
- public void testGet() throws Exception {
- String path = "/v1/applications/"+app.getId()+"/entities/"+entity.getId()+"/config/"+TestEntity.CONF_NAME.getName();
- String val = "\"myname\"";
-
- assertEquals(httpGet("myRoot", path), val);
- assertEquals(httpGet("myReadonly", path), val);
- assert404("myMinimal", path); // can't see app, to retrieve entity
- assert404("unrecognisedUser", path);
-
- StaticDelegatingEntitlementManager.setDelegate(new SeeSelectiveConfig(entity, TestEntity.CONF_NAME.getName()));
- assertEquals(httpGet("myCustom", path), val);
-
- StaticDelegatingEntitlementManager.setDelegate(new SeeSelectiveConfig(entity, "differentConfName"));
- assertForbidden("myCustom", path);
- }
-
- @Test(groups = "Integration")
- public void testCurrentState() throws Exception {
- String path = "/v1/applications/"+app.getId()+"/entities/"+entity.getId()+"/config/current-state";
- String confName = TestEntity.CONF_NAME.getName();
- String regex = ".*"+confName+".*myname.*";
-
- Asserts.assertStringMatchesRegex(httpGet("myRoot", path), regex);
- Asserts.assertStringMatchesRegex(httpGet("myReadonly", path), regex);
- assert404("myMinimal", path); // can't see app, to retrieve entity
- assert404("unrecognisedUser", path);
-
- StaticDelegatingEntitlementManager.setDelegate(new SeeSelectiveConfig(entity, confName));
- Asserts.assertStringMatchesRegex(httpGet("myCustom", path), regex);
-
- StaticDelegatingEntitlementManager.setDelegate(new SeeSelectiveConfig(entity, "differentConfName"));
- String resp = httpGet("myCustom", path);
- assertFalse(resp.matches(regex), "resp="+resp);
- }
-
- public static class SeeSelectiveConfig implements EntitlementManager {
- private final Entity entity;
- private final String regex;
-
- public SeeSelectiveConfig(Entity entity, String regex) {
- this.entity = entity;
- this.regex = regex;
- }
- @Override
- @SuppressWarnings("unchecked")
- public <T> boolean isEntitled(EntitlementContext context, EntitlementClass<T> entitlementClass, T entitlementClassArgument) {
- String type = entitlementClass.entitlementClassIdentifier();
- if (Entitlements.SEE_CONFIG.entitlementClassIdentifier().equals(type)) {
- EntityAndItem<String> entityAndItem = (EntityAndItem<String>) entitlementClassArgument;
- return entity.equals(entityAndItem.getEntity()) && entityAndItem.getItem().matches(regex);
- } else {
- return true;
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/SensorApiEntitlementsTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/SensorApiEntitlementsTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/SensorApiEntitlementsTest.java
deleted file mode 100644
index dab72ec..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/SensorApiEntitlementsTest.java
+++ /dev/null
@@ -1,108 +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.entitlement;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementClass;
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementContext;
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementManager;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.core.config.render.RendererHints;
-import org.apache.brooklyn.core.mgmt.entitlement.Entitlements;
-import org.apache.brooklyn.core.mgmt.entitlement.Entitlements.EntityAndItem;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.rest.api.SensorApi;
-import org.apache.brooklyn.rest.resources.SensorResource;
-import org.apache.brooklyn.test.Asserts;
-import org.testng.annotations.Test;
-
-/**
- * Test the {@link SensorApi} implementation.
- * <p>
- * Check that {@link SensorResource} correctly renders {@link AttributeSensor}
- * values, including {@link RendererHints.DisplayValue} hints.
- */
-@Test(singleThreaded = true)
-public class SensorApiEntitlementsTest extends AbstractRestApiEntitlementsTest {
-
- @Test(groups = "Integration")
- public void testGet() throws Exception {
- entity.sensors().set(TestEntity.NAME, "myval");
-
- String sensorName = TestEntity.NAME.getName();
- String path = "/v1/applications/"+app.getId()+"/entities/"+entity.getId()+"/sensors/"+sensorName;
- String val = "\"myval\"";
-
- assertEquals(httpGet("myRoot", path), val);
- assertEquals(httpGet("myReadonly", path), val);
- assert404("myMinimal", path); // can't see app, to retrieve entity
- assert404("unrecognisedUser", path);
-
- StaticDelegatingEntitlementManager.setDelegate(new SeeSelectiveSensor(entity, sensorName));
- assertEquals(httpGet("myCustom", path), val);
-
- StaticDelegatingEntitlementManager.setDelegate(new SeeSelectiveSensor(entity, "differentConfName"));
- assertForbidden("myCustom", path);
- }
-
- @Test(groups = "Integration")
- public void testCurrentState() throws Exception {
- entity.sensors().set(TestEntity.NAME, "myval");
-
- String path = "/v1/applications/"+app.getId()+"/entities/"+entity.getId()+"/sensors/current-state";
- String sensorName = TestEntity.NAME.getName();
- String regex = ".*"+sensorName+".*myval.*";
-
- Asserts.assertStringMatchesRegex(httpGet("myRoot", path), regex);
- Asserts.assertStringMatchesRegex(httpGet("myReadonly", path), regex);
- assert404("myMinimal", path); // can't see app, to retrieve entity
- assert404("unrecognisedUser", path);
-
- StaticDelegatingEntitlementManager.setDelegate(new SeeSelectiveSensor(entity, sensorName));
- Asserts.assertStringMatchesRegex(httpGet("myCustom", path), regex);
-
- StaticDelegatingEntitlementManager.setDelegate(new SeeSelectiveSensor(entity, "differentSensorName"));
- String resp = httpGet("myCustom", path);
- assertFalse(resp.matches(regex), "resp="+resp);
- }
-
- public static class SeeSelectiveSensor implements EntitlementManager {
- private final Entity entity;
- private final String regex;
-
- public SeeSelectiveSensor(Entity entity, String regex) {
- this.entity = entity;
- this.regex = regex;
- }
- @Override
- @SuppressWarnings("unchecked")
- public <T> boolean isEntitled(EntitlementContext context, EntitlementClass<T> entitlementClass, T entitlementClassArgument) {
- String type = entitlementClass.entitlementClassIdentifier();
- if (Entitlements.SEE_SENSOR.entitlementClassIdentifier().equals(type)) {
- EntityAndItem<String> entityAndItem = (EntityAndItem<String>) entitlementClassArgument;
- return entity.equals(entityAndItem.getEntity()) && entityAndItem.getItem().matches(regex);
- } else {
- return true;
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/ServerApiEntitlementsTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/ServerApiEntitlementsTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/ServerApiEntitlementsTest.java
deleted file mode 100644
index afa42cb..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/ServerApiEntitlementsTest.java
+++ /dev/null
@@ -1,34 +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.entitlement;
-
-import org.testng.annotations.Test;
-
-@Test(singleThreaded = true)
-public class ServerApiEntitlementsTest extends AbstractRestApiEntitlementsTest {
-
- @Test(groups = "Integration")
- public void testGetHealthy() throws Exception {
- String path = "/v1/server/up";
- assertPermitted("myRoot", path);
- assertForbidden("myReadonly", path);
- assertForbidden("myMinimal", path);
- assertForbidden("unrecognisedUser", path);
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/StaticDelegatingEntitlementManager.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/StaticDelegatingEntitlementManager.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/StaticDelegatingEntitlementManager.java
deleted file mode 100644
index 4370ad6..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/entitlement/StaticDelegatingEntitlementManager.java
+++ /dev/null
@@ -1,37 +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.entitlement;
-
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementClass;
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementContext;
-import org.apache.brooklyn.api.mgmt.entitlement.EntitlementManager;
-
-public class StaticDelegatingEntitlementManager implements EntitlementManager {
-
- private static volatile EntitlementManager delegate;
-
- public static void setDelegate(EntitlementManager val) {
- delegate = val;
- }
-
- @Override
- public <T> boolean isEntitled(EntitlementContext context, EntitlementClass<T> entitlementClass, T entitlementClassArgument) {
- return (delegate != null) ? delegate.isEntitled(context, entitlementClass, entitlementClassArgument) : false;
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/AccessResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/AccessResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/AccessResourceTest.java
deleted file mode 100644
index 0839ea5..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/AccessResourceTest.java
+++ /dev/null
@@ -1,68 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import javax.ws.rs.core.Response;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-
-import org.apache.brooklyn.rest.domain.AccessSummary;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-
-import com.sun.jersey.api.client.ClientResponse;
-
-@Test(singleThreaded = true)
-public class AccessResourceTest extends BrooklynRestResourceTest {
-
- @SuppressWarnings("unused")
- private static final Logger log = LoggerFactory.getLogger(AccessResourceTest.class);
-
- @Test
- public void testGetAndSetAccessControl() throws Exception {
- // Default is everything allowed
- AccessSummary summary = client().resource("/v1/access").get(AccessSummary.class);
- assertTrue(summary.isLocationProvisioningAllowed());
-
- // Forbid location provisioning
- ClientResponse response = client().resource(
- "/v1/access/locationProvisioningAllowed")
- .queryParam("allowed", "false")
- .post(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
-
- AccessSummary summary2 = client().resource("/v1/access").get(AccessSummary.class);
- assertFalse(summary2.isLocationProvisioningAllowed());
-
- // Allow location provisioning
- ClientResponse response2 = client().resource(
- "/v1/access/locationProvisioningAllowed")
- .queryParam("allowed", "true")
- .post(ClientResponse.class);
- assertEquals(response2.getStatus(), Response.Status.OK.getStatusCode());
-
- AccessSummary summary3 = client().resource("/v1/access").get(AccessSummary.class);
- assertTrue(summary3.isLocationProvisioningAllowed());
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApidocResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApidocResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApidocResourceTest.java
deleted file mode 100644
index 2064508..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApidocResourceTest.java
+++ /dev/null
@@ -1,173 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import io.swagger.annotations.Api;
-import io.swagger.models.Operation;
-import io.swagger.models.Path;
-import io.swagger.models.Swagger;
-
-import java.util.Collection;
-
-import org.apache.brooklyn.rest.BrooklynRestApi;
-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.filter.SwaggerFilter;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.sun.jersey.api.core.ClassNamesResourceConfig;
-import com.sun.jersey.spi.container.servlet.ServletContainer;
-import com.sun.jersey.test.framework.AppDescriptor;
-import com.sun.jersey.test.framework.JerseyTest;
-import com.sun.jersey.test.framework.WebAppDescriptor;
-import com.sun.jersey.test.framework.spi.container.TestContainerException;
-import com.sun.jersey.test.framework.spi.container.TestContainerFactory;
-import com.sun.jersey.test.framework.spi.container.grizzly2.web.GrizzlyWebTestContainerFactory;
-
-/**
- * @author Adam Lowe
- */
-@Test(singleThreaded = true)
-public class ApidocResourceTest extends BrooklynRestResourceTest {
-
- private static final Logger log = LoggerFactory.getLogger(ApidocResourceTest.class);
-
- @Override
- protected JerseyTest createJerseyTest() {
- return new JerseyTest() {
- @Override
- protected AppDescriptor configure() {
- return new WebAppDescriptor.Builder(
- ImmutableMap.of(
- ServletContainer.RESOURCE_CONFIG_CLASS, ClassNamesResourceConfig.class.getName(),
- ClassNamesResourceConfig.PROPERTY_CLASSNAMES, getResourceClassnames()))
- .addFilter(SwaggerFilter.class, "SwaggerFilter").build();
- }
-
- @Override
- protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
- return new GrizzlyWebTestContainerFactory();
- }
-
- private String getResourceClassnames() {
- Iterable<String> classnames = Collections2.transform(config.getClasses(), new Function<Class<?>, String>() {
- @Override
- public String apply(Class<?> clazz) {
- return clazz.getName();
- }
- });
- classnames = Iterables.concat(classnames, Collections2.transform(config.getSingletons(), new Function<Object, String>() {
- @Override
- public String apply(Object singleton) {
- return singleton.getClass().getName();
- }
- }));
- return Joiner.on(';').join(classnames);
- }
- };
- }
-
- @Override
- protected void addBrooklynResources() {
- for (Object o : BrooklynRestApi.getApidocResources()) {
- addResource(o);
- }
- super.addBrooklynResources();
- }
-
- @Test(enabled = false)
- public void testRootSerializesSensibly() throws Exception {
- String data = resource("/v1/apidoc/swagger.json").get(String.class);
- log.info("apidoc gives: "+data);
- // make sure no scala gets in
- assertFalse(data.contains("$"));
- assertFalse(data.contains("scala"));
- // make sure it's an appropriate swagger 2.0 json
- Swagger swagger = resource("/v1/apidoc/swagger.json").get(Swagger.class);
- assertEquals(swagger.getSwagger(), "2.0");
- }
-
- @Test(enabled = false)
- public void testCountRestResources() throws Exception {
- Swagger swagger = resource("/v1/apidoc/swagger.json").get(Swagger.class);
- assertEquals(swagger.getTags().size(), 1 + Iterables.size(BrooklynRestApi.getBrooklynRestResources()));
- }
-
- @Test(enabled = false)
- public void testApiDocDetails() throws Exception {
- Swagger swagger = resource("/v1/apidoc/swagger.json").get(Swagger.class);
- Collection<Operation> operations = getTaggedOperations(swagger, ApidocResource.class.getAnnotation(Api.class).value());
- assertEquals(operations.size(), 2, "ops="+operations);
- }
-
- @Test(enabled = false)
- public void testEffectorDetails() throws Exception {
- Swagger swagger = resource("/v1/apidoc/swagger.json").get(Swagger.class);
- Collection<Operation> operations = getTaggedOperations(swagger, EffectorApi.class.getAnnotation(Api.class).value());
- assertEquals(operations.size(), 2, "ops="+operations);
- }
-
- @Test(enabled = false)
- public void testEntityDetails() throws Exception {
- Swagger swagger = resource("/v1/apidoc/swagger.json").get(Swagger.class);
- Collection<Operation> operations = getTaggedOperations(swagger, EntityApi.class.getAnnotation(Api.class).value());
- assertEquals(operations.size(), 14, "ops="+operations);
- }
-
- @Test(enabled = false)
- public void testCatalogDetails() throws Exception {
- Swagger swagger = resource("/v1/apidoc/swagger.json").get(Swagger.class);
- Collection<Operation> operations = getTaggedOperations(swagger, CatalogApi.class.getAnnotation(Api.class).value());
- assertEquals(operations.size(), 22, "ops="+operations);
- }
-
- /**
- * Retrieves all operations tagged the given tag from the given swagger spec.
- */
- private Collection<Operation> getTaggedOperations(Swagger swagger, final String requiredTag) {
- Iterable<Operation> allOperations = Iterables.concat(Collections2.transform(swagger.getPaths().values(),
- new Function<Path, Collection<Operation>>() {
- @Override
- public Collection<Operation> apply(Path path) {
- return path.getOperations();
- }
- }));
-
- return Collections2.filter(ImmutableList.copyOf(allOperations), new Predicate<Operation>() {
- @Override
- public boolean apply(Operation operation) {
- return operation.getTags().contains(requiredTag);
- }
- });
- }
-}
-
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceIntegrationTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceIntegrationTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceIntegrationTest.java
deleted file mode 100644
index 865b6f7..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceIntegrationTest.java
+++ /dev/null
@@ -1,133 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.net.URI;
-import java.util.Set;
-
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.core.entity.lifecycle.Lifecycle;
-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.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.MutableMap;
-
-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 com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.GenericType;
-
-@Test(singleThreaded = true)
-public class ApplicationResourceIntegrationTest extends BrooklynRestResourceTest {
-
- @SuppressWarnings("unused")
- private static final Logger log = LoggerFactory.getLogger(ApplicationResourceIntegrationTest.class);
-
- private final ApplicationSpec redisSpec = ApplicationSpec.builder().name("redis-app")
- .entities(ImmutableSet.of(new EntitySpec("redis-ent", "org.apache.brooklyn.entity.nosql.redis.RedisStore")))
- .locations(ImmutableSet.of("localhost"))
- .build();
-
- @Test(groups="Integration")
- public void testDeployRedisApplication() throws Exception {
- ClientResponse response = clientDeploy(redisSpec);
-
- assertEquals(response.getStatus(), 201);
- assertEquals(getManagementContext().getApplications().size(), 1);
- assertTrue(response.getLocation().getPath().startsWith("/v1/applications/"), "path="+response.getLocation().getPath()); // path uses id, rather than app name
-
- waitForApplicationToBeRunning(response.getLocation());
- }
-
- @Test(groups="Integration", dependsOnMethods = "testDeployRedisApplication")
- public void testListEntities() {
- Set<EntitySummary> entities = client().resource("/v1/applications/redis-app/entities")
- .get(new GenericType<Set<EntitySummary>>() {});
-
- for (EntitySummary entity : entities) {
- client().resource(entity.getLinks().get("self")).get(ClientResponse.class);
- // TODO assertions on the above call?
-
- Set<EntitySummary> children = client().resource(entity.getLinks().get("children"))
- .get(new GenericType<Set<EntitySummary>>() {});
- assertEquals(children.size(), 0);
- }
- }
-
- @Test(groups="Integration", dependsOnMethods = "testDeployRedisApplication")
- public void testListSensorsRedis() {
- Set<SensorSummary> sensors = client().resource("/v1/applications/redis-app/entities/redis-ent/sensors")
- .get(new GenericType<Set<SensorSummary>>() {});
- assertTrue(sensors.size() > 0);
- SensorSummary uptime = Iterables.find(sensors, new Predicate<SensorSummary>() {
- @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 {
- ClientResponse response = client().resource("/v1/applications/redis-app/entities/redis-ent/effectors/stop")
- .type(MediaType.APPLICATION_JSON_TYPE)
- .post(ClientResponse.class, ImmutableMap.of());
- assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());
-
- final URI stateSensor = URI.create("/v1/applications/redis-app/entities/redis-ent/sensors/service.state");
- final String expectedStatus = Lifecycle.STOPPED.toString();
- Asserts.succeedsEventually(MutableMap.of("timeout", 60 * 1000), new Runnable() {
- public void run() {
- // Accept with and without quotes; if don't specify "Accepts" header, then
- // might get back json or plain text (depending on compiler / java runtime
- // used for SensorApi!)
- String val = client().resource(stateSensor).get(String.class);
- assertTrue(expectedStatus.equalsIgnoreCase(val) || ("\""+expectedStatus+"\"").equalsIgnoreCase(val), "state="+val);
- }
- });
- }
-
- @Test(groups="Integration", dependsOnMethods = "testTriggerRedisStopEffector" )
- public void testDeleteRedisApplication() throws Exception {
- int size = getManagementContext().getApplications().size();
- ClientResponse response = client().resource("/v1/applications/redis-app")
- .delete(ClientResponse.class);
-
- waitForPageNotFoundResponse("/v1/applications/redis-app", ApplicationSummary.class);
-
- assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());
- assertEquals(getManagementContext().getApplications().size(), size-1);
- }
-
-}
[3/9] brooklyn-server git commit: Remove jersey compatibility
Posted by sj...@apache.org.
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/EntityResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/EntityResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/EntityResourceTest.java
deleted file mode 100644
index 1c091da..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/EntityResourceTest.java
+++ /dev/null
@@ -1,189 +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.resources;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.Nullable;
-import javax.ws.rs.core.MediaType;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.entity.EntityInternal;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.entity.stock.BasicApplication;
-import org.apache.brooklyn.rest.domain.ApplicationSpec;
-import org.apache.brooklyn.rest.domain.EntitySpec;
-import org.apache.brooklyn.rest.domain.TaskSummary;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.http.HttpAsserts;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.common.base.Predicate;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import com.sun.jersey.api.client.ClientResponse;
-
-@Test(singleThreaded = true)
-public class EntityResourceTest extends BrooklynRestResourceTest {
-
- private static final Logger log = LoggerFactory.getLogger(EntityResourceTest.class);
-
- private final ApplicationSpec simpleSpec = ApplicationSpec.builder()
- .name("simple-app")
- .entities(ImmutableSet.of(new EntitySpec("simple-ent", RestMockSimpleEntity.class.getName())))
- .locations(ImmutableSet.of("localhost"))
- .build();
-
- private EntityInternal entity;
-
- private static final String entityEndpoint = "/v1/applications/simple-app/entities/simple-ent";
-
- @BeforeClass(alwaysRun = true)
- @Override
- public void setUp() throws Exception {
- super.setUp();
-
- // Deploy application
- ClientResponse deploy = clientDeploy(simpleSpec);
- waitForApplicationToBeRunning(deploy.getLocation());
-
- // Add tag
- entity = (EntityInternal) Iterables.find(getManagementContext().getEntityManager().getEntities(), new Predicate<Entity>() {
- @Override
- public boolean apply(@Nullable Entity input) {
- return "RestMockSimpleEntity".equals(input.getEntityType().getSimpleName());
- }
- });
- }
-
- @Test
- public void testTagsSanity() throws Exception {
- entity.tags().addTag("foo");
-
- ClientResponse response = client().resource(entityEndpoint + "/tags")
- .accept(MediaType.APPLICATION_JSON_TYPE)
- .get(ClientResponse.class);
- String data = response.getEntity(String.class);
-
- try {
- List<Object> tags = new ObjectMapper().readValue(data, new TypeReference<List<Object>>() {});
- Assert.assertTrue(tags.contains("foo"));
- Assert.assertFalse(tags.contains("bar"));
- } catch (Exception e) {
- Exceptions.propagateIfFatal(e);
- throw new IllegalStateException("Error with deserialization of tags list: "+e+"\n"+data, e);
- }
- }
-
- @Test
- public void testRename() throws Exception {
- try {
- ClientResponse response = client().resource(entityEndpoint + "/name")
- .queryParam("name", "New Name")
- .post(ClientResponse.class);
-
- HttpAsserts.assertHealthyStatusCode(response.getStatus());
- Assert.assertTrue(entity.getDisplayName().equals("New Name"));
- } finally {
- // restore it for other tests!
- entity.setDisplayName("simple-ent");
- }
- }
-
- @Test
- public void testAddChild() throws Exception {
- try {
- // to test in GUI:
- // services: [ { type: org.apache.brooklyn.entity.stock.BasicEntity }]
- ClientResponse response = client().resource(entityEndpoint + "/children?timeout=10s")
- .entity("services: [ { type: "+TestEntity.class.getName()+" }]", "application/yaml")
- .post(ClientResponse.class);
-
- HttpAsserts.assertHealthyStatusCode(response.getStatus());
- Assert.assertEquals(entity.getChildren().size(), 1);
- Entity child = Iterables.getOnlyElement(entity.getChildren());
- Assert.assertTrue(Entities.isManaged(child));
-
- TaskSummary task = response.getEntity(TaskSummary.class);
- Assert.assertEquals(task.getResult(), MutableList.of(child.getId()));
-
- } finally {
- // restore it for other tests
- Collection<Entity> children = entity.getChildren();
- if (!children.isEmpty()) Entities.unmanage(Iterables.getOnlyElement(children));
- }
- }
-
- @Test
- public void testTagsDoNotSerializeTooMuch() throws Exception {
- entity.tags().addTag("foo");
- entity.tags().addTag(entity.getParent());
-
- ClientResponse response = client().resource(entityEndpoint + "/tags")
- .accept(MediaType.APPLICATION_JSON)
- .get(ClientResponse.class);
- String raw = response.getEntity(String.class);
- log.info("TAGS raw: "+raw);
- HttpAsserts.assertHealthyStatusCode(response.getStatus());
-
- Assert.assertTrue(raw.contains(entity.getParent().getId()), "unexpected app tag, does not include ID: "+raw);
-
- Assert.assertTrue(raw.length() < 1000, "unexpected app tag, includes too much mgmt info (len "+raw.length()+"): "+raw);
-
- Assert.assertFalse(raw.contains(entity.getManagementContext().getManagementNodeId()), "unexpected app tag, includes too much mgmt info: "+raw);
- Assert.assertFalse(raw.contains("managementContext"), "unexpected app tag, includes too much mgmt info: "+raw);
- Assert.assertFalse(raw.contains("localhost"), "unexpected app tag, includes too much mgmt info: "+raw);
- Assert.assertFalse(raw.contains("catalog"), "unexpected app tag, includes too much mgmt info: "+raw);
-
- @SuppressWarnings("unchecked")
- List<Object> tags = mapper().readValue(raw, List.class);
- log.info("TAGS are: "+tags);
-
- Assert.assertEquals(tags.size(), 2, "tags are: "+tags);
-
- Assert.assertTrue(tags.contains("foo"));
- Assert.assertFalse(tags.contains("bar"));
-
- MutableList<Object> appTags = MutableList.copyOf(tags);
- appTags.remove("foo");
- Object appTag = Iterables.getOnlyElement( appTags );
-
- // it's a map at this point, because there was no way to make it something stronger than Object
- Assert.assertTrue(appTag instanceof Map, "Should have deserialized an entity: "+appTag);
- // let's re-serialize it as an entity
- appTag = mapper().readValue(mapper().writeValueAsString(appTag), Entity.class);
-
- Assert.assertTrue(appTag instanceof Entity, "Should have deserialized an entity: "+appTag);
- Assert.assertEquals( ((Entity)appTag).getId(), entity.getApplicationId(), "Wrong ID: "+appTag);
- Assert.assertTrue(appTag instanceof BasicApplication, "Should have deserialized BasicApplication: "+appTag);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ErrorResponseTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ErrorResponseTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ErrorResponseTest.java
deleted file mode 100644
index 0979875..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ErrorResponseTest.java
+++ /dev/null
@@ -1,98 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response.Status;
-
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-import org.apache.brooklyn.rest.domain.ApiError;
-import org.apache.brooklyn.rest.domain.ApplicationSpec;
-import org.apache.brooklyn.rest.domain.EntitySpec;
-import org.apache.brooklyn.rest.domain.PolicySummary;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimplePolicy;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Maps;
-import com.sun.jersey.api.client.ClientResponse;
-
-public class ErrorResponseTest extends BrooklynRestResourceTest {
-
- private final ApplicationSpec simpleSpec = ApplicationSpec.builder().name("simple-app").entities(
- ImmutableSet.of(new EntitySpec("simple-ent", RestMockSimpleEntity.class.getName()))).locations(
- ImmutableSet.of("localhost")).build();
- private String policyId;
-
- @BeforeClass(alwaysRun = true)
- @Override
- public void setUp() throws Exception {
- super.setUp();
-
- ClientResponse aResponse = clientDeploy(simpleSpec);
- waitForApplicationToBeRunning(aResponse.getLocation());
-
- String policiesEndpoint = "/v1/applications/simple-app/entities/simple-ent/policies";
-
- ClientResponse pResponse = client().resource(policiesEndpoint)
- .queryParam("type", RestMockSimplePolicy.class.getCanonicalName())
- .type(MediaType.APPLICATION_JSON_TYPE)
- .post(ClientResponse.class, Maps.newHashMap());
- PolicySummary response = pResponse.getEntity(PolicySummary.class);
- assertNotNull(response.getId());
- policyId = response.getId();
- }
-
- @Test
- public void testResponseToBadRequest() {
- String resource = "/v1/applications/simple-app/entities/simple-ent/policies/"+policyId+"/config/"
- + RestMockSimplePolicy.INTEGER_CONFIG.getName() + "/set";
-
- ClientResponse response = client().resource(resource)
- .queryParam("value", "notanumber")
- .post(ClientResponse.class);
-
- assertEquals(response.getStatus(), Status.BAD_REQUEST.getStatusCode());
- assertEquals(response.getHeaders().getFirst("Content-Type"), MediaType.APPLICATION_JSON);
-
- ApiError error = response.getEntity(ApiError.class);
- assertTrue(error.getMessage().toLowerCase().contains("cannot coerce"));
- }
-
- @Test
- public void testResponseToWrongMethod() {
- String resource = "/v1/applications/simple-app/entities/simple-ent/policies/"+policyId+"/config/"
- + RestMockSimplePolicy.INTEGER_CONFIG.getName() + "/set";
-
- // Should be POST, not GET
- ClientResponse response = client().resource(resource)
- .queryParam("value", "4")
- .get(ClientResponse.class);
-
- assertEquals(response.getStatus(), 405);
- // Can we assert anything about the content type?
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/LocationResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/LocationResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/LocationResourceTest.java
deleted file mode 100644
index 7f36af4..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/LocationResourceTest.java
+++ /dev/null
@@ -1,188 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.net.URI;
-import java.util.Map;
-import java.util.Set;
-
-import javax.annotation.Nullable;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import com.google.api.client.repackaged.com.google.common.base.Joiner;
-import com.google.common.base.Predicate;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.GenericType;
-
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.core.location.SimulatedLocation;
-import org.apache.brooklyn.location.jclouds.JcloudsLocation;
-import org.apache.brooklyn.rest.domain.CatalogLocationSummary;
-import org.apache.brooklyn.rest.domain.LocationSummary;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.test.Asserts;
-
-@Test(singleThreaded = true)
-public class LocationResourceTest extends BrooklynRestResourceTest {
-
- private static final Logger log = LoggerFactory.getLogger(LocationResourceTest.class);
- private String legacyLocationName = "my-jungle-legacy";
- private String legacyLocationVersion = "0.0.0.SNAPSHOT";
-
- private String locationName = "my-jungle";
- private String locationVersion = "0.1.2";
-
- @Test
- @Deprecated
- public void testAddLegacyLocationDefinition() {
- Map<String, String> expectedConfig = ImmutableMap.of(
- "identity", "bob",
- "credential", "CR3dential");
- ClientResponse response = client().resource("/v1/locations")
- .type(MediaType.APPLICATION_JSON_TYPE)
- .post(ClientResponse.class, new org.apache.brooklyn.rest.domain.LocationSpec(legacyLocationName, "aws-ec2:us-east-1", expectedConfig));
-
- URI addedLegacyLocationUri = response.getLocation();
- log.info("added legacy, at: " + addedLegacyLocationUri);
- LocationSummary location = client().resource(response.getLocation()).get(LocationSummary.class);
- log.info(" contents: " + location);
- assertEquals(location.getSpec(), "brooklyn.catalog:"+legacyLocationName+":"+legacyLocationVersion);
- assertTrue(addedLegacyLocationUri.getPath().startsWith("/v1/locations/"));
-
- JcloudsLocation l = (JcloudsLocation) getManagementContext().getLocationRegistry().getLocationManaged(legacyLocationName);
- Assert.assertEquals(l.getProvider(), "aws-ec2");
- Assert.assertEquals(l.getRegion(), "us-east-1");
- Assert.assertEquals(l.getIdentity(), "bob");
- Assert.assertEquals(l.getCredential(), "CR3dential");
- }
-
- @SuppressWarnings("deprecation")
- @Test
- public void testAddNewLocationDefinition() {
- String yaml = Joiner.on("\n").join(ImmutableList.of(
- "brooklyn.catalog:",
- " symbolicName: "+locationName,
- " version: " + locationVersion,
- "",
- "brooklyn.locations:",
- "- type: "+"aws-ec2:us-east-1",
- " brooklyn.config:",
- " identity: bob",
- " credential: CR3dential"));
-
-
- ClientResponse response = client().resource("/v1/catalog")
- .post(ClientResponse.class, yaml);
-
- assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
-
-
- URI addedCatalogItemUri = response.getLocation();
- log.info("added, at: " + addedCatalogItemUri);
-
- // Ensure location definition exists
- CatalogLocationSummary locationItem = client().resource("/v1/catalog/locations/"+locationName + "/" + locationVersion)
- .get(CatalogLocationSummary.class);
- log.info(" item: " + locationItem);
- LocationSummary locationSummary = client().resource(URI.create("/v1/locations/"+locationName+"/")).get(LocationSummary.class);
- log.info(" summary: " + locationSummary);
- Assert.assertEquals(locationSummary.getSpec(), "brooklyn.catalog:"+locationName+":"+locationVersion);
-
- // Ensure location is usable - can instantiate, and has right config
- JcloudsLocation l = (JcloudsLocation) getManagementContext().getLocationRegistry().getLocationManaged(locationName);
- Assert.assertEquals(l.getProvider(), "aws-ec2");
- Assert.assertEquals(l.getRegion(), "us-east-1");
- Assert.assertEquals(l.getIdentity(), "bob");
- Assert.assertEquals(l.getCredential(), "CR3dential");
- }
-
- @SuppressWarnings("deprecation")
- @Test(dependsOnMethods = { "testAddNewLocationDefinition" })
- public void testListAllLocationDefinitions() {
- Set<LocationSummary> locations = client().resource("/v1/locations")
- .get(new GenericType<Set<LocationSummary>>() {});
- Iterable<LocationSummary> matching = Iterables.filter(locations, new Predicate<LocationSummary>() {
- @Override
- public boolean apply(@Nullable LocationSummary l) {
- return locationName.equals(l.getName());
- }
- });
- LocationSummary location = Iterables.getOnlyElement(matching);
-
- Assert.assertEquals(location.getSpec(), "brooklyn.catalog:"+locationName+":"+locationVersion);
- Assert.assertEquals(location.getLinks().get("self").getPath(), "/v1/locations/"+locationName);
- }
-
- @SuppressWarnings("deprecation")
- @Test(dependsOnMethods = { "testListAllLocationDefinitions" })
- public void testGetSpecificLocation() {
- URI expectedLocationUri = URI.create("/v1/locations/"+locationName);
- LocationSummary location = client().resource(expectedLocationUri).get(LocationSummary.class);
- assertEquals(location.getSpec(), "brooklyn.catalog:"+locationName+":"+locationVersion);
- }
-
- @SuppressWarnings("deprecation")
- @Test
- public void testGetLocationConfig() {
- SimulatedLocation parentLoc = (SimulatedLocation) getManagementContext().getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class)
- .configure("myParentKey", "myParentVal"));
- SimulatedLocation loc = (SimulatedLocation) getManagementContext().getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class)
- .parent(parentLoc)
- .configure("mykey", "myval")
- .configure("password", "mypassword"));
-
- // "full" means including-inherited, filtered to exclude secrets
- URI uriFull = URI.create("/v1/locations/"+loc.getId()+"?full=true");
- LocationSummary summaryFull = client().resource(uriFull).get(LocationSummary.class);
- assertEquals(summaryFull.getConfig(), ImmutableMap.of("mykey", "myval", "myParentKey", "myParentVal"), "conf="+summaryFull.getConfig());
-
- // Default is local-only, filtered to exclude secrets
- URI uriDefault = URI.create("/v1/locations/"+loc.getId());
- LocationSummary summaryDefault = client().resource(uriDefault).get(LocationSummary.class);
- assertEquals(summaryDefault.getConfig(), ImmutableMap.of("mykey", "myval"), "conf="+summaryDefault.getConfig());
- }
-
- @Test(dependsOnMethods = { "testAddLegacyLocationDefinition" })
- @Deprecated
- public void testDeleteLocation() {
- final int size = getLocationRegistry().getDefinedLocations().size();
- URI expectedLocationUri = URI.create("/v1/locations/"+legacyLocationName);
-
- ClientResponse response = client().resource(expectedLocationUri).delete(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
- Asserts.succeedsEventually(new Runnable() {
- @Override
- public void run() {
- assertEquals(getLocationRegistry().getDefinedLocations().size(), size - 1);
- }
- });
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/PolicyResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/PolicyResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/PolicyResourceTest.java
deleted file mode 100644
index 22dc86d..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/PolicyResourceTest.java
+++ /dev/null
@@ -1,145 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.fail;
-
-import java.util.Map;
-import java.util.Set;
-
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-import org.apache.brooklyn.rest.domain.ApplicationSpec;
-import org.apache.brooklyn.rest.domain.EntitySpec;
-import org.apache.brooklyn.rest.domain.PolicyConfigSummary;
-import org.apache.brooklyn.rest.domain.PolicySummary;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimplePolicy;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.GenericType;
-
-@Test(singleThreaded = true)
-public class PolicyResourceTest extends BrooklynRestResourceTest {
-
- @SuppressWarnings("unused")
- private static final Logger log = LoggerFactory.getLogger(PolicyResourceTest.class);
-
- private static final String ENDPOINT = "/v1/applications/simple-app/entities/simple-ent/policies/";
-
- private final ApplicationSpec simpleSpec = ApplicationSpec.builder().name("simple-app").entities(
- ImmutableSet.of(new EntitySpec("simple-ent", RestMockSimpleEntity.class.getName()))).locations(
- ImmutableSet.of("localhost")).build();
-
- private String policyId;
-
- @BeforeClass(alwaysRun = true)
- @Override
- public void setUp() throws Exception {
- super.setUp();
-
- ClientResponse aResponse = clientDeploy(simpleSpec);
- waitForApplicationToBeRunning(aResponse.getLocation());
-
- ClientResponse pResponse = client().resource(ENDPOINT)
- .queryParam("type", RestMockSimplePolicy.class.getCanonicalName())
- .type(MediaType.APPLICATION_JSON_TYPE)
- .post(ClientResponse.class, Maps.newHashMap());
-
- PolicySummary response = pResponse.getEntity(PolicySummary.class);
- assertNotNull(response.getId());
- policyId = response.getId();
-
- }
-
- @Test
- public void testListConfig() throws Exception {
- Set<PolicyConfigSummary> config = client().resource(ENDPOINT + policyId + "/config")
- .get(new GenericType<Set<PolicyConfigSummary>>() {});
-
- Set<String> configNames = Sets.newLinkedHashSet();
- for (PolicyConfigSummary conf : config) {
- configNames.add(conf.getName());
- }
-
- assertEquals(configNames, ImmutableSet.of(
- RestMockSimplePolicy.SAMPLE_CONFIG.getName(),
- RestMockSimplePolicy.INTEGER_CONFIG.getName()));
- }
-
- @Test
- public void testGetNonExistantConfigReturns404() throws Exception {
- String invalidConfigName = "doesnotexist";
- try {
- PolicyConfigSummary summary = client().resource(ENDPOINT + policyId + "/config/" + invalidConfigName)
- .get(PolicyConfigSummary.class);
- fail("Should have thrown 404, but got "+summary);
- } catch (Exception e) {
- if (!e.toString().contains("404")) throw e;
- }
- }
-
- @Test
- public void testGetDefaultValue() throws Exception {
- String configName = RestMockSimplePolicy.SAMPLE_CONFIG.getName();
- String expectedVal = RestMockSimplePolicy.SAMPLE_CONFIG.getDefaultValue();
-
- String configVal = client().resource(ENDPOINT + policyId + "/config/" + configName)
- .get(String.class);
- assertEquals(configVal, expectedVal);
- }
-
- @Test(dependsOnMethods = "testGetDefaultValue")
- public void testReconfigureConfig() throws Exception {
- String configName = RestMockSimplePolicy.SAMPLE_CONFIG.getName();
-
- ClientResponse response = client().resource(ENDPOINT + policyId + "/config/" + configName + "/set")
- .queryParam("value", "newval")
- .post(ClientResponse.class);
-
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- }
-
- @Test(dependsOnMethods = "testReconfigureConfig")
- public void testGetConfigValue() throws Exception {
- String configName = RestMockSimplePolicy.SAMPLE_CONFIG.getName();
- String expectedVal = "newval";
-
- Map<String, Object> allState = client().resource(ENDPOINT + policyId + "/config/current-state")
- .get(new GenericType<Map<String, Object>>() {});
- assertEquals(allState, ImmutableMap.of(configName, expectedVal));
-
- String configVal = client().resource(ENDPOINT + policyId + "/config/" + configName)
- .get(String.class);
- assertEquals(configVal, expectedVal);
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ScriptResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ScriptResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ScriptResourceTest.java
deleted file mode 100644
index 08b9aa4..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ScriptResourceTest.java
+++ /dev/null
@@ -1,54 +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.resources;
-
-import java.util.Collections;
-
-import org.apache.brooklyn.api.entity.Application;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.rest.domain.ScriptExecutionSummary;
-import org.apache.brooklyn.rest.testing.mocks.RestMockApp;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-public class ScriptResourceTest {
-
- @Test
- public void testGroovy() {
- ManagementContext mgmt = LocalManagementContextForTests.newInstance();
- Application app = mgmt.getEntityManager().createEntity( EntitySpec.create(Application.class, RestMockApp.class) );
- try {
-
- Entities.start(app, Collections.<Location>emptyList());
-
- ScriptResource s = new ScriptResource();
- s.setManagementContext(mgmt);
-
- ScriptExecutionSummary result = s.groovy(null, "def apps = []; mgmt.applications.each { println 'app:'+it; apps << it.id }; apps");
- Assert.assertEquals(Collections.singletonList(app.getId()).toString(), result.getResult());
- Assert.assertTrue(result.getStdout().contains("app:RestMockApp"));
-
- } finally { Entities.destroyAll(mgmt); }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceIntegrationTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceIntegrationTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceIntegrationTest.java
deleted file mode 100644
index 2ecc169..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceIntegrationTest.java
+++ /dev/null
@@ -1,82 +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.resources;
-
-import java.net.URI;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.entity.EntityInternal;
-import org.apache.brooklyn.core.entity.EntityPredicates;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.entity.stock.BasicApplication;
-import org.apache.brooklyn.rest.BrooklynRestApiLauncher;
-import org.apache.brooklyn.rest.BrooklynRestApiLauncherTestFixture;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity;
-import org.apache.brooklyn.test.HttpTestUtils;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.http.HttpTool;
-import org.apache.brooklyn.util.http.HttpToolResponse;
-import org.apache.brooklyn.util.net.Urls;
-import org.apache.http.client.HttpClient;
-import org.eclipse.jetty.server.Server;
-import org.testng.Assert;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-
-public class SensorResourceIntegrationTest extends BrooklynRestApiLauncherTestFixture {
-
- private Server server;
- private ManagementContext mgmt;
- private BasicApplication app;
-
- @BeforeClass(alwaysRun = true)
- protected void setUp() {
- mgmt = LocalManagementContextForTests.newInstance();
- server = useServerForTest(BrooklynRestApiLauncher.launcher()
- .managementContext(mgmt)
- .withoutJsgui()
- .start());
- app = mgmt.getEntityManager().createEntity(EntitySpec.create(BasicApplication.class).displayName("simple-app")
- .child(EntitySpec.create(Entity.class, RestMockSimpleEntity.class).displayName("simple-ent")));
- mgmt.getEntityManager().manage(app);
- app.start(MutableList.of(mgmt.getLocationRegistry().getLocationManaged("localhost")));
- }
-
- // marked integration because of time
- @Test(groups = "Integration")
- public void testSensorBytes() throws Exception {
- EntityInternal entity = (EntityInternal) Iterables.find(mgmt.getEntityManager().getEntities(), EntityPredicates.displayNameEqualTo("simple-ent"));
- SensorResourceTest.addAmphibianSensor(entity);
-
- String baseUri = getBaseUri(server);
- URI url = URI.create(Urls.mergePaths(baseUri, SensorResourceTest.SENSORS_ENDPOINT, SensorResourceTest.SENSOR_NAME));
-
- // Uses explicit "application/json" because failed on jenkins as though "text/plain" was the default on Ubuntu jenkins!
- HttpClient client = HttpTool.httpClientBuilder().uri(baseUri).build();
- HttpToolResponse response = HttpTool.httpGet(client, url, ImmutableMap.<String, String>of("Accept", "application/json"));
- HttpTestUtils.assertHealthyStatusCode(response.getResponseCode());
- Assert.assertEquals(response.getContentAsString(), "\"12345 frogs\"");
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceTest.java
deleted file mode 100644
index 4d2f781..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/SensorResourceTest.java
+++ /dev/null
@@ -1,271 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-
-import java.util.Map;
-
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.core.config.render.RendererHints;
-import org.apache.brooklyn.core.entity.EntityInternal;
-import org.apache.brooklyn.core.entity.EntityPredicates;
-import org.apache.brooklyn.core.sensor.Sensors;
-import org.apache.brooklyn.rest.api.SensorApi;
-import org.apache.brooklyn.rest.domain.ApplicationSpec;
-import org.apache.brooklyn.rest.domain.EntitySpec;
-import org.apache.brooklyn.rest.test.config.render.TestRendererHints;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.http.HttpAsserts;
-import org.apache.brooklyn.util.stream.Streams;
-import org.apache.brooklyn.util.text.StringFunctions;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Functions;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.GenericType;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.api.client.WebResource.Builder;
-
-/**
- * Test the {@link SensorApi} implementation.
- * <p>
- * Check that {@link SensorResource} correctly renders {@link AttributeSensor}
- * values, including {@link RendererHints.DisplayValue} hints.
- */
-@Test(singleThreaded = true)
-public class SensorResourceTest extends BrooklynRestResourceTest {
-
- final static ApplicationSpec SIMPLE_SPEC = ApplicationSpec.builder()
- .name("simple-app")
- .entities(ImmutableSet.of(new EntitySpec("simple-ent", RestMockSimpleEntity.class.getName())))
- .locations(ImmutableSet.of("localhost"))
- .build();
-
- static final String SENSORS_ENDPOINT = "/v1/applications/simple-app/entities/simple-ent/sensors";
- static final String SENSOR_NAME = "amphibian.count";
- static final AttributeSensor<Integer> SENSOR = Sensors.newIntegerSensor(SENSOR_NAME);
-
- EntityInternal entity;
-
- /**
- * Sets up the application and entity.
- * <p>
- * Adds a sensor and sets its value to {@code 12345}. Configures a display value
- * hint that appends {@code frogs} to the value of the sensor.
- */
- @BeforeClass(alwaysRun = true)
- @Override
- public void setUp() throws Exception {
- super.setUp();
-
- // Deploy application
- ClientResponse deploy = clientDeploy(SIMPLE_SPEC);
- waitForApplicationToBeRunning(deploy.getLocation());
-
- entity = (EntityInternal) Iterables.find(getManagementContext().getEntityManager().getEntities(), EntityPredicates.displayNameEqualTo("simple-ent"));
- addAmphibianSensor(entity);
- }
-
- static void addAmphibianSensor(EntityInternal entity) {
- // Add new sensor
- entity.getMutableEntityType().addSensor(SENSOR);
- entity.sensors().set(SENSOR, 12345);
-
- // Register display value hint
- RendererHints.register(SENSOR, RendererHints.displayValue(Functions.compose(StringFunctions.append(" frogs"), Functions.toStringFunction())));
- }
-
- @AfterClass(alwaysRun = true)
- @Override
- public void tearDown() throws Exception {
- TestRendererHints.clearRegistry();
- super.tearDown();
- }
-
- /** Check default is to use display value hint. */
- @Test
- public void testBatchSensorRead() throws Exception {
- ClientResponse response = client().resource(SENSORS_ENDPOINT + "/current-state")
- .accept(MediaType.APPLICATION_JSON)
- .get(ClientResponse.class);
- Map<String, ?> currentState = response.getEntity(new GenericType<Map<String,?>>(Map.class) {});
-
- for (String sensor : currentState.keySet()) {
- if (sensor.equals(SENSOR_NAME)) {
- assertEquals(currentState.get(sensor), "12345 frogs");
- }
- }
- }
-
- /** Check setting {@code raw} to {@code true} ignores display value hint. */
- @Test(dependsOnMethods = "testBatchSensorRead")
- public void testBatchSensorReadRaw() throws Exception {
- ClientResponse response = client().resource(SENSORS_ENDPOINT + "/current-state")
- .queryParam("raw", "true")
- .accept(MediaType.APPLICATION_JSON)
- .get(ClientResponse.class);
- Map<String, ?> currentState = response.getEntity(new GenericType<Map<String,?>>(Map.class) {});
-
- for (String sensor : currentState.keySet()) {
- if (sensor.equals(SENSOR_NAME)) {
- assertEquals(currentState.get(sensor), Integer.valueOf(12345));
- }
- }
- }
-
- protected ClientResponse doSensorTest(Boolean raw, MediaType acceptsType, Object expectedValue) {
- return doSensorTestUntyped(
- raw==null ? null : (""+raw).toLowerCase(),
- acceptsType==null ? null : new String[] { acceptsType.getType() },
- expectedValue);
- }
- protected ClientResponse doSensorTestUntyped(String raw, String[] acceptsTypes, Object expectedValue) {
- WebResource req = client().resource(SENSORS_ENDPOINT + "/" + SENSOR_NAME);
- if (raw!=null) req = req.queryParam("raw", raw);
- ClientResponse response;
- if (acceptsTypes!=null) {
- Builder rb = req.accept(acceptsTypes);
- response = rb.get(ClientResponse.class);
- } else {
- response = req.get(ClientResponse.class);
- }
- if (expectedValue!=null) {
- HttpAsserts.assertHealthyStatusCode(response.getStatus());
- Object value = response.getEntity(expectedValue.getClass());
- assertEquals(value, expectedValue);
- }
- return response;
- }
-
- /**
- * Check we can get a sensor, explicitly requesting json; gives a string picking up the rendering hint.
- *
- * If no "Accepts" header is given, then we don't control whether json or plain text comes back.
- * It is dependent on the method order, which is compiler-specific.
- */
- @Test
- public void testGetJson() throws Exception {
- doSensorTest(null, MediaType.APPLICATION_JSON_TYPE, "\"12345 frogs\"");
- }
-
- @Test
- public void testGetJsonBytes() throws Exception {
- ClientResponse response = doSensorTest(null, MediaType.APPLICATION_JSON_TYPE, null);
- byte[] bytes = Streams.readFully(response.getEntityInputStream());
- // assert we have one set of surrounding quotes
- assertEquals(bytes.length, 13);
- }
-
- /** Check that plain returns a string without quotes, with the rendering hint */
- @Test
- public void testGetPlain() throws Exception {
- doSensorTest(null, MediaType.TEXT_PLAIN_TYPE, "12345 frogs");
- }
-
- /**
- * Check that when we set {@code raw = true}, the result ignores the display value hint.
- *
- * If no "Accepts" header is given, then we don't control whether json or plain text comes back.
- * It is dependent on the method order, which is compiler-specific.
- */
- @Test
- public void testGetRawJson() throws Exception {
- doSensorTest(true, MediaType.APPLICATION_JSON_TYPE, 12345);
- }
-
- /** As {@link #testGetRaw()} but with plain set, returns the number */
- @Test
- public void testGetPlainRaw() throws Exception {
- // have to pass a string because that's how PLAIN is deserialized
- doSensorTest(true, MediaType.TEXT_PLAIN_TYPE, "12345");
- }
-
- /** Check explicitly setting {@code raw} to {@code false} is as before */
- @Test
- public void testGetPlainRawFalse() throws Exception {
- doSensorTest(false, MediaType.TEXT_PLAIN_TYPE, "12345 frogs");
- }
-
- /** Check empty vaue for {@code raw} will revert to using default. */
- @Test
- public void testGetPlainRawEmpty() throws Exception {
- doSensorTestUntyped("", new String[] { MediaType.TEXT_PLAIN }, "12345 frogs");
- }
-
- /** Check unparseable vaue for {@code raw} will revert to using default. */
- @Test
- public void testGetPlainRawError() throws Exception {
- doSensorTestUntyped("biscuits", new String[] { MediaType.TEXT_PLAIN }, "12345 frogs");
- }
-
- /** Check we can set a value */
- @Test
- public void testSet() throws Exception {
- try {
- ClientResponse response = client().resource(SENSORS_ENDPOINT + "/" + SENSOR_NAME)
- .type(MediaType.APPLICATION_JSON_TYPE)
- .post(ClientResponse.class, 67890);
- assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
-
- assertEquals(entity.getAttribute(SENSOR), (Integer)67890);
-
- String value = client().resource(SENSORS_ENDPOINT + "/" + SENSOR_NAME).accept(MediaType.TEXT_PLAIN_TYPE).get(String.class);
- assertEquals(value, "67890 frogs");
-
- } finally { addAmphibianSensor(entity); }
- }
-
- @Test
- public void testSetFromMap() throws Exception {
- try {
- ClientResponse response = client().resource(SENSORS_ENDPOINT)
- .type(MediaType.APPLICATION_JSON_TYPE)
- .post(ClientResponse.class, MutableMap.of(SENSOR_NAME, 67890));
- assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
-
- assertEquals(entity.getAttribute(SENSOR), (Integer)67890);
-
- } finally { addAmphibianSensor(entity); }
- }
-
- /** Check we can delete a value */
- @Test
- public void testDelete() throws Exception {
- try {
- ClientResponse response = client().resource(SENSORS_ENDPOINT + "/" + SENSOR_NAME)
- .delete(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
-
- String value = client().resource(SENSORS_ENDPOINT + "/" + SENSOR_NAME).accept(MediaType.TEXT_PLAIN_TYPE).get(String.class);
- assertEquals(value, "");
-
- } finally { addAmphibianSensor(entity); }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceIntegrationTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceIntegrationTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceIntegrationTest.java
deleted file mode 100644
index ce3fd37..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceIntegrationTest.java
+++ /dev/null
@@ -1,125 +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.resources;
-
-import static org.apache.brooklyn.util.http.HttpTool.httpClientBuilder;
-import static org.testng.Assert.assertEquals;
-
-import java.net.URI;
-import java.util.Collections;
-import java.util.Map;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.rest.BrooklynRestApiLauncher;
-import org.apache.brooklyn.rest.BrooklynRestApiLauncherTestFixture;
-import org.apache.brooklyn.rest.security.provider.TestSecurityProvider;
-import org.apache.brooklyn.test.HttpTestUtils;
-import org.apache.brooklyn.util.http.HttpTool;
-import org.apache.brooklyn.util.http.HttpToolResponse;
-import org.apache.http.HttpStatus;
-import org.apache.http.auth.UsernamePasswordCredentials;
-import org.apache.http.client.HttpClient;
-import org.eclipse.jetty.server.Server;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableMap;
-
-public class ServerResourceIntegrationTest extends BrooklynRestApiLauncherTestFixture {
-
- /**
- * [sam] Other tests rely on brooklyn.properties not containing security properties so ..
- * I think the best way to test this is to set a security provider, then reload properties
- * and check no authentication is required.
- *
- * [aled] Changing this test so doesn't rely on brooklyn.properties having no security
- * provider (that can lead to failures locally when running just this test). Asserts
- */
- @Test(groups = "Integration")
- public void testSecurityProviderUpdatesWhenPropertiesReloaded() {
- BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
- brooklynProperties.put("brooklyn.webconsole.security.users", "admin");
- brooklynProperties.put("brooklyn.webconsole.security.user.admin.password", "mypassword");
- UsernamePasswordCredentials defaultCredential = new UsernamePasswordCredentials("admin", "mypassword");
-
- ManagementContext mgmt = new LocalManagementContext(brooklynProperties);
-
- try {
- Server server = useServerForTest(BrooklynRestApiLauncher.launcher()
- .managementContext(mgmt)
- .withoutJsgui()
- .securityProvider(TestSecurityProvider.class)
- .start());
- String baseUri = getBaseUri(server);
-
- HttpToolResponse response;
- final URI uri = URI.create(getBaseUri() + "/v1/server/properties/reload");
- final Map<String, String> args = Collections.emptyMap();
-
- // Unauthorised when no credentials, and when default credentials.
- response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).build(), uri, args, args);
- assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED);
-
- response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).credentials(defaultCredential).build(),
- uri, args, args);
- assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED);
-
- // Accepts TestSecurityProvider credentials, and we reload.
- response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).credentials(TestSecurityProvider.CREDENTIAL).build(),
- uri, args, args);
- HttpTestUtils.assertHealthyStatusCode(response.getResponseCode());
-
- // Has no gone back to credentials from brooklynProperties; TestSecurityProvider credentials no longer work
- response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).credentials(defaultCredential).build(),
- uri, args, args);
- HttpTestUtils.assertHealthyStatusCode(response.getResponseCode());
-
- response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).credentials(TestSecurityProvider.CREDENTIAL).build(),
- uri, args, args);
- assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED);
-
- } finally {
- ((ManagementContextInternal)mgmt).terminate();
- }
- }
-
- @Test(groups = "Integration")
- public void testGetUser() throws Exception {
- Server server = useServerForTest(BrooklynRestApiLauncher.launcher()
- .securityProvider(TestSecurityProvider.class)
- .withoutJsgui()
- .start());
- assertEquals(getServerUser(server), TestSecurityProvider.USER);
- }
-
- private String getServerUser(Server server) throws Exception {
- HttpClient client = httpClientBuilder()
- .uri(getBaseUri(server))
- .credentials(TestSecurityProvider.CREDENTIAL)
- .build();
-
- HttpToolResponse response = HttpTool.httpGet(client, URI.create(getBaseUri(server) + "/v1/server/user"),
- ImmutableMap.<String, String>of());
- HttpTestUtils.assertHealthyStatusCode(response.getResponseCode());
- return response.getContentAsString();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceTest.java
deleted file mode 100644
index f84cb80..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerResourceTest.java
+++ /dev/null
@@ -1,168 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.BrooklynVersion;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
-import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessDriver;
-import org.apache.brooklyn.entity.software.base.EmptySoftwareProcessImpl;
-import org.apache.brooklyn.rest.domain.HighAvailabilitySummary;
-import org.apache.brooklyn.rest.domain.VersionSummary;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableSet;
-import com.sun.jersey.api.client.UniformInterfaceException;
-
-@Test(singleThreaded = true)
-public class ServerResourceTest extends BrooklynRestResourceTest {
-
- private static final Logger log = LoggerFactory.getLogger(ServerResourceTest.class);
-
- @Test
- public void testGetVersion() throws Exception {
- VersionSummary version = client().resource("/v1/server/version").get(VersionSummary.class);
- assertEquals(version.getVersion(), BrooklynVersion.get());
- }
-
- @Test
- public void testGetStatus() throws Exception {
- String status = client().resource("/v1/server/status").get(String.class);
- assertEquals(status, "MASTER");
- }
-
- @Test
- public void testGetHighAvailability() throws Exception {
- // Note by default management context from super is started without HA enabled.
- // Therefore can only assert a minimal amount of stuff.
- HighAvailabilitySummary summary = client().resource("/v1/server/highAvailability").get(HighAvailabilitySummary.class);
- log.info("HA summary is: "+summary);
-
- String ownNodeId = getManagementContext().getManagementNodeId();
- assertEquals(summary.getOwnId(), ownNodeId);
- assertEquals(summary.getMasterId(), ownNodeId);
- assertEquals(summary.getNodes().keySet(), ImmutableSet.of(ownNodeId));
- assertEquals(summary.getNodes().get(ownNodeId).getNodeId(), ownNodeId);
- assertEquals(summary.getNodes().get(ownNodeId).getStatus(), "MASTER");
- assertNotNull(summary.getNodes().get(ownNodeId).getLocalTimestamp());
- // remote will also be non-null if there is no remote backend (local is re-used)
- assertNotNull(summary.getNodes().get(ownNodeId).getRemoteTimestamp());
- assertEquals(summary.getNodes().get(ownNodeId).getLocalTimestamp(), summary.getNodes().get(ownNodeId).getRemoteTimestamp());
- }
-
- @SuppressWarnings("serial")
- @Test
- public void testReloadsBrooklynProperties() throws Exception {
- final AtomicInteger reloadCount = new AtomicInteger();
- getManagementContext().addPropertiesReloadListener(new ManagementContext.PropertiesReloadListener() {
- @Override public void reloaded() {
- reloadCount.incrementAndGet();
- }});
- client().resource("/v1/server/properties/reload").post();
- assertEquals(reloadCount.get(), 1);
- }
-
- @Test
- void testGetConfig() throws Exception {
- ((ManagementContextInternal)getManagementContext()).getBrooklynProperties().put("foo.bar.baz", "quux");
- try {
- assertEquals(client().resource("/v1/server/config/foo.bar.baz").get(String.class), "quux");
- } finally {
- ((ManagementContextInternal)getManagementContext()).getBrooklynProperties().remove("foo.bar.baz");
- }
- }
-
- @Test
- void testGetMissingConfigThrowsException() throws Exception {
- final String key = "foo.bar.baz";
- BrooklynProperties properties = ((ManagementContextInternal)getManagementContext()).getBrooklynProperties();
- Object existingValue = null;
- boolean keyAlreadyPresent = false;
- String response = null;
- if (properties.containsKey(key)) {
- existingValue = properties.remove(key);
- keyAlreadyPresent = true;
- }
- try {
- response = client().resource("/v1/server/config/" + key).get(String.class);
- Asserts.fail("Expected call to /v1/server/config/" + key + " to fail with status 404, instead server returned " + response);
- } catch (UniformInterfaceException e) {
- assertEquals(e.getResponse().getStatus(), 204);
- } finally {
- if (keyAlreadyPresent) {
- properties.put(key, existingValue);
- }
- }
- }
-
- // Alternatively could reuse a blocking location, see org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest.ReleaseLatchLocation
- @ImplementedBy(StopLatchEntityImpl.class)
- public interface StopLatchEntity extends EmptySoftwareProcess {
- public void unblock();
- public boolean isBlocked();
- }
-
- public static class StopLatchEntityImpl extends EmptySoftwareProcessImpl implements StopLatchEntity {
- private CountDownLatch lock = new CountDownLatch(1);
- private volatile boolean isBlocked;
-
- @Override
- public void unblock() {
- lock.countDown();
- }
-
- @Override
- protected void postStop() {
- super.preStop();
- try {
- isBlocked = true;
- lock.await();
- isBlocked = false;
- } catch (InterruptedException e) {
- throw Exceptions.propagate(e);
- }
- }
-
- @Override
- public Class<?> getDriverInterface() {
- return EmptySoftwareProcessDriver.class;
- }
-
- @Override
- public boolean isBlocked() {
- return isBlocked;
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerShutdownTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerShutdownTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerShutdownTest.java
deleted file mode 100644
index dbe9afd..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ServerShutdownTest.java
+++ /dev/null
@@ -1,185 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertTrue;
-
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.ws.rs.core.MultivaluedMap;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.mgmt.EntityManager;
-import org.apache.brooklyn.api.mgmt.Task;
-import org.apache.brooklyn.core.entity.Attributes;
-import org.apache.brooklyn.core.entity.EntityAsserts;
-import org.apache.brooklyn.core.entity.drivers.BasicEntityDriverManager;
-import org.apache.brooklyn.core.entity.drivers.ReflectiveEntityDriverFactory;
-import org.apache.brooklyn.core.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.core.entity.trait.Startable;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.rest.resources.ServerResourceTest.StopLatchEntity;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.sun.jersey.core.util.MultivaluedMapImpl;
-
-public class ServerShutdownTest extends BrooklynRestResourceTest {
- private static final Logger log = LoggerFactory.getLogger(ServerResourceTest.class);
-
- // Need to initialise the ManagementContext before each test as it is destroyed.
- @Override
- @BeforeClass(alwaysRun = true)
- public void setUp() throws Exception {
- }
-
- @Override
- @AfterClass(alwaysRun = true)
- public void tearDown() throws Exception {
- }
-
- @Override
- @BeforeMethod(alwaysRun = true)
- public void setUpMethod() {
- setUpJersey();
- super.setUpMethod();
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDownMethod() {
- tearDownJersey();
- destroyManagementContext();
- }
-
- @Test
- public void testShutdown() throws Exception {
- assertTrue(getManagementContext().isRunning());
- assertFalse(shutdownListener.isRequested());
-
- MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
- formData.add("requestTimeout", "0");
- formData.add("delayForHttpReturn", "0");
- client().resource("/v1/server/shutdown").entity(formData).post();
-
- Asserts.succeedsEventually(new Runnable() {
- @Override
- public void run() {
- assertTrue(shutdownListener.isRequested());
- }
- });
- Asserts.succeedsEventually(new Runnable() {
- @Override public void run() {
- assertFalse(getManagementContext().isRunning());
- }});
- }
-
- @Test
- public void testStopAppThenShutdownAndStopAppsWaitsForFirstStop() throws InterruptedException {
- ReflectiveEntityDriverFactory f = ((BasicEntityDriverManager)getManagementContext().getEntityDriverManager()).getReflectiveDriverFactory();
- f.addClassFullNameMapping("org.apache.brooklyn.entity.software.base.EmptySoftwareProcessDriver", "org.apache.brooklyn.rest.resources.ServerResourceTest$EmptySoftwareProcessTestDriver");
-
- // Second stop on SoftwareProcess could return early, while the first stop is still in progress
- // This causes the app to shutdown prematurely, leaking machines.
- EntityManager emgr = getManagementContext().getEntityManager();
- EntitySpec<TestApplication> appSpec = EntitySpec.create(TestApplication.class);
- TestApplication app = emgr.createEntity(appSpec);
- emgr.manage(app);
- EntitySpec<StopLatchEntity> latchEntitySpec = EntitySpec.create(StopLatchEntity.class);
- final StopLatchEntity entity = app.createAndManageChild(latchEntitySpec);
- app.start(ImmutableSet.of(app.newLocalhostProvisioningLocation()));
- EntityAsserts.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
-
- try {
- final Task<Void> firstStop = app.invoke(Startable.STOP, ImmutableMap.<String, Object>of());
- Asserts.succeedsEventually(new Runnable() {
- @Override
- public void run() {
- assertTrue(entity.isBlocked());
- }
- });
-
- final AtomicReference<Exception> shutdownError = new AtomicReference<>();
- // Can't use ExecutionContext as it will be stopped on shutdown
- Thread shutdownThread = new Thread() {
- @Override
- public void run() {
- try {
- MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
- formData.add("stopAppsFirst", "true");
- formData.add("shutdownTimeout", "0");
- formData.add("requestTimeout", "0");
- formData.add("delayForHttpReturn", "0");
- client().resource("/v1/server/shutdown").entity(formData).post();
- } catch (Exception e) {
- log.error("Shutdown request error", e);
- shutdownError.set(e);
- throw Exceptions.propagate(e);
- }
- }
- };
- shutdownThread.start();
-
- //shutdown must wait until the first stop completes (or time out)
- Asserts.succeedsContinually(new Runnable() {
- @Override
- public void run() {
- assertFalse(firstStop.isDone());
- assertEquals(getManagementContext().getApplications().size(), 1);
- assertFalse(shutdownListener.isRequested());
- }
- });
-
- // NOTE test is not fully deterministic. Depending on thread scheduling this will
- // execute before or after ServerResource.shutdown does the app stop loop. This
- // means that the shutdown code might not see the app at all. In any case though
- // the test must succeed.
- entity.unblock();
-
- Asserts.succeedsEventually(new Runnable() {
- @Override
- public void run() {
- assertTrue(firstStop.isDone());
- assertTrue(shutdownListener.isRequested());
- assertFalse(getManagementContext().isRunning());
- }
- });
-
- shutdownThread.join();
- assertNull(shutdownError.get(), "Shutdown request error, logged above");
- } finally {
- // Be sure we always unblock entity stop even in the case of an exception.
- // In the success path the entity is already unblocked above.
- entity.unblock();
- }
- }
-
-}
[6/9] brooklyn-server git commit: Remove jersey compatibility
Posted by sj...@apache.org.
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/SwaggerFilter.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/SwaggerFilter.java b/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/SwaggerFilter.java
deleted file mode 100644
index ce8b747..0000000
--- a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/SwaggerFilter.java
+++ /dev/null
@@ -1,76 +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.filter;
-
-import java.io.IOException;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-
-import org.apache.brooklyn.rest.apidoc.RestApiResourceScanner;
-
-import io.swagger.config.ScannerFactory;
-import io.swagger.models.Info;
-import io.swagger.models.License;
-import io.swagger.models.Swagger;
-
-/**
- * Bootstraps swagger.
- * <p>
- * Swagger was intended to run as a servlet.
- *
- * @author Ciprian Ciubotariu <ch...@gmx.net>
- */
-public class SwaggerFilter implements Filter {
-
- static Info info = new Info()
- .title("Brooklyn API Documentation")
- .version("v1") // API version, not BROOKLYN_VERSION
- .license(new License()
- .name("Apache 2.0")
- .url("http://www.apache.org/licenses/LICENSE-2.0.html"));
-
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
-// ReflectiveJaxrsScanner scanner = new ReflectiveJaxrsScanner();
-// scanner.setResourcePackage("org.apache.brooklyn.rest.api,org.apache.brooklyn.rest.apidoc,org.apache.brooklyn.rest.resources");
-// ScannerFactory.setScanner(scanner);
- ScannerFactory.setScanner(new RestApiResourceScanner());
-
- ServletContext context = filterConfig.getServletContext();
- Swagger swagger = new Swagger()
- .info(info);
- context.setAttribute("swagger", swagger);
- }
-
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- chain.doFilter(request, response);
- }
-
- @Override
- public void destroy() {
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/resources/ApiListingResource.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/resources/ApiListingResource.java b/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/resources/ApiListingResource.java
deleted file mode 100644
index 74f8426..0000000
--- a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/resources/ApiListingResource.java
+++ /dev/null
@@ -1,260 +0,0 @@
-/*
- * Copyright 2015 The Apache Software Foundation.
- *
- * 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 org.apache.brooklyn.rest.resources;
-
-import com.sun.jersey.spi.container.servlet.WebConfig;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.config.FilterFactory;
-import io.swagger.config.Scanner;
-import io.swagger.config.ScannerFactory;
-import io.swagger.config.SwaggerConfig;
-import io.swagger.core.filter.SpecFilter;
-import io.swagger.core.filter.SwaggerSpecFilter;
-import io.swagger.jaxrs.Reader;
-import io.swagger.jaxrs.config.JaxrsScanner;
-import io.swagger.jaxrs.config.ReaderConfigUtils;
-import io.swagger.jaxrs.listing.SwaggerSerializers;
-import io.swagger.models.Swagger;
-import io.swagger.util.Yaml;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Cookie;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * ApiListingResource usable within a jersey servlet filter.
- *
- * Taken from io.swagger:swagger-jaxrs, class
- * io.swagger.jaxrs.listing.ApiListingResource, which can only be used within a
- * servlet context. We are here using a filter, but jersey has a WebConfig class
- * that can substitute ServletConfig and FilterConfig.
- *
- * @todo Remove when the rest-server is no longer running within a filter (e.g.
- * as a standalone OSGi http service)
- *
- * @author Ciprian Ciubotariu <ch...@gmx.net>
- */
-public class ApiListingResource {
-
- static Logger LOGGER = LoggerFactory.getLogger(ApiListingResource.class);
-
- @Context
- ServletContext context;
-
- boolean initialized = false;
-
- private static class ServletConfigAdapter implements ServletConfig {
-
- private final WebConfig webConfig;
-
- private ServletConfigAdapter(WebConfig webConfig) {
- this.webConfig = webConfig;
- }
-
- @Override
- public String getServletName() {
- return webConfig.getName();
- }
-
- @Override
- public ServletContext getServletContext() {
- return webConfig.getServletContext();
- }
-
- @Override
- public String getInitParameter(String name) {
- return webConfig.getInitParameter(name);
- }
-
- @Override
- public Enumeration<String> getInitParameterNames() {
- return webConfig.getInitParameterNames();
- }
-
- }
-
- protected synchronized Swagger scan(Application app, WebConfig sc) {
- Swagger swagger = null;
- Scanner scanner = ScannerFactory.getScanner();
- LOGGER.debug("using scanner " + scanner);
-
- if (scanner != null) {
- SwaggerSerializers.setPrettyPrint(scanner.getPrettyPrint());
- swagger = (Swagger) context.getAttribute("swagger");
-
- Set<Class<?>> classes;
- if (scanner instanceof JaxrsScanner) {
- JaxrsScanner jaxrsScanner = (JaxrsScanner) scanner;
- classes = jaxrsScanner.classesFromContext(app, new ServletConfigAdapter(sc));
- } else {
- classes = scanner.classes();
- }
- if (classes != null) {
- Reader reader = new Reader(swagger, ReaderConfigUtils.getReaderConfig(context));
- swagger = reader.read(classes);
- if (scanner instanceof SwaggerConfig) {
- swagger = ((SwaggerConfig) scanner).configure(swagger);
- } else {
- SwaggerConfig configurator = (SwaggerConfig) context.getAttribute("reader");
- if (configurator != null) {
- LOGGER.debug("configuring swagger with " + configurator);
- configurator.configure(swagger);
- } else {
- LOGGER.debug("no configurator");
- }
- }
- context.setAttribute("swagger", swagger);
- }
- }
- initialized = true;
- return swagger;
- }
-
- private Swagger process(
- Application app,
- WebConfig sc,
- HttpHeaders headers,
- UriInfo uriInfo) {
- Swagger swagger = (Swagger) context.getAttribute("swagger");
- if (!initialized) {
- swagger = scan(app, sc);
- }
- if (swagger != null) {
- SwaggerSpecFilter filterImpl = FilterFactory.getFilter();
- if (filterImpl != null) {
- SpecFilter f = new SpecFilter();
- swagger = f.filter(swagger, filterImpl, getQueryParams(uriInfo.getQueryParameters()), getCookies(headers),
- getHeaders(headers));
- }
- }
- return swagger;
- }
-
- @GET
- @Produces({MediaType.APPLICATION_JSON, "application/yaml"})
- @ApiOperation(value = "The swagger definition in either JSON or YAML", hidden = true)
- @Path("/swagger.{type:json|yaml}")
- public Response getListing(
- @Context Application app,
- @Context WebConfig sc,
- @Context HttpHeaders headers,
- @Context UriInfo uriInfo,
- @PathParam("type") String type) {
- if (Strings.isNonBlank(type) && type.trim().equalsIgnoreCase("yaml")) {
- return getListingYaml(app, sc, headers, uriInfo);
- } else {
- return getListingJson(app, sc, headers, uriInfo);
- }
- }
-
- @GET
- @Produces({MediaType.APPLICATION_JSON})
- @Path("/swagger")
- @ApiOperation(value = "The swagger definition in JSON", hidden = true)
- public Response getListingJson(
- @Context Application app,
- @Context WebConfig sc,
- @Context HttpHeaders headers,
- @Context UriInfo uriInfo) {
- Swagger swagger = process(app, sc, headers, uriInfo);
-
- if (swagger != null) {
- return Response.ok().entity(swagger).build();
- } else {
- return Response.status(404).build();
- }
- }
-
- @GET
- @Produces("application/yaml")
- @Path("/swagger")
- @ApiOperation(value = "The swagger definition in YAML", hidden = true)
- public Response getListingYaml(
- @Context Application app,
- @Context WebConfig sc,
- @Context HttpHeaders headers,
- @Context UriInfo uriInfo) {
- Swagger swagger = process(app, sc, headers, uriInfo);
- try {
- if (swagger != null) {
- String yaml = Yaml.mapper().writeValueAsString(swagger);
- StringBuilder b = new StringBuilder();
- String[] parts = yaml.split("\n");
- for (String part : parts) {
- b.append(part);
- b.append("\n");
- }
- return Response.ok().entity(b.toString()).type("application/yaml").build();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return Response.status(404).build();
- }
-
- protected Map<String, List<String>> getQueryParams(MultivaluedMap<String, String> params) {
- Map<String, List<String>> output = new HashMap<>();
- if (params != null) {
- for (String key : params.keySet()) {
- List<String> values = params.get(key);
- output.put(key, values);
- }
- }
- return output;
- }
-
- protected Map<String, String> getCookies(HttpHeaders headers) {
- Map<String, String> output = new HashMap<>();
- if (headers != null) {
- for (String key : headers.getCookies().keySet()) {
- Cookie cookie = headers.getCookies().get(key);
- output.put(key, cookie.getValue());
- }
- }
- return output;
- }
-
- protected Map<String, List<String>> getHeaders(HttpHeaders headers) {
- Map<String, List<String>> output = new HashMap<>();
- if (headers != null) {
- for (String key : headers.getRequestHeaders().keySet()) {
- List<String> values = headers.getRequestHeaders().get(key);
- output.put(key, values);
- }
- }
- return output;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/resources/ApidocResource.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/resources/ApidocResource.java b/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/resources/ApidocResource.java
deleted file mode 100644
index 1cf6523..0000000
--- a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/resources/ApidocResource.java
+++ /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.
- */
-package org.apache.brooklyn.rest.resources;
-
-
-import javax.ws.rs.Path;
-
-import io.swagger.annotations.Api;
-
-/**
- * @author Ciprian Ciubotariu <ch...@gmx.net>
- */
-@Api("API Documentation")
-@Path("/apidoc")
-public class ApidocResource extends ApiListingResource {
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/util/FormMapProvider.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/util/FormMapProvider.java b/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/util/FormMapProvider.java
deleted file mode 100644
index 2b5c19b..0000000
--- a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/util/FormMapProvider.java
+++ /dev/null
@@ -1,81 +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.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.util.List;
-import java.util.Map;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.MessageBodyReader;
-import javax.ws.rs.ext.Provider;
-
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.sun.jersey.core.impl.provider.entity.FormMultivaluedMapProvider;
-import com.sun.jersey.core.util.MultivaluedMapImpl;
-
-/**
- * A MessageBodyReader producing a <code>Map<String, Object></code>, where Object
- * is either a <code>String</code>, a <code>List<String></code> or null.
- */
-@Provider
-@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
-public class FormMapProvider implements MessageBodyReader<Map<String, Object>> {
-
- @Override
- public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
- if (!Map.class.equals(type) || !(genericType instanceof ParameterizedType)) {
- return false;
- }
- ParameterizedType parameterized = (ParameterizedType) genericType;
- return parameterized.getActualTypeArguments().length == 2 &&
- parameterized.getActualTypeArguments()[0] == String.class &&
- parameterized.getActualTypeArguments()[1] == Object.class;
- }
-
- @Override
- public Map<String, Object> readFrom(Class<Map<String, Object>> type, Type genericType, Annotation[] annotations,
- MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
- throws IOException, WebApplicationException {
- FormMultivaluedMapProvider delegate = new FormMultivaluedMapProvider();
- MultivaluedMap<String, String> multi = new MultivaluedMapImpl();
- multi = delegate.readFrom(multi, mediaType, entityStream);
-
- Map<String, Object> map = Maps.newHashMapWithExpectedSize(multi.keySet().size());
- for (String key : multi.keySet()) {
- List<String> value = multi.get(key);
- if (value.size() > 1) {
- map.put(key, Lists.newArrayList(value));
- } else if (value.size() == 1) {
- map.put(key, Iterables.getOnlyElement(value));
- } else {
- map.put(key, null);
- }
- }
- return map;
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/main/resources/build-metadata.properties
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/main/resources/build-metadata.properties b/rest/rest-server-jersey/src/main/resources/build-metadata.properties
deleted file mode 100644
index eab85ef..0000000
--- a/rest/rest-server-jersey/src/main/resources/build-metadata.properties
+++ /dev/null
@@ -1,18 +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.
-git-sha-1 = ${buildNumber}
-git-branch-name = ${scmBranch}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/main/webapp/WEB-INF/web.xml
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/main/webapp/WEB-INF/web.xml b/rest/rest-server-jersey/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 40fb79f..0000000
--- a/rest/rest-server-jersey/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,149 +0,0 @@
-<!DOCTYPE web-app PUBLIC
- "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
- "http://java.sun.com/dtd/web-app_2_3.dtd" >
-<!--
- 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.
--->
-<web-app>
- <display-name>Brooklyn REST API v1</display-name>
-
- <filter>
- <filter-name>Brooklyn Request Tagging Filter</filter-name>
- <filter-class>org.apache.brooklyn.rest.filter.RequestTaggingFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn Request Tagging Filter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <filter>
- <filter-name>Brooklyn Properties Authentication Filter</filter-name>
- <filter-class>org.apache.brooklyn.rest.filter.BrooklynPropertiesSecurityFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn Properties Authentication Filter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <filter>
- <filter-name>Brooklyn Logging Filter</filter-name>
- <filter-class>org.apache.brooklyn.rest.filter.LoggingFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn Logging Filter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <filter>
- <filter-name>Brooklyn HA Master Filter</filter-name>
- <filter-class>org.apache.brooklyn.rest.filter.HaMasterCheckFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn HA Master Filter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <filter>
- <filter-name>Brooklyn Swagger Bootstrap</filter-name>
- <filter-class>org.apache.brooklyn.rest.filter.SwaggerFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn Swagger Bootstrap</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <!-- Brooklyn REST is usually run as a filter so static content can be placed in a webapp
- to which this is added; to run as a servlet directly, replace the filter tags
- below (after the comment) with the servlet tags (commented out immediately below),
- (and do the same for the matching tags at the bottom)
- <servlet>
- <servlet-name>Brooklyn REST API v1 Servlet</servlet-name>
- <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
- -->
- <filter>
- <filter-name>Brooklyn REST API v1 Filter</filter-name>
- <filter-class>com.sun.jersey.spi.container.servlet.ServletContainer</filter-class>
-
- <!-- load our REST API jersey resources explicitly
- (the package scanner will only pick up classes with @Path annotations - doesn't look at implemented interfaces)
- -->
- <init-param>
- <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
- <param-value>com.sun.jersey.api.core.ClassNamesResourceConfig</param-value>
- </init-param>
- <init-param>
- <param-name>com.sun.jersey.config.property.classnames</param-name>
- <param-value>
- io.swagger.jaxrs.listing.SwaggerSerializers;
- org.apache.brooklyn.rest.util.FormMapProvider;
- com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
- org.apache.brooklyn.rest.filter.RequestTaggingRsFilter;
- org.apache.brooklyn.rest.filter.NoCacheFilter;
- org.apache.brooklyn.rest.filter.HaHotCheckResourceFilter;
- org.apache.brooklyn.rest.filter.EntitlementContextFilter;
- org.apache.brooklyn.rest.util.ManagementContextProvider;
- org.apache.brooklyn.rest.resources.AccessResource;
- 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.ServerResource;
- org.apache.brooklyn.rest.resources.UsageResource;
- org.apache.brooklyn.rest.resources.VersionResource;
- </param-value>
- </init-param>
-
- <init-param>
- <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
- <param-value>true</param-value>
- </init-param>
-
- <!-- no need for WADL. of course you can turn it back on it you want. -->
- <init-param>
- <param-name>com.sun.jersey.config.feature.DisableWADL</param-name>
- <param-value>true</param-value>
- </init-param>
-
- <init-param>
- <param-name>com.sun.jersey.config.feature.FilterContextPath</param-name>
- <param-value>/v1</param-value>
- </init-param>
-
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn REST API v1 Filter</filter-name>
- <url-pattern>/v1/*</url-pattern>
- </filter-mapping>
- <!-- Brooklyn REST as a filter above; replace above 5 lines with those commented out below,
- to run it as a servlet (see note above)
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>Brooklyn REST API v1 Servlet</servlet-name>
- <url-pattern>/*</url-pattern>
- </servlet-mapping>
- -->
-</web-app>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynPropertiesSecurityFilterTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynPropertiesSecurityFilterTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynPropertiesSecurityFilterTest.java
deleted file mode 100644
index e855841..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynPropertiesSecurityFilterTest.java
+++ /dev/null
@@ -1,151 +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;
-
-import static org.testng.Assert.assertTrue;
-
-import java.net.URI;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.http.HttpHeaders;
-import org.apache.http.NameValuePair;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.utils.URLEncodedUtils;
-import org.apache.http.entity.ContentType;
-import org.apache.http.message.BasicNameValuePair;
-import org.eclipse.jetty.server.Server;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.rest.security.provider.AnyoneSecurityProvider;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.http.HttpTool;
-import org.apache.brooklyn.util.http.HttpToolResponse;
-import org.apache.brooklyn.util.time.Time;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.common.base.Charsets;
-import com.google.common.base.Stopwatch;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-
-public class BrooklynPropertiesSecurityFilterTest extends BrooklynRestApiLauncherTestFixture {
-
- private static final Logger LOG = LoggerFactory.getLogger(BrooklynPropertiesSecurityFilterTest.class);
-
- /*
- Exception java.lang.AssertionError
-
- Message: error creating app. response code=400 expected [true] but found [false]
- Stacktrace:
-
-
- at org.testng.Assert.fail(Assert.java:94)
- at org.testng.Assert.failNotEquals(Assert.java:494)
- at org.testng.Assert.assertTrue(Assert.java:42)
- at org.apache.brooklyn.rest.BrooklynPropertiesSecurityFilterTest.startAppAtNode(BrooklynPropertiesSecurityFilterTest.java:94)
- at org.apache.brooklyn.rest.BrooklynPropertiesSecurityFilterTest.testInteractionOfSecurityFilterAndFormMapProvider(BrooklynPropertiesSecurityFilterTest.java:64)
- at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
- at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
- at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
- at java.lang.reflect.Method.invoke(Method.java:606)
- at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
- at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
- at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
- at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
- at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
- at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
- at org.testng.TestRunner.privateRun(TestRunner.java:767)
- at org.testng.TestRunner.run(TestRunner.java:617)
- at org.testng.SuiteRunner.runTest(SuiteRunner.java:348)
- at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343)
- at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305)
- at org.testng.SuiteRunner.run(SuiteRunner.java:254)
- at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
- at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
- at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
- at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
- at org.testng.TestNG.run(TestNG.java:1057)
- at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:115)
- at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeMulti(TestNGDirectoryTestSuite.java:205)
- at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:108)
- at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:111)
- at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
- at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
- at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
- */
- // Would be great for this to be a unit test but it takes almost ten seconds.
- @Test(groups = {"Integration","Broken"})
- public void testInteractionOfSecurityFilterAndFormMapProvider() throws Exception {
- Stopwatch stopwatch = Stopwatch.createStarted();
- try {
- Server server = useServerForTest(BrooklynRestApiLauncher.launcher()
- .securityProvider(AnyoneSecurityProvider.class)
- .forceUseOfDefaultCatalogWithJavaClassPath(true)
- .withoutJsgui()
- .start());
- String appId = startAppAtNode(server);
- String entityId = getTestEntityInApp(server, appId);
- HttpClient client = HttpTool.httpClientBuilder()
- .uri(getBaseUri(server))
- .build();
- List<? extends NameValuePair> nvps = Lists.newArrayList(
- new BasicNameValuePair("arg", "bar"));
- String effector = String.format("/v1/applications/%s/entities/%s/effectors/identityEffector", appId, entityId);
- HttpToolResponse response = HttpTool.httpPost(client, URI.create(getBaseUri() + effector),
- ImmutableMap.of(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType()),
- URLEncodedUtils.format(nvps, Charsets.UTF_8).getBytes());
-
- LOG.info("Effector response: {}", response.getContentAsString());
- assertTrue(HttpTool.isStatusCodeHealthy(response.getResponseCode()), "response code=" + response.getResponseCode());
- } finally {
- LOG.info("testInteractionOfSecurityFilterAndFormMapProvider complete in " + Time.makeTimeStringRounded(stopwatch));
- }
- }
-
- private String startAppAtNode(Server server) throws Exception {
- String blueprint = "name: TestApp\n" +
- "location: localhost\n" +
- "services:\n" +
- "- type: org.apache.brooklyn.test.entity.TestEntity";
- HttpClient client = HttpTool.httpClientBuilder()
- .uri(getBaseUri(server))
- .build();
- HttpToolResponse response = HttpTool.httpPost(client, URI.create(getBaseUri() + "/v1/applications"),
- ImmutableMap.of(HttpHeaders.CONTENT_TYPE, "application/x-yaml"),
- blueprint.getBytes());
- assertTrue(HttpTool.isStatusCodeHealthy(response.getResponseCode()), "error creating app. response code=" + response.getResponseCode());
- @SuppressWarnings("unchecked")
- Map<String, Object> body = new ObjectMapper().readValue(response.getContent(), HashMap.class);
- return (String) body.get("entityId");
- }
-
- @SuppressWarnings("rawtypes")
- private String getTestEntityInApp(Server server, String appId) throws Exception {
- HttpClient client = HttpTool.httpClientBuilder()
- .uri(getBaseUri(server))
- .build();
- List entities = new ObjectMapper().readValue(
- HttpTool.httpGet(client, URI.create(getBaseUri() + "/v1/applications/" + appId + "/entities"), MutableMap.<String, String>of()).getContent(), List.class);
- LOG.info((String) ((Map) entities.get(0)).get("id"));
- return (String) ((Map) entities.get(0)).get("id");
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncher.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncher.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncher.java
deleted file mode 100644
index 8b67b12..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncher.java
+++ /dev/null
@@ -1,498 +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;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.io.File;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.EnumSet;
-import java.util.List;
-
-import javax.servlet.DispatcherType;
-import javax.servlet.Filter;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.camp.brooklyn.BrooklynCampPlatformLauncherAbstract;
-import org.apache.brooklyn.camp.brooklyn.BrooklynCampPlatformLauncherNoServer;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.core.server.BrooklynServerConfig;
-import org.apache.brooklyn.core.server.BrooklynServiceAttributes;
-import org.apache.brooklyn.rest.filter.BrooklynPropertiesSecurityFilter;
-import org.apache.brooklyn.rest.filter.HaMasterCheckFilter;
-import org.apache.brooklyn.rest.filter.LoggingFilter;
-import org.apache.brooklyn.rest.filter.NoCacheFilter;
-import org.apache.brooklyn.rest.filter.RequestTaggingFilter;
-import org.apache.brooklyn.rest.filter.SwaggerFilter;
-import org.apache.brooklyn.rest.security.provider.AnyoneSecurityProvider;
-import org.apache.brooklyn.rest.security.provider.SecurityProvider;
-import org.apache.brooklyn.rest.util.ManagementContextProvider;
-import org.apache.brooklyn.rest.util.ServerStoppingShutdownHandler;
-import org.apache.brooklyn.rest.util.ShutdownHandlerProvider;
-import org.apache.brooklyn.util.core.osgi.Compat;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.text.WildcardGlobs;
-import org.eclipse.jetty.server.NetworkConnector;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.handler.ContextHandler;
-import org.eclipse.jetty.servlet.FilterHolder;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-import org.eclipse.jetty.servlet.ServletHolder;
-import org.eclipse.jetty.webapp.WebAppContext;
-import org.reflections.util.ClasspathHelper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Charsets;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-import com.google.common.io.Files;
-import com.sun.jersey.api.core.DefaultResourceConfig;
-import com.sun.jersey.api.core.ResourceConfig;
-import com.sun.jersey.spi.container.servlet.ServletContainer;
-
-/** Convenience and demo for launching programmatically. Also used for automated tests.
- * <p>
- * BrooklynLauncher has a more full-featured CLI way to start,
- * but if you want more control you can:
- * <li> take the WAR this project builds (REST API) -- NB probably want the unshaded one (containing all deps)
- * <li> take the WAR from the brooklyn-jsgui project (brooklyn-ui repo) _and_ this WAR and combine them
- * (this one should run as a filter on the others, _not_ as a ResourceCollection where they fight over who's got root)
- * <li> programmatically install things, following the examples herein;
- * in particular {@link #installAsServletFilter(ServletContextHandler)} is quite handy!
- * <p>
- * You can also just run this class. In most installs it just works, assuming your IDE or maven-fu gives you the classpath.
- * Add more apps and entities on the classpath and they'll show up in the catalog.
- **/
-public class BrooklynRestApiLauncher {
-
- private static final Logger log = LoggerFactory.getLogger(BrooklynRestApiLauncher.class);
- final static int FAVOURITE_PORT = 8081;
- public static final String SCANNING_CATALOG_BOM_URL = "classpath://brooklyn/scanning.catalog.bom";
-
- enum StartMode {
- FILTER, SERVLET, /** web-xml is not fully supported */ @Beta WEB_XML
- }
-
- public static final List<Class<? extends Filter>> DEFAULT_FILTERS = ImmutableList.of(
- RequestTaggingFilter.class,
- BrooklynPropertiesSecurityFilter.class,
- LoggingFilter.class,
- HaMasterCheckFilter.class,
- SwaggerFilter.class);
-
- private boolean forceUseOfDefaultCatalogWithJavaClassPath = false;
- private Class<? extends SecurityProvider> securityProvider;
- private List<Class<? extends Filter>> filters = DEFAULT_FILTERS;
- private StartMode mode = StartMode.FILTER;
- private ManagementContext mgmt;
- private ContextHandler customContext;
- private boolean deployJsgui = true;
- private boolean disableHighAvailability = true;
- private ServerStoppingShutdownHandler shutdownListener;
-
- protected BrooklynRestApiLauncher() {}
-
- public BrooklynRestApiLauncher managementContext(ManagementContext mgmt) {
- this.mgmt = mgmt;
- return this;
- }
-
- public BrooklynRestApiLauncher forceUseOfDefaultCatalogWithJavaClassPath(boolean forceUseOfDefaultCatalogWithJavaClassPath) {
- this.forceUseOfDefaultCatalogWithJavaClassPath = forceUseOfDefaultCatalogWithJavaClassPath;
- return this;
- }
-
- public BrooklynRestApiLauncher securityProvider(Class<? extends SecurityProvider> securityProvider) {
- this.securityProvider = securityProvider;
- return this;
- }
-
- /**
- * Runs the server with the given set of filters.
- * Overrides any previously supplied set (or {@link #DEFAULT_FILTERS} which is used by default).
- */
- public BrooklynRestApiLauncher filters(@SuppressWarnings("unchecked") Class<? extends Filter>... filters) {
- this.filters = Lists.newArrayList(filters);
- return this;
- }
-
- public BrooklynRestApiLauncher mode(StartMode mode) {
- this.mode = checkNotNull(mode, "mode");
- return this;
- }
-
- /** Overrides start mode to use an explicit context */
- public BrooklynRestApiLauncher customContext(ContextHandler customContext) {
- this.customContext = checkNotNull(customContext, "customContext");
- return this;
- }
-
- public BrooklynRestApiLauncher withJsgui() {
- this.deployJsgui = true;
- return this;
- }
-
- public BrooklynRestApiLauncher withoutJsgui() {
- this.deployJsgui = false;
- return this;
- }
-
- public BrooklynRestApiLauncher disableHighAvailability(boolean value) {
- this.disableHighAvailability = value;
- return this;
- }
-
- public Server start() {
- if (this.mgmt == null) {
- mgmt = new LocalManagementContext();
- }
- BrooklynCampPlatformLauncherAbstract platform = new BrooklynCampPlatformLauncherNoServer()
- .useManagementContext(mgmt)
- .launch();
- ((LocalManagementContext)mgmt).noteStartupComplete();
- log.debug("started "+platform);
-
- ContextHandler context;
- String summary;
- if (customContext == null) {
- switch (mode) {
- case SERVLET:
- context = servletContextHandler(mgmt);
- summary = "programmatic Jersey ServletContainer servlet";
- break;
- case WEB_XML:
- context = webXmlContextHandler(mgmt);
- summary = "from WAR at " + ((WebAppContext) context).getWar();
- break;
- case FILTER:
- default:
- context = filterContextHandler(mgmt);
- summary = "programmatic Jersey ServletContainer filter on webapp at " + ((WebAppContext) context).getWar();
- break;
- }
- } else {
- context = customContext;
- summary = (context instanceof WebAppContext)
- ? "from WAR at " + ((WebAppContext) context).getWar()
- : "from custom context";
- }
-
- if (securityProvider != null) {
- ((BrooklynProperties) mgmt.getConfig()).put(
- BrooklynWebConfig.SECURITY_PROVIDER_CLASSNAME, securityProvider.getName());
- }
-
- if (forceUseOfDefaultCatalogWithJavaClassPath) {
- // sets URLs for a surefire
- ((BrooklynProperties) mgmt.getConfig()).put(BrooklynServerConfig.BROOKLYN_CATALOG_URL, SCANNING_CATALOG_BOM_URL);
- ((LocalManagementContext) mgmt).setBaseClassPathForScanning(ClasspathHelper.forJavaClassPath());
- } else {
- // don't use any catalog.xml which is set
- ((BrooklynProperties) mgmt.getConfig()).put(BrooklynServerConfig.BROOKLYN_CATALOG_URL, ManagementContextInternal.EMPTY_CATALOG_URL);
- }
-
- Server server = startServer(mgmt, context, summary, disableHighAvailability);
- if (shutdownListener!=null) {
- // not available in some modes, eg webapp
- shutdownListener.setServer(server);
- }
- return server;
- }
-
- private ContextHandler filterContextHandler(ManagementContext mgmt) {
- WebAppContext context = new WebAppContext();
- context.setAttribute(BrooklynServiceAttributes.BROOKLYN_MANAGEMENT_CONTEXT, mgmt);
- context.setContextPath("/");
- installWar(context);
- installAsServletFilter(context, this.filters);
- return context;
- }
-
- private void installWar(WebAppContext context) {
- // here we run with the JS GUI, for convenience, if we can find it, else set up an empty dir
- // TODO pretty sure there is an option to monitor this dir and load changes to static content
- // NOTE: When running Brooklyn from an IDE (i.e. by launching BrooklynJavascriptGuiLauncher.main())
- // you will need to ensure that the working directory is set to the brooklyn-ui repo folder. For IntelliJ,
- // set the 'Working directory' of the Run/Debug Configuration to $MODULE_DIR$/brooklyn-server/launcher.
- // For Eclipse, use the default option of ${workspace_loc:brooklyn-launcher}.
- // If the working directory is not set correctly, Brooklyn will be unable to find the jsgui .war
- // file and the 'gui not available' message will be shown.
- context.setWar(this.deployJsgui && findJsguiWebappInSource().isPresent()
- ? findJsguiWebappInSource().get()
- : createTempWebDirWithIndexHtml("Brooklyn REST API <p> (gui not available)"));
- }
-
- private ContextHandler servletContextHandler(ManagementContext managementContext) {
- ResourceConfig config = new DefaultResourceConfig();
- for (Object r: BrooklynRestApi.getAllResources())
- config.getSingletons().add(r);
- config.getSingletons().add(new ManagementContextProvider());
- addShutdownListener(config, mgmt);
-
-
- WebAppContext context = new WebAppContext();
- context.setAttribute(BrooklynServiceAttributes.BROOKLYN_MANAGEMENT_CONTEXT, managementContext);
- ServletHolder servletHolder = new ServletHolder(new ServletContainer(config));
- context.addServlet(servletHolder, "/v1/*");
- context.setContextPath("/");
-
- installWar(context);
- installBrooklynFilters(context, this.filters);
- return context;
- }
-
- /** NB: not fully supported; use one of the other {@link StartMode}s */
- private ContextHandler webXmlContextHandler(ManagementContext mgmt) {
- // TODO add security to web.xml
- WebAppContext context;
- if (findMatchingFile("src/main/webapp")!=null) {
- // running in source mode; need to use special classpath
- context = new WebAppContext("src/main/webapp", "/");
- context.setExtraClasspath("./target/classes");
- } else if (findRestApiWar()!=null) {
- context = new WebAppContext(findRestApiWar(), "/");
- } else {
- throw new IllegalStateException("Cannot find WAR for REST API. Expected in target/*.war, Maven repo, or in source directories.");
- }
- context.setAttribute(BrooklynServiceAttributes.BROOKLYN_MANAGEMENT_CONTEXT, mgmt);
- // TODO shutdown hook
-
- return context;
- }
-
- /** starts a server, on all NICs if security is configured,
- * otherwise (no security) only on loopback interface
- * @deprecated since 0.9.0 becoming private */
- @Deprecated
- public static Server startServer(ManagementContext mgmt, ContextHandler context, String summary, boolean disableHighAvailability) {
- // TODO this repeats code in BrooklynLauncher / WebServer. should merge the two paths.
- boolean secure = mgmt != null && !BrooklynWebConfig.hasNoSecurityOptions(mgmt.getConfig());
- if (secure) {
- log.debug("Detected security configured, launching server on all network interfaces");
- } else {
- log.debug("Detected no security configured, launching server on loopback (localhost) network interface only");
- if (mgmt!=null) {
- log.debug("Detected no security configured, running on loopback; disabling authentication");
- ((BrooklynProperties)mgmt.getConfig()).put(BrooklynWebConfig.SECURITY_PROVIDER_CLASSNAME, AnyoneSecurityProvider.class.getName());
- }
- }
- if (mgmt != null && disableHighAvailability)
- mgmt.getHighAvailabilityManager().disabled();
- InetSocketAddress bindLocation = new InetSocketAddress(
- secure ? Networking.ANY_NIC : Networking.LOOPBACK,
- Networking.nextAvailablePort(FAVOURITE_PORT));
- return startServer(context, summary, bindLocation);
- }
-
- /** @deprecated since 0.9.0 becoming private */
- @Deprecated
- public static Server startServer(ContextHandler context, String summary, InetSocketAddress bindLocation) {
- Server server = new Server(bindLocation);
-
- server.setHandler(context);
- try {
- server.start();
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- log.info("Brooklyn REST server started ("+summary+") on");
- log.info(" http://localhost:"+((NetworkConnector)server.getConnectors()[0]).getLocalPort()+"/");
-
- return server;
- }
-
- public static BrooklynRestApiLauncher launcher() {
- return new BrooklynRestApiLauncher();
- }
-
- public static void main(String[] args) throws Exception {
- startRestResourcesViaFilter();
- log.info("Press Ctrl-C to quit.");
- }
-
- public static Server startRestResourcesViaFilter() {
- return new BrooklynRestApiLauncher()
- .mode(StartMode.FILTER)
- .start();
- }
-
- public static Server startRestResourcesViaServlet() throws Exception {
- return new BrooklynRestApiLauncher()
- .mode(StartMode.SERVLET)
- .start();
- }
-
- public static Server startRestResourcesViaWebXml() throws Exception {
- return new BrooklynRestApiLauncher()
- .mode(StartMode.WEB_XML)
- .start();
- }
-
- public void installAsServletFilter(ServletContextHandler context) {
- installAsServletFilter(context, DEFAULT_FILTERS);
- }
-
- private void installAsServletFilter(ServletContextHandler context, List<Class<? extends Filter>> filters) {
- installBrooklynFilters(context, filters);
-
- // now set up the REST servlet resources
- ResourceConfig config = new DefaultResourceConfig();
- // load all our REST API modules, JSON, and Swagger
- for (Object r: BrooklynRestApi.getAllResources())
- config.getSingletons().add(r);
-
- // disable caching for dynamic content
- config.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, NoCacheFilter.class.getName());
- // Checks if appropriate request given HA status
- config.getProperties().put(ResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES, org.apache.brooklyn.rest.filter.HaHotCheckResourceFilter.class.getName());
- // configure to match empty path, or any thing which looks like a file path with /assets/ and extension html, css, js, or png
- // and treat that as static content
- config.getProperties().put(ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX, "(/?|[^?]*/assets/[^?]+\\.[A-Za-z0-9_]+)");
- // and anything which is not matched as a servlet also falls through (but more expensive than a regex check?)
- config.getFeatures().put(ServletContainer.FEATURE_FILTER_FORWARD_ON_404, true);
- // finally create this as a _filter_ which falls through to a web app or something (optionally)
- FilterHolder filterHolder = new FilterHolder(new ServletContainer(config));
- // Let the filter know the context path where it lives
- filterHolder.setInitParameter(ServletContainer.PROPERTY_FILTER_CONTEXT_PATH, "/v1");
- context.addFilter(filterHolder, "/v1/*", EnumSet.allOf(DispatcherType.class));
-
- ManagementContext mgmt = getManagementContext(context);
- config.getSingletons().add(new ManagementContextProvider());
- addShutdownListener(config, mgmt);
- }
-
- protected synchronized void addShutdownListener(ResourceConfig config, ManagementContext mgmt) {
- if (shutdownListener!=null) throw new IllegalStateException("Can only retrieve one shutdown listener");
- shutdownListener = new ServerStoppingShutdownHandler(mgmt);
- config.getSingletons().add(new ShutdownHandlerProvider(shutdownListener));
- }
-
- private static void installBrooklynFilters(ServletContextHandler context, List<Class<? extends Filter>> filters) {
- for (Class<? extends Filter> filter : filters) {
- context.addFilter(filter, "/*", EnumSet.allOf(DispatcherType.class));
- }
- }
-
- /**
- * Starts the server on all nics (even if security not enabled).
- * @deprecated since 0.6.0; use {@link #launcher()} and set a custom context
- */
- @Deprecated
- public static Server startServer(ContextHandler context, String summary) {
- return BrooklynRestApiLauncher.startServer(context, summary,
- new InetSocketAddress(Networking.ANY_NIC, Networking.nextAvailablePort(FAVOURITE_PORT)));
- }
-
- /** look for the JS GUI webapp in common source places, returning path to it if found, or null.
- * assumes `brooklyn-ui` is checked out as a sibling to `brooklyn-server`, and both are 2, 3, 1, or 0
- * levels above the CWD. */
- @Beta
- public static Maybe<String> findJsguiWebappInSource() {
- // normally up 2 levels to where brooklyn-* folders are, then into ui
- // (but in rest projects it might be 3 up, and in some IDEs we might run from parent dirs.)
- // TODO could also look in maven repo ?
- return findFirstMatchingFile(
- "../../brooklyn-ui/src/main/webapp",
- "../../../brooklyn-ui/src/main/webapp",
- "../brooklyn-ui/src/main/webapp",
- "./brooklyn-ui/src/main/webapp",
- "../../brooklyn-ui/target/*.war",
- "../../..brooklyn-ui/target/*.war",
- "../brooklyn-ui/target/*.war",
- "./brooklyn-ui/target/*.war");
- }
-
- /** look for the REST WAR file in common places, returning path to it if found, or null */
- private static String findRestApiWar() {
- // don't look at src/main/webapp here -- because classes won't be there!
- // could also look in maven repo ?
- // TODO looks like this stopped working at runtime a long time ago;
- // only needed for WEB_XML mode, and not used, but should remove or check?
- // (probably will be superseded by CXF/OSGi work however)
- return findMatchingFile("../rest/target/*.war").orNull();
- }
-
- /** as {@link #findMatchingFile(String)} but finding the first */
- public static Maybe<String> findFirstMatchingFile(String ...filenames) {
- for (String f: filenames) {
- Maybe<String> result = findMatchingFile(f);
- if (result.isPresent()) return result;
- }
- return Maybe.absent();
- }
-
- /** returns the supplied filename if it exists (absolute or relative to the current directory);
- * supports globs in the filename portion only, in which case it returns the _newest_ matching file.
- * <p>
- * otherwise returns null */
- @Beta // public because used in dependent test projects
- public static Maybe<String> findMatchingFile(String filename) {
- final File f = new File(filename);
- if (f.exists()) return Maybe.of(filename);
- File dir = f.getParentFile();
- File result = null;
- if (dir.exists()) {
- File[] matchingFiles = dir.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return WildcardGlobs.isGlobMatched(f.getName(), name);
- }
- });
- for (File mf: matchingFiles) {
- if (result==null || mf.lastModified() > result.lastModified()) result = mf;
- }
- }
- if (result==null) return Maybe.absent();
- return Maybe.of(result.getAbsolutePath());
- }
-
- /** create a directory with a simple index.html so we have some content being served up */
- private static String createTempWebDirWithIndexHtml(String indexHtmlContent) {
- File dir = Files.createTempDir();
- dir.deleteOnExit();
- try {
- Files.write(indexHtmlContent, new File(dir, "index.html"), Charsets.UTF_8);
- } catch (IOException e) {
- Exceptions.propagate(e);
- }
- return dir.getAbsolutePath();
- }
-
- /**
- * Compatibility methods between karaf launcher and monolithic launcher.
- *
- * @todo Remove after transition to karaf launcher.
- */
- static ManagementContext getManagementContext(ContextHandler jettyServerHandler) {
- ManagementContext managementContext = Compat.getInstance().getManagementContext();
- if (managementContext == null && jettyServerHandler != null) {
- managementContext = (ManagementContext) jettyServerHandler.getAttribute(BrooklynServiceAttributes.BROOKLYN_MANAGEMENT_CONTEXT);
- }
- return managementContext;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java
deleted file mode 100644
index 1a65f2c..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTest.java
+++ /dev/null
@@ -1,77 +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;
-
-import static org.apache.brooklyn.rest.BrooklynRestApiLauncher.StartMode.FILTER;
-import static org.apache.brooklyn.rest.BrooklynRestApiLauncher.StartMode.SERVLET;
-import static org.apache.brooklyn.rest.BrooklynRestApiLauncher.StartMode.WEB_XML;
-
-import java.util.concurrent.Callable;
-
-import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
-import org.apache.brooklyn.rest.security.provider.AnyoneSecurityProvider;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.http.HttpAsserts;
-import org.apache.brooklyn.util.http.HttpTool;
-import org.apache.http.HttpStatus;
-import org.eclipse.jetty.server.NetworkConnector;
-import org.eclipse.jetty.server.Server;
-import org.testng.annotations.Test;
-
-public class BrooklynRestApiLauncherTest extends BrooklynRestApiLauncherTestFixture {
-
- @Test(enabled = false) // to be deleted
- public void testFilterStart() throws Exception {
- checkRestCatalogEntities(useServerForTest(baseLauncher().mode(FILTER).start()));
- }
-
- @Test(enabled = false) // to be deleted
- public void testServletStart() throws Exception {
- checkRestCatalogEntities(useServerForTest(baseLauncher().mode(SERVLET).start()));
- }
-
- @Test(enabled = false) // to be deleted
- public void testWebAppStart() throws Exception {
- checkRestCatalogEntities(useServerForTest(baseLauncher().mode(WEB_XML).start()));
- }
-
- private BrooklynRestApiLauncher baseLauncher() {
- return BrooklynRestApiLauncher.launcher()
- .securityProvider(AnyoneSecurityProvider.class)
- .forceUseOfDefaultCatalogWithJavaClassPath(true);
- }
-
- private static void checkRestCatalogEntities(Server server) throws Exception {
- final String rootUrl = "http://localhost:"+((NetworkConnector)server.getConnectors()[0]).getLocalPort();
- int code = Asserts.succeedsEventually(new Callable<Integer>() {
- @Override
- public Integer call() throws Exception {
- int code = HttpTool.getHttpStatusCode(rootUrl+"/v1/catalog/entities");
- if (code == HttpStatus.SC_FORBIDDEN) {
- throw new RuntimeException("Retry request");
- } else {
- return code;
- }
- }
- });
- HttpAsserts.assertHealthyStatusCode(code);
- HttpAsserts.assertContentContainsText(rootUrl+"/v1/catalog/entities", BrooklynNode.class.getSimpleName());
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTestFixture.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTestFixture.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTestFixture.java
deleted file mode 100644
index c894f3e..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/BrooklynRestApiLauncherTestFixture.java
+++ /dev/null
@@ -1,109 +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;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.server.BrooklynServerConfig;
-import org.apache.brooklyn.rest.security.provider.AnyoneSecurityProvider;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.eclipse.jetty.server.NetworkConnector;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.handler.ContextHandler;
-import org.reflections.util.ClasspathHelper;
-import org.testng.Assert;
-import org.testng.annotations.AfterMethod;
-
-public abstract class BrooklynRestApiLauncherTestFixture {
-
- Server server = null;
-
- @AfterMethod(alwaysRun=true)
- public void stopServer() throws Exception {
- if (server!=null) {
- ManagementContext mgmt = getManagementContextFromJettyServerAttributes(server);
- server.stop();
- if (mgmt!=null) Entities.destroyAll(mgmt);
- server = null;
- }
- }
-
- protected Server newServer() {
- try {
- Server server = BrooklynRestApiLauncher.launcher()
- .forceUseOfDefaultCatalogWithJavaClassPath(true)
- .securityProvider(AnyoneSecurityProvider.class)
- .start();
- return server;
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }
-
- protected Server useServerForTest(Server server) {
- if (this.server!=null) {
- Assert.fail("Test only meant for single server; already have "+this.server+" when checking "+server);
- } else {
- this.server = server;
- }
- return server;
- }
-
- protected String getBaseUri() {
- return getBaseUri(server);
- }
- public static String getBaseUri(Server server) {
- return "http://localhost:"+((NetworkConnector)server.getConnectors()[0]).getLocalPort();
- }
-
- public static void forceUseOfDefaultCatalogWithJavaClassPath(Server server) {
- ManagementContext mgmt = getManagementContextFromJettyServerAttributes(server);
- forceUseOfDefaultCatalogWithJavaClassPath(mgmt);
- }
-
- public static void forceUseOfDefaultCatalogWithJavaClassPath(ManagementContext manager) {
- // TODO duplication with BrooklynRestApiLauncher ?
-
- // don't use any catalog.xml which is set
- ((BrooklynProperties)manager.getConfig()).put(BrooklynServerConfig.BROOKLYN_CATALOG_URL, BrooklynRestApiLauncher.SCANNING_CATALOG_BOM_URL);
- // sets URLs for a surefire
- ((LocalManagementContext)manager).setBaseClassPathForScanning(ClasspathHelper.forJavaClassPath());
- // this also works
-// ((LocalManagementContext)manager).setBaseClassPathForScanning(ClasspathHelper.forPackage("brooklyn"));
- // but this (near-default behaviour) does not
-// ((LocalManagementContext)manager).setBaseClassLoader(getClass().getClassLoader());
- }
-
- public static void enableAnyoneLogin(Server server) {
- ManagementContext mgmt = getManagementContextFromJettyServerAttributes(server);
- enableAnyoneLogin(mgmt);
- }
-
- public static void enableAnyoneLogin(ManagementContext mgmt) {
- ((BrooklynProperties)mgmt.getConfig()).put(BrooklynWebConfig.SECURITY_PROVIDER_CLASSNAME,
- AnyoneSecurityProvider.class.getName());
- }
-
- public static ManagementContext getManagementContextFromJettyServerAttributes(Server server) {
- return BrooklynRestApiLauncher.getManagementContext((ContextHandler) server.getHandler());
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/HaHotCheckTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/HaHotCheckTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/HaHotCheckTest.java
deleted file mode 100644
index 044e54d..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/HaHotCheckTest.java
+++ /dev/null
@@ -1,160 +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;
-
-import static org.testng.Assert.assertEquals;
-
-import javax.ws.rs.core.MediaType;
-
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityManager;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.rest.filter.HaHotCheckResourceFilter;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.rest.util.TestingHaHotStateCheckClassResource;
-import org.apache.brooklyn.rest.util.TestingHaHotStateCheckResource;
-import org.apache.brooklyn.rest.util.TestingHaMasterCheckResource;
-import org.apache.brooklyn.rest.util.ManagementContextProvider;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource.Builder;
-import com.sun.jersey.api.core.ResourceConfig;
-
-public class HaHotCheckTest extends BrooklynRestResourceTest {
-
- // setup and teardown before/after each method
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception { super.setUp(); }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception { super.tearDown(); }
-
- @Override
- protected void addBrooklynResources() {
- config.getProperties().put(ResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES,
- new HaHotCheckResourceFilter(new ManagementContextProvider(getManagementContext())));
- addResource(new TestingHaHotStateCheckResource());
- addResource(new TestingHaHotStateCheckClassResource());
- addResource(new TestingHaMasterCheckResource());
-
- ((LocalManagementContext)getManagementContext()).noteStartupComplete();
- }
-
- @Test
- public void testHaCheck() {
- HighAvailabilityManager ha = getManagementContext().getHighAvailabilityManager();
- assertEquals(ha.getNodeState(), ManagementNodeState.MASTER);
- testResourceFetch("/v1/ha/method/ok", 200);
- testResourceFetch("/v1/ha/method/fail", 200);
- testResourceFetch("/v1/ha/class/fail", 200);
- testResourcePost("/v1/ha/post", 204);
- testResourcePost("/v1/server/shutdown", 204);
-
- getManagementContext().getHighAvailabilityManager().changeMode(HighAvailabilityMode.STANDBY);
- assertEquals(ha.getNodeState(), ManagementNodeState.STANDBY);
-
- testResourceFetch("/v1/ha/method/ok", 200);
- testResourceFetch("/v1/ha/method/fail", 403);
- testResourceFetch("/v1/ha/class/fail", 403);
- testResourcePost("/v1/ha/post", 403);
- testResourcePost("/v1/server/shutdown", 204);
-
- ((ManagementContextInternal)getManagementContext()).terminate();
- assertEquals(ha.getNodeState(), ManagementNodeState.TERMINATED);
-
- testResourceFetch("/v1/ha/method/ok", 200);
- testResourceFetch("/v1/ha/method/fail", 403);
- testResourceFetch("/v1/ha/class/fail", 403);
- testResourcePost("/v1/ha/post", 403);
- testResourcePost("/v1/server/shutdown", 204);
- }
-
- @Test
- public void testHaCheckForce() {
- HighAvailabilityManager ha = getManagementContext().getHighAvailabilityManager();
- assertEquals(ha.getNodeState(), ManagementNodeState.MASTER);
- testResourceForcedFetch("/v1/ha/method/ok", 200);
- testResourceForcedFetch("/v1/ha/method/fail", 200);
- testResourceForcedFetch("/v1/ha/class/fail", 200);
- testResourceForcedPost("/v1/ha/post", 204);
- testResourceForcedPost("/v1/server/shutdown", 204);
-
- getManagementContext().getHighAvailabilityManager().changeMode(HighAvailabilityMode.STANDBY);
- assertEquals(ha.getNodeState(), ManagementNodeState.STANDBY);
-
- testResourceForcedFetch("/v1/ha/method/ok", 200);
- testResourceForcedFetch("/v1/ha/method/fail", 200);
- testResourceForcedFetch("/v1/ha/class/fail", 200);
- testResourceForcedPost("/v1/ha/post", 204);
- testResourceForcedPost("/v1/server/shutdown", 204);
-
- ((ManagementContextInternal)getManagementContext()).terminate();
- assertEquals(ha.getNodeState(), ManagementNodeState.TERMINATED);
-
- testResourceForcedFetch("/v1/ha/method/ok", 200);
- testResourceForcedFetch("/v1/ha/method/fail", 200);
- testResourceForcedFetch("/v1/ha/class/fail", 200);
- testResourceForcedPost("/v1/ha/post", 204);
- testResourceForcedPost("/v1/server/shutdown", 204);
- }
-
-
- private void testResourceFetch(String resourcePath, int code) {
- testResourceFetch(resourcePath, false, code);
- }
-
- private void testResourcePost(String resourcePath, int code) {
- testResourcePost(resourcePath, false, code);
- }
-
- private void testResourceForcedFetch(String resourcePath, int code) {
- testResourceFetch(resourcePath, true, code);
- }
-
- private void testResourceForcedPost(String resourcePath, int code) {
- testResourcePost(resourcePath, true, code);
- }
-
- private void testResourceFetch(String resourcePath, boolean force, int code) {
- Builder resource = client().resource(resourcePath)
- .accept(MediaType.APPLICATION_JSON_TYPE);
- if (force) {
- resource.header(HaHotCheckResourceFilter.SKIP_CHECK_HEADER, "true");
- }
- ClientResponse response = resource
- .get(ClientResponse.class);
- assertEquals(response.getStatus(), code);
- }
-
- private void testResourcePost(String resourcePath, boolean force, int code) {
- Builder resource = client().resource(resourcePath)
- .accept(MediaType.APPLICATION_JSON_TYPE);
- if (force) {
- resource.header(HaHotCheckResourceFilter.SKIP_CHECK_HEADER, "true");
- }
- ClientResponse response = resource.post(ClientResponse.class);
- assertEquals(response.getStatus(), code);
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/HaMasterCheckFilterTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/HaMasterCheckFilterTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/HaMasterCheckFilterTest.java
deleted file mode 100644
index 424c0c1..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/HaMasterCheckFilterTest.java
+++ /dev/null
@@ -1,218 +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;
-
-import static org.testng.Assert.assertEquals;
-
-import java.io.File;
-import java.net.URI;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeoutException;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.mgmt.EntityManager;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.camp.brooklyn.BrooklynCampPlatformLauncherNoServer;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.entity.stock.BasicApplication;
-import org.apache.http.HttpStatus;
-import org.apache.http.client.HttpClient;
-import org.eclipse.jetty.server.Server;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.rest.security.provider.AnyoneSecurityProvider;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.http.HttpTool;
-import org.apache.brooklyn.util.http.HttpToolResponse;
-import org.apache.brooklyn.util.os.Os;
-import org.apache.brooklyn.util.time.Duration;
-
-import com.google.common.base.Predicates;
-import com.google.common.base.Supplier;
-import com.google.common.collect.ImmutableMap;
-
-public class HaMasterCheckFilterTest extends BrooklynRestApiLauncherTestFixture {
- private static final Duration TIMEOUT = Duration.THIRTY_SECONDS;
-
- private File mementoDir;
- private ManagementContext writeMgmt;
- private ManagementContext readMgmt;
- private String appId;
- private Server server;
- private HttpClient client;
-
- @AfterMethod(alwaysRun=true)
- public void tearDown() throws Exception {
-System.err.println("TEAR DOWN");
- server.stop();
- Entities.destroyAll(writeMgmt);
- Entities.destroyAll(readMgmt);
- Os.deleteRecursively(mementoDir);
- }
-
- @Test(groups = "Integration")
- public void testEntitiesExistOnDisabledHA() throws Exception {
- initHaCluster(HighAvailabilityMode.DISABLED, HighAvailabilityMode.DISABLED);
- assertReadIsMaster();
- assertEntityExists(new ReturnCodeCheck());
- }
-
- @Test(groups = "Integration")
- public void testEntitiesExistOnMasterPromotion() throws Exception {
- initHaCluster(HighAvailabilityMode.AUTO, HighAvailabilityMode.AUTO);
- stopWriteNode();
- assertEntityExists(new ReturnCodeCheck());
- assertReadIsMaster();
- }
-
- @Test(groups = "Integration")
- public void testEntitiesExistOnHotStandbyAndPromotion() throws Exception {
- initHaCluster(HighAvailabilityMode.AUTO, HighAvailabilityMode.HOT_STANDBY);
- assertEntityExists(new ReturnCodeCheck());
- stopWriteNode();
- assertEntityExists(new ReturnCodeAndNodeState());
- assertReadIsMaster();
- }
-
- @Test(groups = "Integration")
- public void testEntitiesExistOnHotBackup() throws Exception {
- initHaCluster(HighAvailabilityMode.AUTO, HighAvailabilityMode.HOT_BACKUP);
- Asserts.continually(
- ImmutableMap.<String,Object>of(
- "timeout", Duration.THIRTY_SECONDS,
- "period", Duration.ZERO),
- new ReturnCodeSupplier(),
- Predicates.or(Predicates.equalTo(200), Predicates.equalTo(403)));
- }
-
- private HttpClient getClient(Server server) {
- HttpClient client = HttpTool.httpClientBuilder()
- .uri(getBaseUri(server))
- .build();
- return client;
- }
-
- private int getAppResponseCode() {
- HttpToolResponse response = HttpTool.httpGet(
- client, URI.create(getBaseUri(server) + "/v1/applications/" + appId),
- ImmutableMap.<String,String>of());
- return response.getResponseCode();
- }
-
- private String createApp(ManagementContext mgmt) {
- EntityManager entityMgr = mgmt.getEntityManager();
- Entity app = entityMgr.createEntity(EntitySpec.create(BasicApplication.class));
- entityMgr.manage(app);
- return app.getId();
- }
-
- private ManagementContext createManagementContext(File mementoDir, HighAvailabilityMode mode) {
- ManagementContext mgmt = RebindTestUtils.managementContextBuilder(mementoDir, getClass().getClassLoader())
- .persistPeriodMillis(1)
- .forLive(false)
- .emptyCatalog(true)
- .buildUnstarted();
-
- if (mode == HighAvailabilityMode.DISABLED) {
- mgmt.getHighAvailabilityManager().disabled();
- } else {
- mgmt.getHighAvailabilityManager().start(mode);
- }
-
- new BrooklynCampPlatformLauncherNoServer()
- .useManagementContext(mgmt)
- .launch();
-
- return mgmt;
- }
-
- private void initHaCluster(HighAvailabilityMode writeMode, HighAvailabilityMode readMode) throws InterruptedException, TimeoutException {
- mementoDir = Os.newTempDir(getClass());
-
- writeMgmt = createManagementContext(mementoDir, writeMode);
- appId = createApp(writeMgmt);
- writeMgmt.getRebindManager().waitForPendingComplete(TIMEOUT, true);
-
- if (readMode == HighAvailabilityMode.DISABLED) {
- //no HA, one node only
- readMgmt = writeMgmt;
- } else {
- readMgmt = createManagementContext(mementoDir, readMode);
- }
-
- server = useServerForTest(BrooklynRestApiLauncher.launcher()
- .managementContext(readMgmt)
- .securityProvider(AnyoneSecurityProvider.class)
- .forceUseOfDefaultCatalogWithJavaClassPath(true)
- .withoutJsgui()
- .disableHighAvailability(false)
- .start());
- client = getClient(server);
- }
-
- private void assertEntityExists(Callable<Integer> c) {
- assertEquals((int)Asserts.succeedsEventually(c), 200);
- }
-
- private void assertReadIsMaster() {
- assertEquals(readMgmt.getHighAvailabilityManager().getNodeState(), ManagementNodeState.MASTER);
- }
-
- private void stopWriteNode() {
- writeMgmt.getHighAvailabilityManager().stop();
- }
-
- private class ReturnCodeCheck implements Callable<Integer> {
- @Override
- public Integer call() {
- int retCode = getAppResponseCode();
- if (retCode == 403) {
- throw new RuntimeException("Not ready, retry. Response - " + retCode);
- } else {
- return retCode;
- }
- }
- }
-
- private class ReturnCodeAndNodeState extends ReturnCodeCheck {
- @Override
- public Integer call() {
- Integer ret = super.call();
- if (ret == HttpStatus.SC_OK) {
- ManagementNodeState state = readMgmt.getHighAvailabilityManager().getNodeState();
- if (state != ManagementNodeState.MASTER) {
- throw new RuntimeException("Not master yet " + state);
- }
- }
- return ret;
- }
- }
-
- private class ReturnCodeSupplier implements Supplier<Integer> {
- @Override
- public Integer get() {
- return getAppResponseCode();
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/AbstractDomainTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/AbstractDomainTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/AbstractDomainTest.java
deleted file mode 100644
index dc1131d..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/domain/AbstractDomainTest.java
+++ /dev/null
@@ -1,44 +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.domain;
-
-import java.io.IOException;
-
-import org.testng.annotations.Test;
-
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.asJson;
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.fromJson;
-import static org.apache.brooklyn.rest.util.RestApiTestUtils.jsonFixture;
-import static org.testng.Assert.assertEquals;
-
-public abstract class AbstractDomainTest {
-
- protected abstract String getPath();
- protected abstract Object getDomainObject();
-
- @Test
- public void testSerializeToJSON() throws IOException {
- assertEquals(asJson(getDomainObject()), jsonFixture(getPath()));
- }
-
- @Test
- public void testDeserializeFromJSON() throws IOException {
- assertEquals(fromJson(jsonFixture(getPath()), getDomainObject().getClass()), getDomainObject());
- }
-}
[8/9] brooklyn-server git commit: Fix failing tests - add missing
test dependency
Posted by sj...@apache.org.
Fix failing tests - add missing test dependency
Test dependencies are not transitive, all need to be explicit.
Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/5838d166
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/5838d166
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/5838d166
Branch: refs/heads/master
Commit: 5838d166f2bbe191bf1b8d1541ee36d3479fe96f
Parents: 3be4fe1
Author: Svetoslav Neykov <sv...@cloudsoftcorp.com>
Authored: Fri Apr 1 09:14:28 2016 +0300
Committer: Svetoslav Neykov <sv...@cloudsoftcorp.com>
Committed: Fri Apr 1 09:31:12 2016 +0300
----------------------------------------------------------------------
launcher/pom.xml | 7 +++++++
1 file changed, 7 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5838d166/launcher/pom.xml
----------------------------------------------------------------------
diff --git a/launcher/pom.xml b/launcher/pom.xml
index 2ecb2f8..7bf7a11 100644
--- a/launcher/pom.xml
+++ b/launcher/pom.xml
@@ -187,6 +187,13 @@
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
+ <artifactId>brooklyn-rest-resources</artifactId>
+ <version>${project.version}</version>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.brooklyn</groupId>
<artifactId>brooklyn-rest-server</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
[4/9] brooklyn-server git commit: Remove jersey compatibility
Posted by sj...@apache.org.
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java
deleted file mode 100644
index ada548b..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/ApplicationResourceTest.java
+++ /dev/null
@@ -1,701 +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.resources;
-
-import static com.google.common.collect.Iterables.find;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-import java.io.IOException;
-import java.net.URI;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.TimeoutException;
-
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Response;
-
-import org.apache.brooklyn.api.entity.Application;
-import org.apache.brooklyn.core.entity.Attributes;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.entity.EntityFunctions;
-import org.apache.brooklyn.core.entity.EntityPredicates;
-import org.apache.brooklyn.core.entity.lifecycle.Lifecycle;
-import org.apache.brooklyn.core.location.AbstractLocation;
-import org.apache.brooklyn.core.location.LocationConfigKeys;
-import org.apache.brooklyn.core.location.geo.HostGeoInfo;
-import org.apache.brooklyn.core.location.internal.LocationInternal;
-import org.apache.brooklyn.entity.stock.BasicApplication;
-import org.apache.brooklyn.entity.stock.BasicEntity;
-import org.apache.brooklyn.rest.domain.ApiError;
-import org.apache.brooklyn.rest.domain.ApplicationSpec;
-import org.apache.brooklyn.rest.domain.ApplicationSummary;
-import org.apache.brooklyn.rest.domain.CatalogEntitySummary;
-import org.apache.brooklyn.rest.domain.CatalogItemSummary;
-import org.apache.brooklyn.rest.domain.EffectorSummary;
-import org.apache.brooklyn.rest.domain.EntityConfigSummary;
-import org.apache.brooklyn.rest.domain.EntitySpec;
-import org.apache.brooklyn.rest.domain.EntitySummary;
-import org.apache.brooklyn.rest.domain.PolicySummary;
-import org.apache.brooklyn.rest.domain.SensorSummary;
-import org.apache.brooklyn.rest.domain.Status;
-import org.apache.brooklyn.rest.domain.TaskSummary;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.rest.testing.mocks.CapitalizePolicy;
-import org.apache.brooklyn.rest.testing.mocks.NameMatcherGroup;
-import org.apache.brooklyn.rest.testing.mocks.RestMockApp;
-import org.apache.brooklyn.rest.testing.mocks.RestMockAppBuilder;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.CollectionFunctionals;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.http.HttpAsserts;
-import org.apache.brooklyn.util.text.Strings;
-import org.apache.brooklyn.util.time.Duration;
-import org.apache.http.HttpHeaders;
-import org.apache.http.entity.ContentType;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Maps;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.GenericType;
-import com.sun.jersey.api.client.UniformInterfaceException;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.core.util.MultivaluedMapImpl;
-
-@Test(singleThreaded = true)
-public class ApplicationResourceTest extends BrooklynRestResourceTest {
-
- /*
- * In simpleSpec, not using EverythingGroup because caused problems! The group is a child of the
- * app, and the app is a member of the group. It failed in jenkins with:
- * BasicApplicationImpl{id=GSPjBCe4} GSPjBCe4
- * service.isUp: true
- * service.problems: {service-lifecycle-indicators-from-children-and-members=Required entity not healthy: EverythingGroupImpl{id=KQ4mSEOJ}}
- * service.state: on-fire
- * service.state.expected: running @ 1412003485617 / Mon Sep 29 15:11:25 UTC 2014
- * EverythingGroupImpl{id=KQ4mSEOJ} KQ4mSEOJ
- * service.isUp: true
- * service.problems: {service-lifecycle-indicators-from-children-and-members=Required entities not healthy: BasicApplicationImpl{id=GSPjBCe4}, EverythingGroupImpl{id=KQ4mSEOJ}}
- * service.state: on-fire
- * I'm guessing there's a race: the app was not yet healthy because EverythingGroup hadn't set itself to running;
- * but then the EverythingGroup would never transition to healthy because one of its members was not healthy.
- */
-
- private static final Logger log = LoggerFactory.getLogger(ApplicationResourceTest.class);
-
- private final ApplicationSpec simpleSpec = ApplicationSpec.builder().name("simple-app")
- .entities(ImmutableSet.of(
- new EntitySpec("simple-ent", RestMockSimpleEntity.class.getName()),
- new EntitySpec("simple-group", NameMatcherGroup.class.getName(), ImmutableMap.of("namematchergroup.regex", "simple-ent"))
- ))
- .locations(ImmutableSet.of("localhost"))
- .build();
-
- // Convenience for finding an EntitySummary within a collection, based on its name
- private static Predicate<EntitySummary> withName(final String name) {
- return new Predicate<EntitySummary>() {
- public boolean apply(EntitySummary input) {
- return name.equals(input.getName());
- }
- };
- }
-
- // Convenience for finding a Map within a collection, based on the value of one of its keys
- private static Predicate<? super Map<?,?>> withValueForKey(final Object key, final Object value) {
- return new Predicate<Object>() {
- public boolean apply(Object input) {
- if (!(input instanceof Map)) return false;
- return value.equals(((Map<?, ?>) input).get(key));
- }
- };
- }
-
- @Test
- public void testGetUndefinedApplication() {
- try {
- client().resource("/v1/applications/dummy-not-found").get(ApplicationSummary.class);
- } catch (UniformInterfaceException e) {
- assertEquals(e.getResponse().getStatus(), 404);
- }
- }
-
- private static void assertRegexMatches(String actual, String patternExpected) {
- if (actual==null) Assert.fail("Actual value is null; expected "+patternExpected);
- if (!actual.matches(patternExpected)) {
- Assert.fail("Text '"+actual+"' does not match expected pattern "+patternExpected);
- }
- }
-
- @Test
- public void testDeployApplication() throws Exception {
- ClientResponse response = clientDeploy(simpleSpec);
-
- HttpAsserts.assertHealthyStatusCode(response.getStatus());
- assertEquals(getManagementContext().getApplications().size(), 1);
- assertRegexMatches(response.getLocation().getPath(), "/v1/applications/.*");
- // Object taskO = response.getEntity(Object.class);
- TaskSummary task = response.getEntity(TaskSummary.class);
- log.info("deployed, got " + task);
- assertEquals(task.getEntityId(), getManagementContext().getApplications().iterator().next().getApplicationId());
-
- waitForApplicationToBeRunning(response.getLocation());
- }
-
- @Test(dependsOnMethods = { "testDeleteApplication" })
- // this must happen after we've deleted the main application, as testLocatedLocations assumes a single location
- public void testDeployApplicationImpl() throws Exception {
- ApplicationSpec spec = ApplicationSpec.builder()
- .type(RestMockApp.class.getCanonicalName())
- .name("simple-app-impl")
- .locations(ImmutableSet.of("localhost"))
- .build();
-
- ClientResponse response = clientDeploy(spec);
- assertTrue(response.getStatus() / 100 == 2, "response is " + response);
-
- // Expect app to be running
- URI appUri = response.getLocation();
- waitForApplicationToBeRunning(response.getLocation());
- assertEquals(client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-impl");
- }
-
- @Test(dependsOnMethods = { "testDeployApplication", "testLocatedLocation" })
- public void testDeployApplicationFromInterface() throws Exception {
- ApplicationSpec spec = ApplicationSpec.builder()
- .type(BasicApplication.class.getCanonicalName())
- .name("simple-app-interface")
- .locations(ImmutableSet.of("localhost"))
- .build();
-
- ClientResponse response = clientDeploy(spec);
- assertTrue(response.getStatus() / 100 == 2, "response is " + response);
-
- // Expect app to be running
- URI appUri = response.getLocation();
- waitForApplicationToBeRunning(response.getLocation());
- assertEquals(client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-interface");
- }
-
- @Test(dependsOnMethods = { "testDeployApplication", "testLocatedLocation" })
- public void testDeployApplicationFromBuilder() throws Exception {
- ApplicationSpec spec = ApplicationSpec.builder()
- .type(RestMockAppBuilder.class.getCanonicalName())
- .name("simple-app-builder")
- .locations(ImmutableSet.of("localhost"))
- .build();
-
- ClientResponse response = clientDeploy(spec);
- assertTrue(response.getStatus() / 100 == 2, "response is " + response);
-
- // Expect app to be running
- URI appUri = response.getLocation();
- waitForApplicationToBeRunning(response.getLocation(), Duration.TEN_SECONDS);
- assertEquals(client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-builder");
-
- // Expect app to have the child-entity
- Set<EntitySummary> entities = client().resource(appUri.toString() + "/entities")
- .get(new GenericType<Set<EntitySummary>>() {});
- assertEquals(entities.size(), 1);
- assertEquals(Iterables.getOnlyElement(entities).getName(), "child1");
- assertEquals(Iterables.getOnlyElement(entities).getType(), RestMockSimpleEntity.class.getCanonicalName());
- }
-
- @Test(dependsOnMethods = { "testDeployApplication", "testLocatedLocation" })
- public void testDeployApplicationYaml() throws Exception {
- String yaml = "{ name: simple-app-yaml, location: localhost, services: [ { serviceType: "+BasicApplication.class.getCanonicalName()+" } ] }";
-
- ClientResponse response = client().resource("/v1/applications")
- .entity(yaml, "application/x-yaml")
- .post(ClientResponse.class);
- assertTrue(response.getStatus()/100 == 2, "response is "+response);
-
- // Expect app to be running
- URI appUri = response.getLocation();
- waitForApplicationToBeRunning(response.getLocation());
- assertEquals(client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-yaml");
- }
-
- @Test
- public void testReferenceCatalogEntity() throws Exception {
- getManagementContext().getCatalog().addItems("{ name: "+BasicEntity.class.getName()+", "
- + "services: [ { type: "+BasicEntity.class.getName()+" } ] }");
-
- String yaml = "{ name: simple-app-yaml, location: localhost, services: [ { type: " + BasicEntity.class.getName() + " } ] }";
-
- ClientResponse response = client().resource("/v1/applications")
- .entity(yaml, "application/x-yaml")
- .post(ClientResponse.class);
- assertTrue(response.getStatus()/100 == 2, "response is "+response);
-
- // Expect app to be running
- URI appUri = response.getLocation();
- waitForApplicationToBeRunning(response.getLocation());
- assertEquals(client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-yaml");
-
- ClientResponse response2 = client().resource(appUri.getPath())
- .delete(ClientResponse.class);
- assertEquals(response2.getStatus(), Response.Status.ACCEPTED.getStatusCode());
- }
-
- @Test
- public void testDeployWithInvalidEntityType() {
- try {
- clientDeploy(ApplicationSpec.builder()
- .name("invalid-app")
- .entities(ImmutableSet.of(new EntitySpec("invalid-ent", "not.existing.entity")))
- .locations(ImmutableSet.of("localhost"))
- .build());
-
- } catch (UniformInterfaceException e) {
- ApiError error = e.getResponse().getEntity(ApiError.class);
- assertEquals(error.getMessage(), "Undefined type 'not.existing.entity'");
- }
- }
-
- @Test
- public void testDeployWithInvalidLocation() {
- try {
- clientDeploy(ApplicationSpec.builder()
- .name("invalid-app")
- .entities(ImmutableSet.of(new EntitySpec("simple-ent", RestMockSimpleEntity.class.getName())))
- .locations(ImmutableSet.of("3423"))
- .build());
-
- } catch (UniformInterfaceException e) {
- ApiError error = e.getResponse().getEntity(ApiError.class);
- assertEquals(error.getMessage(), "Undefined location '3423'");
- }
- }
-
- @Test(dependsOnMethods = "testDeployApplication")
- public void testListEntities() {
- Set<EntitySummary> entities = client().resource("/v1/applications/simple-app/entities")
- .get(new GenericType<Set<EntitySummary>>() {});
-
- assertEquals(entities.size(), 2);
-
- EntitySummary entity = Iterables.find(entities, withName("simple-ent"), null);
- EntitySummary group = Iterables.find(entities, withName("simple-group"), null);
- Assert.assertNotNull(entity);
- Assert.assertNotNull(group);
-
- client().resource(entity.getLinks().get("self")).get(ClientResponse.class);
-
- Set<EntitySummary> children = client().resource(entity.getLinks().get("children"))
- .get(new GenericType<Set<EntitySummary>>() {});
- assertEquals(children.size(), 0);
- }
-
- @Test(dependsOnMethods = "testDeployApplication")
- public void testListApplications() {
- Set<ApplicationSummary> applications = client().resource("/v1/applications")
- .get(new GenericType<Set<ApplicationSummary>>() { });
- log.info("Applications listed are: " + applications);
- for (ApplicationSummary app : applications) {
- if (simpleSpec.getName().equals(app.getSpec().getName())) return;
- }
- Assert.fail("simple-app not found in list of applications: "+applications);
- }
-
- @Test(dependsOnMethods = "testDeployApplication")
- public void testGetApplicationOnFire() {
- Application app = Iterables.find(manager.getApplications(), EntityPredicates.displayNameEqualTo(simpleSpec.getName()));
- Lifecycle origState = app.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
-
- ApplicationSummary summary = client().resource("/v1/applications/"+app.getId())
- .get(ApplicationSummary.class);
- assertEquals(summary.getStatus(), Status.RUNNING);
-
- app.sensors().set(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
- try {
- ApplicationSummary summary2 = client().resource("/v1/applications/"+app.getId())
- .get(ApplicationSummary.class);
- log.info("Application: " + summary2);
- assertEquals(summary2.getStatus(), Status.ERROR);
-
- } finally {
- app.sensors().set(Attributes.SERVICE_STATE_ACTUAL, origState);
- }
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Test(dependsOnMethods = "testDeployApplication")
- public void testFetchApplicationsAndEntity() {
- Collection apps = client().resource("/v1/applications/fetch").get(Collection.class);
- log.info("Applications fetched are: " + apps);
-
- Map app = null;
- for (Object appI : apps) {
- Object name = ((Map) appI).get("name");
- if ("simple-app".equals(name)) {
- app = (Map) appI;
- }
- if (ImmutableSet.of("simple-ent", "simple-group").contains(name))
- Assert.fail(name + " should not be listed at high level: " + apps);
- }
-
- Assert.assertNotNull(app);
- Assert.assertFalse(Strings.isBlank((String) app.get("applicationId")),
- "expected value for applicationId, was: " + app.get("applicationId"));
- Assert.assertFalse(Strings.isBlank((String) app.get("serviceState")),
- "expected value for serviceState, was: " + app.get("serviceState"));
- Assert.assertNotNull(app.get("serviceUp"), "expected non-null value for serviceUp");
-
- Collection children = (Collection) app.get("children");
- Assert.assertEquals(children.size(), 2);
-
- Map entitySummary = (Map) Iterables.find(children, withValueForKey("name", "simple-ent"), null);
- Map groupSummary = (Map) Iterables.find(children, withValueForKey("name", "simple-group"), null);
- Assert.assertNotNull(entitySummary);
- Assert.assertNotNull(groupSummary);
-
- String itemIds = app.get("id") + "," + entitySummary.get("id") + "," + groupSummary.get("id");
- Collection entities = client().resource("/v1/applications/fetch?items="+itemIds)
- .get(Collection.class);
- log.info("Applications+Entities fetched are: " + entities);
-
- Assert.assertEquals(entities.size(), apps.size() + 2);
- Map entityDetails = (Map) Iterables.find(entities, withValueForKey("name", "simple-ent"), null);
- Map groupDetails = (Map) Iterables.find(entities, withValueForKey("name", "simple-group"), null);
- Assert.assertNotNull(entityDetails);
- Assert.assertNotNull(groupDetails);
-
- Assert.assertEquals(entityDetails.get("parentId"), app.get("id"));
- Assert.assertNull(entityDetails.get("children"));
- Assert.assertEquals(groupDetails.get("parentId"), app.get("id"));
- Assert.assertNull(groupDetails.get("children"));
-
- Collection entityGroupIds = (Collection) entityDetails.get("groupIds");
- Assert.assertNotNull(entityGroupIds);
- Assert.assertEquals(entityGroupIds.size(), 1);
- Assert.assertEquals(entityGroupIds.iterator().next(), groupDetails.get("id"));
-
- Collection groupMembers = (Collection) groupDetails.get("members");
- Assert.assertNotNull(groupMembers);
-
- for (Application appi : getManagementContext().getApplications()) {
- Entities.dumpInfo(appi);
- }
- log.info("MEMBERS: " + groupMembers);
-
- Assert.assertEquals(groupMembers.size(), 1);
- Map entityMemberDetails = (Map) Iterables.find(groupMembers, withValueForKey("name", "simple-ent"), null);
- Assert.assertNotNull(entityMemberDetails);
- Assert.assertEquals(entityMemberDetails.get("id"), entityDetails.get("id"));
- }
-
- @Test(dependsOnMethods = "testDeployApplication")
- public void testListSensors() {
- Set<SensorSummary> sensors = client().resource("/v1/applications/simple-app/entities/simple-ent/sensors")
- .get(new GenericType<Set<SensorSummary>>() { });
- assertTrue(sensors.size() > 0);
- SensorSummary sample = Iterables.find(sensors, new Predicate<SensorSummary>() {
- @Override
- public boolean apply(SensorSummary sensorSummary) {
- return sensorSummary.getName().equals(RestMockSimpleEntity.SAMPLE_SENSOR.getName());
- }
- });
- assertEquals(sample.getType(), "java.lang.String");
- }
-
- @Test(dependsOnMethods = "testDeployApplication")
- public void testListConfig() {
- Set<EntityConfigSummary> config = client().resource("/v1/applications/simple-app/entities/simple-ent/config")
- .get(new GenericType<Set<EntityConfigSummary>>() { });
- assertTrue(config.size() > 0);
- System.out.println(("CONFIG: " + config));
- }
-
- @Test(dependsOnMethods = "testListConfig")
- public void testListConfig2() {
- Set<EntityConfigSummary> config = client().resource("/v1/applications/simple-app/entities/simple-ent/config")
- .get(new GenericType<Set<EntityConfigSummary>>() {});
- assertTrue(config.size() > 0);
- System.out.println(("CONFIG: " + config));
- }
-
- @Test(dependsOnMethods = "testDeployApplication")
- public void testListEffectors() {
- Set<EffectorSummary> effectors = client().resource("/v1/applications/simple-app/entities/simple-ent/effectors")
- .get(new GenericType<Set<EffectorSummary>>() {});
-
- assertTrue(effectors.size() > 0);
-
- EffectorSummary sampleEffector = find(effectors, new Predicate<EffectorSummary>() {
- @Override
- public boolean apply(EffectorSummary input) {
- return input.getName().equals("sampleEffector");
- }
- });
- assertEquals(sampleEffector.getReturnType(), "java.lang.String");
- }
-
- @Test(dependsOnMethods = "testListSensors")
- public void testTriggerSampleEffector() throws InterruptedException, IOException {
- ClientResponse response = client()
- .resource("/v1/applications/simple-app/entities/simple-ent/effectors/"+RestMockSimpleEntity.SAMPLE_EFFECTOR.getName())
- .type(MediaType.APPLICATION_JSON_TYPE)
- .post(ClientResponse.class, ImmutableMap.of("param1", "foo", "param2", 4));
-
- assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());
-
- String result = response.getEntity(String.class);
- assertEquals(result, "foo4");
- }
-
- @Test(dependsOnMethods = "testListSensors")
- public void testTriggerSampleEffectorWithFormData() throws InterruptedException, IOException {
- MultivaluedMap<String, String> data = new MultivaluedMapImpl();
- data.add("param1", "foo");
- data.add("param2", "4");
- ClientResponse response = client()
- .resource("/v1/applications/simple-app/entities/simple-ent/effectors/"+RestMockSimpleEntity.SAMPLE_EFFECTOR.getName())
- .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
- .post(ClientResponse.class, data);
-
- assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());
-
- String result = response.getEntity(String.class);
- assertEquals(result, "foo4");
- }
-
- @Test(dependsOnMethods = "testTriggerSampleEffector")
- public void testBatchSensorValues() {
- WebResource resource = client().resource("/v1/applications/simple-app/entities/simple-ent/sensors/current-state");
- Map<String, Object> sensors = resource.get(new GenericType<Map<String, Object>>() {});
- assertTrue(sensors.size() > 0);
- assertEquals(sensors.get(RestMockSimpleEntity.SAMPLE_SENSOR.getName()), "foo4");
- }
-
- @Test(dependsOnMethods = "testBatchSensorValues")
- public void testReadEachSensor() {
- Set<SensorSummary> sensors = client().resource("/v1/applications/simple-app/entities/simple-ent/sensors")
- .get(new GenericType<Set<SensorSummary>>() {});
-
- Map<String, String> readings = Maps.newHashMap();
- for (SensorSummary sensor : sensors) {
- try {
- readings.put(sensor.getName(), client().resource(sensor.getLinks().get("self")).accept(MediaType.TEXT_PLAIN).get(String.class));
- } catch (UniformInterfaceException uie) {
- if (uie.getResponse().getStatus() == 204) { // no content
- readings.put(sensor.getName(), null);
- } else {
- Exceptions.propagate(uie);
- }
- }
- }
-
- assertEquals(readings.get(RestMockSimpleEntity.SAMPLE_SENSOR.getName()), "foo4");
- }
-
- @Test(dependsOnMethods = "testTriggerSampleEffector")
- public void testPolicyWhichCapitalizes() {
- String policiesEndpoint = "/v1/applications/simple-app/entities/simple-ent/policies";
- Set<PolicySummary> policies = client().resource(policiesEndpoint).get(new GenericType<Set<PolicySummary>>(){});
- assertEquals(policies.size(), 0);
-
- ClientResponse response = client().resource(policiesEndpoint)
- .queryParam("type", CapitalizePolicy.class.getCanonicalName())
- .type(MediaType.APPLICATION_JSON_TYPE)
- .post(ClientResponse.class, Maps.newHashMap());
- assertEquals(response.getStatus(), 200);
- PolicySummary policy = response.getEntity(PolicySummary.class);
- assertNotNull(policy.getId());
- String newPolicyId = policy.getId();
- log.info("POLICY CREATED: " + newPolicyId);
- policies = client().resource(policiesEndpoint).get(new GenericType<Set<PolicySummary>>() {});
- assertEquals(policies.size(), 1);
-
- Lifecycle status = client().resource(policiesEndpoint + "/" + newPolicyId).get(Lifecycle.class);
- log.info("POLICY STATUS: " + status);
-
- response = client().resource(policiesEndpoint+"/"+newPolicyId+"/start")
- .post(ClientResponse.class);
- assertEquals(response.getStatus(), 204);
- status = client().resource(policiesEndpoint + "/" + newPolicyId).get(Lifecycle.class);
- assertEquals(status, Lifecycle.RUNNING);
-
- response = client().resource(policiesEndpoint+"/"+newPolicyId+"/stop")
- .post(ClientResponse.class);
- assertEquals(response.getStatus(), 204);
- status = client().resource(policiesEndpoint + "/" + newPolicyId).get(Lifecycle.class);
- assertEquals(status, Lifecycle.STOPPED);
-
- response = client().resource(policiesEndpoint+"/"+newPolicyId+"/destroy")
- .post(ClientResponse.class);
- assertEquals(response.getStatus(), 204);
-
- response = client().resource(policiesEndpoint+"/"+newPolicyId).get(ClientResponse.class);
- log.info("POLICY STATUS RESPONSE AFTER DESTROY: " + response.getStatus());
- assertEquals(response.getStatus(), 404);
-
- policies = client().resource(policiesEndpoint).get(new GenericType<Set<PolicySummary>>() {});
- assertEquals(0, policies.size());
- }
-
- @SuppressWarnings({ "rawtypes" })
- @Test(dependsOnMethods = "testDeployApplication")
- public void testLocatedLocation() {
- log.info("starting testLocatedLocations");
- testListApplications();
-
- LocationInternal l = (LocationInternal) getManagementContext().getApplications().iterator().next().getLocations().iterator().next();
- if (l.config().getLocalRaw(LocationConfigKeys.LATITUDE).isAbsent()) {
- log.info("Supplying fake locations for localhost because could not be autodetected");
- ((AbstractLocation) l).setHostGeoInfo(new HostGeoInfo("localhost", "localhost", 50, 0));
- }
- Map result = client().resource("/v1/locations/usage/LocatedLocations")
- .get(Map.class);
- log.info("LOCATIONS: " + result);
- Assert.assertEquals(result.size(), 1);
- Map details = (Map) result.values().iterator().next();
- assertEquals(details.get("leafEntityCount"), 2);
- }
-
- @Test(dependsOnMethods = {"testListEffectors", "testFetchApplicationsAndEntity", "testTriggerSampleEffector", "testListApplications","testReadEachSensor","testPolicyWhichCapitalizes","testLocatedLocation"})
- public void testDeleteApplication() throws TimeoutException, InterruptedException {
- waitForPageFoundResponse("/v1/applications/simple-app", ApplicationSummary.class);
- Collection<Application> apps = getManagementContext().getApplications();
- log.info("Deleting simple-app from " + apps);
- int size = apps.size();
-
- ClientResponse response = client().resource("/v1/applications/simple-app")
- .delete(ClientResponse.class);
-
- assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());
- TaskSummary task = response.getEntity(TaskSummary.class);
- assertTrue(task.getDescription().toLowerCase().contains("destroy"), task.getDescription());
- assertTrue(task.getDescription().toLowerCase().contains("simple-app"), task.getDescription());
-
- waitForPageNotFoundResponse("/v1/applications/simple-app", ApplicationSummary.class);
-
- log.info("App appears gone, apps are: " + getManagementContext().getApplications());
- // more logging above, for failure in the check below
-
- Asserts.eventually(
- EntityFunctions.applications(getManagementContext()),
- Predicates.compose(Predicates.equalTo(size-1), CollectionFunctionals.sizeFunction()) );
- }
-
- @Test
- public void testDisabledApplicationCatalog() throws TimeoutException, InterruptedException {
- String itemSymbolicName = "my.catalog.item.id.for.disabling";
- String itemVersion = "1.0";
- String serviceType = "org.apache.brooklyn.entity.stock.BasicApplication";
-
- // Deploy the catalog item
- addTestCatalogItem(itemSymbolicName, "template", itemVersion, serviceType);
- List<CatalogEntitySummary> itemSummaries = client().resource("/v1/catalog/applications")
- .queryParam("fragment", itemSymbolicName).queryParam("allVersions", "true").get(new GenericType<List<CatalogEntitySummary>>() {});
- CatalogItemSummary itemSummary = Iterables.getOnlyElement(itemSummaries);
- String itemVersionedId = String.format("%s:%s", itemSummary.getSymbolicName(), itemSummary.getVersion());
- assertEquals(itemSummary.getId(), itemVersionedId);
-
- try {
- // Create an app before disabling: this should work
- String yaml = "{ name: my-app, location: localhost, services: [ { type: \""+itemVersionedId+"\" } ] }";
- ClientResponse response = client().resource("/v1/applications")
- .entity(yaml, "application/x-yaml")
- .post(ClientResponse.class);
- HttpAsserts.assertHealthyStatusCode(response.getStatus());
- waitForPageFoundResponse("/v1/applications/my-app", ApplicationSummary.class);
-
- // Deprecate
- deprecateCatalogItem(itemSymbolicName, itemVersion, true);
-
- // Create an app when deprecated: this should work
- String yaml2 = "{ name: my-app2, location: localhost, services: [ { type: \""+itemVersionedId+"\" } ] }";
- ClientResponse response2 = client().resource("/v1/applications")
- .entity(yaml2, "application/x-yaml")
- .post(ClientResponse.class);
- HttpAsserts.assertHealthyStatusCode(response2.getStatus());
- waitForPageFoundResponse("/v1/applications/my-app2", ApplicationSummary.class);
-
- // Disable
- disableCatalogItem(itemSymbolicName, itemVersion, true);
-
- // Now try creating an app; this should fail because app is disabled
- String yaml3 = "{ name: my-app3, location: localhost, services: [ { type: \""+itemVersionedId+"\" } ] }";
- ClientResponse response3 = client().resource("/v1/applications")
- .entity(yaml3, "application/x-yaml")
- .post(ClientResponse.class);
- HttpAsserts.assertClientErrorStatusCode(response3.getStatus());
- assertTrue(response3.getEntity(String.class).toLowerCase().contains("unable to match"));
- waitForPageNotFoundResponse("/v1/applications/my-app3", ApplicationSummary.class);
-
- } finally {
- client().resource("/v1/applications/my-app")
- .delete(ClientResponse.class);
-
- client().resource("/v1/applications/my-app2")
- .delete(ClientResponse.class);
-
- client().resource("/v1/applications/my-app3")
- .delete(ClientResponse.class);
-
- client().resource("/v1/catalog/entities/"+itemVersionedId+"/"+itemVersion)
- .delete(ClientResponse.class);
- }
- }
-
- private void deprecateCatalogItem(String symbolicName, String version, boolean deprecated) {
- String id = String.format("%s:%s", symbolicName, version);
- ClientResponse response = client().resource(String.format("/v1/catalog/entities/%s/deprecated", id))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .post(ClientResponse.class, deprecated);
- assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
- }
-
- private void disableCatalogItem(String symbolicName, String version, boolean disabled) {
- String id = String.format("%s:%s", symbolicName, version);
- ClientResponse response = client().resource(String.format("/v1/catalog/entities/%s/disabled", id))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .post(ClientResponse.class, disabled);
- assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
- }
-
- private void addTestCatalogItem(String catalogItemId, String itemType, String version, String service) {
- String yaml =
- "brooklyn.catalog:\n"+
- " id: " + catalogItemId + "\n"+
- " name: My Catalog App\n"+
- (itemType!=null ? " item_type: "+itemType+"\n" : "")+
- " description: My description\n"+
- " icon_url: classpath:///redis-logo.png\n"+
- " version: " + version + "\n"+
- "\n"+
- "services:\n"+
- "- type: " + service + "\n";
-
- client().resource("/v1/catalog").post(yaml);
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/CatalogResetTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/CatalogResetTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/CatalogResetTest.java
deleted file mode 100644
index cadea54..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/CatalogResetTest.java
+++ /dev/null
@@ -1,113 +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.resources;
-
-import static org.testng.Assert.assertNotNull;
-
-import javax.ws.rs.core.MediaType;
-
-import org.apache.http.HttpStatus;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.catalog.BrooklynCatalog;
-import org.apache.brooklyn.api.typereg.BrooklynTypeRegistry;
-import org.apache.brooklyn.test.http.TestHttpRequestHandler;
-import org.apache.brooklyn.test.http.TestHttpServer;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.util.core.ResourceUtils;
-
-import com.sun.jersey.api.client.UniformInterfaceException;
-
-public class CatalogResetTest extends BrooklynRestResourceTest {
-
- private TestHttpServer server;
- private String serverUrl;
-
- @BeforeClass(alwaysRun=true)
- @Override
- public void setUp() throws Exception {
- useLocalScannedCatalog();
- super.setUp();
- server = new TestHttpServer()
- .handler("/404", new TestHttpRequestHandler().code(HttpStatus.SC_NOT_FOUND).response("Not Found"))
- .handler("/200", new TestHttpRequestHandler().response("OK"))
- .start();
- serverUrl = server.getUrl();
- }
-
- @Override
- protected void addBrooklynResources() {
- addResource(new CatalogResource());
- }
-
- @AfterClass(alwaysRun=true)
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- server.stop();
- }
-
- @Test(expectedExceptions=UniformInterfaceException.class, expectedExceptionsMessageRegExp="Client response status: 500")
- public void testConnectionError() throws Exception {
- reset("http://0.0.0.0/can-not-connect", false);
- }
-
- @Test
- public void testConnectionErrorIgnore() throws Exception {
- reset("http://0.0.0.0/can-not-connect", true);
- }
-
- @Test(expectedExceptions=UniformInterfaceException.class, expectedExceptionsMessageRegExp="Client response status: 500")
- public void testResourceMissingError() throws Exception {
- reset(serverUrl + "/404", false);
- }
-
- @Test
- public void testResourceMissingIgnore() throws Exception {
- reset(serverUrl + "/404", true);
- }
-
- @Test(expectedExceptions=UniformInterfaceException.class, expectedExceptionsMessageRegExp="Client response status: 500")
- public void testResourceInvalidError() throws Exception {
- reset(serverUrl + "/200", false);
- }
-
- @Test
- public void testResourceInvalidIgnore() throws Exception {
- reset(serverUrl + "/200", true);
- }
-
- private void reset(String bundleLocation, boolean ignoreErrors) throws Exception {
- String xml = ResourceUtils.create(this).getResourceAsString("classpath://reset-catalog.xml");
- client().resource("/v1/catalog/reset")
- .queryParam("ignoreErrors", Boolean.toString(ignoreErrors))
- .header("Content-type", MediaType.APPLICATION_XML)
- .post(xml.replace("${bundle-location}", bundleLocation));
- //if above succeeds assert catalog contents
- assertItems();
- }
-
- private void assertItems() {
- BrooklynTypeRegistry types = getManagementContext().getTypeRegistry();
- assertNotNull(types.get("org.apache.brooklyn.entity.stock.BasicApplication", BrooklynCatalog.DEFAULT_VERSION));
- assertNotNull(types.get("org.apache.brooklyn.test.osgi.entities.SimpleApplication", BrooklynCatalog.DEFAULT_VERSION));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/CatalogResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/CatalogResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/CatalogResourceTest.java
deleted file mode 100644
index a810e6d..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/CatalogResourceTest.java
+++ /dev/null
@@ -1,515 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.awt.*;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URL;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.apache.brooklyn.api.typereg.OsgiBundleWithUrl;
-import org.apache.brooklyn.api.typereg.RegisteredType;
-import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
-import org.apache.brooklyn.core.mgmt.osgi.OsgiStandaloneTest;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.policy.autoscaling.AutoScalerPolicy;
-import org.apache.brooklyn.rest.domain.CatalogEntitySummary;
-import org.apache.brooklyn.rest.domain.CatalogItemSummary;
-import org.apache.brooklyn.rest.domain.CatalogLocationSummary;
-import org.apache.brooklyn.rest.domain.CatalogPolicySummary;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.test.support.TestResourceUnavailableException;
-import org.apache.brooklyn.util.javalang.Reflections;
-import org.apache.http.HttpHeaders;
-import org.apache.http.entity.ContentType;
-import org.eclipse.jetty.http.HttpStatus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-import org.testng.reporters.Files;
-
-import com.google.common.base.Joiner;
-import com.google.common.collect.Iterables;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.GenericType;
-
-public class CatalogResourceTest extends BrooklynRestResourceTest {
-
- private static final Logger log = LoggerFactory.getLogger(CatalogResourceTest.class);
-
- private static String TEST_VERSION = "0.1.2";
-
- @BeforeClass(alwaysRun=true)
- @Override
- public void setUp() throws Exception {
- useLocalScannedCatalog();
- super.setUp();
- }
-
- @Override
- protected void addBrooklynResources() {
- addResource(new CatalogResource());
- }
-
- @Test
- /** based on CampYamlLiteTest */
- public void testRegisterCustomEntityTopLevelSyntaxWithBundleWhereEntityIsFromCoreAndIconFromBundle() {
- TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
-
- String symbolicName = "my.catalog.entity.id";
- String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
- String yaml =
- "brooklyn.catalog:\n"+
- " id: " + symbolicName + "\n"+
- " name: My Catalog App\n"+
- " description: My description\n"+
- " icon_url: classpath:/org/apache/brooklyn/test/osgi/entities/icon.gif\n"+
- " version: " + TEST_VERSION + "\n"+
- " libraries:\n"+
- " - url: " + bundleUrl + "\n"+
- "\n"+
- "services:\n"+
- "- type: org.apache.brooklyn.core.test.entity.TestEntity\n";
-
- ClientResponse response = client().resource("/v1/catalog")
- .post(ClientResponse.class, yaml);
-
- assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
-
- CatalogEntitySummary entityItem = client().resource("/v1/catalog/entities/"+symbolicName + "/" + TEST_VERSION)
- .get(CatalogEntitySummary.class);
-
- Assert.assertNotNull(entityItem.getPlanYaml());
- Assert.assertTrue(entityItem.getPlanYaml().contains("org.apache.brooklyn.core.test.entity.TestEntity"));
-
- assertEquals(entityItem.getId(), ver(symbolicName));
- assertEquals(entityItem.getSymbolicName(), symbolicName);
- assertEquals(entityItem.getVersion(), TEST_VERSION);
-
- // and internally let's check we have libraries
- RegisteredType item = getManagementContext().getTypeRegistry().get(symbolicName, TEST_VERSION);
- Assert.assertNotNull(item);
- Collection<OsgiBundleWithUrl> libs = item.getLibraries();
- assertEquals(libs.size(), 1);
- assertEquals(Iterables.getOnlyElement(libs).getUrl(), bundleUrl);
-
- // now let's check other things on the item
- assertEquals(entityItem.getName(), "My Catalog App");
- assertEquals(entityItem.getDescription(), "My description");
- assertEquals(URI.create(entityItem.getIconUrl()).getPath(), "/v1/catalog/icon/" + symbolicName + "/" + entityItem.getVersion());
- assertEquals(item.getIconUrl(), "classpath:/org/apache/brooklyn/test/osgi/entities/icon.gif");
-
- // an InterfacesTag should be created for every catalog item
- assertEquals(entityItem.getTags().size(), 1);
- Object tag = entityItem.getTags().iterator().next();
- @SuppressWarnings("unchecked")
- List<String> actualInterfaces = ((Map<String, List<String>>) tag).get("traits");
- List<Class<?>> expectedInterfaces = Reflections.getAllInterfaces(TestEntity.class);
- assertEquals(actualInterfaces.size(), expectedInterfaces.size());
- for (Class<?> expectedInterface : expectedInterfaces) {
- assertTrue(actualInterfaces.contains(expectedInterface.getName()));
- }
-
- byte[] iconData = client().resource("/v1/catalog/icon/" + symbolicName + "/" + TEST_VERSION).get(byte[].class);
- assertEquals(iconData.length, 43);
- }
-
- @Test
- // osgi fails in IDE, should work on CLI though
- public void testRegisterOsgiPolicyTopLevelSyntax() {
- TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
-
- String symbolicName = "my.catalog.policy.id";
- String policyType = "org.apache.brooklyn.test.osgi.entities.SimplePolicy";
- String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
-
- String yaml =
- "brooklyn.catalog:\n"+
- " id: " + symbolicName + "\n"+
- " name: My Catalog App\n"+
- " description: My description\n"+
- " version: " + TEST_VERSION + "\n" +
- " libraries:\n"+
- " - url: " + bundleUrl + "\n"+
- "\n"+
- "brooklyn.policies:\n"+
- "- type: " + policyType;
-
- CatalogPolicySummary entityItem = Iterables.getOnlyElement( client().resource("/v1/catalog")
- .post(new GenericType<Map<String,CatalogPolicySummary>>() {}, yaml).values() );
-
- Assert.assertNotNull(entityItem.getPlanYaml());
- Assert.assertTrue(entityItem.getPlanYaml().contains(policyType));
- assertEquals(entityItem.getId(), ver(symbolicName));
- assertEquals(entityItem.getSymbolicName(), symbolicName);
- assertEquals(entityItem.getVersion(), TEST_VERSION);
- }
-
- @Test
- public void testListAllEntities() {
- List<CatalogEntitySummary> entities = client().resource("/v1/catalog/entities")
- .get(new GenericType<List<CatalogEntitySummary>>() {});
- assertTrue(entities.size() > 0);
- }
-
- @Test
- public void testListAllEntitiesAsItem() {
- // ensure things are happily downcasted and unknown properties ignored (e.g. sensors, effectors)
- List<CatalogItemSummary> entities = client().resource("/v1/catalog/entities")
- .get(new GenericType<List<CatalogItemSummary>>() {});
- assertTrue(entities.size() > 0);
- }
-
- @Test
- public void testFilterListOfEntitiesByName() {
- List<CatalogEntitySummary> entities = client().resource("/v1/catalog/entities")
- .queryParam("fragment", "brOOkLynENTITYmiRrOr").get(new GenericType<List<CatalogEntitySummary>>() {});
- assertEquals(entities.size(), 1);
-
- log.info("BrooklynEntityMirror-like entities are: " + entities);
-
- List<CatalogEntitySummary> entities2 = client().resource("/v1/catalog/entities")
- .queryParam("regex", "[Bb]ro+klynEntityMi[ro]+").get(new GenericType<List<CatalogEntitySummary>>() {});
- assertEquals(entities2.size(), 1);
-
- assertEquals(entities, entities2);
-
- List<CatalogEntitySummary> entities3 = client().resource("/v1/catalog/entities")
- .queryParam("fragment", "bweqQzZ").get(new GenericType<List<CatalogEntitySummary>>() {});
- assertEquals(entities3.size(), 0);
-
- List<CatalogEntitySummary> entities4 = client().resource("/v1/catalog/entities")
- .queryParam("regex", "bweq+z+").get(new GenericType<List<CatalogEntitySummary>>() {});
- assertEquals(entities4.size(), 0);
- }
-
- @Test
- @Deprecated
- // If we move to using a yaml catalog item, the details will be of the wrapping app,
- // not of the entity itself, so the test won't make sense any more.
- public void testGetCatalogEntityDetails() {
- CatalogEntitySummary details = client()
- .resource(URI.create("/v1/catalog/entities/org.apache.brooklyn.entity.brooklynnode.BrooklynNode"))
- .get(CatalogEntitySummary.class);
- assertTrue(details.toString().contains("download.url"), "expected more config, only got: "+details);
- }
-
- @Test
- @Deprecated
- // If we move to using a yaml catalog item, the details will be of the wrapping app,
- // not of the entity itself, so the test won't make sense any more.
- public void testGetCatalogEntityPlusVersionDetails() {
- CatalogEntitySummary details = client()
- .resource(URI.create("/v1/catalog/entities/org.apache.brooklyn.entity.brooklynnode.BrooklynNode:0.0.0.SNAPSHOT"))
- .get(CatalogEntitySummary.class);
- assertTrue(details.toString().contains("download.url"), "expected more config, only got: "+details);
- }
-
- @Test
- public void testGetCatalogEntityIconDetails() throws IOException {
- String catalogItemId = "testGetCatalogEntityIconDetails";
- addTestCatalogItemBrooklynNodeAsEntity(catalogItemId);
- ClientResponse response = client().resource(URI.create("/v1/catalog/icon/" + catalogItemId + "/" + TEST_VERSION))
- .get(ClientResponse.class);
- response.bufferEntity();
- Assert.assertEquals(response.getStatus(), 200);
- Assert.assertEquals(response.getType(), MediaType.valueOf("image/jpeg"));
- Image image = Toolkit.getDefaultToolkit().createImage(Files.readFile(response.getEntityInputStream()));
- Assert.assertNotNull(image);
- }
-
- private void addTestCatalogItemBrooklynNodeAsEntity(String catalogItemId) {
- addTestCatalogItem(catalogItemId, null, TEST_VERSION, "org.apache.brooklyn.entity.brooklynnode.BrooklynNode");
- }
-
- private void addTestCatalogItem(String catalogItemId, String itemType, String version, String service) {
- String yaml =
- "brooklyn.catalog:\n"+
- " id: " + catalogItemId + "\n"+
- " name: My Catalog App\n"+
- (itemType!=null ? " item_type: "+itemType+"\n" : "")+
- " description: My description\n"+
- " icon_url: classpath:///brooklyn-test-logo.jpg\n"+
- " version: " + version + "\n"+
- "\n"+
- "services:\n"+
- "- type: " + service + "\n";
-
- client().resource("/v1/catalog").post(yaml);
- }
-
- private enum DeprecateStyle {
- NEW_STYLE,
- LEGACY_STYLE
- }
- private void deprecateCatalogItem(DeprecateStyle style, String symbolicName, String version, boolean deprecated) {
- String id = String.format("%s:%s", symbolicName, version);
- ClientResponse response;
- if (style == DeprecateStyle.NEW_STYLE) {
- response = client().resource(String.format("/v1/catalog/entities/%s/deprecated", id))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .post(ClientResponse.class, deprecated);
- } else {
- response = client().resource(String.format("/v1/catalog/entities/%s/deprecated/%s", id, deprecated))
- .post(ClientResponse.class);
- }
- assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
- }
-
- private void disableCatalogItem(String symbolicName, String version, boolean disabled) {
- String id = String.format("%s:%s", symbolicName, version);
- ClientResponse getDisableResponse = client().resource(String.format("/v1/catalog/entities/%s/disabled", id))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .post(ClientResponse.class, disabled);
- assertEquals(getDisableResponse.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
- }
-
- @Test
- public void testListPolicies() {
- Set<CatalogPolicySummary> policies = client().resource("/v1/catalog/policies")
- .get(new GenericType<Set<CatalogPolicySummary>>() {});
-
- assertTrue(policies.size() > 0);
- CatalogItemSummary asp = null;
- for (CatalogItemSummary p : policies) {
- if (AutoScalerPolicy.class.getName().equals(p.getType()))
- asp = p;
- }
- Assert.assertNotNull(asp, "didn't find AutoScalerPolicy");
- }
-
- @Test
- public void testLocationAddGetAndRemove() {
- String symbolicName = "my.catalog.location.id";
- String locationType = "localhost";
- String yaml = Joiner.on("\n").join(
- "brooklyn.catalog:",
- " id: " + symbolicName,
- " name: My Catalog Location",
- " description: My description",
- " version: " + TEST_VERSION,
- "",
- "brooklyn.locations:",
- "- type: " + locationType);
-
- // Create location item
- Map<String, CatalogLocationSummary> items = client().resource("/v1/catalog")
- .post(new GenericType<Map<String,CatalogLocationSummary>>() {}, yaml);
- CatalogLocationSummary locationItem = Iterables.getOnlyElement(items.values());
-
- Assert.assertNotNull(locationItem.getPlanYaml());
- Assert.assertTrue(locationItem.getPlanYaml().contains(locationType));
- assertEquals(locationItem.getId(), ver(symbolicName));
- assertEquals(locationItem.getSymbolicName(), symbolicName);
- assertEquals(locationItem.getVersion(), TEST_VERSION);
-
- // Retrieve location item
- CatalogLocationSummary location = client().resource("/v1/catalog/locations/"+symbolicName+"/"+TEST_VERSION)
- .get(CatalogLocationSummary.class);
- assertEquals(location.getSymbolicName(), symbolicName);
-
- // Retrieve all locations
- Set<CatalogLocationSummary> locations = client().resource("/v1/catalog/locations")
- .get(new GenericType<Set<CatalogLocationSummary>>() {});
- boolean found = false;
- for (CatalogLocationSummary contender : locations) {
- if (contender.getSymbolicName().equals(symbolicName)) {
- found = true;
- break;
- }
- }
- Assert.assertTrue(found, "contenders="+locations);
-
- // Delete
- ClientResponse deleteResponse = client().resource("/v1/catalog/locations/"+symbolicName+"/"+TEST_VERSION)
- .delete(ClientResponse.class);
- assertEquals(deleteResponse.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
-
- ClientResponse getPostDeleteResponse = client().resource("/v1/catalog/locations/"+symbolicName+"/"+TEST_VERSION)
- .get(ClientResponse.class);
- assertEquals(getPostDeleteResponse.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
- }
-
- @Test
- public void testDeleteCustomEntityFromCatalog() {
- String symbolicName = "my.catalog.app.id.to.subsequently.delete";
- String yaml =
- "name: "+symbolicName+"\n"+
- // FIXME name above should be unnecessary when brooklyn.catalog below is working
- "brooklyn.catalog:\n"+
- " id: " + symbolicName + "\n"+
- " name: My Catalog App To Be Deleted\n"+
- " description: My description\n"+
- " version: " + TEST_VERSION + "\n"+
- "\n"+
- "services:\n"+
- "- type: org.apache.brooklyn.core.test.entity.TestEntity\n";
-
- client().resource("/v1/catalog")
- .post(ClientResponse.class, yaml);
-
- ClientResponse deleteResponse = client().resource("/v1/catalog/entities/"+symbolicName+"/"+TEST_VERSION)
- .delete(ClientResponse.class);
-
- assertEquals(deleteResponse.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
-
- ClientResponse getPostDeleteResponse = client().resource("/v1/catalog/entities/"+symbolicName+"/"+TEST_VERSION)
- .get(ClientResponse.class);
- assertEquals(getPostDeleteResponse.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
- }
-
- @Test
- public void testSetDeprecated() {
- runSetDeprecated(DeprecateStyle.NEW_STYLE);
- }
-
- // Uses old-style "/v1/catalog/{itemId}/deprecated/true", rather than the "true" in the request body.
- @Test
- @Deprecated
- public void testSetDeprecatedLegacy() {
- runSetDeprecated(DeprecateStyle.LEGACY_STYLE);
- }
-
- protected void runSetDeprecated(DeprecateStyle style) {
- String symbolicName = "my.catalog.item.id.for.deprecation";
- String serviceType = "org.apache.brooklyn.entity.stock.BasicApplication";
- addTestCatalogItem(symbolicName, "template", TEST_VERSION, serviceType);
- addTestCatalogItem(symbolicName, "template", "2.0", serviceType);
- try {
- List<CatalogEntitySummary> applications = client().resource("/v1/catalog/applications")
- .queryParam("fragment", symbolicName).queryParam("allVersions", "true").get(new GenericType<List<CatalogEntitySummary>>() {});
- assertEquals(applications.size(), 2);
- CatalogItemSummary summary0 = applications.get(0);
- CatalogItemSummary summary1 = applications.get(1);
-
- // Deprecate: that app should be excluded
- deprecateCatalogItem(style, summary0.getSymbolicName(), summary0.getVersion(), true);
-
- List<CatalogEntitySummary> applicationsAfterDeprecation = client().resource("/v1/catalog/applications")
- .queryParam("fragment", "basicapp").queryParam("allVersions", "true").get(new GenericType<List<CatalogEntitySummary>>() {});
-
- assertEquals(applicationsAfterDeprecation.size(), 1);
- assertTrue(applicationsAfterDeprecation.contains(summary1));
-
- // Un-deprecate: that app should be included again
- deprecateCatalogItem(style, summary0.getSymbolicName(), summary0.getVersion(), false);
-
- List<CatalogEntitySummary> applicationsAfterUnDeprecation = client().resource("/v1/catalog/applications")
- .queryParam("fragment", "basicapp").queryParam("allVersions", "true").get(new GenericType<List<CatalogEntitySummary>>() {});
-
- assertEquals(applications, applicationsAfterUnDeprecation);
- } finally {
- client().resource("/v1/catalog/entities/"+symbolicName+"/"+TEST_VERSION)
- .delete(ClientResponse.class);
- client().resource("/v1/catalog/entities/"+symbolicName+"/"+"2.0")
- .delete(ClientResponse.class);
- }
- }
-
- @Test
- public void testSetDisabled() {
- String symbolicName = "my.catalog.item.id.for.disabling";
- String serviceType = "org.apache.brooklyn.entity.stock.BasicApplication";
- addTestCatalogItem(symbolicName, "template", TEST_VERSION, serviceType);
- addTestCatalogItem(symbolicName, "template", "2.0", serviceType);
- try {
- List<CatalogEntitySummary> applications = client().resource("/v1/catalog/applications")
- .queryParam("fragment", symbolicName).queryParam("allVersions", "true").get(new GenericType<List<CatalogEntitySummary>>() {});
- assertEquals(applications.size(), 2);
- CatalogItemSummary summary0 = applications.get(0);
- CatalogItemSummary summary1 = applications.get(1);
-
- // Disable: that app should be excluded
- disableCatalogItem(summary0.getSymbolicName(), summary0.getVersion(), true);
-
- List<CatalogEntitySummary> applicationsAfterDisabled = client().resource("/v1/catalog/applications")
- .queryParam("fragment", "basicapp").queryParam("allVersions", "true").get(new GenericType<List<CatalogEntitySummary>>() {});
-
- assertEquals(applicationsAfterDisabled.size(), 1);
- assertTrue(applicationsAfterDisabled.contains(summary1));
-
- // Un-disable: that app should be included again
- disableCatalogItem(summary0.getSymbolicName(), summary0.getVersion(), false);
-
- List<CatalogEntitySummary> applicationsAfterUnDisabled = client().resource("/v1/catalog/applications")
- .queryParam("fragment", "basicapp").queryParam("allVersions", "true").get(new GenericType<List<CatalogEntitySummary>>() {});
-
- assertEquals(applications, applicationsAfterUnDisabled);
- } finally {
- client().resource("/v1/catalog/entities/"+symbolicName+"/"+TEST_VERSION)
- .delete(ClientResponse.class);
- client().resource("/v1/catalog/entities/"+symbolicName+"/"+"2.0")
- .delete(ClientResponse.class);
- }
- }
-
- @Test
- public void testAddUnreachableItem() {
- addInvalidCatalogItem("http://0.0.0.0/can-not-connect");
- }
-
- @Test
- public void testAddInvalidItem() {
- //equivalent to HTTP response 200 text/html
- addInvalidCatalogItem("classpath://not-a-jar-file.txt");
- }
-
- @Test
- public void testAddMissingItem() {
- //equivalent to HTTP response 404 text/html
- addInvalidCatalogItem("classpath://missing-jar-file.txt");
- }
-
- private void addInvalidCatalogItem(String bundleUrl) {
- String symbolicName = "my.catalog.entity.id";
- String yaml =
- "brooklyn.catalog:\n"+
- " id: " + symbolicName + "\n"+
- " name: My Catalog App\n"+
- " description: My description\n"+
- " icon_url: classpath:/org/apache/brooklyn/test/osgi/entities/icon.gif\n"+
- " version: " + TEST_VERSION + "\n"+
- " libraries:\n"+
- " - url: " + bundleUrl + "\n"+
- "\n"+
- "services:\n"+
- "- type: org.apache.brooklyn.core.test.entity.TestEntity\n";
-
- ClientResponse response = client().resource("/v1/catalog")
- .post(ClientResponse.class, yaml);
-
- assertEquals(response.getStatus(), HttpStatus.BAD_REQUEST_400);
- }
-
- private static String ver(String id) {
- return CatalogUtils.getVersionedId(id, TEST_VERSION);
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/DelegatingPrintStream.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/DelegatingPrintStream.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/DelegatingPrintStream.java
deleted file mode 100644
index 713dccb..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/DelegatingPrintStream.java
+++ /dev/null
@@ -1,183 +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.resources;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.Locale;
-
-public abstract class DelegatingPrintStream extends PrintStream {
-
- public DelegatingPrintStream() {
- super(new IllegalOutputStream());
- }
-
- public static class IllegalOutputStream extends OutputStream {
- @Override public void write(int b) {
- throw new IllegalStateException("should not write to this output stream");
- }
- @Override public void write(byte[] b, int off, int len) {
- throw new IllegalStateException("should not write to this output stream");
- }
- }
-
- protected abstract PrintStream getDelegate();
-
- public int hashCode() {
- return getDelegate().hashCode();
- }
-
- public void write(byte[] b) throws IOException {
- getDelegate().write(b);
- }
-
- public boolean equals(Object obj) {
- return getDelegate().equals(obj);
- }
-
- public String toString() {
- return getDelegate().toString();
- }
-
- public void flush() {
- getDelegate().flush();
- }
-
- public void close() {
- getDelegate().close();
- }
-
- public boolean checkError() {
- return getDelegate().checkError();
- }
-
- public void write(int b) {
- getDelegate().write(b);
- }
-
- public void write(byte[] buf, int off, int len) {
- getDelegate().write(buf, off, len);
- }
-
- public void print(boolean b) {
- getDelegate().print(b);
- }
-
- public void print(char c) {
- getDelegate().print(c);
- }
-
- public void print(int i) {
- getDelegate().print(i);
- }
-
- public void print(long l) {
- getDelegate().print(l);
- }
-
- public void print(float f) {
- getDelegate().print(f);
- }
-
- public void print(double d) {
- getDelegate().print(d);
- }
-
- public void print(char[] s) {
- getDelegate().print(s);
- }
-
- public void print(String s) {
- getDelegate().print(s);
- }
-
- public void print(Object obj) {
- getDelegate().print(obj);
- }
-
- public void println() {
- getDelegate().println();
- }
-
- public void println(boolean x) {
- getDelegate().println(x);
- }
-
- public void println(char x) {
- getDelegate().println(x);
- }
-
- public void println(int x) {
- getDelegate().println(x);
- }
-
- public void println(long x) {
- getDelegate().println(x);
- }
-
- public void println(float x) {
- getDelegate().println(x);
- }
-
- public void println(double x) {
- getDelegate().println(x);
- }
-
- public void println(char[] x) {
- getDelegate().println(x);
- }
-
- public void println(String x) {
- getDelegate().println(x);
- }
-
- public void println(Object x) {
- getDelegate().println(x);
- }
-
- public PrintStream printf(String format, Object... args) {
- return getDelegate().printf(format, args);
- }
-
- public PrintStream printf(Locale l, String format, Object... args) {
- return getDelegate().printf(l, format, args);
- }
-
- public PrintStream format(String format, Object... args) {
- return getDelegate().format(format, args);
- }
-
- public PrintStream format(Locale l, String format, Object... args) {
- return getDelegate().format(l, format, args);
- }
-
- public PrintStream append(CharSequence csq) {
- return getDelegate().append(csq);
- }
-
- public PrintStream append(CharSequence csq, int start, int end) {
- return getDelegate().append(csq, start, end);
- }
-
- public PrintStream append(char c) {
- return getDelegate().append(c);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/DescendantsTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/DescendantsTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/DescendantsTest.java
deleted file mode 100644
index 3f42c8d..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/DescendantsTest.java
+++ /dev/null
@@ -1,130 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.TimeoutException;
-
-import org.apache.brooklyn.api.entity.Application;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.core.sensor.Sensors;
-import org.apache.brooklyn.rest.domain.ApplicationSpec;
-import org.apache.brooklyn.rest.domain.EntitySpec;
-import org.apache.brooklyn.rest.domain.EntitySummary;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.text.StringEscapes;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import com.sun.jersey.api.client.ClientHandlerException;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.GenericType;
-import com.sun.jersey.api.client.UniformInterfaceException;
-
-@Test(singleThreaded = true)
-public class DescendantsTest extends BrooklynRestResourceTest {
-
- private static final Logger log = LoggerFactory.getLogger(DescendantsTest.class);
-
- private final ApplicationSpec simpleSpec = ApplicationSpec.builder().name("simple-app").
- entities(ImmutableSet.of(
- new EntitySpec("simple-ent-1", RestMockSimpleEntity.class.getName()),
- new EntitySpec("simple-ent-2", RestMockSimpleEntity.class.getName()))).
- locations(ImmutableSet.of("localhost")).
- build();
-
- @Test
- public void testDescendantsInSimpleDeployedApplication() throws InterruptedException, TimeoutException, UniformInterfaceException, ClientHandlerException, IOException {
- ClientResponse response = clientDeploy(simpleSpec);
- assertTrue(response.getStatus()/100 == 2, "response is "+response);
- Application application = Iterables.getOnlyElement( getManagementContext().getApplications() );
- List<Entity> entities = MutableList.copyOf( application.getChildren() );
- log.debug("Created app "+application+" with children entities "+entities);
- assertEquals(entities.size(), 2);
-
- Set<EntitySummary> descs;
- descs = client().resource("/v1/applications/"+application.getApplicationId()+"/descendants")
- .get(new GenericType<Set<EntitySummary>>() {});
- // includes itself
- assertEquals(descs.size(), 3);
-
- descs = client().resource("/v1/applications/"+application.getApplicationId()+"/descendants"
- + "?typeRegex="+StringEscapes.escapeUrlParam(".*\\.RestMockSimpleEntity"))
- .get(new GenericType<Set<EntitySummary>>() {});
- assertEquals(descs.size(), 2);
-
- descs = client().resource("/v1/applications/"+application.getApplicationId()+"/descendants"
- + "?typeRegex="+StringEscapes.escapeUrlParam(".*\\.BestBockSimpleEntity"))
- .get(new GenericType<Set<EntitySummary>>() {});
- assertEquals(descs.size(), 0);
-
- descs = client().resource("/v1/applications/"+application.getApplicationId()
- + "/entities/"+entities.get(1).getId()
- + "/descendants"
- + "?typeRegex="+StringEscapes.escapeUrlParam(".*\\.RestMockSimpleEntity"))
- .get(new GenericType<Set<EntitySummary>>() {});
- assertEquals(descs.size(), 1);
-
- Map<String,Object> sensors = client().resource("/v1/applications/"+application.getApplicationId()+"/descendants/sensor/foo"
- + "?typeRegex="+StringEscapes.escapeUrlParam(".*\\.RestMockSimpleEntity"))
- .get(new GenericType<Map<String,Object>>() {});
- assertEquals(sensors.size(), 0);
-
- long v = 0;
- application.sensors().set(Sensors.newLongSensor("foo"), v);
- for (Entity e: entities)
- e.sensors().set(Sensors.newLongSensor("foo"), v+=123);
-
- sensors = client().resource("/v1/applications/"+application.getApplicationId()+"/descendants/sensor/foo")
- .get(new GenericType<Map<String,Object>>() {});
- assertEquals(sensors.size(), 3);
- assertEquals(sensors.get(entities.get(1).getId()), 246);
-
- sensors = client().resource("/v1/applications/"+application.getApplicationId()+"/descendants/sensor/foo"
- + "?typeRegex="+StringEscapes.escapeUrlParam(".*\\.RestMockSimpleEntity"))
- .get(new GenericType<Map<String,Object>>() {});
- assertEquals(sensors.size(), 2);
-
- sensors = client().resource("/v1/applications/"+application.getApplicationId()+"/"
- + "entities/"+entities.get(1).getId()+"/"
- + "descendants/sensor/foo"
- + "?typeRegex="+StringEscapes.escapeUrlParam(".*\\.RestMockSimpleEntity"))
- .get(new GenericType<Map<String,Object>>() {});
- assertEquals(sensors.size(), 1);
-
- sensors = client().resource("/v1/applications/"+application.getApplicationId()+"/"
- + "entities/"+entities.get(1).getId()+"/"
- + "descendants/sensor/foo"
- + "?typeRegex="+StringEscapes.escapeUrlParam(".*\\.FestPockSimpleEntity"))
- .get(new GenericType<Map<String,Object>>() {});
- assertEquals(sensors.size(), 0);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/EntityConfigResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/EntityConfigResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/EntityConfigResourceTest.java
deleted file mode 100644
index 014053f..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/EntityConfigResourceTest.java
+++ /dev/null
@@ -1,172 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertTrue;
-
-import java.net.URI;
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.Nullable;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.core.entity.EntityInternal;
-import org.apache.brooklyn.core.entity.EntityPredicates;
-import org.apache.brooklyn.rest.domain.ApplicationSpec;
-import org.apache.brooklyn.rest.domain.EntityConfigSummary;
-import org.apache.brooklyn.rest.domain.EntitySpec;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity;
-import org.apache.brooklyn.util.collections.MutableMap;
-
-import com.google.common.base.Optional;
-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 com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.GenericType;
-
-@Test(singleThreaded = true)
-public class EntityConfigResourceTest extends BrooklynRestResourceTest {
-
- private final static Logger log = LoggerFactory.getLogger(EntityConfigResourceTest.class);
- private URI applicationUri;
- private EntityInternal entity;
-
- @BeforeClass(alwaysRun = true)
- @Override
- public void setUp() throws Exception {
- super.setUp(); // We require that the superclass setup is done first, as we will be calling out to Jersey
-
- // Deploy an application that we'll use to read the configuration of
- final ApplicationSpec simpleSpec = ApplicationSpec.builder().name("simple-app").
- entities(ImmutableSet.of(new EntitySpec("simple-ent", RestMockSimpleEntity.class.getName(), ImmutableMap.of("install.version", "1.0.0")))).
- locations(ImmutableSet.of("localhost")).
- build();
-
- ClientResponse response = clientDeploy(simpleSpec);
- int status = response.getStatus();
- assertTrue(status >= 200 && status <= 299, "expected HTTP Response of 2xx but got " + status);
- applicationUri = response.getLocation();
- log.debug("Built app: application");
- waitForApplicationToBeRunning(applicationUri);
-
- entity = (EntityInternal) Iterables.find(getManagementContext().getEntityManager().getEntities(), EntityPredicates.displayNameEqualTo("simple-ent"));
- }
-
- @Test
- public void testList() throws Exception {
- List<EntityConfigSummary> entityConfigSummaries = client().resource(
- URI.create("/v1/applications/simple-app/entities/simple-ent/config"))
- .get(new GenericType<List<EntityConfigSummary>>() {
- });
-
- // Default entities have over a dozen config entries, but it's unnecessary to test them all; just pick one
- // representative config key
- Optional<EntityConfigSummary> configKeyOptional = Iterables.tryFind(entityConfigSummaries, new Predicate<EntityConfigSummary>() {
- @Override
- public boolean apply(@Nullable EntityConfigSummary input) {
- return input != null && "install.version".equals(input.getName());
- }
- });
- assertTrue(configKeyOptional.isPresent());
-
- assertEquals(configKeyOptional.get().getType(), "java.lang.String");
- assertEquals(configKeyOptional.get().getDescription(), "Suggested version");
- assertFalse(configKeyOptional.get().isReconfigurable());
- assertNull(configKeyOptional.get().getDefaultValue());
- assertNull(configKeyOptional.get().getLabel());
- assertNull(configKeyOptional.get().getPriority());
- }
-
- @Test
- public void testBatchConfigRead() throws Exception {
- Map<String, Object> currentState = client().resource(
- URI.create("/v1/applications/simple-app/entities/simple-ent/config/current-state"))
- .get(new GenericType<Map<String, Object>>() {
- });
- assertTrue(currentState.containsKey("install.version"));
- assertEquals(currentState.get("install.version"), "1.0.0");
- }
-
- @Test
- public void testGetJson() throws Exception {
- String configValue = client().resource(
- URI.create("/v1/applications/simple-app/entities/simple-ent/config/install.version"))
- .accept(MediaType.APPLICATION_JSON_TYPE)
- .get(String.class);
- assertEquals(configValue, "\"1.0.0\"");
- }
-
- @Test
- public void testGetPlain() throws Exception {
- String configValue = client().resource(
- URI.create("/v1/applications/simple-app/entities/simple-ent/config/install.version"))
- .accept(MediaType.TEXT_PLAIN_TYPE)
- .get(String.class);
- assertEquals(configValue, "1.0.0");
- }
-
- @Test
- public void testSet() throws Exception {
- try {
- String uri = "/v1/applications/simple-app/entities/simple-ent/config/"+
- RestMockSimpleEntity.SAMPLE_CONFIG.getName();
- ClientResponse response = client().resource(uri)
- .type(MediaType.APPLICATION_JSON_TYPE)
- .post(ClientResponse.class, "\"hello world\"");
- assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
-
- assertEquals(entity.getConfig(RestMockSimpleEntity.SAMPLE_CONFIG), "hello world");
-
- String value = client().resource(uri).accept(MediaType.APPLICATION_JSON_TYPE).get(String.class);
- assertEquals(value, "\"hello world\"");
-
- } finally { entity.config().set(RestMockSimpleEntity.SAMPLE_CONFIG, RestMockSimpleEntity.SAMPLE_CONFIG.getDefaultValue()); }
- }
-
- @Test
- public void testSetFromMap() throws Exception {
- try {
- String uri = "/v1/applications/simple-app/entities/simple-ent/config";
- ClientResponse response = client().resource(uri)
- .type(MediaType.APPLICATION_JSON_TYPE)
- .post(ClientResponse.class, MutableMap.of(
- RestMockSimpleEntity.SAMPLE_CONFIG.getName(), "hello world"));
- assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
-
- assertEquals(entity.getConfig(RestMockSimpleEntity.SAMPLE_CONFIG), "hello world");
-
- String value = client().resource(uri+"/"+RestMockSimpleEntity.SAMPLE_CONFIG.getName()).accept(MediaType.APPLICATION_JSON_TYPE).get(String.class);
- assertEquals(value, "\"hello world\"");
-
- } finally { entity.config().set(RestMockSimpleEntity.SAMPLE_CONFIG, RestMockSimpleEntity.SAMPLE_CONFIG.getDefaultValue()); }
- }
-
-}
[7/9] brooklyn-server git commit: Remove jersey compatibility
Posted by sj...@apache.org.
Remove jersey compatibility
Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/3be4fe11
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/3be4fe11
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/3be4fe11
Branch: refs/heads/master
Commit: 3be4fe11e74b01a85234fe5d0c96d043d3cb44e1
Parents: 36a2918
Author: Svetoslav Neykov <sv...@cloudsoftcorp.com>
Authored: Thu Mar 31 11:37:30 2016 +0300
Committer: Svetoslav Neykov <sv...@cloudsoftcorp.com>
Committed: Fri Apr 1 09:31:08 2016 +0300
----------------------------------------------------------------------
camp/camp-server-jersey/pom.xml | 225 ------
.../brooklyn/camp/server/RestApiSetup.java | 53 --
.../rest/resource/ApiListingResource.java | 260 -------
.../rest/resource/ApidocRestResource.java | 32 -
.../src/main/webapp/WEB-INF/web.xml | 142 ----
camp/pom.xml | 1 -
karaf/features/src/main/feature/feature.xml | 3 -
launcher/pom.xml | 25 +-
parent/pom.xml | 59 --
pom.xml | 3 -
rest/rest-client/pom.xml | 13 -
rest/rest-server-jersey/pom.xml | 351 ----------
.../org/apache/brooklyn/rest/RestApiSetup.java | 113 ---
.../rest/filter/EntitlementContextFilter.java | 63 --
.../rest/filter/HaHotCheckResourceFilter.java | 196 ------
.../brooklyn/rest/filter/NoCacheFilter.java | 42 --
.../rest/filter/RequestTaggingRsFilter.java | 76 --
.../brooklyn/rest/filter/SwaggerFilter.java | 76 --
.../rest/resources/ApiListingResource.java | 260 -------
.../brooklyn/rest/resources/ApidocResource.java | 33 -
.../brooklyn/rest/util/FormMapProvider.java | 81 ---
.../main/resources/build-metadata.properties | 18 -
.../src/main/webapp/WEB-INF/web.xml | 149 ----
.../BrooklynPropertiesSecurityFilterTest.java | 151 ----
.../brooklyn/rest/BrooklynRestApiLauncher.java | 498 -------------
.../rest/BrooklynRestApiLauncherTest.java | 77 --
.../BrooklynRestApiLauncherTestFixture.java | 109 ---
.../apache/brooklyn/rest/HaHotCheckTest.java | 160 -----
.../brooklyn/rest/HaMasterCheckFilterTest.java | 218 ------
.../rest/domain/AbstractDomainTest.java | 44 --
.../brooklyn/rest/domain/ApiErrorTest.java | 71 --
.../rest/domain/ApplicationSpecTest.java | 40 --
.../brooklyn/rest/domain/ApplicationTest.java | 87 ---
.../rest/domain/EffectorSummaryTest.java | 44 --
.../brooklyn/rest/domain/EntitySpecTest.java | 48 --
.../brooklyn/rest/domain/EntitySummaryTest.java | 48 --
.../brooklyn/rest/domain/LocationSpecTest.java | 58 --
.../rest/domain/LocationSummaryTest.java | 41 --
.../brooklyn/rest/domain/SensorSummaryTest.java | 103 ---
.../rest/domain/VersionSummaryTest.java | 49 --
.../AbstractRestApiEntitlementsTest.java | 111 ---
.../ActivityApiEntitlementsTest.java | 122 ----
.../AuthenticateAnyoneSecurityProvider.java | 41 --
.../EntityConfigApiEntitlementsTest.java | 103 ---
.../entitlement/SensorApiEntitlementsTest.java | 108 ---
.../entitlement/ServerApiEntitlementsTest.java | 34 -
.../StaticDelegatingEntitlementManager.java | 37 -
.../rest/resources/AccessResourceTest.java | 68 --
.../rest/resources/ApidocResourceTest.java | 173 -----
.../ApplicationResourceIntegrationTest.java | 133 ----
.../rest/resources/ApplicationResourceTest.java | 701 -------------------
.../rest/resources/CatalogResetTest.java | 113 ---
.../rest/resources/CatalogResourceTest.java | 515 --------------
.../rest/resources/DelegatingPrintStream.java | 183 -----
.../rest/resources/DescendantsTest.java | 130 ----
.../resources/EntityConfigResourceTest.java | 172 -----
.../rest/resources/EntityResourceTest.java | 189 -----
.../rest/resources/ErrorResponseTest.java | 98 ---
.../rest/resources/LocationResourceTest.java | 188 -----
.../rest/resources/PolicyResourceTest.java | 145 ----
.../rest/resources/ScriptResourceTest.java | 54 --
.../SensorResourceIntegrationTest.java | 82 ---
.../rest/resources/SensorResourceTest.java | 271 -------
.../ServerResourceIntegrationTest.java | 125 ----
.../rest/resources/ServerResourceTest.java | 168 -----
.../rest/resources/ServerShutdownTest.java | 185 -----
.../rest/resources/UsageResourceTest.java | 443 ------------
.../rest/resources/VersionResourceTest.java | 52 --
.../rest/security/PasswordHasherTest.java | 37 -
.../security/provider/TestSecurityProvider.java | 46 --
.../test/config/render/TestRendererHints.java | 36 -
.../brooklynnode/DeployBlueprintTest.java | 89 ---
.../rest/testing/BrooklynRestApiTest.java | 223 ------
.../rest/testing/BrooklynRestResourceTest.java | 154 ----
.../rest/testing/mocks/CapitalizePolicy.java | 33 -
.../rest/testing/mocks/EverythingGroup.java | 27 -
.../rest/testing/mocks/EverythingGroupImpl.java | 32 -
.../rest/testing/mocks/NameMatcherGroup.java | 30 -
.../testing/mocks/NameMatcherGroupImpl.java | 33 -
.../rest/testing/mocks/RestMockApp.java | 24 -
.../rest/testing/mocks/RestMockAppBuilder.java | 39 --
.../testing/mocks/RestMockSimpleEntity.java | 103 ---
.../testing/mocks/RestMockSimplePolicy.java | 64 --
.../util/BrooklynRestResourceUtilsTest.java | 213 ------
.../rest/util/EntityLocationUtilsTest.java | 72 --
.../rest/util/NoOpRecordingShutdownHandler.java | 39 --
.../util/NullHttpServletRequestProvider.java | 46 --
.../rest/util/NullServletConfigProvider.java | 51 --
.../brooklyn/rest/util/RestApiTestUtils.java | 58 --
.../util/ServerStoppingShutdownHandler.java | 75 --
.../TestingHaHotStateCheckClassResource.java | 38 -
.../util/TestingHaHotStateCheckResource.java | 44 --
.../rest/util/TestingHaMasterCheckResource.java | 41 --
.../json/BrooklynJacksonSerializerTest.java | 399 -----------
.../resources/brooklyn/scanning.catalog.bom | 19 -
.../resources/fixtures/api-error-basic.json | 4 -
.../fixtures/api-error-no-details.json | 3 -
.../resources/fixtures/application-list.json | 44 --
.../resources/fixtures/application-spec.json | 16 -
.../resources/fixtures/application-tree.json | 43 --
.../test/resources/fixtures/application.json | 22 -
.../fixtures/catalog-application-list.json | 29 -
.../resources/fixtures/catalog-application.json | 9 -
.../fixtures/effector-summary-list.json | 47 --
.../resources/fixtures/effector-summary.json | 9 -
.../resources/fixtures/entity-only-type.json | 3 -
.../resources/fixtures/entity-summary-list.json | 14 -
.../test/resources/fixtures/entity-summary.json | 13 -
.../src/test/resources/fixtures/entity.json | 7 -
.../src/test/resources/fixtures/ha-summary.json | 19 -
.../test/resources/fixtures/location-list.json | 10 -
.../resources/fixtures/location-summary.json | 8 -
.../fixtures/location-without-credential.json | 5 -
.../src/test/resources/fixtures/location.json | 4 -
.../fixtures/sensor-current-state.json | 6 -
.../resources/fixtures/sensor-summary-list.json | 42 --
.../test/resources/fixtures/sensor-summary.json | 8 -
.../test/resources/fixtures/server-version.json | 14 -
.../test/resources/fixtures/service-state.json | 1 -
.../resources/fixtures/task-summary-list.json | 15 -
rest/rest-server/pom.xml | 5 +-
121 files changed, 4 insertions(+), 11325 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/camp/camp-server-jersey/pom.xml
----------------------------------------------------------------------
diff --git a/camp/camp-server-jersey/pom.xml b/camp/camp-server-jersey/pom.xml
deleted file mode 100644
index 8854b7b..0000000
--- a/camp/camp-server-jersey/pom.xml
+++ /dev/null
@@ -1,225 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- 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.
--->
-<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/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <artifactId>camp-server-jersey</artifactId>
- <packaging>jar</packaging>
- <name>CAMP Server Jersey</name>
- <description>
- REST Server classes for CAMP server implementation, using Jersey dependencies
- </description>
-
- <parent>
- <groupId>org.apache.brooklyn.camp</groupId>
- <artifactId>camp-parent</artifactId>
- <version>0.10.0-SNAPSHOT</version> <!-- BROOKLYN_VERSION -->
- <relativePath>../pom.xml</relativePath>
- </parent>
-
- <dependencies>
- <dependency>
- <groupId>org.apache.brooklyn.camp</groupId>
- <artifactId>camp-base</artifactId>
- <version>${project.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-utils-test-support</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn.camp</groupId>
- <artifactId>camp-base</artifactId>
- <version>${project.version}</version>
- <classifier>tests</classifier>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <!-- jackson-core and jackson-annotations are pulled in from this, with the right version -->
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.jaxrs</groupId>
- <artifactId>jackson-jaxrs-json-provider</artifactId>
- </dependency>
-
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-server</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-servlet</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-json</artifactId>
- <exclusions>
- <exclusion>
- <groupId>com.sun.xml.bind</groupId>
- <artifactId>jaxb-impl</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-core</artifactId>
- </dependency>
-
- <dependency>
- <groupId>javax.validation</groupId>
- <artifactId>validation-api</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-webapp</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-server</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-servlet</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-util</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-utils-rest-swagger</artifactId>
- <version>${project.version}</version>
- <exclusions>
- <exclusion>
- <groupId>javax.ws.rs</groupId>
- <artifactId>javax.ws.rs-api</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-utils-common</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
-
- <!-- TODO have a camp.log / logging module -->
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-logback-xml</artifactId>
- <version>${project.version}</version>
- <!-- optional so that this project has logging; dependencies may redeclare or supply their own -->
- <optional>true</optional>
- </dependency>
-
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-resources-plugin</artifactId>
- <executions>
- <execution>
- <id>copy-rest-sources</id>
- <phase>generate-sources</phase>
- <goals><goal>copy-resources</goal></goals>
- <configuration>
- <outputDirectory>target/generated-sources/rest-deps</outputDirectory>
- <resources>
- <resource>
- <directory>../camp-server/src/main/java</directory>
- <excludes>
- <exclude>**/RestApiSetup.java</exclude>
- <exclude>**/ApidocRestResource.java</exclude>
- </excludes>
- </resource>
- </resources>
- </configuration>
- </execution>
- <execution>
- <id>copy-test-rest-sources</id>
- <phase>generate-sources</phase>
- <goals><goal>copy-resources</goal></goals>
- <configuration>
- <outputDirectory>target/generated-sources/test-rest-deps</outputDirectory>
- <resources>
- <resource>
- <directory>../camp-server/src/test/java</directory>
- </resource>
- </resources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>rest-sources</id>
- <phase>generate-sources</phase>
- <goals><goal>add-source</goal></goals>
- <configuration>
- <sources>
- <source>target/generated-sources/rest-deps</source>
- </sources>
- </configuration>
- </execution>
- <execution>
- <id>test-rest-sources</id>
- <phase>generate-sources</phase>
- <goals><goal>add-test-source</goal></goals>
- <configuration>
- <sources>
- <source>target/generated-sources/test-rest-deps</source>
- </sources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/RestApiSetup.java
----------------------------------------------------------------------
diff --git a/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/RestApiSetup.java b/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/RestApiSetup.java
deleted file mode 100644
index 60a44e0..0000000
--- a/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/RestApiSetup.java
+++ /dev/null
@@ -1,53 +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.camp.server;
-
-import java.util.EnumSet;
-
-import javax.servlet.DispatcherType;
-
-import org.apache.brooklyn.camp.server.rest.CampRestResources;
-import org.eclipse.jetty.servlet.FilterHolder;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-
-import com.sun.jersey.api.core.DefaultResourceConfig;
-import com.sun.jersey.api.core.ResourceConfig;
-import com.sun.jersey.spi.container.servlet.ServletContainer;
-
-public class RestApiSetup {
-
- public static void install(ServletContextHandler context) {
- ResourceConfig config = new DefaultResourceConfig();
- // load all our REST API modules, JSON, and Swagger
- for (Object r: CampRestResources.getAllResources())
- config.getSingletons().add(r);
-
- // configure to match empty path, or any thing which looks like a file path with /assets/ and extension html, css, js, or png
- // and treat that as static content
- config.getProperties().put(ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX, "(/?|[^?]*/assets/[^?]+\\.[A-Za-z0-9_]+)");
-
- // and anything which is not matched as a servlet also falls through (but more expensive than a regex check?)
- config.getFeatures().put(ServletContainer.FEATURE_FILTER_FORWARD_ON_404, true);
-
- // finally create this as a _filter_ which falls through to a web app or something (optionally)
- FilterHolder filterHolder = new FilterHolder(new ServletContainer(config));
- context.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/rest/resource/ApiListingResource.java
----------------------------------------------------------------------
diff --git a/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/rest/resource/ApiListingResource.java b/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/rest/resource/ApiListingResource.java
deleted file mode 100644
index af656cc..0000000
--- a/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/rest/resource/ApiListingResource.java
+++ /dev/null
@@ -1,260 +0,0 @@
-/*
- * Copyright 2015 The Apache Software Foundation.
- *
- * 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 org.apache.brooklyn.camp.server.rest.resource;
-
-import com.sun.jersey.spi.container.servlet.WebConfig;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.config.FilterFactory;
-import io.swagger.config.Scanner;
-import io.swagger.config.ScannerFactory;
-import io.swagger.config.SwaggerConfig;
-import io.swagger.core.filter.SpecFilter;
-import io.swagger.core.filter.SwaggerSpecFilter;
-import io.swagger.jaxrs.Reader;
-import io.swagger.jaxrs.config.JaxrsScanner;
-import io.swagger.jaxrs.config.ReaderConfigUtils;
-import io.swagger.jaxrs.listing.SwaggerSerializers;
-import io.swagger.models.Swagger;
-import io.swagger.util.Yaml;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Cookie;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * ApiListingResource usable within a jersey servlet filter.
- *
- * Taken from io.swagger:swagger-jaxrs, class
- * io.swagger.jaxrs.listing.ApiListingResource, which can only be used within a
- * servlet context. We are here using a filter, but jersey has a WebConfig class
- * that can substitute ServletConfig and FilterConfig.
- *
- * @todo Remove when the rest-server is no longer running within a filter (e.g.
- * as a standalone OSGi http service)
- *
- * @author Ciprian Ciubotariu <ch...@gmx.net>
- */
-public class ApiListingResource {
-
- static Logger LOGGER = LoggerFactory.getLogger(ApiListingResource.class);
-
- @Context
- ServletContext context;
-
- boolean initialized = false;
-
- private static class ServletConfigAdapter implements ServletConfig {
-
- private final WebConfig webConfig;
-
- private ServletConfigAdapter(WebConfig webConfig) {
- this.webConfig = webConfig;
- }
-
- @Override
- public String getServletName() {
- return webConfig.getName();
- }
-
- @Override
- public ServletContext getServletContext() {
- return webConfig.getServletContext();
- }
-
- @Override
- public String getInitParameter(String name) {
- return webConfig.getInitParameter(name);
- }
-
- @Override
- public Enumeration<String> getInitParameterNames() {
- return webConfig.getInitParameterNames();
- }
-
- }
-
- protected synchronized Swagger scan(Application app, WebConfig sc) {
- Swagger swagger = null;
- Scanner scanner = ScannerFactory.getScanner();
- LOGGER.debug("using scanner " + scanner);
-
- if (scanner != null) {
- SwaggerSerializers.setPrettyPrint(scanner.getPrettyPrint());
- swagger = (Swagger) context.getAttribute("swagger");
-
- Set<Class<?>> classes;
- if (scanner instanceof JaxrsScanner) {
- JaxrsScanner jaxrsScanner = (JaxrsScanner) scanner;
- classes = jaxrsScanner.classesFromContext(app, new ServletConfigAdapter(sc));
- } else {
- classes = scanner.classes();
- }
- if (classes != null) {
- Reader reader = new Reader(swagger, ReaderConfigUtils.getReaderConfig(context));
- swagger = reader.read(classes);
- if (scanner instanceof SwaggerConfig) {
- swagger = ((SwaggerConfig) scanner).configure(swagger);
- } else {
- SwaggerConfig configurator = (SwaggerConfig) context.getAttribute("reader");
- if (configurator != null) {
- LOGGER.debug("configuring swagger with " + configurator);
- configurator.configure(swagger);
- } else {
- LOGGER.debug("no configurator");
- }
- }
- context.setAttribute("swagger", swagger);
- }
- }
- initialized = true;
- return swagger;
- }
-
- private Swagger process(
- Application app,
- WebConfig sc,
- HttpHeaders headers,
- UriInfo uriInfo) {
- Swagger swagger = (Swagger) context.getAttribute("swagger");
- if (!initialized) {
- swagger = scan(app, sc);
- }
- if (swagger != null) {
- SwaggerSpecFilter filterImpl = FilterFactory.getFilter();
- if (filterImpl != null) {
- SpecFilter f = new SpecFilter();
- swagger = f.filter(swagger, filterImpl, getQueryParams(uriInfo.getQueryParameters()), getCookies(headers),
- getHeaders(headers));
- }
- }
- return swagger;
- }
-
- @GET
- @Produces({MediaType.APPLICATION_JSON, "application/yaml"})
- @ApiOperation(value = "The swagger definition in either JSON or YAML", hidden = true)
- @Path("/swagger.{type:json|yaml}")
- public Response getListing(
- @Context Application app,
- @Context WebConfig sc,
- @Context HttpHeaders headers,
- @Context UriInfo uriInfo,
- @PathParam("type") String type) {
- if (Strings.isNonBlank(type) && type.trim().equalsIgnoreCase("yaml")) {
- return getListingYaml(app, sc, headers, uriInfo);
- } else {
- return getListingJson(app, sc, headers, uriInfo);
- }
- }
-
- @GET
- @Produces({MediaType.APPLICATION_JSON})
- @Path("/swagger")
- @ApiOperation(value = "The swagger definition in JSON", hidden = true)
- public Response getListingJson(
- @Context Application app,
- @Context WebConfig sc,
- @Context HttpHeaders headers,
- @Context UriInfo uriInfo) {
- Swagger swagger = process(app, sc, headers, uriInfo);
-
- if (swagger != null) {
- return Response.ok().entity(swagger).build();
- } else {
- return Response.status(404).build();
- }
- }
-
- @GET
- @Produces("application/yaml")
- @Path("/swagger")
- @ApiOperation(value = "The swagger definition in YAML", hidden = true)
- public Response getListingYaml(
- @Context Application app,
- @Context WebConfig sc,
- @Context HttpHeaders headers,
- @Context UriInfo uriInfo) {
- Swagger swagger = process(app, sc, headers, uriInfo);
- try {
- if (swagger != null) {
- String yaml = Yaml.mapper().writeValueAsString(swagger);
- StringBuilder b = new StringBuilder();
- String[] parts = yaml.split("\n");
- for (String part : parts) {
- b.append(part);
- b.append("\n");
- }
- return Response.ok().entity(b.toString()).type("application/yaml").build();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return Response.status(404).build();
- }
-
- protected Map<String, List<String>> getQueryParams(MultivaluedMap<String, String> params) {
- Map<String, List<String>> output = new HashMap<>();
- if (params != null) {
- for (String key : params.keySet()) {
- List<String> values = params.get(key);
- output.put(key, values);
- }
- }
- return output;
- }
-
- protected Map<String, String> getCookies(HttpHeaders headers) {
- Map<String, String> output = new HashMap<>();
- if (headers != null) {
- for (String key : headers.getCookies().keySet()) {
- Cookie cookie = headers.getCookies().get(key);
- output.put(key, cookie.getValue());
- }
- }
- return output;
- }
-
- protected Map<String, List<String>> getHeaders(HttpHeaders headers) {
- Map<String, List<String>> output = new HashMap<>();
- if (headers != null) {
- for (String key : headers.getRequestHeaders().keySet()) {
- List<String> values = headers.getRequestHeaders().get(key);
- output.put(key, values);
- }
- }
- return output;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/rest/resource/ApidocRestResource.java
----------------------------------------------------------------------
diff --git a/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/rest/resource/ApidocRestResource.java b/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/rest/resource/ApidocRestResource.java
deleted file mode 100644
index 1696855..0000000
--- a/camp/camp-server-jersey/src/main/java/org/apache/brooklyn/camp/server/rest/resource/ApidocRestResource.java
+++ /dev/null
@@ -1,32 +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.camp.server.rest.resource;
-
-import javax.ws.rs.Path;
-
-import io.swagger.annotations.Api;
-
-
-@Path(ApidocRestResource.API_URI_PATH)
-@Api("Web API Documentation")
-public class ApidocRestResource extends ApiListingResource {
-
- public static final String API_URI_PATH = PlatformRestResource.CAMP_URI_PATH + "/apidoc";
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/camp/camp-server-jersey/src/main/webapp/WEB-INF/web.xml
----------------------------------------------------------------------
diff --git a/camp/camp-server-jersey/src/main/webapp/WEB-INF/web.xml b/camp/camp-server-jersey/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 0ea4373..0000000
--- a/camp/camp-server-jersey/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,142 +0,0 @@
-<!DOCTYPE web-app PUBLIC
- "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
- "http://java.sun.com/dtd/web-app_2_3.dtd" >
-<!--
- 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.
--->
-<web-app>
- <display-name>Brooklyn REST API v1</display-name>
-
- <filter>
- <filter-name>Brooklyn Request Tagging Filter</filter-name>
- <filter-class>org.apache.brooklyn.rest.filter.RequestTaggingFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn Request Tagging Filter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <filter>
- <filter-name>Brooklyn Properties Authentication Filter</filter-name>
- <filter-class>org.apache.brooklyn.rest.filter.BrooklynPropertiesSecurityFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn Properties Authentication Filter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <filter>
- <filter-name>Brooklyn Logging Filter</filter-name>
- <filter-class>org.apache.brooklyn.rest.filter.LoggingFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn Logging Filter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <filter>
- <filter-name>Brooklyn HA Master Filter</filter-name>
- <filter-class>org.apache.brooklyn.rest.filter.HaMasterCheckFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn HA Master Filter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <filter>
- <filter-name>Brooklyn Swagger Bootstrap</filter-name>
- <filter-class>org.apache.brooklyn.rest.filter.SwaggerFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn Swagger Bootstrap</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <!-- Brooklyn REST is usually run as a filter so static content can be placed in a webapp
- to which this is added; to run as a servlet directly, replace the filter tags
- below (after the comment) with the servlet tags (commented out immediately below),
- (and do the same for the matching tags at the bottom)
- <servlet>
- <servlet-name>Brooklyn REST API v1 Servlet</servlet-name>
- <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
- -->
- <filter>
- <filter-name>Brooklyn REST API v1 Filter</filter-name>
- <filter-class>com.sun.jersey.spi.container.servlet.ServletContainer</filter-class>
-
- <!-- load our REST API jersey resources explicitly
- (the package scanner will only pick up classes with @Path annotations - doesn't look at implemented interfaces)
- -->
- <init-param>
- <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
- <param-value>com.sun.jersey.api.core.ClassNamesResourceConfig</param-value>
- </init-param>
- <init-param>
- <param-name>com.sun.jersey.config.property.classnames</param-name>
- <param-value>
- io.swagger.jaxrs.listing.SwaggerSerializers;
- org.apache.brooklyn.rest.util.FormMapProvider;
- org.codehaus.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.UsageResource;
- org.apache.brooklyn.rest.resources.VersionResource;
- </param-value>
- </init-param>
-
- <init-param>
- <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
- <param-value>true</param-value>
- </init-param>
-
- <!-- no need for WADL. of course you can turn it back on it you want. -->
- <init-param>
- <param-name>com.sun.jersey.config.feature.DisableWADL</param-name>
- <param-value>true</param-value>
- </init-param>
-
- <init-param>
- <param-name>com.sun.jersey.config.feature.FilterContextPath</param-name>
- <param-value>/v1</param-value>
- </init-param>
-
- </filter>
- <filter-mapping>
- <filter-name>Brooklyn REST API v1 Filter</filter-name>
- <url-pattern>/v1/*</url-pattern>
- </filter-mapping>
- <!-- Brooklyn REST as a filter above; replace above 5 lines with those commented out below,
- to run it as a servlet (see note above)
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>Brooklyn REST API v1 Servlet</servlet-name>
- <url-pattern>/*</url-pattern>
- </servlet-mapping>
- -->
-</web-app>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/camp/pom.xml
----------------------------------------------------------------------
diff --git a/camp/pom.xml b/camp/pom.xml
index 441d0dd..4038247 100644
--- a/camp/pom.xml
+++ b/camp/pom.xml
@@ -39,7 +39,6 @@
<modules>
<module>camp-base</module>
<module>camp-server</module>
- <module>camp-server-jersey</module>
<module>camp-brooklyn</module>
</modules>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/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 6200b88..5de0241 100644
--- a/karaf/features/src/main/feature/feature.xml
+++ b/karaf/features/src/main/feature/feature.xml
@@ -88,15 +88,12 @@
<bundle>mvn:org.apache.brooklyn/brooklyn-rest-api/${project.version}</bundle>
- <bundle dependency="true">mvn:com.sun.jersey.contribs/jersey-multipart/${jersey.version}</bundle>
<bundle dependency="true">mvn:org.jvnet.mimepull/mimepull/1.9.3</bundle>
<bundle dependency="true">mvn:commons-lang/commons-lang/${commons-lang.version}</bundle>
<!-- TODO: version 1.1.0.Final has OSGi manifest; check if upgrade doesn't get rid of wrap -->
<bundle dependency="true">wrap:mvn:javax.validation/validation-api/${validation-api.version}</bundle>
- <!--<feature>jersey</feature>-->
- <bundle dependency="true">mvn:com.sun.jersey/jersey-servlet/${jersey.version}</bundle>
<bundle dependency="true">mvn:org.apache.commons/commons-lang3/${commons-lang3.version}</bundle>
<bundle dependency="true">mvn:com.fasterxml.jackson.core/jackson-annotations/${fasterxml.jackson.version}</bundle>
<bundle dependency="true">mvn:com.fasterxml.jackson.core/jackson-databind/${fasterxml.jackson.version}</bundle>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/launcher/pom.xml
----------------------------------------------------------------------
diff --git a/launcher/pom.xml b/launcher/pom.xml
index b5a3575..2ecb2f8 100644
--- a/launcher/pom.xml
+++ b/launcher/pom.xml
@@ -53,7 +53,7 @@
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-rest-server${rest-server-classifier}</artifactId>
+ <artifactId>brooklyn-rest-server</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
@@ -68,7 +68,7 @@
</dependency>
<dependency>
<groupId>org.apache.brooklyn.camp</groupId>
- <artifactId>camp-server${rest-server-classifier}</artifactId>
+ <artifactId>camp-server</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
@@ -187,7 +187,7 @@
</dependency>
<dependency>
<groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-rest-server${rest-server-classifier}</artifactId>
+ <artifactId>brooklyn-rest-server</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
@@ -267,23 +267,4 @@
</plugin>
</plugins>
</build>
- <profiles>
- <profile>
- <id>jax-rs-jersey</id>
- <activation>
- <property>
- <name>!jar-rs</name>
- </property>
- </activation>
- <dependencies>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-rest-resources</artifactId>
- <version>${project.version}</version>
- <classifier>tests</classifier>
- <scope>test</scope>
- </dependency>
- </dependencies>
- </profile>
- </profiles>
</project>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/parent/pom.xml
----------------------------------------------------------------------
diff --git a/parent/pom.xml b/parent/pom.xml
index b2e2e8e..4efc785 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -52,10 +52,6 @@
http://stackoverflow.com/questions/5309379/how-to-keep-maven-profiles-which-are-activebydefault-active-even-if-another-prof )
-->
- <properties>
- <rest-server-classifier />
- </properties>
-
<dependencyManagement>
<dependencies>
<dependency>
@@ -469,12 +465,6 @@
</dependency>
<!-- JAX-RS dependencies-->
- <!-- JAX-RS 1.1 API -->
- <dependency>
- <groupId>javax.ws.rs</groupId>
- <artifactId>jsr311-api</artifactId>
- <version>${jsr311-api.version}</version>
- </dependency>
<!-- JAX-RS 2.0 API -->
<dependency>
<groupId>javax.ws.rs</groupId>
@@ -502,42 +492,6 @@
<artifactId>cxf-rt-rs-client</artifactId>
<version>${cxf.version}</version>
</dependency>
- <!-- JAX-RS 1.1 Jersey Implementation -->
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-core</artifactId>
- <version>${jersey.version}</version>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-client</artifactId>
- <version>${jersey.version}</version>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-server</artifactId>
- <version>${jersey.version}</version>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-servlet</artifactId>
- <version>${jersey.version}</version>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-json</artifactId>
- <version>${jersey.version}</version>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey.jersey-test-framework</groupId>
- <artifactId>jersey-test-framework-inmemory</artifactId>
- <version>${jersey.version}</version>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey.jersey-test-framework</groupId>
- <artifactId>jersey-test-framework-grizzly2</artifactId>
- <version>${jersey.version}</version>
- </dependency>
<!-- JAX-RS 2.0 RESTEasy Implementation -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
@@ -1787,18 +1741,5 @@
</pluginManagement>
</build>
</profile>
-
- <profile>
- <id>jersey-deps</id>
- <activation>
- <property>
- <name>jax-rs</name>
- <value>jersey</value>
- </property>
- </activation>
- <properties>
- <rest-server-classifier>-jersey</rest-server-classifier>
- </properties>
- </profile>
</profiles>
</project>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 433e912..cff3d4f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -102,7 +102,6 @@
<!-- double-check downstream projects before changing jackson and resteasy versions -->
<fasterxml.jackson.version>2.4.5</fasterxml.jackson.version>
<resteasy.version>3.0.8.Final</resteasy.version>
- <jersey.version>1.19</jersey.version>
<cxf.version>3.1.4</cxf.version>
<httpclient.version>4.4.1</httpclient.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
@@ -150,7 +149,6 @@
<commons-configuration.version>1.7</commons-configuration.version>
<commons-lang.version>2.4</commons-lang.version>
<hamcrest.version>1.1</hamcrest.version>
- <jsr311-api.version>1.1.1</jsr311-api.version>
<jax-rs-api.version>2.0.1</jax-rs-api.version>
<maxmind.version>0.8.1</maxmind.version>
<maxmind-db.version>0.3.4</maxmind-db.version>
@@ -216,7 +214,6 @@
<module>rest/rest-client</module>
<module>rest/rest-resources</module>
<module>rest/rest-server</module>
- <module>rest/rest-server-jersey</module>
<module>test-framework</module>
<module>test-support</module>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-client/pom.xml
----------------------------------------------------------------------
diff --git a/rest/rest-client/pom.xml b/rest/rest-client/pom.xml
index 1828f8f..069bce5 100644
--- a/rest/rest-client/pom.xml
+++ b/rest/rest-client/pom.xml
@@ -89,19 +89,6 @@
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
- <!--
- mvn dependency:analyze complains that these dependencies are unused when present but
- used and undeclared when removed!
- -->
- <!--dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.jboss.resteasy</groupId>
- <artifactId>jaxrs-api</artifactId>
- </dependency-->
-
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/pom.xml
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/pom.xml b/rest/rest-server-jersey/pom.xml
deleted file mode 100644
index b4fabd8..0000000
--- a/rest/rest-server-jersey/pom.xml
+++ /dev/null
@@ -1,351 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- 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.
--->
-<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/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <artifactId>brooklyn-rest-server-jersey</artifactId>
- <packaging>jar</packaging>
- <name>Brooklyn REST Server with Jersey dependencies</name>
- <description>
- Brooklyn REST Endpoint, using Jersey as the JAR-RS implementation
- </description>
-
- <parent>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-parent</artifactId>
- <version>0.10.0-SNAPSHOT</version><!-- BROOKLYN_VERSION -->
- <relativePath>../../parent/pom.xml</relativePath>
- </parent>
-
- <dependencies>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-core</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.validation</groupId>
- <artifactId>validation-api</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.code.findbugs</groupId>
- <artifactId>jsr305</artifactId>
- </dependency>
- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-core</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-utils-common</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>io.swagger</groupId>
- <artifactId>swagger-annotations</artifactId>
- </dependency>
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-test-support</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
-
-
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-camp</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn.camp</groupId>
- <artifactId>camp-base</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-software-base</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-utils-rest-swagger</artifactId>
- <version>${project.version}</version>
- <exclusions>
- <exclusion>
- <groupId>javax.ws.rs</groupId>
- <artifactId>javax.ws.rs-api</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- </dependency>
- <dependency>
- <groupId>org.reflections</groupId>
- <artifactId>reflections</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.ws.rs</groupId>
- <artifactId>jsr311-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.jaxrs</groupId>
- <artifactId>jackson-jaxrs-json-provider</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-server</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-servlet</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-webapp</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-jaas</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-server</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-servlet</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-policy</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-core</artifactId>
- <version>${project.version}</version>
- <classifier>tests</classifier>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-software-base</artifactId>
- <version>${project.version}</version>
- <classifier>tests</classifier>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-locations-jclouds</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-all</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-client</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey.jersey-test-framework</groupId>
- <artifactId>jersey-test-framework-inmemory</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey.jersey-test-framework</groupId>
- <artifactId>jersey-test-framework-grizzly2</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.brooklyn</groupId>
- <artifactId>brooklyn-utils-common</artifactId>
- <version>${project.version}</version>
- <classifier>tests</classifier>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <resources>
- <resource>
- <directory>../rest-server/src/main/resources</directory>
- <!-- Required to set values in build-metadata.properties -->
- <filtering>true</filtering>
- </resource>
- <resource>
- <directory>src/main/webapp</directory>
- </resource>
- </resources>
- <plugins>
- <plugin>
- <artifactId>maven-resources-plugin</artifactId>
- <executions>
- <execution>
- <id>copy-rest-sources</id>
- <phase>generate-sources</phase>
- <goals><goal>copy-resources</goal></goals>
- <configuration>
- <outputDirectory>target/generated-sources/rest-deps</outputDirectory>
- <resources>
- <resource>
- <directory>../rest-api/src/main/java</directory>
- </resource>
- <resource>
- <directory>../rest-resources/src/main/java</directory>
- <excludes>
- <exclude>**/NoCacheFilter.java</exclude>
- <exclude>**/HaHotCheckResourceFilter.java</exclude>
- <exclude>**/FormMapProvider.java</exclude>
- <exclude>**/ApidocResource.java</exclude>
- <exclude>**/RequestTaggingFilter.java</exclude>
- <exclude>**/EntitlementContextFilter.java</exclude>
- <exclude>**/RequestTaggingRsFilter.java</exclude>
- <exclude>**/ScannerInjectHelper.java</exclude>
- </excludes>
- </resource>
- <resource>
- <directory>../rest-server/src/main/java</directory>
- <excludes>
- <exclude>**/RestApiSetup.java</exclude>
- </excludes>
- </resource>
- </resources>
- </configuration>
- </execution>
- <execution>
- <id>copy-rest-resources</id>
- <phase>generate-resources</phase>
- <goals><goal>copy-resources</goal></goals>
- <configuration>
- <outputDirectory>target/generated-resources/rest-deps</outputDirectory>
- <resources>
- <resource>
- <directory>../rest-resources/src/main/resources</directory>
- <includes>
- <include>**/jaas.conf</include>
- </includes>
- </resource>
- </resources>
- </configuration>
- </execution>
- <execution>
- <id>copy-rest-test-resources</id>
- <phase>generate-test-resources</phase>
- <goals><goal>copy-resources</goal></goals>
- <configuration>
- <outputDirectory>target/generated-test-resources/rest-deps</outputDirectory>
- <resources>
- <resource>
- <directory>../rest-resources/src/test/resources</directory>
- </resource>
- <resource>
- <directory>../rest-server/src/test/resources</directory>
- </resource>
- </resources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>rest-sources</id>
- <phase>generate-sources</phase>
- <goals><goal>add-source</goal></goals>
- <configuration>
- <sources>
- <source>target/generated-sources/rest-deps</source>
- </sources>
- </configuration>
- </execution>
- <execution>
- <id>rest-resources</id>
- <phase>generate-resources</phase>
- <goals><goal>add-resource</goal></goals>
- <configuration>
- <resources>
- <resource>
- <directory>target/generated-resources/rest-deps</directory>
- </resource>
- </resources>
- </configuration>
- </execution>
- <execution>
- <id>rest-test-resources</id>
- <phase>generate-test-resources</phase>
- <goals><goal>add-test-resource</goal></goals>
- <configuration>
- <resources>
- <resource>
- <directory>target/generated-test-resources/rest-deps</directory>
- </resource>
- </resources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/RestApiSetup.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/RestApiSetup.java b/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/RestApiSetup.java
deleted file mode 100644
index 1cb4d5d..0000000
--- a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/RestApiSetup.java
+++ /dev/null
@@ -1,113 +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;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.EnumSet;
-import java.util.List;
-
-import javax.servlet.DispatcherType;
-import javax.servlet.Filter;
-import javax.ws.rs.ext.ContextResolver;
-
-import org.apache.brooklyn.rest.filter.HaHotCheckResourceFilter;
-import org.apache.brooklyn.rest.filter.SwaggerFilter;
-import org.apache.brooklyn.rest.util.ManagementContextProvider;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.eclipse.jetty.servlet.FilterHolder;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-
-import com.sun.jersey.api.container.filter.GZIPContentEncodingFilter;
-import com.sun.jersey.api.core.DefaultResourceConfig;
-import com.sun.jersey.api.core.ResourceConfig;
-import com.sun.jersey.spi.container.ContainerRequestFilter;
-import com.sun.jersey.spi.container.ContainerResponseFilter;
-import com.sun.jersey.spi.container.ResourceFilterFactory;
-import com.sun.jersey.spi.container.servlet.ServletContainer;
-
-public class RestApiSetup {
-
- public static void installRest(ServletContextHandler context, Object... providers) {
- List<Object> providerList = MutableList.copyOf(Arrays.asList(providers))
- .append(new GZIPContentEncodingFilter());
-
- injectHa(providers);
-
- ResourceConfig config = new DefaultResourceConfig();
- // load all our REST API modules, JSON, and Swagger
- for (Object r: BrooklynRestApi.getAllResources())
- config.getSingletons().add(r);
- for (Object o: getProvidersOfType(providerList, ContextResolver.class))
- config.getSingletons().add(o);
-
- config.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, getProvidersOfType(providerList, ContainerRequestFilter.class));
- config.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, getProvidersOfType(providerList, ContainerResponseFilter.class));
- config.getProperties().put(ResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES, getProvidersOfType(providerList, ResourceFilterFactory.class));
-
- // configure to match empty path, or any thing which looks like a file path with /assets/ and extension html, css, js, or png
- // and treat that as static content
- config.getProperties().put(ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX, "(/?|[^?]*/assets/[^?]+\\.[A-Za-z0-9_]+)");
- // and anything which is not matched as a servlet also falls through (but more expensive than a regex check?)
- config.getFeatures().put(ServletContainer.FEATURE_FILTER_FORWARD_ON_404, true);
- // finally create this as a _filter_ which falls through to a web app or something (optionally)
- FilterHolder filterHolder = new FilterHolder(new ServletContainer(config));
-
- filterHolder.setInitParameter(ServletContainer.PROPERTY_FILTER_CONTEXT_PATH, "/v1");
- context.addFilter(filterHolder, "/v1/*", EnumSet.allOf(DispatcherType.class));
-
- installServletFilters(context, SwaggerFilter.class);
- }
-
- // An ugly hack to work around injection missing for HaHotCheckProvider
- private static void injectHa(Object[] providers) {
- HaHotCheckResourceFilter haFilter = null;
- ManagementContextProvider mgmtProvider = null;
- for (Object o : providers) {
- if (o instanceof HaHotCheckResourceFilter) {
- haFilter = (HaHotCheckResourceFilter) o;
- } else if (o instanceof ManagementContextProvider) {
- mgmtProvider = (ManagementContextProvider) o;
- }
- }
- haFilter.setManagementContext(mgmtProvider);
- }
-
- private static List<Object> getProvidersOfType(List<Object> providers, Class<?> type) {
- List<Object> ret = new ArrayList<>();
- for (Object o : providers) {
- if (type.isInstance(o)) {
- ret.add(o);
- }
- }
- return ret;
- }
-
- @SafeVarargs
- public static void installServletFilters(ServletContextHandler context, Class<? extends Filter>... filters) {
- installServletFilters(context, Arrays.asList(filters));
- }
-
- public static void installServletFilters(ServletContextHandler context, Collection<Class<? extends Filter>> filters) {
- for (Class<? extends Filter> filter : filters) {
- context.addFilter(filter, "/*", EnumSet.allOf(DispatcherType.class));
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/EntitlementContextFilter.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/EntitlementContextFilter.java b/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/EntitlementContextFilter.java
deleted file mode 100644
index 2c3e200..0000000
--- a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/EntitlementContextFilter.java
+++ /dev/null
@@ -1,63 +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.filter;
-
-import java.security.Principal;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.SecurityContext;
-
-import org.apache.brooklyn.core.mgmt.entitlement.Entitlements;
-import org.apache.brooklyn.core.mgmt.entitlement.WebEntitlementContext;
-
-import com.sun.jersey.core.util.Priority;
-import com.sun.jersey.spi.container.ContainerRequest;
-import com.sun.jersey.spi.container.ContainerRequestFilter;
-import com.sun.jersey.spi.container.ContainerResponse;
-import com.sun.jersey.spi.container.ContainerResponseFilter;
-
-@Priority(400)
-public class EntitlementContextFilter implements ContainerRequestFilter, ContainerResponseFilter {
- @Context
- private HttpServletRequest servletRequest;
-
- @Override
- public ContainerRequest filter(ContainerRequest request) {
- SecurityContext securityContext = request.getSecurityContext();
- Principal user = securityContext.getUserPrincipal();
-
- if (user != null) {
- String uri = servletRequest.getRequestURI();
- String remoteAddr = servletRequest.getRemoteAddr();
-
- String uid = RequestTaggingFilter.getTag();
- WebEntitlementContext entitlementContext = new WebEntitlementContext(user.getName(), remoteAddr, uri, uid);
- Entitlements.setEntitlementContext(entitlementContext);
- }
- return request;
- }
-
- @Override
- public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
- Entitlements.clearEntitlementContext();
- return response;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/HaHotCheckResourceFilter.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/HaHotCheckResourceFilter.java b/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/HaHotCheckResourceFilter.java
deleted file mode 100644
index 920b982..0000000
--- a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/HaHotCheckResourceFilter.java
+++ /dev/null
@@ -1,196 +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.filter;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.ContextResolver;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.ha.ManagementNodeState;
-import org.apache.brooklyn.rest.domain.ApiError;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.ImmutableSet;
-import com.sun.jersey.api.model.AbstractMethod;
-import com.sun.jersey.core.util.Priority;
-import com.sun.jersey.spi.container.ContainerRequest;
-import com.sun.jersey.spi.container.ContainerRequestFilter;
-import com.sun.jersey.spi.container.ContainerResponseFilter;
-import com.sun.jersey.spi.container.ResourceFilter;
-import com.sun.jersey.spi.container.ResourceFilterFactory;
-
-/**
- * Checks that if the method or resource class corresponding to a request
- * has a {@link HaHotStateRequired} annotation,
- * that the server is in that state (and up).
- * Requests with {@link #SKIP_CHECK_HEADER} set as a header skip this check.
- * <p>
- * This follows a different pattern to {@link HaMasterCheckFilter}
- * as this needs to know the method being invoked.
- */
-@Priority(300)
-public class HaHotCheckResourceFilter implements ResourceFilterFactory {
- private static final Set<String> SAFE_STANDBY_METHODS = ImmutableSet.of("GET", "HEAD");
- public static final String SKIP_CHECK_HEADER = "Brooklyn-Allow-Non-Master-Access";
-
- private static final Logger log = LoggerFactory.getLogger(HaHotCheckResourceFilter.class);
-
- private static final Set<ManagementNodeState> HOT_STATES = ImmutableSet.of(
- ManagementNodeState.MASTER, ManagementNodeState.HOT_STANDBY, ManagementNodeState.HOT_BACKUP);
-
- @Context
- private ContextResolver<ManagementContext> mgmt;
-
- public HaHotCheckResourceFilter() {}
-
- @VisibleForTesting
- public HaHotCheckResourceFilter(ContextResolver<ManagementContext> mgmt) {
- this.mgmt = mgmt;
- }
-
- // mgmt doesn't get injected for some reason, instead of looking for the cause just pass it at init time
- public void setManagementContext(ContextResolver<ManagementContext> mgmt) {
- this.mgmt = mgmt;
- }
-
- private ManagementContext mgmt() {
- return mgmt.getContext(ManagementContext.class);
- }
-
- private static class MethodFilter implements ResourceFilter, ContainerRequestFilter {
-
- private AbstractMethod am;
- private ManagementContext mgmt;
-
- public MethodFilter(AbstractMethod am, ManagementContext mgmt) {
- this.am = am;
- this.mgmt = mgmt;
- }
-
- @Override
- public ContainerRequestFilter getRequestFilter() {
- return this;
- }
-
- @Override
- public ContainerResponseFilter getResponseFilter() {
- return null;
- }
-
- private String lookForProblem(ContainerRequest request) {
- if (isSkipCheckHeaderSet(request))
- return null;
-
- if (isMasterRequiredForRequest(request) && !isMaster()) {
- return "server not in required HA master state";
- }
-
- if (!isHaHotStateRequired(request))
- return null;
-
- String problem = lookForProblemIfServerNotRunning(mgmt);
- if (Strings.isNonBlank(problem))
- return problem;
-
- if (!isHaHotStatus())
- return "server not in required HA hot state";
- if (isStateNotYetValid())
- return "server not yet completed loading data for required HA hot state";
-
- return null;
- }
-
- @Override
- public ContainerRequest filter(ContainerRequest request) {
- String problem = lookForProblem(request);
- if (Strings.isNonBlank(problem)) {
- log.warn("Disallowing web request as "+problem+": "+request.getRequestUri()+"/"+am+" (caller should set '"+SKIP_CHECK_HEADER+"' to force)");
- throw new WebApplicationException(ApiError.builder()
- .message("This request is only permitted against an active hot Brooklyn server")
- .errorCode(Response.Status.FORBIDDEN).build().asJsonResponse());
- }
- return request;
- }
-
- // Maybe there should be a separate state to indicate that we have switched state
- // but still haven't finished rebinding. (Previously there was a time delay and an
- // isRebinding check, but introducing RebindManager#isAwaitingInitialRebind() seems cleaner.)
- private boolean isStateNotYetValid() {
- return mgmt.getRebindManager().isAwaitingInitialRebind();
- }
-
- private boolean isMaster() {
- return ManagementNodeState.MASTER.equals(
- mgmt.getHighAvailabilityManager()
- .getNodeState());
- }
-
- private boolean isMasterRequiredForRequest(ContainerRequest requestContext) {
- // gets usually okay
- if (SAFE_STANDBY_METHODS.contains(requestContext.getMethod())) return false;
-
- String uri = requestContext.getRequestUri().toString();
- // explicitly allow calls to shutdown
- // (if stopAllApps is specified, the method itself will fail; but we do not want to consume parameters here, that breaks things!)
- // TODO use an annotation HaAnyStateAllowed or HaHotCheckRequired(false) or similar
- if ("server/shutdown".equals(uri) ||
- // Jersey compat
- "/v1/server/shutdown".equals(uri)) return false;
-
- return true;
- }
-
- private boolean isHaHotStateRequired(ContainerRequest request) {
- return (am.getAnnotation(HaHotStateRequired.class) != null ||
- am.getResource().getAnnotation(HaHotStateRequired.class) != null);
- }
-
- private boolean isSkipCheckHeaderSet(ContainerRequest request) {
- return "true".equalsIgnoreCase(request.getHeaderValue(SKIP_CHECK_HEADER));
- }
-
- private boolean isHaHotStatus() {
- ManagementNodeState state = mgmt.getHighAvailabilityManager().getNodeState();
- return HOT_STATES.contains(state);
- }
-
- }
-
- public static String lookForProblemIfServerNotRunning(ManagementContext mgmt) {
- if (mgmt==null) return "no management context available";
- if (!mgmt.isRunning()) return "server no longer running";
- if (!mgmt.isStartupComplete()) return "server not in required startup-completed state";
- return null;
- }
-
- @Override
- public List<ResourceFilter> create(AbstractMethod am) {
- return Collections.<ResourceFilter>singletonList(new MethodFilter(am, mgmt()));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/NoCacheFilter.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/NoCacheFilter.java b/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/NoCacheFilter.java
deleted file mode 100644
index b66b3dc..0000000
--- a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/NoCacheFilter.java
+++ /dev/null
@@ -1,42 +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.filter;
-
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MultivaluedMap;
-
-import com.sun.jersey.core.util.Priority;
-import com.sun.jersey.spi.container.ContainerRequest;
-import com.sun.jersey.spi.container.ContainerResponse;
-import com.sun.jersey.spi.container.ContainerResponseFilter;
-
-@Priority(200)
-public class NoCacheFilter implements ContainerResponseFilter {
-
- @Override
- public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
- //https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching_FAQ
- MultivaluedMap<String, Object> headers = response.getHttpHeaders();
- headers.putSingle(HttpHeaders.CACHE_CONTROL, "no-cache, no-store");
- headers.putSingle("Pragma", "no-cache");
- headers.putSingle(HttpHeaders.EXPIRES, "0");
- return response;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/RequestTaggingRsFilter.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/RequestTaggingRsFilter.java b/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/RequestTaggingRsFilter.java
deleted file mode 100644
index 588c5c1..0000000
--- a/rest/rest-server-jersey/src/main/java/org/apache/brooklyn/rest/filter/RequestTaggingRsFilter.java
+++ /dev/null
@@ -1,76 +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.filter;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-
-import org.apache.brooklyn.util.text.Identifiers;
-
-import com.sun.jersey.core.util.Priority;
-import com.sun.jersey.spi.container.ContainerRequest;
-import com.sun.jersey.spi.container.ContainerRequestFilter;
-import com.sun.jersey.spi.container.ContainerResponse;
-import com.sun.jersey.spi.container.ContainerResponseFilter;
-
-/**
- * Tags each request with a probabilistically unique id. Should be included before other
- * filters to make sense.
- */
-@Priority(100)
-public class RequestTaggingRsFilter implements ContainerRequestFilter, ContainerResponseFilter {
- public static final String ATT_REQUEST_ID = RequestTaggingRsFilter.class.getName() + ".id";
-
- @Context
- private HttpServletRequest req;
-
- private static ThreadLocal<String> tag = new ThreadLocal<String>();
-
- protected static String getTag() {
- // Alternatively could use
- // PhaseInterceptorChain.getCurrentMessage().getId()
-
- return checkNotNull(tag.get());
- }
-
- @Override
- public ContainerRequest filter(ContainerRequest request) {
- String requestId = getRequestId();
- tag.set(requestId);
- return request;
- }
-
- private String getRequestId() {
- Object id = req.getAttribute(ATT_REQUEST_ID);
- if (id != null) {
- return id.toString();
- } else {
- return Identifiers.makeRandomId(6);
- }
- }
-
- @Override
- public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
- tag.remove();
- return response;
- }
-
-}
[9/9] brooklyn-server git commit: This closes #95
Posted by sj...@apache.org.
This closes #95
Remove jersey compatibility
Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/d27d6c72
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/d27d6c72
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/d27d6c72
Branch: refs/heads/master
Commit: d27d6c72b570405f71ea8316f0bda6581b8237ea
Parents: dc6a313 5838d16
Author: Sam Corbett <sa...@cloudsoftcorp.com>
Authored: Thu Apr 7 12:13:43 2016 +0100
Committer: Sam Corbett <sa...@cloudsoftcorp.com>
Committed: Thu Apr 7 12:13:43 2016 +0100
----------------------------------------------------------------------
camp/camp-server-jersey/pom.xml | 225 ------
.../brooklyn/camp/server/RestApiSetup.java | 53 --
.../rest/resource/ApiListingResource.java | 260 -------
.../rest/resource/ApidocRestResource.java | 32 -
.../src/main/webapp/WEB-INF/web.xml | 142 ----
camp/pom.xml | 1 -
karaf/features/src/main/feature/feature.xml | 3 -
launcher/pom.xml | 32 +-
parent/pom.xml | 59 --
pom.xml | 3 -
rest/rest-client/pom.xml | 13 -
rest/rest-server-jersey/pom.xml | 351 ----------
.../org/apache/brooklyn/rest/RestApiSetup.java | 113 ---
.../rest/filter/EntitlementContextFilter.java | 63 --
.../rest/filter/HaHotCheckResourceFilter.java | 196 ------
.../brooklyn/rest/filter/NoCacheFilter.java | 42 --
.../rest/filter/RequestTaggingRsFilter.java | 76 --
.../brooklyn/rest/filter/SwaggerFilter.java | 76 --
.../rest/resources/ApiListingResource.java | 260 -------
.../brooklyn/rest/resources/ApidocResource.java | 33 -
.../brooklyn/rest/util/FormMapProvider.java | 81 ---
.../main/resources/build-metadata.properties | 18 -
.../src/main/webapp/WEB-INF/web.xml | 149 ----
.../BrooklynPropertiesSecurityFilterTest.java | 151 ----
.../brooklyn/rest/BrooklynRestApiLauncher.java | 498 -------------
.../rest/BrooklynRestApiLauncherTest.java | 77 --
.../BrooklynRestApiLauncherTestFixture.java | 109 ---
.../apache/brooklyn/rest/HaHotCheckTest.java | 160 -----
.../brooklyn/rest/HaMasterCheckFilterTest.java | 218 ------
.../rest/domain/AbstractDomainTest.java | 44 --
.../brooklyn/rest/domain/ApiErrorTest.java | 71 --
.../rest/domain/ApplicationSpecTest.java | 40 --
.../brooklyn/rest/domain/ApplicationTest.java | 87 ---
.../rest/domain/EffectorSummaryTest.java | 44 --
.../brooklyn/rest/domain/EntitySpecTest.java | 48 --
.../brooklyn/rest/domain/EntitySummaryTest.java | 48 --
.../brooklyn/rest/domain/LocationSpecTest.java | 58 --
.../rest/domain/LocationSummaryTest.java | 41 --
.../brooklyn/rest/domain/SensorSummaryTest.java | 103 ---
.../rest/domain/VersionSummaryTest.java | 49 --
.../AbstractRestApiEntitlementsTest.java | 111 ---
.../ActivityApiEntitlementsTest.java | 122 ----
.../AuthenticateAnyoneSecurityProvider.java | 41 --
.../EntityConfigApiEntitlementsTest.java | 103 ---
.../entitlement/SensorApiEntitlementsTest.java | 108 ---
.../entitlement/ServerApiEntitlementsTest.java | 34 -
.../StaticDelegatingEntitlementManager.java | 37 -
.../rest/resources/AccessResourceTest.java | 68 --
.../rest/resources/ApidocResourceTest.java | 173 -----
.../ApplicationResourceIntegrationTest.java | 133 ----
.../rest/resources/ApplicationResourceTest.java | 701 -------------------
.../rest/resources/CatalogResetTest.java | 113 ---
.../rest/resources/CatalogResourceTest.java | 515 --------------
.../rest/resources/DelegatingPrintStream.java | 183 -----
.../rest/resources/DescendantsTest.java | 130 ----
.../resources/EntityConfigResourceTest.java | 172 -----
.../rest/resources/EntityResourceTest.java | 189 -----
.../rest/resources/ErrorResponseTest.java | 98 ---
.../rest/resources/LocationResourceTest.java | 188 -----
.../rest/resources/PolicyResourceTest.java | 145 ----
.../rest/resources/ScriptResourceTest.java | 54 --
.../SensorResourceIntegrationTest.java | 82 ---
.../rest/resources/SensorResourceTest.java | 271 -------
.../ServerResourceIntegrationTest.java | 125 ----
.../rest/resources/ServerResourceTest.java | 168 -----
.../rest/resources/ServerShutdownTest.java | 185 -----
.../rest/resources/UsageResourceTest.java | 443 ------------
.../rest/resources/VersionResourceTest.java | 52 --
.../rest/security/PasswordHasherTest.java | 37 -
.../security/provider/TestSecurityProvider.java | 46 --
.../test/config/render/TestRendererHints.java | 36 -
.../brooklynnode/DeployBlueprintTest.java | 89 ---
.../rest/testing/BrooklynRestApiTest.java | 223 ------
.../rest/testing/BrooklynRestResourceTest.java | 154 ----
.../rest/testing/mocks/CapitalizePolicy.java | 33 -
.../rest/testing/mocks/EverythingGroup.java | 27 -
.../rest/testing/mocks/EverythingGroupImpl.java | 32 -
.../rest/testing/mocks/NameMatcherGroup.java | 30 -
.../testing/mocks/NameMatcherGroupImpl.java | 33 -
.../rest/testing/mocks/RestMockApp.java | 24 -
.../rest/testing/mocks/RestMockAppBuilder.java | 39 --
.../testing/mocks/RestMockSimpleEntity.java | 103 ---
.../testing/mocks/RestMockSimplePolicy.java | 64 --
.../util/BrooklynRestResourceUtilsTest.java | 213 ------
.../rest/util/EntityLocationUtilsTest.java | 72 --
.../rest/util/NoOpRecordingShutdownHandler.java | 39 --
.../util/NullHttpServletRequestProvider.java | 46 --
.../rest/util/NullServletConfigProvider.java | 51 --
.../brooklyn/rest/util/RestApiTestUtils.java | 58 --
.../util/ServerStoppingShutdownHandler.java | 75 --
.../TestingHaHotStateCheckClassResource.java | 38 -
.../util/TestingHaHotStateCheckResource.java | 44 --
.../rest/util/TestingHaMasterCheckResource.java | 41 --
.../json/BrooklynJacksonSerializerTest.java | 399 -----------
.../resources/brooklyn/scanning.catalog.bom | 19 -
.../resources/fixtures/api-error-basic.json | 4 -
.../fixtures/api-error-no-details.json | 3 -
.../resources/fixtures/application-list.json | 44 --
.../resources/fixtures/application-spec.json | 16 -
.../resources/fixtures/application-tree.json | 43 --
.../test/resources/fixtures/application.json | 22 -
.../fixtures/catalog-application-list.json | 29 -
.../resources/fixtures/catalog-application.json | 9 -
.../fixtures/effector-summary-list.json | 47 --
.../resources/fixtures/effector-summary.json | 9 -
.../resources/fixtures/entity-only-type.json | 3 -
.../resources/fixtures/entity-summary-list.json | 14 -
.../test/resources/fixtures/entity-summary.json | 13 -
.../src/test/resources/fixtures/entity.json | 7 -
.../src/test/resources/fixtures/ha-summary.json | 19 -
.../test/resources/fixtures/location-list.json | 10 -
.../resources/fixtures/location-summary.json | 8 -
.../fixtures/location-without-credential.json | 5 -
.../src/test/resources/fixtures/location.json | 4 -
.../fixtures/sensor-current-state.json | 6 -
.../resources/fixtures/sensor-summary-list.json | 42 --
.../test/resources/fixtures/sensor-summary.json | 8 -
.../test/resources/fixtures/server-version.json | 14 -
.../test/resources/fixtures/service-state.json | 1 -
.../resources/fixtures/task-summary-list.json | 15 -
rest/rest-server/pom.xml | 5 +-
121 files changed, 11 insertions(+), 11325 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d27d6c72/karaf/features/src/main/feature/feature.xml
----------------------------------------------------------------------
[2/9] brooklyn-server git commit: Remove jersey compatibility
Posted by sj...@apache.org.
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java
deleted file mode 100644
index 72392fe..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/UsageResourceTest.java
+++ /dev/null
@@ -1,443 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import javax.ws.rs.core.Response;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.location.NoMachinesAvailableException;
-import org.apache.brooklyn.core.mgmt.internal.LocalUsageManager;
-import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.entity.software.base.SoftwareProcessEntityTest;
-import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
-import org.apache.brooklyn.location.ssh.SshMachineLocation;
-import org.apache.brooklyn.rest.domain.ApplicationSpec;
-import org.apache.brooklyn.rest.domain.Status;
-import org.apache.brooklyn.rest.domain.TaskSummary;
-import org.apache.brooklyn.rest.domain.UsageStatistic;
-import org.apache.brooklyn.rest.domain.UsageStatistics;
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-import org.apache.brooklyn.rest.testing.mocks.RestMockSimpleEntity;
-import org.apache.brooklyn.util.repeat.Repeater;
-import org.apache.brooklyn.util.time.Time;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.GenericType;
-
-public class UsageResourceTest extends BrooklynRestResourceTest {
-
- @SuppressWarnings("unused")
- private static final Logger LOG = LoggerFactory.getLogger(UsageResourceTest.class);
-
- private static final long TIMEOUT_MS = 10*1000;
-
- private Calendar testStartTime;
-
- private final ApplicationSpec simpleSpec = ApplicationSpec.builder().name("simple-app").
- entities(ImmutableSet.of(new org.apache.brooklyn.rest.domain.EntitySpec("simple-ent", RestMockSimpleEntity.class.getName()))).
- locations(ImmutableSet.of("localhost")).
- build();
-
- @BeforeMethod(alwaysRun=true)
- public void setUpMethod() {
- ((ManagementContextInternal)getManagementContext()).getStorage().remove(LocalUsageManager.APPLICATION_USAGE_KEY);
- ((ManagementContextInternal)getManagementContext()).getStorage().remove(LocalUsageManager.LOCATION_USAGE_KEY);
- testStartTime = new GregorianCalendar();
- }
-
- @Test
- public void testListApplicationUsages() throws Exception {
- // Create an app
- Calendar preStart = new GregorianCalendar();
- String appId = createApp(simpleSpec);
- Calendar postStart = new GregorianCalendar();
-
- // We will retrieve usage from one millisecond after start; this guarantees to not be
- // told about both STARTING+RUNNING, which could otherwise happen if they are in the
- // same milliscond.
- Calendar afterPostStart = Time.newCalendarFromMillisSinceEpochUtc(postStart.getTime().getTime()+1);
-
- // Check that app's usage is returned
- ClientResponse response = client().resource("/v1/usage/applications").get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- Iterable<UsageStatistics> usages = response.getEntity(new GenericType<List<UsageStatistics>>() {});
- UsageStatistics usage = Iterables.getOnlyElement(usages);
- assertAppUsage(usage, appId, ImmutableList.of(Status.STARTING, Status.RUNNING), roundDown(preStart), postStart);
-
- // check app ignored if endCalendar before app started
- response = client().resource("/v1/usage/applications?start="+0+"&end="+(preStart.getTime().getTime()-1)).get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- usages = response.getEntity(new GenericType<List<UsageStatistics>>() {});
- assertTrue(Iterables.isEmpty(usages), "usages="+usages);
-
- // Wait, so that definitely asking about things that have happened (not things in the future,
- // or events that are happening this exact same millisecond)
- waitForFuture(afterPostStart.getTime().getTime());
-
- // Check app start + end date truncated, even if running for longer (i.e. only tell us about this time window).
- // Note that start==end means we get a snapshot of the apps in use at that exact time.
- //
- // The start/end times in UsageStatistic are in String format, and are rounded down to the nearest second.
- // The comparison does use the milliseconds passed in the REST call though.
- // The rounding down result should be the same as roundDown(afterPostStart), because that is the time-window
- // we asked for.
- response = client().resource("/v1/usage/applications?start="+afterPostStart.getTime().getTime()+"&end="+afterPostStart.getTime().getTime()).get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- usages = response.getEntity(new GenericType<List<UsageStatistics>>() {});
- usage = Iterables.getOnlyElement(usages);
- assertAppUsage(usage, appId, ImmutableList.of(Status.RUNNING), roundDown(preStart), postStart);
- assertAppUsageTimesTruncated(usage, roundDown(afterPostStart), roundDown(afterPostStart));
-
- // Delete the app
- Calendar preDelete = new GregorianCalendar();
- deleteApp(appId);
- Calendar postDelete = new GregorianCalendar();
-
- // Deleted app still returned, if in time range
- response = client().resource("/v1/usage/applications").get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- usages = response.getEntity(new GenericType<List<UsageStatistics>>() {});
- usage = Iterables.getOnlyElement(usages);
- assertAppUsage(usage, appId, ImmutableList.of(Status.STARTING, Status.RUNNING, Status.DESTROYED), roundDown(preStart), postDelete);
- assertAppUsage(ImmutableList.copyOf(usage.getStatistics()).subList(2, 3), appId, ImmutableList.of(Status.DESTROYED), roundDown(preDelete), postDelete);
-
- long afterPostDelete = postDelete.getTime().getTime()+1;
- waitForFuture(afterPostDelete);
-
- response = client().resource("/v1/usage/applications?start=" + afterPostDelete).get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- usages = response.getEntity(new GenericType<List<UsageStatistics>>() {});
- assertTrue(Iterables.isEmpty(usages), "usages="+usages);
- }
-
- @Test
- public void testGetApplicationUsagesForNonExistantApp() throws Exception {
- ClientResponse response = client().resource("/v1/usage/applications/wrongid").get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
- }
-
- @Test
- public void testGetApplicationUsage() throws Exception {
- // Create an app
- Calendar preStart = new GregorianCalendar();
- String appId = createApp(simpleSpec);
- Calendar postStart = new GregorianCalendar();
-
- // Normal request returns all
- ClientResponse response = client().resource("/v1/usage/applications/" + appId).get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- UsageStatistics usage = response.getEntity(new GenericType<UsageStatistics>() {});
- assertAppUsage(usage, appId, ImmutableList.of(Status.STARTING, Status.RUNNING), roundDown(preStart), postStart);
-
- // Time-constrained requests
- response = client().resource("/v1/usage/applications/" + appId + "?start=1970-01-01T00:00:00-0100").get(ClientResponse.class);
- usage = response.getEntity(new GenericType<UsageStatistics>() {});
- assertAppUsage(usage, appId, ImmutableList.of(Status.STARTING, Status.RUNNING), roundDown(preStart), postStart);
-
- response = client().resource("/v1/usage/applications/" + appId + "?start=9999-01-01T00:00:00+0100").get(ClientResponse.class);
- assertTrue(response.getStatus() >= 400, "end defaults to NOW, so future start should fail, instead got code "+response.getStatus());
-
- response = client().resource("/v1/usage/applications/" + appId + "?start=9999-01-01T00:00:00%2B0100&end=9999-01-02T00:00:00%2B0100").get(ClientResponse.class);
- usage = response.getEntity(new GenericType<UsageStatistics>() {});
- assertTrue(usage.getStatistics().isEmpty());
-
- response = client().resource("/v1/usage/applications/" + appId + "?end=9999-01-01T00:00:00+0100").get(ClientResponse.class);
- usage = response.getEntity(new GenericType<UsageStatistics>() {});
- assertAppUsage(usage, appId, ImmutableList.of(Status.STARTING, Status.RUNNING), roundDown(preStart), postStart);
-
- response = client().resource("/v1/usage/applications/" + appId + "?start=9999-01-01T00:00:00+0100&end=9999-02-01T00:00:00+0100").get(ClientResponse.class);
- usage = response.getEntity(new GenericType<UsageStatistics>() {});
- assertTrue(usage.getStatistics().isEmpty());
-
- response = client().resource("/v1/usage/applications/" + appId + "?start=1970-01-01T00:00:00-0100&end=9999-01-01T00:00:00+0100").get(ClientResponse.class);
- usage = response.getEntity(new GenericType<UsageStatistics>() {});
- assertAppUsage(usage, appId, ImmutableList.of(Status.STARTING, Status.RUNNING), roundDown(preStart), postStart);
-
- response = client().resource("/v1/usage/applications/" + appId + "?end=1970-01-01T00:00:00-0100").get(ClientResponse.class);
- usage = response.getEntity(new GenericType<UsageStatistics>() {});
- assertTrue(usage.getStatistics().isEmpty());
-
- // Delete the app
- Calendar preDelete = new GregorianCalendar();
- deleteApp(appId);
- Calendar postDelete = new GregorianCalendar();
-
- // Deleted app still returned, if in time range
- response = client().resource("/v1/usage/applications/" + appId).get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- usage = response.getEntity(new GenericType<UsageStatistics>() {});
- assertAppUsage(usage, appId, ImmutableList.of(Status.STARTING, Status.RUNNING, Status.DESTROYED), roundDown(preStart), postDelete);
- assertAppUsage(ImmutableList.copyOf(usage.getStatistics()).subList(2, 3), appId, ImmutableList.of(Status.DESTROYED), roundDown(preDelete), postDelete);
-
- // Deleted app not returned if terminated before time range begins
- long afterPostDelete = postDelete.getTime().getTime()+1;
- waitForFuture(afterPostDelete);
- response = client().resource("/v1/usage/applications/" + appId +"?start=" + afterPostDelete).get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- usage = response.getEntity(new GenericType<UsageStatistics>() {});
- assertTrue(usage.getStatistics().isEmpty(), "usages="+usage);
- }
-
- @Test
- public void testGetMachineUsagesForNonExistantMachine() throws Exception {
- ClientResponse response = client().resource("/v1/usage/machines/wrongid").get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
- }
-
- @Test
- public void testGetMachineUsagesInitiallyEmpty() throws Exception {
- // All machines: empty
- ClientResponse response = client().resource("/v1/usage/machines").get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- Iterable<UsageStatistics> usages = response.getEntity(new GenericType<List<UsageStatistics>>() {});
- assertTrue(Iterables.isEmpty(usages));
-
- // Specific machine that does not exist: get 404
- response = client().resource("/v1/usage/machines/machineIdThatDoesNotExist").get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
- }
-
- @Test
- public void testListAndGetMachineUsage() throws Exception {
- Location location = getManagementContext().getLocationManager().createLocation(LocationSpec.create(DynamicLocalhostMachineProvisioningLocation.class));
- TestApplication app = getManagementContext().getEntityManager().createEntity(EntitySpec.create(TestApplication.class));
- SoftwareProcessEntityTest.MyService entity = app.createAndManageChild(org.apache.brooklyn.api.entity.EntitySpec.create(SoftwareProcessEntityTest.MyService.class));
-
- Calendar preStart = new GregorianCalendar();
- app.start(ImmutableList.of(location));
- Calendar postStart = new GregorianCalendar();
- Location machine = Iterables.getOnlyElement(entity.getLocations());
-
- // All machines
- ClientResponse response = client().resource("/v1/usage/machines").get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- Iterable<UsageStatistics> usages = response.getEntity(new GenericType<List<UsageStatistics>>() {});
- UsageStatistics usage = Iterables.getOnlyElement(usages);
- assertMachineUsage(usage, app.getId(), machine.getId(), ImmutableList.of(Status.ACCEPTED), roundDown(preStart), postStart);
-
- // Specific machine
- response = client().resource("/v1/usage/machines/"+machine.getId()).get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- usage = response.getEntity(new GenericType<UsageStatistics>() {});
- assertMachineUsage(usage, app.getId(), machine.getId(), ImmutableList.of(Status.ACCEPTED), roundDown(preStart), postStart);
- }
-
- @Test
- public void testListMachinesUsageForApp() throws Exception {
- Location location = getManagementContext().getLocationManager().createLocation(LocationSpec.create(DynamicLocalhostMachineProvisioningLocation.class));
- TestApplication app = getManagementContext().getEntityManager().createEntity(EntitySpec.create(TestApplication.class));
- SoftwareProcessEntityTest.MyService entity = app.createAndManageChild(org.apache.brooklyn.api.entity.EntitySpec.create(SoftwareProcessEntityTest.MyService.class));
- String appId = app.getId();
-
- Calendar preStart = new GregorianCalendar();
- app.start(ImmutableList.of(location));
- Calendar postStart = new GregorianCalendar();
- Location machine = Iterables.getOnlyElement(entity.getLocations());
-
- // For running machine
- ClientResponse response = client().resource("/v1/usage/machines?application="+appId).get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- Iterable<UsageStatistics> usages = response.getEntity(new GenericType<List<UsageStatistics>>() {});
- UsageStatistics usage = Iterables.getOnlyElement(usages);
- assertMachineUsage(usage, app.getId(), machine.getId(), ImmutableList.of(Status.ACCEPTED), roundDown(preStart), postStart);
-
- // Stop the machine
- Calendar preStop = new GregorianCalendar();
- app.stop();
- Calendar postStop = new GregorianCalendar();
-
- // Deleted machine still returned, if in time range
- response = client().resource("/v1/usage/machines?application=" + appId).get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- usages = response.getEntity(new GenericType<List<UsageStatistics>>() {});
- usage = Iterables.getOnlyElement(usages);
- assertMachineUsage(usage, app.getId(), machine.getId(), ImmutableList.of(Status.ACCEPTED, Status.DESTROYED), roundDown(preStart), postStop);
- assertMachineUsage(ImmutableList.copyOf(usage.getStatistics()).subList(1,2), appId, machine.getId(), ImmutableList.of(Status.DESTROYED), roundDown(preStop), postStop);
-
- // Terminated machines ignored if terminated since start-time
- long futureTime = postStop.getTime().getTime()+1;
- waitForFuture(futureTime);
- response = client().resource("/v1/usage/applications?start=" + futureTime).get(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- usages = response.getEntity(new GenericType<List<UsageStatistics>>() {});
- assertTrue(Iterables.isEmpty(usages), "usages="+usages);
- }
-
- private String createApp(ApplicationSpec spec) {
- ClientResponse response = clientDeploy(spec);
- assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
- TaskSummary createTask = response.getEntity(TaskSummary.class);
- waitForTask(createTask.getId());
- return createTask.getEntityId();
- }
-
- private void deleteApp(String appId) {
- ClientResponse response = client().resource("/v1/applications/"+appId)
- .delete(ClientResponse.class);
- assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());
- TaskSummary deletionTask = response.getEntity(TaskSummary.class);
- waitForTask(deletionTask.getId());
- }
-
- private void assertCalendarOrders(Object context, Calendar... Calendars) {
- if (Calendars.length <= 1) return;
-
- long[] times = new long[Calendars.length];
- for (int i = 0; i < times.length; i++) {
- times[i] = millisSinceStart(Calendars[i]);
- }
- String err = "context="+context+"; Calendars="+Arrays.toString(Calendars) + "; CalendarsSanitized="+Arrays.toString(times);
-
- Calendar Calendar = Calendars[0];
- for (int i = 1; i < Calendars.length; i++) {
- assertTrue(Calendar.getTime().getTime() <= Calendars[i].getTime().getTime(), err);
- }
- }
-
- private void waitForTask(final String taskId) {
- boolean success = Repeater.create()
- .repeat(new Runnable() { public void run() {}})
- .until(new Callable<Boolean>() {
- @Override public Boolean call() {
- ClientResponse response = client().resource("/v1/activities/"+taskId).get(ClientResponse.class);
- if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
- return true;
- }
- TaskSummary summary = response.getEntity(TaskSummary.class);
- return summary != null && summary.getEndTimeUtc() != null;
- }})
- .every(10L, TimeUnit.MILLISECONDS)
- .limitTimeTo(TIMEOUT_MS, TimeUnit.MILLISECONDS)
- .run();
- assertTrue(success, "task "+taskId+" not finished");
- }
-
- private long millisSinceStart(Calendar time) {
- return time.getTime().getTime() - testStartTime.getTime().getTime();
- }
-
- private Calendar roundDown(Calendar calendar) {
- long time = calendar.getTime().getTime();
- long timeDown = ((long)(time / 1000)) * 1000;
- return Time.newCalendarFromMillisSinceEpochUtc(timeDown);
- }
-
- @SuppressWarnings("unused")
- private Calendar roundUp(Calendar calendar) {
- long time = calendar.getTime().getTime();
- long timeDown = ((long)(time / 1000)) * 1000;
- long timeUp = (time == timeDown) ? time : timeDown + 1000;
- return Time.newCalendarFromMillisSinceEpochUtc(timeUp);
- }
-
- private void assertMachineUsage(UsageStatistics usage, String appId, String machineId, List<Status> states, Calendar pre, Calendar post) throws Exception {
- assertUsage(usage.getStatistics(), appId, machineId, states, pre, post, false);
- }
-
- private void assertMachineUsage(Iterable<UsageStatistic> usages, String appId, String machineId, List<Status> states, Calendar pre, Calendar post) throws Exception {
- assertUsage(usages, appId, machineId, states, pre, post, false);
- }
-
- private void assertAppUsage(UsageStatistics usage, String appId, List<Status> states, Calendar pre, Calendar post) throws Exception {
- assertUsage(usage.getStatistics(), appId, appId, states, pre, post, false);
- }
-
- private void assertAppUsage(Iterable<UsageStatistic> usages, String appId, List<Status> states, Calendar pre, Calendar post) throws Exception {
- assertUsage(usages, appId, appId, states, pre, post, false);
- }
-
- private void assertUsage(Iterable<UsageStatistic> usages, String appId, String id, List<Status> states, Calendar pre, Calendar post, boolean allowGaps) throws Exception {
- String errMsg = "usages="+usages;
- Calendar now = new GregorianCalendar();
- Calendar lowerBound = pre;
- Calendar strictStart = null;
-
- assertEquals(Iterables.size(usages), states.size(), errMsg);
- for (int i = 0; i < Iterables.size(usages); i++) {
- UsageStatistic usage = Iterables.get(usages, i);
- Calendar usageStart = Time.parseCalendar(usage.getStart());
- Calendar usageEnd = Time.parseCalendar(usage.getEnd());
- assertEquals(usage.getId(), id, errMsg);
- assertEquals(usage.getApplicationId(), appId, errMsg);
- assertEquals(usage.getStatus(), states.get(i), errMsg);
- assertCalendarOrders(usages, lowerBound, usageStart, post);
- assertCalendarOrders(usages, usageEnd, now);
- if (strictStart != null) {
- assertEquals(usageStart, strictStart, errMsg);
- }
- if (!allowGaps) {
- strictStart = usageEnd;
- }
- lowerBound = usageEnd;
- }
- }
-
- private void assertAppUsageTimesTruncated(UsageStatistics usages, Calendar strictStart, Calendar strictEnd) throws Exception {
- String errMsg = "strictStart="+Time.makeDateString(strictStart)+"; strictEnd="+Time.makeDateString(strictEnd)+";usages="+usages;
- Calendar usageStart = Time.parseCalendar(Iterables.getFirst(usages.getStatistics(), null).getStart());
- Calendar usageEnd = Time.parseCalendar(Iterables.getLast(usages.getStatistics()).getStart());
- // time zones might be different - so must convert to date
- assertEquals(usageStart.getTime(), strictStart.getTime(), "usageStart="+Time.makeDateString(usageStart)+";"+errMsg);
- assertEquals(usageEnd.getTime(), strictEnd.getTime(), errMsg);
- }
-
- public static class DynamicLocalhostMachineProvisioningLocation extends LocalhostMachineProvisioningLocation {
- @Override
- public SshMachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
- return super.obtain(flags);
- }
-
- @Override
- public void release(SshMachineLocation machine) {
- super.release(machine);
- super.machines.remove(machine);
- getManagementContext().getLocationManager().unmanage(machine);
- }
- }
-
- private void waitForFuture(long futureTime) throws InterruptedException {
- long now;
- while ((now = System.currentTimeMillis()) < futureTime) {
- Thread.sleep(futureTime - now);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/VersionResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/VersionResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/VersionResourceTest.java
deleted file mode 100644
index 384feb0..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/resources/VersionResourceTest.java
+++ /dev/null
@@ -1,52 +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.resources;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import javax.ws.rs.core.Response;
-
-import org.testng.annotations.Test;
-
-import org.apache.brooklyn.rest.testing.BrooklynRestResourceTest;
-
-import com.sun.jersey.api.client.ClientResponse;
-
-public class VersionResourceTest extends BrooklynRestResourceTest {
-
- @Test
- public void testGetVersion() {
- ClientResponse response = client().resource("/v1/version")
- .get(ClientResponse.class);
-
- assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
- String version = response.getEntity(String.class);
-// TODO johnmccabe - 19/12/2015 :: temporarily disabled while the repo split work is ongoing,
-// must be restored when switching back to a valid brooklyn version
-// assertTrue(version.matches("^\\d+\\.\\d+\\.\\d+.*"));
- assertTrue(true);
- }
-
- @SuppressWarnings("deprecation")
- @Override
- protected void addBrooklynResources() {
- addResource(new VersionResource());
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/security/PasswordHasherTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/security/PasswordHasherTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/security/PasswordHasherTest.java
deleted file mode 100644
index 575d6a4..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/security/PasswordHasherTest.java
+++ /dev/null
@@ -1,37 +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.security;
-
-import static org.testng.Assert.assertEquals;
-
-import org.testng.annotations.Test;
-
-public class PasswordHasherTest {
-
- @Test
- public void testHashSha256() throws Exception {
- // Note: expected hash values generated externally:
- // echo -n mysaltmypassword | openssl dgst -sha256
-
- assertEquals(PasswordHasher.sha256("mysalt", "mypassword"), "d02878b06efa88579cd84d9e50b211c0a7caa92cf243bad1622c66081f7e2692");
- assertEquals(PasswordHasher.sha256("", "mypassword"), "89e01536ac207279409d4de1e5253e01f4a1769e696db0d6062ca9b8f56767c8");
- assertEquals(PasswordHasher.sha256(null, "mypassword"), "89e01536ac207279409d4de1e5253e01f4a1769e696db0d6062ca9b8f56767c8");
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/security/provider/TestSecurityProvider.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/security/provider/TestSecurityProvider.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/security/provider/TestSecurityProvider.java
deleted file mode 100644
index cad251f..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/security/provider/TestSecurityProvider.java
+++ /dev/null
@@ -1,46 +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.security.provider;
-
-import javax.servlet.http.HttpSession;
-
-import org.apache.http.auth.UsernamePasswordCredentials;
-
-public class TestSecurityProvider implements SecurityProvider {
-
- public static final String USER = "test";
- public static final String PASSWORD = "opensesame";
- public static final UsernamePasswordCredentials CREDENTIAL =
- new UsernamePasswordCredentials(TestSecurityProvider.USER, TestSecurityProvider.PASSWORD);
-
- @Override
- public boolean isAuthenticated(HttpSession session) {
- return false;
- }
-
- @Override
- public boolean authenticate(HttpSession session, String user, String password) {
- return USER.equals(user) && PASSWORD.equals(password);
- }
-
- @Override
- public boolean logout(HttpSession session) {
- return false;
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/test/config/render/TestRendererHints.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/test/config/render/TestRendererHints.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/test/config/render/TestRendererHints.java
deleted file mode 100644
index 91294db..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/test/config/render/TestRendererHints.java
+++ /dev/null
@@ -1,36 +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.test.config.render;
-
-import org.apache.brooklyn.core.config.render.RendererHints;
-
-/** Methods used when testing the {@link RendererHints} regiostry. */
-public class TestRendererHints {
-
- /** Clear the registry.
- *
- * MUST be used by a single test only.
- * TestNG interleaves the tests (sequentially) which results in tearDown
- * executing in the middle of another class' tests. Only one tearDown may
- * call this method.
- **/
- public static void clearRegistry() {
- RendererHints.getRegistry().clear();
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/test/entity/brooklynnode/DeployBlueprintTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/test/entity/brooklynnode/DeployBlueprintTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/test/entity/brooklynnode/DeployBlueprintTest.java
deleted file mode 100644
index 399e303..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/test/entity/brooklynnode/DeployBlueprintTest.java
+++ /dev/null
@@ -1,89 +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.test.entity.brooklynnode;
-
-import static org.testng.Assert.assertEquals;
-
-import java.net.URI;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.mgmt.EntityManager;
-import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
-import org.apache.brooklyn.entity.brooklynnode.BrooklynNode.DeployBlueprintEffector;
-import org.apache.brooklyn.entity.stock.BasicApplication;
-import org.apache.brooklyn.feed.http.JsonFunctions;
-import org.apache.brooklyn.rest.BrooklynRestApiLauncherTestFixture;
-import org.apache.brooklyn.test.HttpTestUtils;
-import org.apache.brooklyn.util.guava.Functionals;
-import org.eclipse.jetty.server.Server;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-public class DeployBlueprintTest extends BrooklynRestApiLauncherTestFixture {
-
- private static final Logger log = LoggerFactory.getLogger(DeployBlueprintTest.class);
-
- Server server;
-
- @BeforeMethod(alwaysRun=true)
- public void setUp() throws Exception {
- server = newServer();
- useServerForTest(server);
- }
-
- @Test(enabled = false) // to be deleted
- public void testStartsAppViaEffector() throws Exception {
- URI webConsoleUri = URI.create(getBaseUri());
-
- EntitySpec<BrooklynNode> spec = EntitySpec.create(BrooklynNode.class);
- EntityManager mgr = getManagementContextFromJettyServerAttributes(server).getEntityManager();
- BrooklynNode node = mgr.createEntity(spec);
- node.sensors().set(BrooklynNode.WEB_CONSOLE_URI, webConsoleUri);
- mgr.manage(node);
- Map<String, String> params = ImmutableMap.of(DeployBlueprintEffector.BLUEPRINT_CAMP_PLAN.getName(), "{ services: [ serviceType: \"java:"+BasicApplication.class.getName()+"\" ] }");
- String id = node.invoke(BrooklynNode.DEPLOY_BLUEPRINT, params).getUnchecked();
-
- log.info("got: "+id);
-
- String apps = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications");
- List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class);
- assertEquals(appType, ImmutableList.of(BasicApplication.class.getName()));
-
- String status = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications/"+id+"/entities/"+id+"/sensors/service.status");
- log.info("STATUS: "+status);
- }
-
- private <T> List<T> parseJsonList(String json, List<String> elements, Class<T> clazz) {
- Function<String, List<T>> func = Functionals.chain(
- JsonFunctions.asJson(),
- JsonFunctions.forEach(Functionals.chain(
- JsonFunctions.walk(elements),
- JsonFunctions.cast(clazz))));
- return func.apply(json);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestApiTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestApiTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestApiTest.java
deleted file mode 100644
index 35a2d04..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestApiTest.java
+++ /dev/null
@@ -1,223 +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.testing;
-
-import java.net.URI;
-
-import org.apache.brooklyn.api.location.LocationRegistry;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.camp.brooklyn.BrooklynCampPlatformLauncherNoServer;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.location.BasicLocationRegistry;
-import org.apache.brooklyn.core.mgmt.ManagementContextInjectable;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.rest.BrooklynRestApi;
-import org.apache.brooklyn.rest.BrooklynRestApiLauncherTest;
-import org.apache.brooklyn.rest.util.BrooklynRestResourceUtils;
-import org.apache.brooklyn.rest.util.ManagementContextProvider;
-import org.apache.brooklyn.rest.util.NoOpRecordingShutdownHandler;
-import org.apache.brooklyn.rest.util.NullHttpServletRequestProvider;
-import org.apache.brooklyn.rest.util.NullServletConfigProvider;
-import org.apache.brooklyn.rest.util.ShutdownHandlerProvider;
-import org.apache.brooklyn.rest.util.json.BrooklynJacksonJsonProvider;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeMethod;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.common.base.Preconditions;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.api.core.DefaultResourceConfig;
-import com.sun.jersey.test.framework.AppDescriptor;
-import com.sun.jersey.test.framework.JerseyTest;
-import com.sun.jersey.test.framework.LowLevelAppDescriptor;
-import com.sun.jersey.test.framework.spi.container.TestContainer;
-import com.sun.jersey.test.framework.spi.container.TestContainerException;
-import com.sun.jersey.test.framework.spi.container.TestContainerFactory;
-import com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory;
-
-public abstract class BrooklynRestApiTest {
-
- protected ManagementContext manager;
-
- protected boolean useLocalScannedCatalog = false;
- protected NoOpRecordingShutdownHandler shutdownListener = createShutdownHandler();
-
- @BeforeMethod(alwaysRun = true)
- public void setUpMethod() {
- shutdownListener.reset();
- }
-
- protected synchronized void useLocalScannedCatalog() {
- if (manager!=null && !useLocalScannedCatalog)
- throw new IllegalStateException("useLocalScannedCatalog must be specified before manager is accessed/created");
- useLocalScannedCatalog = true;
- }
-
- private NoOpRecordingShutdownHandler createShutdownHandler() {
- return new NoOpRecordingShutdownHandler();
- }
-
- protected synchronized ManagementContext getManagementContext() {
- if (manager==null) {
- if (useLocalScannedCatalog) {
- manager = new LocalManagementContext();
- BrooklynRestApiLauncherTest.forceUseOfDefaultCatalogWithJavaClassPath(manager);
- } else {
- manager = new LocalManagementContextForTests();
- }
- manager.getHighAvailabilityManager().disabled();
- BasicLocationRegistry.addNamedLocationLocalhost(manager);
-
- new BrooklynCampPlatformLauncherNoServer()
- .useManagementContext(manager)
- .launch();
- }
- return manager;
- }
-
- protected ObjectMapper mapper() {
- return BrooklynJacksonJsonProvider.findSharedObjectMapper(getManagementContext());
- }
-
- @AfterClass
- public void tearDown() throws Exception {
- destroyManagementContext();
- }
-
- protected void destroyManagementContext() {
- if (manager!=null) {
- Entities.destroyAll(manager);
- manager = null;
- }
- }
-
- public LocationRegistry getLocationRegistry() {
- return new BrooklynRestResourceUtils(getManagementContext()).getLocationRegistry();
- }
-
- private JerseyTest jerseyTest;
- protected DefaultResourceConfig config = new DefaultResourceConfig();
-
- protected final void addResource(Object resource) {
- Preconditions.checkNotNull(config, "Must run before setUpJersey");
-
- if (resource instanceof Class)
- config.getClasses().add((Class<?>)resource);
- else
- config.getSingletons().add(resource);
-
- if (resource instanceof ManagementContextInjectable) {
- ((ManagementContextInjectable)resource).setManagementContext(getManagementContext());
- }
- }
-
- protected final void addProvider(Class<?> provider) {
- Preconditions.checkNotNull(config, "Must run before setUpJersey");
-
- config.getClasses().add(provider);
- }
-
- protected void addDefaultResources() {
- // seems we have to provide our own injector because the jersey test framework
- // doesn't inject ServletConfig and it all blows up
- // and the servlet config provider must be an instance; addClasses doesn't work for some reason
- addResource(new NullServletConfigProvider());
- addResource(new ManagementContextProvider(getManagementContext()));
- addProvider(NullHttpServletRequestProvider.class);
- addResource(new ShutdownHandlerProvider(shutdownListener));
- }
-
- protected final void setUpResources() {
- addDefaultResources();
- addBrooklynResources();
- for (Object r: BrooklynRestApi.getMiscResources())
- addResource(r);
- }
-
- /** intended for overriding if you only want certain resources added, or additional ones added */
- protected void addBrooklynResources() {
- for (Object r: BrooklynRestApi.getBrooklynRestResources())
- addResource(r);
- }
-
- protected void setUpJersey() {
- setUpResources();
-
- jerseyTest = createJerseyTest();
- config = null;
- try {
- jerseyTest.setUp();
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }
-
- protected JerseyTest createJerseyTest() {
- return new JerseyTest() {
- @Override
- protected AppDescriptor configure() {
- return new LowLevelAppDescriptor.Builder(config).build();
- }
-
- @Override
- protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
- return new TestContainerFactory() {
- TestContainerFactory delegate = new InMemoryTestContainerFactory();
-
- @Override
- public Class<? extends AppDescriptor> supports() {
- return delegate.supports();
- }
-
- @Override
- public TestContainer create(URI baseUri, AppDescriptor ad)
- throws IllegalArgumentException {
- URI uri = URI.create(baseUri.toString() + "v1/");
- System.out.println(uri);;
- return delegate.create(uri, (LowLevelAppDescriptor)ad);
- }
- };
- }
- };
- }
-
- protected void tearDownJersey() {
- if (jerseyTest != null) {
- try {
- jerseyTest.tearDown();
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }
- config = new DefaultResourceConfig();
- }
-
- public Client client() {
- Preconditions.checkNotNull(jerseyTest, "Must run setUpJersey first");
- return jerseyTest.client();
- }
-
- public WebResource resource(String uri) {
- Preconditions.checkNotNull(jerseyTest, "Must run setUpJersey first");
- return jerseyTest.resource().path(uri);
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestResourceTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestResourceTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestResourceTest.java
deleted file mode 100644
index b94e73c..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/BrooklynRestResourceTest.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.testing;
-
-import static org.testng.Assert.assertTrue;
-
-import java.net.URI;
-import java.util.Collection;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-import java.util.logging.Level;
-
-import javax.ws.rs.core.MediaType;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.apache.brooklyn.api.entity.Application;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.rest.domain.ApplicationSpec;
-import org.apache.brooklyn.rest.domain.ApplicationSummary;
-import org.apache.brooklyn.rest.domain.Status;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.repeat.Repeater;
-import org.apache.brooklyn.util.time.Duration;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.UniformInterfaceException;
-import com.sun.jersey.spi.inject.Errors;
-
-public abstract class BrooklynRestResourceTest extends BrooklynRestApiTest {
-
- private static final Logger log = LoggerFactory.getLogger(BrooklynRestResourceTest.class);
-
- @BeforeClass(alwaysRun = true)
- public void setUp() throws Exception {
- // need this to debug jersey inject errors
- java.util.logging.Logger.getLogger(Errors.class.getName()).setLevel(Level.INFO);
-
- setUpJersey();
- }
-
- @Override
- @AfterClass(alwaysRun = true)
- public void tearDown() throws Exception {
- tearDownJersey();
- super.tearDown();
- }
-
-
- protected ClientResponse clientDeploy(ApplicationSpec spec) {
- try {
- // dropwizard TestClient won't skip deserialization of trivial things like string and byte[] and inputstream
- // if we pass in an object it serializes, so we have to serialize things ourselves
- return client().resource("/v1/applications")
- .entity(new ObjectMapper().writer().writeValueAsBytes(spec), MediaType.APPLICATION_OCTET_STREAM)
- .post(ClientResponse.class);
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }
-
- protected void waitForApplicationToBeRunning(final URI applicationRef) {
- waitForApplicationToBeRunning(applicationRef, Duration.minutes(3));
- }
- protected void waitForApplicationToBeRunning(final URI applicationRef, Duration timeout) {
- if (applicationRef==null)
- throw new NullPointerException("No application URI available (consider using BrooklynRestResourceTest.clientDeploy)");
-
- boolean started = Repeater.create("Wait for application startup")
- .until(new Callable<Boolean>() {
- @Override
- public Boolean call() throws Exception {
- Status status = getApplicationStatus(applicationRef);
- if (status == Status.ERROR) {
- Assert.fail("Application failed with ERROR");
- }
- return status == Status.RUNNING;
- }
- })
- .backoffTo(Duration.ONE_SECOND)
- .limitTimeTo(timeout)
- .run();
-
- if (!started) {
- log.warn("Did not start application "+applicationRef+":");
- Collection<Application> apps = getManagementContext().getApplications();
- for (Application app: apps)
- Entities.dumpInfo(app);
- }
- assertTrue(started);
- }
-
- protected Status getApplicationStatus(URI uri) {
- return client().resource(uri).get(ApplicationSummary.class).getStatus();
- }
-
- protected void waitForPageFoundResponse(final String resource, final Class<?> clazz) {
- boolean found = Repeater.create("Wait for page found")
- .until(new Callable<Boolean>() {
- @Override
- public Boolean call() throws Exception {
- try {
- client().resource(resource).get(clazz);
- return true;
- } catch (UniformInterfaceException e) {
- return false;
- }
- }
- })
- .every(1, TimeUnit.SECONDS)
- .limitTimeTo(30, TimeUnit.SECONDS)
- .run();
- assertTrue(found);
- }
-
- protected void waitForPageNotFoundResponse(final String resource, final Class<?> clazz) {
- boolean success = Repeater.create("Wait for page not found")
- .until(new Callable<Boolean>() {
- @Override
- public Boolean call() throws Exception {
- try {
- client().resource(resource).get(clazz);
- return false;
- } catch (UniformInterfaceException e) {
- return e.getResponse().getStatus() == 404;
- }
- }
- })
- .every(1, TimeUnit.SECONDS)
- .limitTimeTo(30, TimeUnit.SECONDS)
- .run();
- assertTrue(success);
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/CapitalizePolicy.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/CapitalizePolicy.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/CapitalizePolicy.java
deleted file mode 100644
index 7d80a6f..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/CapitalizePolicy.java
+++ /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.
- */
-package org.apache.brooklyn.rest.testing.mocks;
-
-import org.apache.brooklyn.api.entity.EntityLocal;
-import org.apache.brooklyn.core.policy.AbstractPolicy;
-
-@SuppressWarnings("deprecation")
-public class CapitalizePolicy extends AbstractPolicy {
-
- @Override
- public void setEntity(EntityLocal entity) {
- super.setEntity(entity);
- // TODO subscribe to foo and emit an enriched sensor on different channel which is capitalized
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/EverythingGroup.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/EverythingGroup.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/EverythingGroup.java
deleted file mode 100644
index 707c4a3..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/EverythingGroup.java
+++ /dev/null
@@ -1,27 +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.testing.mocks;
-
-import org.apache.brooklyn.api.entity.Group;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-
-@ImplementedBy(EverythingGroupImpl.class)
-public interface EverythingGroup extends Group {
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/EverythingGroupImpl.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/EverythingGroupImpl.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/EverythingGroupImpl.java
deleted file mode 100644
index 8b2c98b..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/EverythingGroupImpl.java
+++ /dev/null
@@ -1,32 +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.testing.mocks;
-
-import org.apache.brooklyn.entity.group.DynamicGroupImpl;
-
-import com.google.common.base.Predicates;
-
-public class EverythingGroupImpl extends DynamicGroupImpl implements EverythingGroup {
-
- public EverythingGroupImpl() {
- super();
- config().set(ENTITY_FILTER, Predicates.alwaysTrue());
- }
-
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/NameMatcherGroup.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/NameMatcherGroup.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/NameMatcherGroup.java
deleted file mode 100644
index f9a2e21..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/NameMatcherGroup.java
+++ /dev/null
@@ -1,30 +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.testing.mocks;
-
-import org.apache.brooklyn.api.entity.Group;
-import org.apache.brooklyn.api.entity.ImplementedBy;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-
-@ImplementedBy(NameMatcherGroupImpl.class)
-public interface NameMatcherGroup extends Group {
-
- public static final ConfigKey<String> NAME_REGEX = ConfigKeys.newStringConfigKey("namematchergroup.regex");
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/NameMatcherGroupImpl.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/NameMatcherGroupImpl.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/NameMatcherGroupImpl.java
deleted file mode 100644
index bec416f..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/NameMatcherGroupImpl.java
+++ /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.
- */
-package org.apache.brooklyn.rest.testing.mocks;
-
-import org.apache.brooklyn.core.entity.EntityPredicates;
-import org.apache.brooklyn.entity.group.DynamicGroupImpl;
-import org.apache.brooklyn.util.text.StringPredicates;
-
-public class NameMatcherGroupImpl extends DynamicGroupImpl implements NameMatcherGroup {
-
- @Override
- public void init() {
- super.init();
- config().set(ENTITY_FILTER, EntityPredicates.displayNameSatisfies(StringPredicates.matchesRegex(getConfig(NAME_REGEX))));
- rescanEntities();
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockApp.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockApp.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockApp.java
deleted file mode 100644
index 6d92e65..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockApp.java
+++ /dev/null
@@ -1,24 +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.testing.mocks;
-
-import org.apache.brooklyn.core.entity.AbstractApplication;
-
-public class RestMockApp extends AbstractApplication {
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockAppBuilder.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockAppBuilder.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockAppBuilder.java
deleted file mode 100644
index 1ca10bd..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockAppBuilder.java
+++ /dev/null
@@ -1,39 +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.testing.mocks;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.core.entity.StartableApplication;
-import org.apache.brooklyn.core.entity.factory.ApplicationBuilder;
-import org.apache.brooklyn.util.javalang.Reflections;
-
-public class RestMockAppBuilder extends ApplicationBuilder {
-
- public RestMockAppBuilder() {
- super(EntitySpec.create(StartableApplication.class).impl(RestMockApp.class));
- }
-
- @Override
- protected void doBuild() {
- addChild(EntitySpec.create(Entity.class).impl(RestMockSimpleEntity.class)
- .additionalInterfaces(Reflections.getAllInterfaces(RestMockSimpleEntity.class))
- .displayName("child1"));
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java
deleted file mode 100644
index 58d24aa..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimpleEntity.java
+++ /dev/null
@@ -1,103 +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.testing.mocks;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntityLocal;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.annotation.Effector;
-import org.apache.brooklyn.core.annotation.EffectorParam;
-import org.apache.brooklyn.core.config.BasicConfigKey;
-import org.apache.brooklyn.core.effector.MethodEffector;
-import org.apache.brooklyn.core.sensor.BasicAttributeSensor;
-import org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver;
-import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.location.ssh.SshMachineLocation;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-
-public class RestMockSimpleEntity extends SoftwareProcessImpl {
-
- private static final Logger log = LoggerFactory.getLogger(RestMockSimpleEntity.class);
-
- public RestMockSimpleEntity() {
- super();
- }
-
- public RestMockSimpleEntity(Entity parent) {
- super(parent);
- }
-
- public RestMockSimpleEntity(@SuppressWarnings("rawtypes") Map flags, Entity parent) {
- super(flags, parent);
- }
-
- public RestMockSimpleEntity(@SuppressWarnings("rawtypes") Map flags) {
- super(flags);
- }
-
- @Override
- protected void connectSensors() {
- super.connectSensors();
- connectServiceUpIsRunning();
- }
-
- @SetFromFlag("sampleConfig")
- public static final ConfigKey<String> SAMPLE_CONFIG = new BasicConfigKey<String>(
- String.class, "brooklyn.rest.mock.sample.config", "Mock sample config", "DEFAULT_VALUE");
-
- public static final AttributeSensor<String> SAMPLE_SENSOR = new BasicAttributeSensor<String>(
- String.class, "brooklyn.rest.mock.sample.sensor", "Mock sample sensor");
-
- public static final MethodEffector<String> SAMPLE_EFFECTOR = new MethodEffector<String>(RestMockSimpleEntity.class, "sampleEffector");
-
- @Effector
- public String sampleEffector(@EffectorParam(name="param1", description="param one") String param1,
- @EffectorParam(name="param2") Integer param2) {
- log.info("Invoked sampleEffector("+param1+","+param2+")");
- String result = ""+param1+param2;
- sensors().set(SAMPLE_SENSOR, result);
- return result;
- }
-
- @SuppressWarnings("rawtypes")
- @Override
- public Class getDriverInterface() {
- return MockSshDriver.class;
- }
-
- public static class MockSshDriver extends AbstractSoftwareProcessSshDriver {
- public MockSshDriver(EntityLocal entity, SshMachineLocation machine) {
- super(entity, machine);
- }
- public boolean isRunning() { return true; }
- public void stop() {}
- public void kill() {}
- public void install() {}
- public void customize() {}
- public void launch() {}
- public void setup() { }
- public void copyInstallResources() { }
- public void copyRuntimeResources() { }
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimplePolicy.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimplePolicy.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimplePolicy.java
deleted file mode 100644
index e15cdd1..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/testing/mocks/RestMockSimplePolicy.java
+++ /dev/null
@@ -1,64 +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.testing.mocks;
-
-import java.util.Map;
-
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.BasicConfigKey;
-import org.apache.brooklyn.core.policy.AbstractPolicy;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class RestMockSimplePolicy extends AbstractPolicy {
-
- @SuppressWarnings("unused")
- private static final Logger log = LoggerFactory.getLogger(RestMockSimplePolicy.class);
-
- public RestMockSimplePolicy() {
- super();
- }
-
- @SuppressWarnings("rawtypes")
- public RestMockSimplePolicy(Map flags) {
- super(flags);
- }
-
- @SetFromFlag("sampleConfig")
- public static final ConfigKey<String> SAMPLE_CONFIG = BasicConfigKey.builder(String.class)
- .name("brooklyn.rest.mock.sample.config")
- .description("Mock sample config")
- .defaultValue("DEFAULT_VALUE")
- .reconfigurable(true)
- .build();
-
- @SetFromFlag
- public static final ConfigKey<Integer> INTEGER_CONFIG = BasicConfigKey.builder(Integer.class)
- .name("brooklyn.rest.mock.sample.integer")
- .description("Mock integer config")
- .defaultValue(1)
- .reconfigurable(true)
- .build();
-
- @Override
- protected <T> void doReconfigureConfig(ConfigKey<T> key, T val) {
- // no-op
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/3be4fe11/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/BrooklynRestResourceUtilsTest.java
----------------------------------------------------------------------
diff --git a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/BrooklynRestResourceUtilsTest.java b/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/BrooklynRestResourceUtilsTest.java
deleted file mode 100644
index 48908e3..0000000
--- a/rest/rest-server-jersey/src/test/java/org/apache/brooklyn/rest/util/BrooklynRestResourceUtilsTest.java
+++ /dev/null
@@ -1,213 +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.util;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.catalog.Catalog;
-import org.apache.brooklyn.api.entity.Application;
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.policy.Policy;
-import org.apache.brooklyn.core.catalog.internal.CatalogItemBuilder;
-import org.apache.brooklyn.core.catalog.internal.CatalogTemplateItemDto;
-import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
-import org.apache.brooklyn.core.entity.AbstractApplication;
-import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
-import org.apache.brooklyn.core.objs.proxy.EntityProxy;
-import org.apache.brooklyn.core.policy.AbstractPolicy;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.entity.stock.BasicEntity;
-import org.apache.brooklyn.rest.domain.ApplicationSpec;
-import org.apache.brooklyn.rest.domain.EntitySpec;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Iterables;
-
-public class BrooklynRestResourceUtilsTest {
-
- private LocalManagementContext managementContext;
- private BrooklynRestResourceUtils util;
-
- @BeforeMethod(alwaysRun=true)
- public void setUp() throws Exception {
- managementContext = LocalManagementContextForTests.newInstance();
- util = new BrooklynRestResourceUtils(managementContext);
- }
-
- @AfterMethod(alwaysRun=true)
- public void tearDown() throws Exception {
- if (managementContext != null) managementContext.terminate();
- }
-
- @Test
- public void testCreateAppFromImplClass() {
- ApplicationSpec spec = ApplicationSpec.builder()
- .name("myname")
- .type(SampleNoOpApplication.class.getName())
- .locations(ImmutableSet.of("localhost"))
- .build();
- Application app = util.create(spec);
-
- assertEquals(ImmutableList.copyOf(managementContext.getApplications()), ImmutableList.of(app));
- assertEquals(app.getDisplayName(), "myname");
- assertTrue(app instanceof EntityProxy);
- assertTrue(app instanceof MyInterface);
- assertFalse(app instanceof SampleNoOpApplication);
- }
-
- @Test
- public void testCreateAppFromCatalogByType() {
- createAppFromCatalog(SampleNoOpApplication.class.getName());
- }
-
- @Test
- public void testCreateAppFromCatalogByName() {
- createAppFromCatalog("app.noop");
- }
-
- @Test
- public void testCreateAppFromCatalogById() {
- createAppFromCatalog("app.noop:0.0.1");
- }
-
- @Test
- @SuppressWarnings("deprecation")
- public void testCreateAppFromCatalogByTypeMultipleItems() {
- CatalogTemplateItemDto item = CatalogItemBuilder.newTemplate("app.noop", "0.0.2-SNAPSHOT")
- .javaType(SampleNoOpApplication.class.getName())
- .build();
- managementContext.getCatalog().addItem(item);
- createAppFromCatalog(SampleNoOpApplication.class.getName());
- }
-
- @SuppressWarnings("deprecation")
- private void createAppFromCatalog(String type) {
- CatalogTemplateItemDto item = CatalogItemBuilder.newTemplate("app.noop", "0.0.1")
- .javaType(SampleNoOpApplication.class.getName())
- .build();
- managementContext.getCatalog().addItem(item);
-
- ApplicationSpec spec = ApplicationSpec.builder()
- .name("myname")
- .type(type)
- .locations(ImmutableSet.of("localhost"))
- .build();
- Application app = util.create(spec);
-
- assertEquals(app.getCatalogItemId(), "app.noop:0.0.1");
- }
-
- @Test
- public void testEntityAppFromCatalogByType() {
- createEntityFromCatalog(BasicEntity.class.getName());
- }
-
- @Test
- public void testEntityAppFromCatalogByName() {
- createEntityFromCatalog("app.basic");
- }
-
- @Test
- public void testEntityAppFromCatalogById() {
- createEntityFromCatalog("app.basic:0.0.1");
- }
-
- @Test
- @SuppressWarnings("deprecation")
- public void testEntityAppFromCatalogByTypeMultipleItems() {
- CatalogTemplateItemDto item = CatalogItemBuilder.newTemplate("app.basic", "0.0.2-SNAPSHOT")
- .javaType(SampleNoOpApplication.class.getName())
- .build();
- managementContext.getCatalog().addItem(item);
- createEntityFromCatalog(BasicEntity.class.getName());
- }
-
- @SuppressWarnings("deprecation")
- private void createEntityFromCatalog(String type) {
- String symbolicName = "app.basic";
- String version = "0.0.1";
- CatalogTemplateItemDto item = CatalogItemBuilder.newTemplate(symbolicName, version)
- .javaType(BasicEntity.class.getName())
- .build();
- managementContext.getCatalog().addItem(item);
-
- ApplicationSpec spec = ApplicationSpec.builder()
- .name("myname")
- .entities(ImmutableSet.of(new EntitySpec(type)))
- .locations(ImmutableSet.of("localhost"))
- .build();
- Application app = util.create(spec);
-
- Entity entity = Iterables.getOnlyElement(app.getChildren());
- assertEquals(entity.getCatalogItemId(), CatalogUtils.getVersionedId(symbolicName, version));
- }
-
- @Test
- public void testNestedApplications() {
- // hierarchy is: app -> subapp -> subentity (where subentity has a policy)
-
- Application app = managementContext.getEntityManager().createEntity(org.apache.brooklyn.api.entity.EntitySpec.create(TestApplication.class)
- .displayName("app")
- .child(org.apache.brooklyn.api.entity.EntitySpec.create(TestApplication.class)
- .displayName("subapp")
- .child(org.apache.brooklyn.api.entity.EntitySpec.create(TestEntity.class)
- .displayName("subentity")
- .policy(org.apache.brooklyn.api.policy.PolicySpec.create(MyPolicy.class)
- .displayName("mypolicy")))));
-
- Application subapp = (Application) Iterables.getOnlyElement(app.getChildren());
- TestEntity subentity = (TestEntity) Iterables.getOnlyElement(subapp.getChildren());
-
- Entity subappRetrieved = util.getEntity(app.getId(), subapp.getId());
- assertEquals(subappRetrieved.getDisplayName(), "subapp");
-
- Entity subentityRetrieved = util.getEntity(app.getId(), subentity.getId());
- assertEquals(subentityRetrieved.getDisplayName(), "subentity");
-
- Policy subappPolicy = util.getPolicy(app.getId(), subentity.getId(), "mypolicy");
- assertEquals(subappPolicy.getDisplayName(), "mypolicy");
- }
-
- public interface MyInterface {
- }
-
- @Catalog(name="Sample No-Op Application",
- description="Application which does nothing, included only as part of the test cases.",
- iconUrl="")
- public static class SampleNoOpApplication extends AbstractApplication implements MyInterface {
- }
-
- public static class MyPolicy extends AbstractPolicy {
- public MyPolicy() {
- }
- public MyPolicy(Map<String, ?> flags) {
- super(flags);
- }
- }
-}