org.apache.tomcat.util.descriptor.web.ContextEnvironment Java Examples

The following examples show how to use org.apache.tomcat.util.descriptor.web.ContextEnvironment. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NamingResourcesMBean.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Return the MBean Names of the set of defined environment entries for
 * this web application
 * @return an array of object names as strings
 */
public String[] getEnvironments() {
    ContextEnvironment[] envs = ((NamingResourcesImpl)this.resource).findEnvironments();
    ArrayList<String> results = new ArrayList<>();
    for (int i = 0; i < envs.length; i++) {
        try {
            ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), envs[i]);
            results.add(oname.toString());
        } catch (MalformedObjectNameException e) {
            IllegalArgumentException iae = new IllegalArgumentException (
                    "Cannot create object name for environment " + envs[i]);
            iae.initCause(e);
            throw iae;
        }
    }
    return results.toArray(new String[results.size()]);
}
 
Example #2
Source File: MBeanUtils.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Create, register, and return an MBean for this
 * <code>ContextEnvironment</code> object.
 *
 * @param environment The ContextEnvironment to be managed
 * @return a new MBean
 * @exception Exception if an MBean cannot be created or registered
 */
public static DynamicMBean createMBean(ContextEnvironment environment)
    throws Exception {

    String mname = createManagedName(environment);
    ManagedBean managed = registry.findManagedBean(mname);
    if (managed == null) {
        Exception e = new Exception("ManagedBean is not found with "+mname);
        throw new MBeanException(e);
    }
    String domain = managed.getDomain();
    if (domain == null)
        domain = mserver.getDefaultDomain();
    DynamicMBean mbean = managed.createMBean(environment);
    ObjectName oname = createObjectName(domain, environment);
    if( mserver.isRegistered( oname ))  {
        mserver.unregisterMBean(oname);
    }
    mserver.registerMBean(mbean, oname);
    return mbean;

}
 
Example #3
Source File: MBeanUtils.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Deregister the MBean for this
 * <code>ContextEnvironment</code> object.
 *
 * @param environment The ContextEnvironment to be managed
 *
 * @exception Exception if an MBean cannot be deregistered
 */
public static void destroyMBean(ContextEnvironment environment)
    throws Exception {

    String mname = createManagedName(environment);
    ManagedBean managed = registry.findManagedBean(mname);
    if (managed == null) {
        return;
    }
    String domain = managed.getDomain();
    if (domain == null)
        domain = mserver.getDefaultDomain();
    ObjectName oname = createObjectName(domain, environment);
    if( mserver.isRegistered(oname) )
        mserver.unregisterMBean(oname);

}
 
Example #4
Source File: TestNamingContext.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testBug53465() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    tomcat.enableNaming();

    File appDir =
        new File("test/webapp");
    // app dir is relative to server home
    org.apache.catalina.Context ctxt =
            tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() +
            "/test/bug5nnnn/bug53465.jsp", bc, null);

    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertTrue(bc.toString().contains("<p>10</p>"));

    ContextEnvironment ce =
            ctxt.getNamingResources().findEnvironment("bug53465");
    Assert.assertEquals("Bug53465MappedName", ce.getProperty("mappedName"));
}
 
Example #5
Source File: NamingResourcesImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Remove any environment entry with the specified name.
 *
 * @param name Name of the environment entry to remove
 */
@Override
public void removeEnvironment(String name) {

    entries.remove(name);

    ContextEnvironment environment = null;
    synchronized (envs) {
        environment = envs.remove(name);
    }
    if (environment != null) {
        support.firePropertyChange("environment", environment, null);
        // De-register with JMX
        if (resourceRequireExplicitRegistration) {
            try {
                MBeanUtils.destroyMBean(environment);
            } catch (Exception e) {
                log.warn(sm.getString("namingResources.mbeanDestroyFail",
                        environment.getName()), e);
            }
        }
        environment.setNamingResources(null);
    }
}
 
Example #6
Source File: TestTomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testEnableNaming() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Enable JNDI - it is disabled by default
    tomcat.enableNaming();

    ContextEnvironment environment = new ContextEnvironment();
    environment.setType("java.lang.String");
    environment.setName(HelloWorldJndi.JNDI_ENV_NAME);
    environment.setValue("Tomcat User");
    ctx.getNamingResources().addEnvironment(environment);

    Tomcat.addServlet(ctx, "jndiServlet", new HelloWorldJndi());
    ctx.addServletMappingDecoded("/", "jndiServlet");

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    Assert.assertEquals("Hello, Tomcat User", res.toString());
}
 
