/*
 * Copyright The WildFly Authors
 * SPDX-License-Identifier: Apache-2.0
 */

package org.jboss.as.test.integration.messaging.jms.deployment;

import static org.jboss.as.test.shared.PermissionUtils.createPermissionsXmlAsset;
import static org.jboss.shrinkwrap.api.ShrinkWrap.create;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

import java.net.URL;
import java.util.PropertyPermission;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.as.test.integration.common.jms.JMSOperations;
import org.jboss.as.test.integration.common.jms.JMSOperationsProvider;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * Test that invoking a management operation that removes a JMS resource that is used by a deployed archive must fail:
 * the resource must not be removed and any depending services must be recovered.
 * The deployment must still be operating after the failing management operation.

 * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2014 Red Hat inc.
 */
@RunWith(Arquillian.class)
@RunAsClient
@ServerSetup(DependentMessagingDeploymentTestCase.MessagingResourcesSetupTask.class)
public class DependentMessagingDeploymentTestCase {

    public static final String QUEUE_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myQueue";
    public static final String TOPIC_LOOKUP = "java:/jms/DependentMessagingDeploymentTestCase/myTopic";

    private static final String QUEUE_NAME = "myQueue";
    private static final String TOPIC_NAME = "myTopic";

    @ContainerResource
    private ManagementClient managementClient;

    @ArquillianResource
    private URL url;

    static class MessagingResourcesSetupTask implements ServerSetupTask {

        @Override
        public void setup(ManagementClient managementClient, String containerId) throws Exception {
            JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
            jmsOperations.createJmsQueue(QUEUE_NAME, QUEUE_LOOKUP);
            jmsOperations.createJmsTopic(TOPIC_NAME, TOPIC_LOOKUP);
        }


        @Override
        public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
            JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
            jmsOperations.removeJmsQueue(QUEUE_NAME);
            jmsOperations.removeJmsTopic(TOPIC_NAME);
        }
    }

    @Deployment
    public static WebArchive createArchive() {
        return create(WebArchive.class, "DependentMessagingDeploymentTestCase.war")
                .addClasses(MessagingServlet.class, TimeoutUtil.class)
                .addClasses(QueueMDB.class, TopicMDB.class)
                .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
                .addAsManifestResource(createPermissionsXmlAsset(
                        new PropertyPermission(TimeoutUtil.FACTOR_SYS_PROP, "read")
                ), "permissions.xml");
    }

    @Test
    public void testRemoveDependingQueue() throws Exception {
        sendAndReceiveMessage(true);

        try {
            JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
            jmsOperations.removeJmsQueue(QUEUE_NAME);
            fail("removing a JMS resource that the deployment is depending upon must fail");
        } catch(Exception e) {
        }

        sendAndReceiveMessage(true);
    }

    @Test
    public void testRemoveDependingTopic() throws Exception {
        sendAndReceiveMessage(false);

        try {
            JMSOperations jmsOperations = JMSOperationsProvider.getInstance(managementClient.getControllerClient());
            jmsOperations.removeJmsTopic(TOPIC_NAME);
            fail("removing a JMS resource that the deployment is depending upon must fail");
        } catch(Exception e) {
        }
        sendAndReceiveMessage(false);
    }

    private void sendAndReceiveMessage(boolean sendToQueue) throws Exception {
        String destination = sendToQueue ? "queue" : "topic";
        String text = UUID.randomUUID().toString();
        URL servletUrl = new URL(this.url.toExternalForm() + "DependentMessagingDeploymentTestCase?destination=" + destination + "&text=" + text);
        String reply = HttpRequest.get(servletUrl.toExternalForm(), 10, TimeUnit.SECONDS);
        assertNotNull(reply);
        assertEquals(text, reply);
    }
}