Example #7
Source File: TestNamingContextListener.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testBug49132() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Enable JNDI - it is disabled by default
    tomcat.enableNaming();

    ContextEnvironment environment = new ContextEnvironment();
    environment.setType(BUG49132_VALUE.getClass().getName());
    environment.setName(BUG49132_NAME);
    environment.setValue(BUG49132_VALUE);
    ctx.getNamingResources().addEnvironment(environment);

    ctx.addApplicationListener(Bug49132Listener.class.getName());

    tomcat.start();

    Assert.assertEquals(LifecycleState.STARTED, ctx.getState());
}
 
Example #8
Source File: NamingResourcesMBean.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Remove any environment entry with the specified name.
 *
 * @param envName Name of the environment entry to remove
 */
public void removeEnvironment(String envName) {
    NamingResourcesImpl nresources = (NamingResourcesImpl) this.resource;
    if (nresources == null) {
        return;
    }
    ContextEnvironment env = nresources.findEnvironment(envName);
    if (env == null) {
        throw new IllegalArgumentException("Invalid environment name '" + envName + "'");
    }
    nresources.removeEnvironment(envName);
}
 
Example #9
Source File: OpenEJBNamingContextListener.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void processInitialNamingResources() {
    // Resource links
    final ContextResourceLink[] resourceLinks = namingResources.findResourceLinks();
    for (final ContextResourceLink resourceLink : resourceLinks) {
        addResourceLink(resourceLink);
    }

    // Resources
    final ContextResource[] resources = namingResources.findResources();
    for (final ContextResource resource : resources) {
        addResource(resource);
    }

    // Resources Env
    final ContextResourceEnvRef[] resourceEnvRefs = namingResources.findResourceEnvRefs();
    for (final ContextResourceEnvRef resourceEnvRef : resourceEnvRefs) {
        addResourceEnvRef(resourceEnvRef);
    }

    // Environment entries
    final ContextEnvironment[] contextEnvironments = namingResources.findEnvironments();
    for (final ContextEnvironment contextEnvironment : contextEnvironments) {
        addEnvironment(contextEnvironment);
    }

    // EJB references
    final ContextEjb[] ejbs = namingResources.findEjbs();
    for (final ContextEjb ejb : ejbs) {
        addEjb(ejb);
    }
}
 
Example #10
Source File: HeartbeatTest.java    From TeaStore with Apache License 2.0 5 votes vote down vote up
private Tomcat createClientTomcat(Service service, Tomcat tomcat) throws ServletException, LifecycleException {
		int clientPort = getNextClientPort();
		tomcat.getEngine().setName("Catalina" + clientPort);
		tomcat.setPort(clientPort);
		tomcat.setBaseDir(testWorkingDir);
		tomcat.enableNaming();
		Context context = tomcat.addWebapp("/" + service.getServiceName(), testWorkingDir);
		ContextEnvironment registryURL = new ContextEnvironment();
		registryURL.setDescription("");
		registryURL.setOverride(false);
		registryURL.setType("java.lang.String");
		registryURL.setName("registryURL");
		registryURL.setValue("http://localhost:" + getRegistryPort() + "/test/rest/services/");
		context.getNamingResources().addEnvironment(registryURL);
		ContextEnvironment servicePort = new ContextEnvironment();
		servicePort.setDescription("");
		servicePort.setOverride(false);
		servicePort.setType("java.lang.String");
	    servicePort.setName("servicePort");
	    servicePort.setValue("" + clientPort);
		context.getNamingResources().addEnvironment(servicePort);		
		context.addApplicationListener(TestRegistryClientStartup.class.getName());
//		HeartbeatServlet heartbeatServlet = new HeartbeatServlet();
//		tomcat.addServlet("/" + service.getServiceName(), "heartbeatServlet", heartbeatServlet);
//		context.addServletMappingDecoded("/heartbeat", "heartbeatServlet");
		tomcat.start();
		return tomcat;
	}
 
Example #11
Source File: ExternalizedConfigurationWebApplicationBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 5 votes vote down vote up
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> webServerFactoryCustomizer() {
    return factory ->
            factory.addContextCustomizers(
                    context -> {
                        // 设置 JNDI 信息
                        ContextEnvironment environment = new ContextEnvironment();
                        environment.setName("jndi-name");
                        environment.setValue("My JNDI");
                        environment.setType(String.class.getName());
                        // 配置 Environment,等同于 <Environment/> 元素
                        context.getNamingResources().addEnvironment(environment);
                    }
            );
}
 
Example #12
Source File: TestNamingContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testBug52830() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    tomcat.enableNaming();

    // No file system docBase required
    org.apache.catalina.Context ctx = tomcat.addContext("", null);

    // Create the resource
    ContextEnvironment env = new ContextEnvironment();
    env.setName("boolean");
    env.setType(Boolean.class.getName());
    env.setValue("true");
    ctx.getNamingResources().addEnvironment(env);

    // Map the test Servlet
    Bug52830Servlet bug52830Servlet = new Bug52830Servlet();
    Tomcat.addServlet(ctx, "bug52830Servlet", bug52830Servlet);
    ctx.addServletMappingDecoded("/", "bug52830Servlet");

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/", bc, null);
    Assert.assertEquals(200, rc);
    Assert.assertTrue(bc.toString().contains("truetrue"));
}
 
Example #13
Source File: TestNamingContextListener.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testBug54096() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Enable JNDI - it is disabled by default
    tomcat.enableNaming();

    ContextEnvironment environmentA = new ContextEnvironment();
    environmentA.setType(Bug54096EnvA.class.getName());
    environmentA.setName(BUG54096_NameA);
    environmentA.setValue(BUG54096_ValueA);
    ctx.getNamingResources().addEnvironment(environmentA);

    ContextEnvironment environmentB = new ContextEnvironment();
    environmentB.setType(Bug54096EnvB.class.getName());
    environmentB.setName(BUG54096_NameB);
    environmentB.setValue(BUG54096_ValueB);
    ctx.getNamingResources().addEnvironment(environmentB);

    ctx.addApplicationListener(Bug54096Listener.class.getName());

    tomcat.start();

    Assert.assertEquals(LifecycleState.STARTED, ctx.getState());
}
 
Example #14
Source File: TestTomcat.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testEnableNamingGlobal() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Enable JNDI - it is disabled by default
    tomcat.enableNaming();

    ContextEnvironment environment = new ContextEnvironment();
    environment.setType("java.lang.String");
    environment.setName("globalTest");
    environment.setValue("Tomcat User");
    tomcat.getServer().getGlobalNamingResources().addEnvironment(environment);

    ContextResourceLink link = new ContextResourceLink();
    link.setGlobal("globalTest");
    link.setName(HelloWorldJndi.JNDI_ENV_NAME);
    link.setType("java.lang.String");
    ctx.getNamingResources().addResourceLink(link);

    Tomcat.addServlet(ctx, "jndiServlet", new HelloWorldJndi());
    ctx.addServletMappingDecoded("/", "jndiServlet");

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    Assert.assertEquals("Hello, Tomcat User", res.toString());
}
 
Example #15
Source File: NamingResourcesSF.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Store the specified NamingResources properties.
 *
 * @param aWriter
 *            PrintWriter to which we are storing
 * @param indent
 *            Number of spaces to indent this element
 * @param aElement
 *            Object whose properties are being stored
 * @param elementDesc
 *            element descriptor
 *
 * @exception Exception
 *                if an exception occurs while storing
 *
 * @see org.apache.catalina.storeconfig.StoreFactoryBase#storeChildren(java.io.PrintWriter,
 *      int, java.lang.Object, StoreDescription)
 */
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aElement,
        StoreDescription elementDesc) throws Exception {

    if (aElement instanceof NamingResourcesImpl) {
        NamingResourcesImpl resources = (NamingResourcesImpl) aElement;
        // Store nested <Ejb> elements
        ContextEjb[] ejbs = resources.findEjbs();
        storeElementArray(aWriter, indent, ejbs);
        // Store nested <Environment> elements
        ContextEnvironment[] envs = resources.findEnvironments();
        storeElementArray(aWriter, indent, envs);
        // Store nested <LocalEjb> elements
        ContextLocalEjb[] lejbs = resources.findLocalEjbs();
        storeElementArray(aWriter, indent, lejbs);

        // Store nested <Resource> elements
        ContextResource[] dresources = resources.findResources();
        storeElementArray(aWriter, indent, dresources);

        // Store nested <ResourceEnvRef> elements
        ContextResourceEnvRef[] resEnv = resources.findResourceEnvRefs();
        storeElementArray(aWriter, indent, resEnv);

        // Store nested <ResourceLink> elements
        ContextResourceLink[] resourceLinks = resources.findResourceLinks();
        storeElementArray(aWriter, indent, resourceLinks);
    }
}
 
Example #16
Source File: NamingResourcesImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * @return the set of defined environment entries for this web
 * application.  If none have been defined, a zero-length array
 * is returned.
 */
public ContextEnvironment[] findEnvironments() {

    synchronized (envs) {
        ContextEnvironment results[] = new ContextEnvironment[envs.size()];
        return envs.values().toArray(results);
    }

}
 
Example #17
Source File: NamingResourcesImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * @return the environment entry with the specified name, if any;
 * otherwise, return <code>null</code>.
 *
 * @param name Name of the desired environment entry
 */
public ContextEnvironment findEnvironment(String name) {

    synchronized (envs) {
        return envs.get(name);
    }

}
 
Example #18
Source File: ContextEnvironmentMBean.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Set the value of a specific attribute of this MBean.
 *
 * @param attribute The identification of the attribute to be set
 *  and the new value
 *
 * @exception AttributeNotFoundException if this attribute is not
 *  supported by this MBean
 * @exception MBeanException if the initializer of an object
 *  throws an exception
 * @exception ReflectionException if a Java reflection exception
 *  occurs when invoking the getter
 */
 @Override
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException,
        ReflectionException {

    super.setAttribute(attribute);

    ContextEnvironment ce = doGetManagedResource();

    // cannot use side-effects.  It's removed and added back each time
    // there is a modification in a resource.
    NamingResources nr = ce.getNamingResources();
    nr.removeEnvironment(ce.getName());
    nr.addEnvironment(ce);
}
 
Example #19
Source File: TestNamingContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testGlobalNaming() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    tomcat.enableNaming();

    org.apache.catalina.Context ctx = tomcat.addContext("", null);

    tomcat.start();

    Context webappInitial = ContextBindings.getContext(ctx);

    // Nothing added at the moment so should be null
    Object obj = doLookup(webappInitial, COMP_ENV + "/" + LOCAL_NAME);
    Assert.assertNull(obj);

    ContextEnvironment ce = new ContextEnvironment();
    ce.setName(GLOBAL_NAME);
    ce.setValue(DATA);
    ce.setType(DATA.getClass().getName());

    tomcat.getServer().getGlobalNamingResources().addEnvironment(ce);

    // No link so still should be null
    obj = doLookup(webappInitial, COMP_ENV + "/" + LOCAL_NAME);
    Assert.assertNull(obj);

    // Now add a resource link to the context
    ContextResourceLink crl = new ContextResourceLink();
    crl.setGlobal(GLOBAL_NAME);
    crl.setName(LOCAL_NAME);
    crl.setType(DATA.getClass().getName());
    ctx.getNamingResources().addResourceLink(crl);

    // Link exists so should be OK now
    obj = doLookup(webappInitial, COMP_ENV + "/" + LOCAL_NAME);
    Assert.assertEquals(DATA, obj);

    // Try shortcut
    ResourceLinkFactory factory = new ResourceLinkFactory();
    ResourceLinkRef rlr = new ResourceLinkRef(DATA.getClass().getName(), GLOBAL_NAME, null, null);
    obj = factory.getObjectInstance(rlr, null, null, null);
    Assert.assertEquals(DATA, obj);

    // Remove the link
    ctx.getNamingResources().removeResourceLink(LOCAL_NAME);

    // No link so should be null
    obj = doLookup(webappInitial, COMP_ENV + "/" + LOCAL_NAME);
    Assert.assertNull(obj);

    // Shortcut should fail too
    obj = factory.getObjectInstance(rlr, null, null, null);
    Assert.assertNull(obj);
}
 
Example #20
Source File: AbstractUiTest.java    From TeaStore with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws ServletException, LifecycleException, InterruptedException, JsonProcessingException {
	webUITomcat = new Tomcat();
	webUITomcat.setPort(3000);
	webUITomcat.setBaseDir(testWorkingDir);
	webUITomcat.enableNaming();
	Context context = webUITomcat.addWebapp(CONTEXT, System.getProperty("user.dir") + File.separator + "src"
			+ File.separator + "main" + File.separator + "webapp");
	ContextEnvironment registryURL = new ContextEnvironment();
	registryURL.setDescription("");
	registryURL.setOverride(false);
	registryURL.setType("java.lang.String");
	registryURL.setName("registryURL");
	registryURL.setValue("http://localhost:9001/tools.descartes.teastore.registry/rest/services/");
	context.getNamingResources().addEnvironment(registryURL);
	webUITomcat.addServlet(CONTEXT, "servlet", getServlet());
	webUITomcat.addServlet(CONTEXT, "index", new IndexServlet());
	webUITomcat.addServlet(CONTEXT, "login", new LoginServlet());
	webUITomcat.addServlet(CONTEXT, "order", new OrderServlet());
	context.addServletMappingDecoded("/test", "servlet");
	context.addServletMappingDecoded("/index", "index");
	context.addServletMappingDecoded("/login", "login");
	context.addServletMappingDecoded("/order", "order");
	context.addWelcomeFile("/index");
	webUITomcat.start();

	// Mock registry
	List<String> strings = new LinkedList<String>();
	strings.add("localhost:9001");
	String json = new ObjectMapper().writeValueAsString(strings);
	wireMockRule.stubFor(get(urlEqualTo(
			"/tools.descartes.teastore.registry/rest/services/" + Service.IMAGE.getServiceName() + "/"))
					.willReturn(okJson(json)));
	wireMockRule.stubFor(get(urlEqualTo(
			"/tools.descartes.teastore.registry/rest/services/" + Service.AUTH.getServiceName() + "/"))
					.willReturn(okJson(json)));
	wireMockRule.stubFor(get(urlEqualTo(
			"/tools.descartes.teastore.registry/rest/services/" + Service.PERSISTENCE.getServiceName() + "/"))
					.willReturn(okJson(json)));
	wireMockRule.stubFor(get(urlEqualTo(
			"/tools.descartes.teastore.registry/rest/services/" + Service.RECOMMENDER.getServiceName() + "/"))
					.willReturn(okJson(json)));

	// Mock images
	HashMap<String, String> img = new HashMap<>();
	img.put("andreBauer", "andreBauer");
	img.put("johannesGrohmann", "johannesGrohmann");
	img.put("joakimKistowski", "joakimKistowski");
	img.put("simonEismann", "simonEismann");
	img.put("norbertSchmitt", "norbertSchmitt");
	img.put("descartesLogo", "descartesLogo");
	img.put("icon", "icon");
	mockValidPostRestCall(img, "/tools.descartes.teastore.image/rest/image/getWebImages");
}
 
Example #21
Source File: AbstractRecommenderRestTest.java    From TeaStore with Apache License 2.0 4 votes vote down vote up
/**
 * Sets up a registry, a persistance unit and a store.
 * 
 * @throws Throwable
 *             Throws uncaught throwables for test to fail.
 */
@Before
public void setup() throws Throwable {
	persistence = new MockPersistenceProvider(persistenceWireMockRule);

	otherrecommender = new MockOtherRecommenderProvider(otherRecommenderWireMockRule);

	setRegistry(new MockRegistry(registryWireMockRule, Arrays.asList(getPersistence().getPort()),
			Arrays.asList(RECOMMENDER_TEST_PORT, otherrecommender.getPort())));

	// debuggging response
	// Response response1 = ClientBuilder
	// .newBuilder().build().target("http://localhost:" + otherrecommender.getPort()
	// + "/"
	// + Service.RECOMMENDER.getServiceName() + "/rest/train/timestamp")
	// .request(MediaType.APPLICATION_JSON).get();
	// System.out.println(response1.getStatus() + ":" +
	// response1.readEntity(String.class));

	// debuggging response
	// Response response0 = ClientBuilder.newBuilder().build()
	// .target("http://localhost:" + MockRegistry.DEFAULT_MOCK_REGISTRY_PORT
	// + "/tools.descartes.teastore.registry/rest/services/"
	// + Service.PERSISTENCE.getServiceName() + "/")
	// .request(MediaType.APPLICATION_JSON).get();
	// System.out.println(response0.getStatus() + ":" +
	// response0.readEntity(String.class));
	//
	// Response response1 = ClientBuilder.newBuilder().build()
	// .target("http://localhost:" + persistence.getPort()
	// + "/tools.descartes.teastore.persistence/rest/orderitems")
	// .request(MediaType.APPLICATION_JSON).get();
	// System.out.println(response1.getStatus() + ":" +
	// response1.readEntity(String.class));

	// Setup recommend tomcat
	testTomcat = new Tomcat();
	testTomcat.setPort(RECOMMENDER_TEST_PORT);
	testTomcat.setBaseDir(testWorkingDir);
	testTomcat.enableNaming();
	Context context = testTomcat.addWebapp("/" + Service.RECOMMENDER.getServiceName(), testWorkingDir);
	ContextEnvironment registryURL3 = new ContextEnvironment();
	registryURL3.setDescription("");
	registryURL3.setOverride(false);
	registryURL3.setType("java.lang.String");
	registryURL3.setName("registryURL");
	registryURL3.setValue(
			"http://localhost:" + registry.getPort() + "/tools.descartes.teastore.registry/rest/services/");
	context.getNamingResources().addEnvironment(registryURL3);
	ContextEnvironment servicePort3 = new ContextEnvironment();
	servicePort3.setDescription("");
	servicePort3.setOverride(false);
	servicePort3.setType("java.lang.String");
	servicePort3.setName("servicePort");
	servicePort3.setValue("" + RECOMMENDER_TEST_PORT);
	context.getNamingResources().addEnvironment(servicePort3);
	ResourceConfig restServletConfig3 = new ResourceConfig();
	restServletConfig3.register(TrainEndpoint.class);
	restServletConfig3.register(RecommendEndpoint.class);
	restServletConfig3.register(RecommendSingleEndpoint.class);
	ServletContainer restServlet3 = new ServletContainer(restServletConfig3);
	testTomcat.addServlet("/" + Service.RECOMMENDER.getServiceName(), "restServlet", restServlet3);
	context.addServletMappingDecoded("/rest/*", "restServlet");
	context.addApplicationListener(RecommenderStartup.class.getName());

	ContextEnvironment recommender = new ContextEnvironment();
	recommender.setDescription("");
	recommender.setOverride(false);
	recommender.setType("java.lang.String");
	recommender.setName("recommenderAlgorithm");
	recommender.setValue("PreprocessedSlopeOne");
	context.getNamingResources().addEnvironment(recommender);

	ContextEnvironment retrainlooptime = new ContextEnvironment();
	retrainlooptime.setDescription("");
	retrainlooptime.setOverride(false);
	retrainlooptime.setType("java.lang.Long");
	retrainlooptime.setName("recommenderLoopTime");
	retrainlooptime.setValue("100");
	context.getNamingResources().addEnvironment(retrainlooptime);

	testTomcat.start();

	try {
		Thread.sleep(5000);
	} catch (InterruptedException e) {
	}
}
 
Example #22
Source File: TomcatTestHandler.java    From TeaStore with Apache License 2.0 4 votes vote down vote up
/**
 * Create a Tomcat test handler for persistence testing.
 * @param count Number of testing tomcats.
 * @param startPort Port to start with (do not use 0 for auto-assigning).
 * @param wireMockRule Wire mock rule for mocking the registry.The test handler will
 * add all services with respective stubs to the rule.
 * @param endpoints Class objects for the endpoints.
 * @throws ServletException Exception on failure.
 * @throws LifecycleException Exception on failure.
 * @throws JsonProcessingException Exception on failure.
 */
public TomcatTestHandler(int count, int startPort, WireMockRule wireMockRule, Class<?>... endpoints)
		throws ServletException, LifecycleException, JsonProcessingException {
	tomcats = new Tomcat[count];
	EMFManagerInitializer.initializeEMF();
	for (int i = 0; i < count; i++) {
		tomcats[i] = new Tomcat();
		tomcats[i].setPort(startPort + i);
		tomcats[i].setBaseDir(testWorkingDir);
		Context context = tomcats[i].addWebapp(CONTEXT, testWorkingDir);
		//Registry
		if (wireMockRule != null) {
			ContextEnvironment registryURL = new ContextEnvironment();
			registryURL.setDescription("");
			registryURL.setOverride(false);
			registryURL.setType("java.lang.String");
			registryURL.setName("registryURL");
			registryURL.setValue("http://localhost:" + wireMockRule.port()
			+ "/tools.descartes.teastore.registry/rest/services/");
			context.getNamingResources().addEnvironment(registryURL);
			ContextEnvironment servicePort = new ContextEnvironment();
			servicePort.setDescription("");
			servicePort.setOverride(false);
			servicePort.setType("java.lang.String");
		    servicePort.setName("servicePort");
		    servicePort.setValue("" + startPort + i);
			context.getNamingResources().addEnvironment(servicePort);
			context.addApplicationListener(RegistrationDaemon.class.getName());
		}
		//REST endpoints
		ResourceConfig restServletConfig = new ResourceConfig();
		for (Class<?> endpoint: endpoints) {
			restServletConfig.register(endpoint);
		}
		ServletContainer restServlet = new ServletContainer(restServletConfig);
		tomcats[i].addServlet(CONTEXT, "restServlet", restServlet);
		context.addServletMappingDecoded("/rest/*", "restServlet");
		tomcats[i].start();
	}
	if (wireMockRule != null) {
		initializeMockRegistry(wireMockRule, count, startPort);
	}
	System.out.println("Initializing Database with size " + CategoryRepository.REPOSITORY.getAllEntities().size());
}
 
Example #23
Source File: AbstractStoreRestTest.java    From TeaStore with Apache License 2.0 4 votes vote down vote up
/**
 * Sets up a store.
 * 
 * @throws Throwable
 *           Throws uncaught throwables for test to fail.
 */
@Before
public void setup() throws Throwable {
  BasicConfigurator.configure();

  storeTomcat = new Tomcat();
  storeTomcat.setPort(3000);
  storeTomcat.setBaseDir(testWorkingDir);
  storeTomcat.enableNaming();
  ContextEnvironment registryUrl3 = new ContextEnvironment();
  registryUrl3.setDescription("");
  registryUrl3.setOverride(false);
  registryUrl3.setType("java.lang.String");
  registryUrl3.setName("registryURL");
  registryUrl3
      .setValue("http://localhost:18080/tools.descartes.teastore.registry/rest/services/");
  Context context3 = storeTomcat.addWebapp("/tools.descartes.teastore.auth", testWorkingDir);
  context3.getNamingResources().addEnvironment(registryUrl3);
  ContextEnvironment servicePort3 = new ContextEnvironment();
  servicePort3.setDescription("");
  servicePort3.setOverride(false);
  servicePort3.setType("java.lang.String");
  servicePort3.setName("servicePort");
  servicePort3.setValue("3000");
  context3.getNamingResources().addEnvironment(servicePort3);
  ResourceConfig restServletConfig3 = new ResourceConfig();
  restServletConfig3.register(AuthCartRest.class);
  restServletConfig3.register(AuthUserActionsRest.class);
  ServletContainer restServlet3 = new ServletContainer(restServletConfig3);
  storeTomcat.addServlet("/tools.descartes.teastore.auth", "restServlet", restServlet3);
  context3.addServletMappingDecoded("/rest/*", "restServlet");
  context3.addApplicationListener(EmptyAuthStartup.class.getName());

  // Mock registry
  List<String> strings = new LinkedList<String>();
  strings.add("localhost:18080");
  String json = new ObjectMapper().writeValueAsString(strings);
  List<String> strings2 = new LinkedList<String>();
  strings2.add("localhost:3000");
  String json2 = new ObjectMapper().writeValueAsString(strings2);
  wireMockRule.stubFor(get(urlEqualTo(
      "/tools.descartes.teastore.registry/rest/services/" + Service.IMAGE.getServiceName() + "/"))
          .willReturn(okJson(json)));
  wireMockRule.stubFor(get(urlEqualTo(
      "/tools.descartes.teastore.registry/rest/services/" + Service.AUTH.getServiceName() + "/"))
          .willReturn(okJson(json2)));
  wireMockRule.stubFor(
      WireMock.put(WireMock.urlMatching("/tools.descartes.teastore.registry/rest/services/"
          + Service.AUTH.getServiceName() + "/.*")).willReturn(okJson(json2)));
  wireMockRule.stubFor(
      WireMock.delete(WireMock.urlMatching("/tools.descartes.teastore.registry/rest/services/"
          + Service.AUTH.getServiceName() + "/.*")).willReturn(okJson(json2)));
  wireMockRule.stubFor(get(urlEqualTo("/tools.descartes.teastore.registry/rest/services/"
      + Service.PERSISTENCE.getServiceName() + "/")).willReturn(okJson(json)));
  wireMockRule.stubFor(get(urlEqualTo("/tools.descartes.teastore.registry/rest/services/"
      + Service.RECOMMENDER.getServiceName() + "/")).willReturn(okJson(json)));

  // Mock images
  HashMap<String, String> img = new HashMap<>();
  img.put("andreBauer", "andreBauer");
  img.put("johannesGrohmann", "johannesGrohmann");
  img.put("joakimKistowski", "joakimKistowski");
  img.put("simonEismann", "simonEismann");
  img.put("norbertSchmitt", "norbertSchmitt");
  img.put("descartesLogo", "descartesLogo");
  img.put("icon", "icon");
  mockValidPostRestCall(img, "/tools.descartes.teastore.image/rest/image/getWebImages");

  storeTomcat.start();
}
 
Example #24
Source File: NamingResourcesImpl.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Add an environment entry for this web application.
 *
 * @param environment New environment entry
 */
@Override
public void addEnvironment(ContextEnvironment environment) {

    if (entries.contains(environment.getName())) {
        ContextEnvironment ce = findEnvironment(environment.getName());
        ContextResourceLink rl = findResourceLink(environment.getName());
        if (ce != null) {
            if (ce.getOverride()) {
                removeEnvironment(environment.getName());
            } else {
                return;
            }
        } else if (rl != null) {
            // Link. Need to look at the global resources
            NamingResourcesImpl global = getServer().getGlobalNamingResources();
            if (global.findEnvironment(rl.getGlobal()) != null) {
                if (global.findEnvironment(rl.getGlobal()).getOverride()) {
                    removeResourceLink(environment.getName());
                } else {
                    return;
                }
            }
        } else {
            // It exists but it isn't an env or a res link...
            return;
        }
    }

    List<InjectionTarget> injectionTargets = environment.getInjectionTargets();
    String value = environment.getValue();
    String lookupName = environment.getLookupName();

    // Entries with injection targets but no value are effectively ignored
    if (injectionTargets != null && injectionTargets.size() > 0 &&
            (value == null || value.length() == 0)) {
        return;
    }

    // Entries with lookup-name and value are an error (EE.5.4.1.3)
    if (value != null && value.length() > 0 && lookupName != null && lookupName.length() > 0) {
        throw new IllegalArgumentException(
                sm.getString("namingResources.envEntryLookupValue", environment.getName()));
    }

    if (!checkResourceType(environment)) {
        throw new IllegalArgumentException(sm.getString(
                "namingResources.resourceTypeFail", environment.getName(),
                environment.getType()));
    }

    entries.add(environment.getName());

    synchronized (envs) {
        environment.setNamingResources(this);
        envs.put(environment.getName(), environment);
    }
    support.firePropertyChange("environment", null, environment);

    // Register with JMX
    if (resourceRequireExplicitRegistration) {
        try {
            MBeanUtils.createMBean(environment);
        } catch (Exception e) {
            log.warn(sm.getString("namingResources.mbeanCreateFail",
                    environment.getName()), e);
        }
    }
}
 
Example #25
Source File: OpenEJBNamingResource.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public void addEnvironment(final ContextEnvironment environment) {
    normalize(environment);
    super.addEnvironment(environment);
}
 
Example #26
Source File: OpenEJBNamingContextListener.java    From tomee with Apache License 2.0 4 votes vote down vote up
public void addEnvironment(final ContextEnvironment env) {
    bindResource(env);
}