repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jsp/JspCompilerTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.jsp;
import java.net.URL;
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.test.integration.common.HttpRequest;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* test JDK8 code constructs inside JSPs
* See WFLY-2690
*/
@RunWith(Arquillian.class)
@RunAsClient
public class JspCompilerTestCase {
private static final StringAsset WEB_XML = new StringAsset(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<web-app xmlns=\"http://java.sun.com/xml/ns/javaee\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd\"\n" +
" version=\"3.1\">\n" +
"</web-app>");
@Deployment
public static WebArchive deploy() {
return ShrinkWrap.create(WebArchive.class)
.addAsWebInfResource(WEB_XML, "web.xml")
.addClasses(AnswerToEverythingComputation.class)
.addAsWebResource(JspCompilerTestCase.class.getResource("jsp-with-lambdas.jsp"), "index.jsp");
}
@Test
public void test(@ArquillianResource URL url) throws Exception {
HttpRequest.get(url + "index.jsp", TimeoutUtil.adjust(15), TimeUnit.SECONDS);
}
}
| 2,799 | 39.57971 | 133 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/jsp/JspELDisableImportedClassELResolverTestCase.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* 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.wildfly.test.integration.jsp;
import org.hamcrest.MatcherAssert;
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.test.integration.common.HttpRequest;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.hamcrest.CoreMatchers;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.test.integration.security.common.AbstractSystemPropertiesServerSetupTask;
/**
* Tests EL evaluation in JSPs
*
* @author rmartinc
*/
@RunWith(Arquillian.class)
@ServerSetup({JspELDisableImportedClassELResolverTestCase.SystemPropertiesSetup.class})
@RunAsClient
public class JspELDisableImportedClassELResolverTestCase {
/**
* Setup the system property to disable the disableImportedClassELResolver
* and act exactly as the specification says delegating in .
*/
static class SystemPropertiesSetup extends AbstractSystemPropertiesServerSetupTask {
@Override
protected SystemProperty[] getSystemProperties() {
return new SystemProperty[] {
new DefaultSystemProperty("org.wildfly.extension.undertow.deployment.disableImportedClassELResolver", "true")
};
}
}
static final String POSSIBLE_ISSUES_LINKS = "Might be caused by: https://issues.jboss.org/browse/WFLY-6939 or" +
" https://issues.jboss.org/browse/WFLY-11065 or https://issues.jboss.org/browse/WFLY-11086 or" +
" https://issues.jboss.org/browse/WFLY-12650";
@Deployment
public static WebArchive deploy() {
return ShrinkWrap.create(WebArchive.class)
.addClasses(DummyConstants.class, DummyEnum.class, DummyBean.class)
.addAsWebResource(JspELDisableImportedClassELResolverTestCase.class.getResource("jsp-with-el-static-class.jsp"), "index.jsp");
}
/**
* Test that for web application using default version of servlet spec, EL expressions that use implicitly imported
* classes from <code>java.lang</code> package are evaluated correctly, and the bean is resolved OK as per specification.
*
* @param url
* @throws Exception
*/
@Test
public void testStaticImportSameName(@ArquillianResource URL url) throws Exception {
commonTestPart(url, POSSIBLE_ISSUES_LINKS);
commonTestPart(url, POSSIBLE_ISSUES_LINKS);
}
private void commonTestPart(final URL url, final String possibleCausingIssues) throws Exception {
final String responseBody = HttpRequest.get(url + "index.jsp", 10, TimeUnit.SECONDS);
MatcherAssert.assertThat("Unexpected EL evaluation for ${Boolean.TRUE}; " + possibleCausingIssues, responseBody,
CoreMatchers.containsString("Boolean.TRUE: --- " + Boolean.TRUE + " ---"));
MatcherAssert.assertThat("Unexpected EL evaluation for ${Integer.MAX_VALUE}; " + possibleCausingIssues, responseBody,
CoreMatchers.containsString("Integer.MAX_VALUE: --- " + Integer.MAX_VALUE + " ---"));
MatcherAssert.assertThat("Unexpected EL evaluation for ${DummyConstants.FOO}; " + possibleCausingIssues, responseBody,
CoreMatchers.containsString("DummyConstants.FOO: --- " + DummyConstants.FOO + " ---"));
MatcherAssert.assertThat("Unexpected EL evaluation for ${DummyEnum.VALUE}; " + possibleCausingIssues, responseBody,
CoreMatchers.containsString("DummyEnum.VALUE: --- " + DummyEnum.VALUE + " ---"));
MatcherAssert.assertThat("Unexpected EL evaluation for ${DummyBean.test}; " + possibleCausingIssues, responseBody,
CoreMatchers.containsString("DummyBean.test: --- " + DummyBean.DEFAULT_VALUE + " ---"));
}
}
| 4,592 | 45.867347 | 142 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/asyncobserver/TestObserver.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.weld.asyncobserver;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.ObservesAsync;
import javax.naming.InitialContext;
import javax.naming.NamingException;
@ApplicationScoped
public class TestObserver {
public void recieve(@ObservesAsync TestEvent event) {
try {
InitialContext initialContext = new InitialContext();
initialContext.lookup("java:comp/TransactionSynchronizationRegistry");
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
public static class TestEvent {
}
}
| 1,649 | 34.869565 | 79 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/asyncobserver/AsyncObserverAccessCompNamespaceTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.weld.asyncobserver;
import jakarta.enterprise.event.Event;
import jakarta.inject.Inject;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class AsyncObserverAccessCompNamespaceTestCase {
@Deployment
public static Archive<?> getDeployment() {
JavaArchive lib = ShrinkWrap.create(JavaArchive.class)
.addClasses(TestObserver.class, AsyncObserverAccessCompNamespaceTestCase.class);
return lib;
}
@Inject
Event<TestObserver.TestEvent> testEvents;
@Test
public void testSendingEvent() throws Exception {
CompletableFuture<TestObserver.TestEvent> future = testEvents.fireAsync(new TestObserver.TestEvent()).toCompletableFuture();
// just a sanity check - should throw exception on future.get in case of problems
Assert.assertNotNull(future.get(500, TimeUnit.MILLISECONDS));
}
}
| 2,294 | 36.622951 | 130 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/builtinBeans/BeanWithInjectedPrincipal.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* 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.wildfly.test.integration.weld.builtinBeans;
import java.security.Principal;
import jakarta.enterprise.context.SessionScoped;
import jakarta.inject.Inject;
import java.io.Serializable;
@SessionScoped
public class BeanWithInjectedPrincipal implements Serializable {
@Inject
Principal principal;
public String getPrincipalName() {
return principal.getName();
}
}
| 997 | 27.514286 | 75 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/builtinBeans/BeanWithSecuredPrincipal.java
|
package org.wildfly.test.integration.weld.builtinBeans;
import jakarta.annotation.Resource;
import jakarta.annotation.security.RunAs;
import jakarta.ejb.EJBContext;
import jakarta.ejb.Stateless;
import org.jboss.ejb3.annotation.RunAsPrincipal;
@RunAs("Admin")
@RunAsPrincipal("non-anonymous")
@Stateless
public class BeanWithSecuredPrincipal {
@Resource
private EJBContext ctx;
public String getPrincipalName() {
return ctx.getCallerPrincipal().getName();
}
}
| 489 | 21.272727 | 55 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/builtinBeans/CallerWithIdentity.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* 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.wildfly.test.integration.weld.builtinBeans;
import jakarta.annotation.security.RunAs;
import jakarta.ejb.Stateless;
import jakarta.inject.Inject;
import org.jboss.ejb3.annotation.RunAsPrincipal;
@Stateless
@RunAs("Admin")
@RunAsPrincipal("non-anonymous")
public class CallerWithIdentity {
@Inject
BeanWithInjectedPrincipal beanA;
@Inject
BeanWithPrincipalFromEJBContext beanB;
@Inject
BeanWithSecuredPrincipal beanC;
public String getCallerPrincipalInjected() {
return beanA.getPrincipalName();
}
public String getCallerPrincipalFromEJBContext() {
return beanB.getPrincipalName();
}
public String getCallerPrincipalFromEJBContextSecuredBean() {
return beanC.getPrincipalName();
}
}
| 1,370 | 26.42 | 75 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/builtinBeans/BeanWithPrincipalFromEJBContext.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* 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.wildfly.test.integration.weld.builtinBeans;
import jakarta.ejb.Stateless;
import jakarta.ejb.EJBContext;
import jakarta.annotation.Resource;
@Stateless
public class BeanWithPrincipalFromEJBContext {
@Resource
private EJBContext ctx;
public String getPrincipalName() {
return ctx.getCallerPrincipal().getName();
}
}
| 950 | 28.71875 | 75 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/builtinBeans/InjectPrincipalTestCase.java
|
/*
* Copyright 2019 Red Hat, Inc.
*
* 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.wildfly.test.integration.weld.builtinBeans;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.security.auth.permission.ChangeRoleMapperPermission;
import org.wildfly.security.permission.ElytronPermission;
/**
* See <a href="https://issues.jboss.org/browse/WFLY-11587">WFLY-11587</a>.
*/
@RunWith(Arquillian.class)
public class InjectPrincipalTestCase {
public static final String ANONYMOUS_PRINCIPAL = "anonymous";
public static final String NON_ANONYMOUS_PRINCIPAL = "non-anonymous";
@Deployment
public static Archive<?> createTestArchive() {
return ShrinkWrap.create(WebArchive.class).addPackage(InjectPrincipalTestCase.class.getPackage())
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsWebInfResource(InjectPrincipalTestCase.class.getPackage(), "jboss-ejb3.xml", "jboss-ejb3.xml")
.addAsManifestResource(createPermissionsXmlAsset(
new ElytronPermission("getIdentity"),
new ElytronPermission("createAdHocIdentity"),
new ChangeRoleMapperPermission("ejb")
), "permissions.xml");
}
@Test
public void testAnonymousPrincipalInjected(BeanWithInjectedPrincipal beanA, BeanWithPrincipalFromEJBContext beanB) {
try {
Assert.assertEquals(ANONYMOUS_PRINCIPAL, beanA.getPrincipalName());
Assert.assertEquals(ANONYMOUS_PRINCIPAL, beanB.getPrincipalName());
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@Test
public void testNonAnonymousPrincipalInjected(CallerWithIdentity callerWithIdentity) throws Exception {
try {
// Assert.assertEquals(NON_ANONYMOUS_PRINCIPAL, callerWithIdentity.getCallerPrincipalInjected()); TODO see issue WFLY-12538
Assert.assertEquals(NON_ANONYMOUS_PRINCIPAL, callerWithIdentity.getCallerPrincipalFromEJBContext());
Assert.assertEquals(NON_ANONYMOUS_PRINCIPAL, callerWithIdentity.getCallerPrincipalFromEJBContextSecuredBean());
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
}
| 3,220 | 41.946667 | 135 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/beanarchives/TestExtension.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2017, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.weld.beanarchives;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import jakarta.enterprise.context.Dependent;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.spi.AfterBeanDiscovery;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.Extension;
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.enterprise.util.TypeLiteral;
/**
* @author Martin Kouba
*/
public class TestExtension implements Extension {
public void beforeBeanDiscovery(@Observes AfterBeanDiscovery event) {
Map<String, String> alphaMap = new HashMap<>();
alphaMap.put("foo", "bar");
event.addBean(new MapBean(alphaMap, Alpha.Literal.INSTANCE));
Map<String, String> bravoMap = new HashMap<>();
bravoMap.put("foo", "bar");
event.addBean(new MapBean(bravoMap, Bravo.Literal.INSTANCE));
}
private static class MapBean implements Bean<Map<String, String>> {
private final Map<String, String> instance;
private final Set<Annotation> qualifiers;
MapBean(Map<String, String> instance, Annotation... qualifiers) {
this.instance = instance;
this.qualifiers = new HashSet<>();
Collections.addAll(this.qualifiers, qualifiers);
}
@Override
public Map<String, String> create(CreationalContext<Map<String, String>> creationalContext) {
return instance;
}
@Override
public void destroy(Map<String, String> instance, CreationalContext<Map<String, String>> creationalContext) {
instance.clear();
}
@SuppressWarnings("serial")
@Override
public Set<Type> getTypes() {
return Collections.singleton(new TypeLiteral<Map<String, String>>() {
}.getType());
}
@Override
public Set<Annotation> getQualifiers() {
return qualifiers;
}
@Override
public Class<? extends Annotation> getScope() {
return Dependent.class;
}
@Override
public String getName() {
return null;
}
@Override
public Set<Class<? extends Annotation>> getStereotypes() {
return Collections.emptySet();
}
@Override
public boolean isAlternative() {
return false;
}
@Override
public Class<?> getBeanClass() {
return Map.class;
}
@Override
public Set<InjectionPoint> getInjectionPoints() {
return Collections.emptySet();
}
//@Override Not part of Bean interface in CDI 4
public boolean isNullable() {
return false;
}
}
}
| 4,028 | 30.724409 | 117 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/beanarchives/Bravo.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2017, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.wildfly.test.integration.weld.beanarchives;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import jakarta.enterprise.util.AnnotationLiteral;
import jakarta.inject.Qualifier;
@Qualifier
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
public @interface Bravo {
@SuppressWarnings("all")
public static class Literal extends AnnotationLiteral<Bravo> implements Bravo {
private Literal() {
}
public static final Literal INSTANCE = new Literal();
}
}
| 1,599 | 34.555556 | 83 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/beanarchives/BootstrapBeanDeploymentArchiveTestCase.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2017, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.weld.beanarchives;
import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import jakarta.enterprise.inject.spi.Extension;
import javax.naming.NamingException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* See also <a href="https://issues.jboss.org/browse/WFLY-7025">WFLY-7025</a>.
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class BootstrapBeanDeploymentArchiveTestCase {
@Deployment
public static Archive<?> createTestArchive() {
return ShrinkWrap.create(WebArchive.class).addPackage(BootstrapBeanDeploymentArchiveTestCase.class.getPackage())
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsServiceProvider(Extension.class, TestExtension.class)
.addAsManifestResource(createPermissionsXmlAsset(new RuntimePermission("accessDeclaredMembers")),"permissions.xml");
}
@Test
public void testDeployment(@Alpha Map<String, String> alphaMap, @Bravo Map<String, String> bravoMap) throws NamingException {
// Test that the deployment does not fail due to non-unique bean deployment identifiers and also the custom beans
assertEquals(alphaMap.get("foo"), bravoMap.get("foo"));
}
}
| 2,687 | 41 | 132 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/beanarchives/Alpha.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2017, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.wildfly.test.integration.weld.beanarchives;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import jakarta.enterprise.util.AnnotationLiteral;
import jakarta.inject.Qualifier;
@Qualifier
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
public @interface Alpha {
@SuppressWarnings("all")
public static class Literal extends AnnotationLiteral<Alpha> implements Alpha {
private Literal() {
}
public static final Literal INSTANCE = new Literal();
}
}
| 1,599 | 34.555556 | 83 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/resource/EnvEntryInjectionBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.weld.resource;
import jakarta.annotation.Resource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.Initialized;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Named;
@SuppressWarnings({"FieldCanBeLocal", "FieldMayBeFinal"})
@Named("envEntry")
@ApplicationScoped
public class EnvEntryInjectionBean {
@Resource(name = "unmappedEnvEntry")
private Integer unmappedEnvEntry = 1;
@Resource(name = "mappedEnvEntry")
private Integer mappedEnvEntry = 0;
@Resource()
private Integer unnamedMappedEnvEntry = 0;
private String unannotatedString = "notInjected";
private boolean unannotatedBoolean = false;
private char unannotatedChar = 'a';
private byte unannotatedByte = 0;
private short unannotatedShort = 0;
private int unannotatedInt = 0;
private long unannotatedLong = 0L;
private float unannotatedFloat = 0;
private double unannotatedDouble = 0;
private String unannotatedStringProperty = "notInjected";
private boolean unannotatedBooleanProperty = false;
private int unannotatedIntProperty = 0;
private int unannotatedIntLookup = 0;
@SuppressWarnings("unused")
public void setUnannotatedStringProperty(String unannotatedStringProperty) {
this.unannotatedStringProperty = unannotatedStringProperty;
}
@SuppressWarnings("unused")
public void setUnannotatedBooleanProperty(boolean unannotatedBooleanProperty) {
this.unannotatedBooleanProperty = unannotatedBooleanProperty;
}
@SuppressWarnings("unused")
public void setUnannotatedIntProperty(int unannotatedIntProperty) {
this.unannotatedIntProperty = unannotatedIntProperty;
}
// Force deployment-time instantiation
@SuppressWarnings("unused")
public void xxx(@Observes @Initialized(ApplicationScoped.class) Object context) {
SimpleEnvEntryResourceInjectionTestCase.setBean(this);
}
public Integer getUnmappedEnvEntry() {
return unmappedEnvEntry;
}
public Integer getMappedEnvEntry() {
return mappedEnvEntry;
}
public Integer getUnnamedMappedEnvEntry() {
return unnamedMappedEnvEntry;
}
public String getUnannotatedString() {
return unannotatedString;
}
public boolean isUnannotatedBoolean() {
return unannotatedBoolean;
}
public char getUnannotatedChar() {
return unannotatedChar;
}
public byte getUnannotatedByte() {
return unannotatedByte;
}
public short getUnannotatedShort() {
return unannotatedShort;
}
public int getUnannotatedInt() {
return unannotatedInt;
}
public long getUnannotatedLong() {
return unannotatedLong;
}
public float getUnannotatedFloat() {
return unannotatedFloat;
}
public double getUnannotatedDouble() {
return unannotatedDouble;
}
public String getUnannotatedStringProperty() {
return unannotatedStringProperty;
}
public boolean isUnannotatedBooleanProperty() {
return unannotatedBooleanProperty;
}
public int getUnannotatedIntProperty() {
return unannotatedIntProperty;
}
public int getUnannotatedIntLookup() {
return unannotatedIntLookup;
}
}
| 4,376 | 29.186207 | 85 |
java
|
null |
wildfly-main/testsuite/integration/basic/src/test/java/org/wildfly/test/integration/weld/resource/SimpleEnvEntryResourceInjectionTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.integration.weld.resource;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test of behavior of {@code SimpleEnvEntryCdiResourceInjectionProcessor}.
*/
@RunWith(Arquillian.class)
public class SimpleEnvEntryResourceInjectionTestCase {
@Deployment
public static WebArchive deploy() {
return ShrinkWrap.create(WebArchive.class, "SimpleEnvEntryResourceInjectionTestCase.war")
.addClasses(SimpleEnvEntryResourceInjectionTestCase.class, EnvEntryInjectionBean.class)
.addAsWebInfResource(SimpleEnvEntryResourceInjectionTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
private static EnvEntryInjectionBean bean;
static void setBean(EnvEntryInjectionBean initialized) {
bean = initialized;
}
EnvEntryInjectionBean getBean() {
Assert.assertNotNull(EnvEntryInjectionBean.class.getSimpleName() + " was not initialized", bean);
return bean;
}
@AfterClass
public static void afterClass() {
bean = null;
}
@Test
public void testUnmapped() {
org.junit.Assert.assertNotNull("Null should not be injected into unmappedEnvEntry", getBean().getUnmappedEnvEntry());
org.junit.Assert.assertEquals("unmappedEnvEntry should have its initial value",1, getBean().getUnmappedEnvEntry().intValue());
}
@Test
public void testMapped() {
org.junit.Assert.assertEquals("mappedEnvEntry should have its deployment descriptor value",1, getBean().getMappedEnvEntry().intValue());
}
@Test
public void testUnnamedMapped() {
org.junit.Assert.assertEquals("unnamedMappedEnvEntry should have its deployment descriptor value",1, getBean().getUnnamedMappedEnvEntry().intValue());
}
@Test
public void testUnannotatedString() {
org.junit.Assert.assertEquals("unannotatedString should have its deployment descriptor value","injected", getBean().getUnannotatedString());
}
@Test
public void testUnannotatedBoolean() {
org.junit.Assert.assertTrue("unannotatedBoolean should have its deployment descriptor value", getBean().isUnannotatedBoolean());
}
@Test
public void testUnannotatedChar() {
org.junit.Assert.assertEquals("unannotatedChar should have its deployment descriptor value", Character.valueOf('b'), Character.valueOf(getBean().getUnannotatedChar()));
}
@Test
public void testUnannotatedByte() {
org.junit.Assert.assertEquals("unannotatedByte should have its deployment descriptor value", Byte.valueOf((byte)1), Byte.valueOf(getBean().getUnannotatedByte()));
}
@Test
public void testUnannotatedShort() {
org.junit.Assert.assertEquals("unannotatedShort should have its deployment descriptor value", 1, getBean().getUnannotatedShort());
}
@Test
public void testUnannotatedInt() {
org.junit.Assert.assertEquals("unannotatedInt should have its deployment descriptor value", 1, getBean().getUnannotatedInt());
}
@Test
public void testUnannotatedLong() {
org.junit.Assert.assertEquals("unannotatedLong should have its deployment descriptor value", 1L, getBean().getUnannotatedLong());
}
@Test
public void testUnannotatedFloat() {
org.junit.Assert.assertEquals("unannotatedFloat should have its deployment descriptor value", (float) 1, getBean().getUnannotatedFloat(), 0.1);
}
@Test
public void testUnannotatedDouble() {
org.junit.Assert.assertEquals("unannotatedDouble should have its deployment descriptor value", (double) 1, getBean().getUnannotatedDouble(), 0.1);
}
@Test
public void testUnannotatedStringProperty() {
org.junit.Assert.assertEquals("unannotatedStringProperty should have its deployment descriptor value","injected", getBean().getUnannotatedStringProperty());
}
@Test
public void testUnannotatedBooleanProperty() {
org.junit.Assert.assertTrue("unannotatedBooleanProperty should have its deployment descriptor value", getBean().isUnannotatedBooleanProperty());
}
@Test
public void testUnannotatedIntProperty() {
org.junit.Assert.assertEquals("unannotatedIntProperty should have its deployment descriptor value", 1, getBean().getUnannotatedIntProperty());
}
@Test
public void testUnannotatedIntLookup() {
org.junit.Assert.assertEquals("unannotatedIntLookup should have its deployment descriptor value", 1, getBean().getUnannotatedIntLookup());
}
}
| 5,938 | 39.958621 | 176 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/CoordinatorTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.SocketPermission;
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.container.ManagementClient;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.jbossts.star.util.TxMediaType;
import org.jboss.jbossts.star.util.TxStatusMediaType;
import org.jboss.jbossts.star.util.TxSupport;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.extension.rts.common.WorkRestATResource;
import org.wildfly.test.extension.rts.common.Work;
/**
*
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
* @author <a href="mailto:[email protected]">Michael Musgrove</a>
*
*/
@RunAsClient
@RunWith(Arquillian.class)
public final class CoordinatorTestCase extends AbstractTestCase {
private static final String DEPENDENCIES = "Dependencies: org.jboss.narayana.rts\n";
private static final String SERVER_HOST_PORT = TestSuiteEnvironment.getServerAddress() + ":"
+ TestSuiteEnvironment.getHttpPort();
@ArquillianResource
private ManagementClient managementClient;
@Deployment
public static WebArchive getDeployment() {
return AbstractTestCase.getDeployment()
.addClasses(WorkRestATResource.class, Work.class)
.addAsWebInfResource(CoordinatorTestCase.class.getClassLoader().getResource("web.xml"),"web.xml")
.addAsManifestResource(new StringAsset(DEPENDENCIES), "MANIFEST.MF")
.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(
// Permissions required to access SERVER_HOST_PORT
new SocketPermission(SERVER_HOST_PORT, "connect,resolve")
), "permissions.xml");
}
@Before
public void before() {
super.before();
WorkRestATResource.clearFaults();
}
@Test
public void testListTransactions() {
TxSupport[] txns = { new TxSupport(), new TxSupport() };
int txnCount = new TxSupport().txCount();
for (TxSupport txn : txns) {
txn.startTx();
}
// there should be txns.length more transactions
Assert.assertEquals(txnCount + txns.length, txns[0].txCount());
for (TxSupport txn : txns) {
txn.commitTx();
}
// the number of transactions should be back to the original number
Assert.assertEquals(txnCount, txns[0].txCount());
}
@Test
public void test1PCAbort() throws Exception {
TxSupport txn = new TxSupport();
String pUrl = getDeploymentUrl() + WorkRestATResource.PATH_SEGMENT;
String pid = null;
String pVal;
pid = modifyResource(txn, pUrl, pid, "p1", "v1");
pVal = getResourceProperty(txn, pUrl, pid, "p1");
Assert.assertEquals(pVal, "v1");
txn.startTx();
pid = enlistResource(txn, pUrl + "?pId=" + pid);
modifyResource(txn, pUrl, pid, "p1", "v2");
pVal = getResourceProperty(txn, pUrl, pid, "p1");
Assert.assertEquals(pVal, "v2");
txn.rollbackTx();
pVal = getResourceProperty(txn, pUrl, pid, "p1");
Assert.assertEquals(pVal, "v1");
}
@Test
public void test1PCCommit() throws Exception {
TxSupport txn = new TxSupport();
String pUrl = getDeploymentUrl() + WorkRestATResource.PATH_SEGMENT;
String pid = null;
String pVal;
pid = modifyResource(txn, pUrl, pid, "p1", "v1");
pVal = getResourceProperty(txn, pUrl, pid, "p1");
Assert.assertEquals(pVal, "v1");
txn.startTx();
pid = enlistResource(txn, pUrl + "?pId=" + pid);
modifyResource(txn, pUrl, pid, "p1", "v2");
pVal = getResourceProperty(txn, pUrl, pid, "p1");
Assert.assertEquals(pVal, "v2");
txn.commitTx();
pVal = getResourceProperty(txn, pUrl, pid, "p1");
Assert.assertEquals(pVal, "v2");
}
@Test
public void test2PC() throws Exception {
TxSupport txn = new TxSupport();
String pUrl = getDeploymentUrl() + WorkRestATResource.PATH_SEGMENT;
String[] pid = new String[2];
String[] pVal = new String[2];
for (int i = 0; i < pid.length; i++) {
pid[i] = modifyResource(txn, pUrl, null, "p1", "v1");
pVal[i] = getResourceProperty(txn, pUrl, pid[i], "p1");
Assert.assertEquals(pVal[i], "v1");
}
txn.startTx();
for (int i = 0; i < pid.length; i++) {
enlistResource(txn, pUrl + "?pId=" + pid[i]);
modifyResource(txn, pUrl, pid[i], "p1", "v2");
pVal[i] = getResourceProperty(txn, pUrl, pid[i], "p1");
Assert.assertEquals(pVal[i], "v2");
}
txn.rollbackTx();
for (int i = 0; i < pid.length; i++) {
pVal[i] = getResourceProperty(txn, pUrl, pid[i], "p1");
Assert.assertEquals(pVal[i], "v1");
}
}
@Test
public void testCommitInvalidTx() throws IOException {
TxSupport txn = new TxSupport().startTx();
String terminator = txn.getTerminatorURI();
terminator += "/_dead";
// an attempt to commit on this URI should fail:
txn.httpRequest(new int[] { HttpURLConnection.HTTP_NOT_FOUND }, terminator, "PUT", TxMediaType.TX_STATUS_MEDIA_TYPE,
TxStatusMediaType.TX_COMMITTED);
// commit it properly
txn.commitTx();
}
@Test
public void testTimeoutCleanup() throws InterruptedException {
TxSupport txn = new TxSupport();
int txnCount = txn.txCount();
txn.startTx(1000);
txn.enlistTestResource(getDeploymentUrl() + WorkRestATResource.PATH_SEGMENT, false);
// Let the txn timeout
Thread.sleep(2000);
Assert.assertEquals(txnCount, txn.txCount());
}
protected String getBaseUrl() {
return managementClient.getWebUri().toString();
}
private String enlistResource(final TxSupport txn, final String pUrl) {
return txn.enlistTestResource(pUrl, false);
}
private String modifyResource(final TxSupport txn, final String pUrl, final String pid, final String name,
final String value) {
final int[] expected = new int[] { HttpURLConnection.HTTP_OK };
final String url = getResourceUpdateUrl(pUrl, pid, name, value).toString();
final String method = "GET";
return txn.httpRequest(expected, url, method, TxMediaType.PLAIN_MEDIA_TYPE);
}
private String getResourceProperty(final TxSupport txn, final String pUrl, final String pid, final String name) {
final int[] expected = new int[] { HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NO_CONTENT };
final String updateUrl = getResourceUpdateUrl(pUrl, pid, name, null).toString();
final String method = "GET";
return txn.httpRequest(expected, updateUrl, method, TxMediaType.PLAIN_MEDIA_TYPE);
}
private StringBuilder getResourceUpdateUrl(final String pUrl, final String pid, final String name, final String value) {
final StringBuilder sb = new StringBuilder(pUrl);
if (pid != null) {
sb.append("?pId=").append(pid).append("&name=");
} else {
sb.append("?name=");
}
sb.append(name);
if (value != null) {
sb.append("&value=").append(value);
}
return sb;
}
}
| 8,958 | 34.133333 | 124 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/InboundBridgeTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts;
import jakarta.json.JsonArray;
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.container.ManagementClient;
import org.jboss.jbossts.star.util.TxStatusMediaType;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.extension.rts.common.InboundBridgeResource;
import org.wildfly.test.extension.rts.common.LoggingRestATResource;
import org.wildfly.test.extension.rts.common.LoggingXAResource;
/**
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*/
@RunAsClient
@RunWith(Arquillian.class)
public final class InboundBridgeTestCase extends AbstractTestCase {
private static final String DEPENDENCIES = "Dependencies: org.jboss.narayana.rts, org.jboss.jts\n";
private InboundBridgeUtilities utils;
@ArquillianResource
private ManagementClient managementClient;
@Deployment
public static WebArchive getDeployment() {
return AbstractTestCase.getDeployment()
.addClasses(InboundBridgeResource.class, LoggingXAResource.class, LoggingRestATResource.class)
.addAsWebInfResource(InboundBridgeTestCase.class.getClassLoader().getResource("web.xml"),"web.xml")
.addAsManifestResource(new StringAsset(DEPENDENCIES), "MANIFEST.MF");
}
@Before
public void before() {
super.before();
utils = new InboundBridgeUtilities(txSupport,
getDeploymentUrl() + InboundBridgeResource.URL_SEGMENT, // inboundBridgeResourceUrl
getDeploymentUrl() + LoggingRestATResource.BASE_URL_SEGMENT, // loggingRestATParticipantUrl
getDeploymentUrl() + LoggingRestATResource.BASE_URL_SEGMENT + "/" + LoggingRestATResource.INVOCATIONS_URL_SEGMENT); // loggingRestATParticipantInvocationsUrl
utils.resetInvocations();
}
@Test
public void testCommit() throws Exception {
txSupport.startTx();
utils.enlistInboundBridgeResource();
txSupport.commitTx();
final JsonArray jsonArray = utils.getInboundBridgeResourceInvocations();
utils.assertJsonArray(jsonArray, "LoggingXAResource.start", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.end", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.prepare", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.commit", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.rollback", 0);
}
@Test
public void testRollback() throws Exception {
txSupport.startTx();
utils.enlistInboundBridgeResource();
txSupport.rollbackTx();
JsonArray jsonArray = utils.getInboundBridgeResourceInvocations();
utils.assertJsonArray(jsonArray, "LoggingXAResource.start", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.end", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.prepare", 0);
utils.assertJsonArray(jsonArray, "LoggingXAResource.commit", 0);
utils.assertJsonArray(jsonArray, "LoggingXAResource.rollback", 1);
}
@Test
public void testCommitWithTwoParticipants() throws Exception {
txSupport.startTx();
utils.enlistLoggingRestATParticipant();
utils.enlistInboundBridgeResource();
txSupport.commitTx();
JsonArray participantResourceInvocations = utils.getLoggingRestATParticipantInvocations();
JsonArray xaResourceInvocations = utils.getInboundBridgeResourceInvocations();
Assert.assertEquals(2, participantResourceInvocations.size());
Assert.assertEquals("LoggingRestATResource.terminateParticipant(" + TxStatusMediaType.TX_PREPARED + ")",
participantResourceInvocations.getString(0));
Assert.assertEquals("LoggingRestATResource.terminateParticipant(" + TxStatusMediaType.TX_COMMITTED + ")",
participantResourceInvocations.getString(1));
utils.assertJsonArray(xaResourceInvocations, "LoggingXAResource.start", 1);
utils.assertJsonArray(xaResourceInvocations, "LoggingXAResource.end", 1);
utils.assertJsonArray(xaResourceInvocations, "LoggingXAResource.prepare", 1);
utils.assertJsonArray(xaResourceInvocations, "LoggingXAResource.commit", 1);
utils.assertJsonArray(xaResourceInvocations, "LoggingXAResource.rollback", 0);
}
@Test
public void testRollbackWithTwoParticipants() throws Exception {
txSupport.startTx();
utils.enlistLoggingRestATParticipant();
utils.enlistInboundBridgeResource();
txSupport.rollbackTx();
JsonArray participantResourceInvocations = utils.getLoggingRestATParticipantInvocations();
JsonArray xaResourceInvocations = utils.getInboundBridgeResourceInvocations();
Assert.assertEquals(1, participantResourceInvocations.size());
Assert.assertEquals("LoggingRestATResource.terminateParticipant(" + TxStatusMediaType.TX_ROLLEDBACK + ")",
participantResourceInvocations.getString(0));
utils.assertJsonArray(xaResourceInvocations, "LoggingXAResource.start", 1);
utils.assertJsonArray(xaResourceInvocations, "LoggingXAResource.end", 1);
utils.assertJsonArray(xaResourceInvocations, "LoggingXAResource.prepare", 0);
utils.assertJsonArray(xaResourceInvocations, "LoggingXAResource.commit", 0);
utils.assertJsonArray(xaResourceInvocations, "LoggingXAResource.rollback", 1);
}
protected String getBaseUrl() {
return managementClient.getWebUri().toString();
}
}
| 6,900 | 45.006667 | 173 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/ProvidersTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts;
import jakarta.xml.bind.JAXBException;
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.container.ManagementClient;
import org.jboss.jbossts.star.util.TxStatus;
import org.jboss.jbossts.star.util.TxSupport;
import org.jboss.jbossts.star.util.media.txstatusext.TransactionManagerElement;
import org.jboss.jbossts.star.util.media.txstatusext.TransactionStatisticsElement;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test if all providers work as required.
*
* Some of the media types and XML elements are covered in another tests. Therefore, they were emitted here.
*
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*
*/
@RunAsClient
@RunWith(Arquillian.class)
public final class ProvidersTestCase extends AbstractTestCase {
@ArquillianResource
private ManagementClient managementClient;
@Deployment
public static WebArchive getDeployment() {
return AbstractTestCase.getDeployment();
}
@Before
public void before() {
super.before();
txSupport.startTx();
}
@Test
public void testTxStatusMediaType() {
Assert.assertEquals(TxStatus.TransactionActive.name(), TxSupport.getStatus(txSupport.txStatus()));
}
@Test
public void testTransactionManagerElement() throws JAXBException {
TransactionManagerElement transactionManagerElement = txSupport.getTransactionManagerInfo();
Assert.assertNotNull(transactionManagerElement);
Assert.assertEquals(1, transactionManagerElement.getCoordinatorURIs().size());
}
@Test
public void testTransactionStatisticsElement() throws JAXBException {
TransactionStatisticsElement transactionStatisticsElement = txSupport.getTransactionStatistics();
Assert.assertNotNull(transactionStatisticsElement);
Assert.assertEquals(1, transactionStatisticsElement.getActive());
}
protected String getBaseUrl() {
return managementClient.getWebUri().toString();
}
}
| 3,346 | 34.989247 | 108 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/InboundBridgeUtilities.java
|
package org.wildfly.test.extension.rts;
import static org.wildfly.common.Assert.checkNotNullParamWithNullPointerException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.UncheckedIOException;
import jakarta.json.Json;
import jakarta.json.JsonArray;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Link;
import jakarta.ws.rs.core.Response;
import org.jboss.jbossts.star.util.TxLinkNames;
import org.jboss.jbossts.star.util.TxSupport;
import org.junit.Assert;
final class InboundBridgeUtilities {
private final TxSupport txSupport;
private final String inboundBridgeResourceUrl;
private final String loggingRestATParticipantUrl;
private final String loggingRestATParticipantInvocationsUrl;
InboundBridgeUtilities(TxSupport txSupport, String inboundBridgeResourceUrl, String loggingRestATParticipantUrl, String loggingRestATParticipantInvocationsUrl) {
this.txSupport = txSupport;
this.inboundBridgeResourceUrl = inboundBridgeResourceUrl;
this.loggingRestATParticipantUrl = loggingRestATParticipantUrl;
this.loggingRestATParticipantInvocationsUrl = loggingRestATParticipantInvocationsUrl;
}
void enlistInboundBridgeResource() {
final Link participantLink = Link.fromUri(txSupport.getTxnUri()).rel(TxLinkNames.PARTICIPANT).title(TxLinkNames.PARTICIPANT).build();
final Response response = ClientBuilder.newClient().target(inboundBridgeResourceUrl).request()
.header("link", participantLink).post(null);
Assert.assertEquals(200, response.getStatus());
}
protected void enlistLoggingRestATParticipant() {
String linkHeader = txSupport.makeTwoPhaseAwareParticipantLinkHeader(loggingRestATParticipantUrl, false, null, null);
String recoveryUrl = txSupport.enlistParticipant(txSupport.getTxnUri(), linkHeader);
Assert.assertFalse(recoveryUrl == null);
}
protected void resetInvocations() {
Response response = ClientBuilder.newClient().target(inboundBridgeResourceUrl).request().put(null);
Assert.assertEquals(200, response.getStatus());
response = ClientBuilder.newClient().target(loggingRestATParticipantInvocationsUrl).request().put(null);
Assert.assertEquals(200, response.getStatus());
}
protected JsonArray getInboundBridgeResourceInvocations() throws Exception {
final String response = ClientBuilder.newClient().target(inboundBridgeResourceUrl).request().get(String.class);
return createJsonArray(response);
}
protected JsonArray getLoggingRestATParticipantInvocations() throws Exception {
String response = ClientBuilder.newClient().target(loggingRestATParticipantInvocationsUrl).request().get(String.class);
return createJsonArray(response);
}
/**
* Checking if the parameter <code>recordToAssert</code>
* is placed exactly once in the {@link JsonArray}.
*/
protected void assertJsonArray(JsonArray invocationsJSONArray, String recordToAssert, int expectedRecordFoundCount) {
checkNotNullParamWithNullPointerException("recordToAssert", recordToAssert);
int recordFoundCount = 0;
for(int i = 0; i < invocationsJSONArray.size(); i++) {
if(recordToAssert.equals(invocationsJSONArray.getString(i))) {
recordFoundCount++;
}
}
if (recordFoundCount != expectedRecordFoundCount) {
Assert.fail("Invocation result returned as a JSON array '" + invocationsJSONArray + "' "
+ "expected to contain the record '" + recordToAssert + "' " + expectedRecordFoundCount + " times "
+ "but the record was " + recordFoundCount + " times in the array");
}
}
private JsonArray createJsonArray(final String response) {
try (Reader reader = new StringReader(response)) {
return Json.createReader(reader).readArray();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
| 4,091 | 43 | 165 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/AbstractTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts;
import org.jboss.jbossts.star.util.TxSupport;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
/**
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*/
public abstract class AbstractTestCase {
protected static final String DEPLOYMENT_NAME = "test-deployment";
protected TxSupport txSupport;
public static WebArchive getDeployment() {
return ShrinkWrap.create(WebArchive.class, DEPLOYMENT_NAME + ".war");
}
@Before
public void before() {
TxSupport.setTxnMgrUrl(getBaseUrl() + "/rest-at-coordinator/tx/transaction-manager");
txSupport = new TxSupport();
}
@After
public void after() {
try {
txSupport.rollbackTx();
} catch (Throwable t) {
}
Assert.assertEquals(0, txSupport.txCount());
}
protected String getDeploymentUrl() {
return getBaseUrl() + "/" + DEPLOYMENT_NAME + "/";
}
protected abstract String getBaseUrl();
}
| 2,164 | 31.313433 | 93 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/ParticipantTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts;
import java.lang.reflect.ReflectPermission;
import java.net.SocketPermission;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.PropertyPermission;
import jakarta.xml.bind.JAXBException;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils;
import org.jboss.jbossts.star.util.TxStatus;
import org.jboss.jbossts.star.util.TxSupport;
import org.jboss.narayana.rest.integration.api.Aborted;
import org.jboss.narayana.rest.integration.api.HeuristicType;
import org.jboss.narayana.rest.integration.api.ParticipantsManagerFactory;
import org.jboss.narayana.rest.integration.api.Prepared;
import org.jboss.narayana.rest.integration.api.ReadOnly;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.extension.rts.common.LoggingParticipant;
/**
*
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*
*/
@RunWith(Arquillian.class)
public final class ParticipantTestCase extends AbstractTestCase {
private static final String APPLICATION_ID = "org.wildfly.test.extension.rts";
private static final String DEPENDENCIES = "Dependencies: org.jboss.narayana.rts\n";
private static final String SERVER_HOST_PORT = TestSuiteEnvironment.getServerAddress() + ":"
+ TestSuiteEnvironment.getHttpPort();
@Deployment
public static WebArchive getDeployment() {
return AbstractTestCase.getDeployment()
.addClasses(LoggingParticipant.class, AbstractTestCase.class, TestSuiteEnvironment.class)
.addAsWebInfResource(ParticipantTestCase.class.getClassLoader().getResource("web.xml"),"web.xml")
.addAsManifestResource(new StringAsset(DEPENDENCIES), "MANIFEST.MF")
.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(
// Permissions required to get SERVER_HOST_PORT
new PropertyPermission("management.address", "read"),
new PropertyPermission("node0", "read"),
new PropertyPermission("jboss.http.port", "read"),
new PropertyPermission("arquillian.debug", "read"),
new ReflectPermission("suppressAccessChecks"),
new RuntimePermission("accessDeclaredMembers"),
// Permissions required to access SERVER_HOST_PORT
new SocketPermission(SERVER_HOST_PORT, "connect,resolve")
), "permissions.xml");
}
@Test
public void testCommit() {
txSupport.startTx();
LoggingParticipant participant1 = new LoggingParticipant(new Prepared());
LoggingParticipant participant2 = new LoggingParticipant(new Prepared());
ParticipantsManagerFactory.getInstance().enlist(APPLICATION_ID, txSupport.getDurableParticipantEnlistmentURI(),
participant1);
ParticipantsManagerFactory.getInstance().enlist(APPLICATION_ID, txSupport.getDurableParticipantEnlistmentURI(),
participant2);
txSupport.commitTx();
Assert.assertEquals(Arrays.asList(new String[] { "prepare", "commit" }), participant1.getInvocations());
Assert.assertEquals(Arrays.asList(new String[] { "prepare", "commit" }), participant2.getInvocations());
}
@Test
public void testCommitOnePhase() {
txSupport.startTx();
LoggingParticipant participant = new LoggingParticipant(new Prepared());
ParticipantsManagerFactory.getInstance().enlist(APPLICATION_ID, txSupport.getDurableParticipantEnlistmentURI(),
participant);
txSupport.commitTx();
Assert.assertEquals(Arrays.asList(new String[] { "commitOnePhase" }), participant.getInvocations());
}
@Test
public void testReadOnly() {
txSupport.startTx();
final List<LoggingParticipant> participants = Arrays.asList(new LoggingParticipant[] {
new LoggingParticipant(new ReadOnly()), new LoggingParticipant(new Prepared()),
new LoggingParticipant(new Prepared()) });
for (LoggingParticipant p : participants) {
ParticipantsManagerFactory.getInstance().enlist(APPLICATION_ID,
txSupport.getDurableParticipantEnlistmentURI(), p);
}
txSupport.commitTx();
// One of the participants was only prepared, while other two were prepared and committed.
Assert.assertEquals(5, participants.get(0).getInvocations().size() + participants.get(1).getInvocations().size()
+ participants.get(2).getInvocations().size());
for (LoggingParticipant p : participants) {
if (p.getInvocations().size() == 1) {
Assert.assertEquals(Arrays.asList(new String[] { "prepare" }), p.getInvocations());
} else {
Assert.assertEquals(Arrays.asList(new String[] { "prepare", "commit" }), p.getInvocations());
}
}
}
@Test
public void testRollback() {
txSupport.startTx();
LoggingParticipant participant1 = new LoggingParticipant(new Prepared());
LoggingParticipant participant2 = new LoggingParticipant(new Prepared());
ParticipantsManagerFactory.getInstance().enlist(APPLICATION_ID, txSupport.getDurableParticipantEnlistmentURI(),
participant1);
ParticipantsManagerFactory.getInstance().enlist(APPLICATION_ID, txSupport.getDurableParticipantEnlistmentURI(),
participant2);
txSupport.rollbackTx();
Assert.assertEquals(Arrays.asList(new String[] { "rollback" }), participant1.getInvocations());
Assert.assertEquals(Arrays.asList(new String[] { "rollback" }), participant2.getInvocations());
}
@Test
public void testRollbackByParticipant() {
txSupport.startTx();
final List<LoggingParticipant> participants = Arrays.asList(new LoggingParticipant[] {
new LoggingParticipant(new Aborted()), new LoggingParticipant(new Aborted()), });
for (LoggingParticipant p : participants) {
ParticipantsManagerFactory.getInstance().enlist(APPLICATION_ID,
txSupport.getDurableParticipantEnlistmentURI(), p);
}
txSupport.commitTx();
// One of the participants was prepared and then decided to rollback, the other was rolledback straight away.
Assert.assertEquals(3, participants.get(0).getInvocations().size() + participants.get(1).getInvocations().size());
for (LoggingParticipant p : participants) {
if (p.getInvocations().size() == 1) {
Assert.assertEquals(Arrays.asList(new String[] { "rollback" }), p.getInvocations());
} else {
Assert.assertEquals(Arrays.asList(new String[] { "prepare", "rollback" }), p.getInvocations());
}
}
}
@Test
public void testHeuristicRollbackBeforePrepare() throws JAXBException {
txSupport.startTx();
final List<LoggingParticipant> participants = Arrays.asList(new LoggingParticipant[] {
new LoggingParticipant(new Prepared()), new LoggingParticipant(new Prepared()) });
String lastParticipantid = null;
for (LoggingParticipant p : participants) {
lastParticipantid = ParticipantsManagerFactory.getInstance().enlist(APPLICATION_ID,
txSupport.getDurableParticipantEnlistmentURI(), p);
}
ParticipantsManagerFactory.getInstance().reportHeuristic(lastParticipantid, HeuristicType.HEURISTIC_ROLLBACK);
final String transactionStatus = TxSupport.getStatus(txSupport.commitTx());
Assert.assertEquals(TxStatus.TransactionRolledBack.name(), transactionStatus);
if (participants.get(0).getInvocations().size() == 1) {
Assert.assertEquals(Arrays.asList(new String[] { "rollback" }), participants.get(0).getInvocations());
} else {
Assert.assertEquals(Arrays.asList(new String[] { "prepare", "rollback" }), participants.get(0).getInvocations());
}
}
@Test
public void testHeuristicCommitBeforePrepare() throws JAXBException {
txSupport.startTx();
final List<LoggingParticipant> participants = Arrays.asList(new LoggingParticipant[] {
new LoggingParticipant(new Prepared()), new LoggingParticipant(new Prepared()) });
String lastParticipantid = null;
for (LoggingParticipant p : participants) {
lastParticipantid = ParticipantsManagerFactory.getInstance().enlist(APPLICATION_ID,
txSupport.getDurableParticipantEnlistmentURI(), p);
}
ParticipantsManagerFactory.getInstance().reportHeuristic(lastParticipantid, HeuristicType.HEURISTIC_COMMIT);
final String transactionStatus = TxSupport.getStatus(txSupport.commitTx());
Assert.assertEquals(TxStatus.TransactionCommitted.name(), transactionStatus);
Assert.assertEquals(Arrays.asList(new String[] { "prepare", "commit" }), participants.get(0).getInvocations());
Assert.assertEquals(Collections.EMPTY_LIST, participants.get(1).getInvocations());
}
protected String getBaseUrl() {
return "http://" + SERVER_HOST_PORT;
}
}
| 10,662 | 42.70082 | 125 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/InboundBridgeEjbTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts;
import jakarta.json.JsonArray;
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.container.ManagementClient;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.test.extension.rts.common.InboundBridgeResourceEjb;
import org.wildfly.test.extension.rts.common.LoggingRestATResource;
import org.wildfly.test.extension.rts.common.LoggingXAResource;
@RunAsClient
@RunWith(Arquillian.class)
public final class InboundBridgeEjbTestCase extends AbstractTestCase {
private static final String DEPENDENCIES = "Dependencies: org.jboss.narayana.rts, org.jboss.jts\n";
private InboundBridgeUtilities utils;
@ArquillianResource
private ManagementClient managementClient;
@Deployment
public static WebArchive getDeployment() {
return AbstractTestCase.getDeployment()
.addClasses(InboundBridgeResourceEjb.class, LoggingXAResource.class, LoggingRestATResource.class)
.addAsWebInfResource(InboundBridgeEjbTestCase.class.getClassLoader().getResource("web.xml"),"web.xml")
.addAsManifestResource(new StringAsset(DEPENDENCIES), "MANIFEST.MF");
}
@Before
public void before() {
super.before();
utils = new InboundBridgeUtilities(txSupport,
getDeploymentUrl() + InboundBridgeResourceEjb.URL_SEGMENT, // inboundBridgeResourceUrl
getDeploymentUrl() + LoggingRestATResource.BASE_URL_SEGMENT, // loggingRestATParticipantUrl
getDeploymentUrl() + LoggingRestATResource.BASE_URL_SEGMENT + "/" + LoggingRestATResource.INVOCATIONS_URL_SEGMENT); // loggingRestATParticipantInvocationsUrl
utils.resetInvocations();
}
@Test
public void testCommit() throws Exception {
txSupport.startTx();
utils.enlistInboundBridgeResource();
txSupport.commitTx();
final JsonArray jsonArray = utils.getInboundBridgeResourceInvocations();
utils.assertJsonArray(jsonArray, "LoggingXAResource.start", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.end", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.prepare", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.commit", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.rollback", 0);
}
@Test
public void testRollback() throws Exception {
txSupport.startTx();
utils.enlistInboundBridgeResource();
txSupport.rollbackTx();
JsonArray jsonArray = utils.getInboundBridgeResourceInvocations();
utils.assertJsonArray(jsonArray, "LoggingXAResource.start", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.end", 1);
utils.assertJsonArray(jsonArray, "LoggingXAResource.prepare", 0);
utils.assertJsonArray(jsonArray, "LoggingXAResource.commit", 0);
utils.assertJsonArray(jsonArray, "LoggingXAResource.rollback", 1);
}
protected String getBaseUrl() {
return managementClient.getWebUri().toString();
}
}
| 4,392 | 42.068627 | 173 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/common/LoggingParticipant.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts.common;
import java.util.ArrayList;
import java.util.List;
import org.jboss.narayana.rest.integration.api.Participant;
import org.jboss.narayana.rest.integration.api.Vote;
/**
*
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*
*/
public final class LoggingParticipant implements Participant {
private static final long serialVersionUID = 7584938841973602732L;
private final List<String> invocations;
private final Vote outcome;
public LoggingParticipant(final Vote outcome) {
this.outcome = outcome;
this.invocations = new ArrayList<String>();
}
@Override
public Vote prepare() {
invocations.add("prepare");
return outcome;
}
@Override
public void commit() {
invocations.add("commit");
}
@Override
public void commitOnePhase() {
invocations.add("commitOnePhase");
}
@Override
public void rollback() {
invocations.add("rollback");
}
public List<String> getInvocations() {
return invocations;
}
}
| 2,120 | 27.662162 | 70 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/common/Work.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts.common;
import java.util.HashMap;
import java.util.Map;
import org.jboss.jbossts.star.util.TxStatus;
public final class Work {
String id;
String tid;
String uri;
String pLinks;
String enlistUrl;
String recoveryUrl;
String fault;
Map<String, String> oldState;
Map<String, String> newState;
String status;
int vStatus = 0;
int syncCount = 0;
int commitCnt = 0;
int prepareCnt = 0;
int rollbackCnt = 0;
int commmitOnePhaseCnt = 0;
Work(String id, String tid, String uri, String pLinks, String enlistUrl, String recoveryUrl, String fault) {
this.id = id;
this.tid = tid;
this.uri = uri;
this.pLinks = pLinks;
this.enlistUrl = enlistUrl;
this.recoveryUrl = recoveryUrl;
this.fault = fault;
this.oldState = new HashMap<String, String>();
this.newState = new HashMap<String, String>();
}
public void start() {
newState.clear();
newState.putAll(oldState);
}
public void end(boolean commit) {
if (commit) {
oldState.clear();
oldState.putAll(newState);
}
}
public boolean inTxn() {
return status != null && TxStatus.fromStatus(status).isActive();
// return TxSupport.isActive(status);
}
}
| 2,378 | 29.896104 | 112 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/common/LoggingXAResource.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts.common;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
*
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*
*/
public class LoggingXAResource implements XAResource {
private static final Logger LOG = Logger.getLogger(LoggingXAResource.class);
private List<String> invocations = new ArrayList<String>();
@Override
public void commit(Xid xid, boolean onePhase) throws XAException {
String str = "LoggingXAResource.commit";
invocations.add(str);
LOG.trace(str);
}
@Override
public void end(Xid xid, int flags) throws XAException {
String str = "LoggingXAResource.end";
invocations.add(str);
LOG.trace(str);
}
@Override
public void forget(Xid xid) throws XAException {
String str = "LoggingXAResource.forget";
invocations.add(str);
LOG.trace(str);
}
@Override
public int getTransactionTimeout() throws XAException {
String str = "LoggingXAResource.getTransactionTimeout";
invocations.add(str);
LOG.trace(str);
return 0;
}
@Override
public boolean isSameRM(XAResource xares) throws XAException {
String str = "LoggingXAResource.isSameRM";
invocations.add(str);
LOG.trace(str);
return false;
}
@Override
public int prepare(Xid xid) throws XAException {
String str = "LoggingXAResource.prepare";
invocations.add(str);
LOG.trace(str);
return XAResource.XA_OK;
}
@Override
public Xid[] recover(int flag) throws XAException {
String str = "LoggingXAResource.recover";
invocations.add(str);
LOG.trace(str);
return null;
}
@Override
public void rollback(Xid xid) throws XAException {
String str = "LoggingXAResource.rollback";
invocations.add(str);
LOG.trace(str);
}
@Override
public boolean setTransactionTimeout(int seconds) throws XAException {
String str = "LoggingXAResource.setTransactionTimeout";
invocations.add(str);
LOG.trace(str);
return false;
}
@Override
public void start(Xid xid, int flags) throws XAException {
String str = "LoggingXAResource.start";
invocations.add(str);
LOG.trace(str);
}
public List<String> getInvocations() {
return invocations;
}
public void resetInvocations() {
invocations.clear();
}
}
| 3,734 | 23.411765 | 80 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/common/InboundBridgeResource.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts.common;
import jakarta.json.Json;
import jakarta.transaction.Transaction;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import com.arjuna.ats.jta.TransactionManager;
import org.jboss.logging.Logger;
/**
*
* @author Gytis Trikleris
*
*/
@Path(InboundBridgeResource.URL_SEGMENT)
public class InboundBridgeResource {
public static final String URL_SEGMENT = "inbound-bridge-resource";
private static final Logger LOG = Logger.getLogger(LoggingRestATResource.class);
private static LoggingXAResource loggingXAResource;
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getInvocations() {
if (LOG.isTraceEnabled()) {
LOG.trace("InboundBridgeResource.getInvocations()");
}
if (loggingXAResource == null) {
throw new WebApplicationException(409);
}
return Json.createArrayBuilder(loggingXAResource.getInvocations()).build().toString();
}
@POST
@Transactional
public Response enlistXAResource() {
if (LOG.isTraceEnabled()) {
LOG.trace("InboundBridgeResource.enlistXAResource()");
}
try {
loggingXAResource = new LoggingXAResource();
Transaction t = TransactionManager.transactionManager().getTransaction();
t.enlistResource(loggingXAResource);
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
return Response.serverError().build();
}
return Response.ok().build();
}
@PUT
public Response resetXAResource() {
if (LOG.isTraceEnabled()) {
LOG.trace("InboundBridgeResource.resetXAResource()");
}
if (loggingXAResource != null) {
loggingXAResource.resetInvocations();
}
return Response.ok().build();
}
}
| 3,143 | 29.230769 | 94 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/common/LoggingRestATResource.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts.common;
import org.jboss.jbossts.star.util.TxLinkNames;
import org.jboss.jbossts.star.util.TxStatus;
import org.jboss.jbossts.star.util.TxSupport;
import org.jboss.logging.Logger;
import jakarta.json.Json;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HEAD;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author <a href="mailto:[email protected]">Gytis Trikleris</a>
*
*/
@Path(LoggingRestATResource.BASE_URL_SEGMENT)
public class LoggingRestATResource {
public static final String BASE_URL_SEGMENT = "logging-rest-at-participant";
public static final String INVOCATIONS_URL_SEGMENT = "invocations";
private static final Logger LOG = Logger.getLogger(LoggingRestATResource.class);
private static final List<String> invocations = new ArrayList<String>();
/**
* Returns links to the participant terminator.
*
* @return Link to the participant terminator.
*/
@HEAD
public Response headParticipant(@Context final UriInfo uriInfo) {
if (LOG.isTraceEnabled()) {
LOG.trace("LoggingRestATResource.headParticipant()");
}
invocations.add("LoggingRestATResource.headParticipant()");
final String serviceURL = uriInfo.getBaseUri() + uriInfo.getPath();
final String linkHeader = new TxSupport().makeTwoPhaseAwareParticipantLinkHeader(serviceURL, false, null, null);
return Response.ok().header("Link", linkHeader).build();
}
/**
* Returns current status of the participant.
*
* @return
*/
@GET
public Response getStatus() {
if (LOG.isTraceEnabled()) {
LOG.trace("LoggingRestATResource.getStatus()");
}
invocations.add("LoggingRestATResource.getStatus()");
return null;
}
/**
* Terminates participant.
*
* @param content
* @return
*/
@PUT
@Path(TxLinkNames.TERMINATOR)
public Response terminateParticipant(String content) {
if (LOG.isTraceEnabled()) {
LOG.trace("LoggingRestATResource.terminateParticipant(" + content + ")");
}
invocations.add("LoggingRestATResource.terminateParticipant(" + content + ")");
TxStatus txStatus = TxSupport.toTxStatus(content);
String responseStatus = null;
if (txStatus.isPrepare()) {
responseStatus = TxStatus.TransactionPrepared.name();
} else if (txStatus.isCommit()) {
responseStatus = TxStatus.TransactionCommitted.name();
} else if (txStatus.isCommitOnePhase()) {
responseStatus = TxStatus.TransactionCommittedOnePhase.name();
} else if (txStatus.isAbort()) {
responseStatus = TxStatus.TransactionRolledBack.name();
}
if (responseStatus == null) {
return Response.status(HttpURLConnection.HTTP_BAD_REQUEST).build();
} else {
return Response.ok(TxSupport.toStatusContent(responseStatus)).build();
}
}
@GET
@Path(INVOCATIONS_URL_SEGMENT)
@Produces(MediaType.APPLICATION_JSON)
public String getInvocations() {
if (LOG.isTraceEnabled()) {
LOG.trace("LoggingRestATResource.getInvocations()");
}
return Json.createArrayBuilder(invocations).build().toString();
}
@PUT
@Path(INVOCATIONS_URL_SEGMENT)
public Response resetInvocations() {
if (LOG.isTraceEnabled()) {
LOG.trace("LoggingRestATResource.resetInvocations()");
}
invocations.clear();
return Response.ok().build();
}
}
| 4,902 | 30.632258 | 120 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/common/WorkRestATResource.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts.common;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HEAD;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.jboss.jbossts.star.provider.HttpResponseException;
import org.jboss.jbossts.star.util.TxLinkNames;
import org.jboss.jbossts.star.util.TxMediaType;
import org.jboss.jbossts.star.util.TxStatus;
import org.jboss.jbossts.star.util.TxStatusMediaType;
import org.jboss.jbossts.star.util.TxSupport;
@Path(WorkRestATResource.PATH_SEGMENT)
public final class WorkRestATResource {
public static final String PATH_SEGMENT = "txresource";
private static int pid = 0;
private static Map<String, Work> faults = new HashMap<String, Work>();
public static void clearFaults() {
faults.clear();
}
@GET
public String getBasic(@Context UriInfo info, @QueryParam("pId") @DefaultValue("") String pId,
@QueryParam("context") @DefaultValue("") String ctx, @QueryParam("name") @DefaultValue("") String name,
@QueryParam("value") @DefaultValue("") String value, @QueryParam("query") @DefaultValue("pUrl") String query,
@QueryParam("arg") @DefaultValue("") String arg,
@QueryParam("twoPhaseAware") @DefaultValue("true") String twoPhaseAware,
@QueryParam("isVolatile") @DefaultValue("false") String isVolatileParticipant,
@QueryParam("register") @DefaultValue("true") String register) {
Work work = faults.get(pId);
String res = null;
boolean isVolatile = "true".equals(isVolatileParticipant);
boolean isTwoPhaseAware = "true".equals(twoPhaseAware);
if (name.length() != 0) {
if (value.length() != 0) {
if (work == null) {
work = makeWork(new TxSupport(), info.getAbsolutePath().toString(), String.valueOf(++pid), null, null,
isTwoPhaseAware, isVolatile, null, null);
work.oldState.put(name, value);
faults.put(work.id, work);
return work.id;
}
work.newState.put(name, value);
}
if (work != null) {
if ("syncCount".equals(name))
res = String.valueOf(work.syncCount);
else if ("commitCnt".equals(name))
res = String.valueOf(work.commitCnt);
else if ("prepareCnt".equals(name))
res = String.valueOf(work.prepareCnt);
else if ("rollbackCnt".equals(name))
res = String.valueOf(work.rollbackCnt);
else if ("commmitOnePhaseCnt".equals(name))
res = String.valueOf(work.commmitOnePhaseCnt);
else if (work.inTxn())
res = work.newState.get(name);
else
res = work.oldState.get(name);
}
}
if (work == null)
throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
if ("move".equals(query)) {
/* Ignore*/
}else if ("recoveryUrl".equals(query))
res = work.recoveryUrl;
else if ("status".equals(query))
res = work.status;
else if (res == null)
res = work.pLinks;
return res; // null will generate a 204 status code (no content)
}
@POST
@Produces(TxMediaType.PLAIN_MEDIA_TYPE)
public String enlist(@Context UriInfo info, @QueryParam("pId") @DefaultValue("") String pId,
@QueryParam("fault") @DefaultValue("") String fault,
@QueryParam("twoPhaseAware") @DefaultValue("true") String twoPhaseAware,
@QueryParam("isVolatile") @DefaultValue("false") String isVolatile, String enlistUrl) throws IOException {
Work work = faults.get(pId);
TxSupport txn = new TxSupport();
String txId = enlistUrl.substring(enlistUrl.lastIndexOf('/') + 1);
boolean isTwoPhaseAware = "true".equals(twoPhaseAware);
boolean isVolatileParticipant = "true".equals(isVolatile);
String vRegistration = null; // URI for registering with the volatile phase
String vParticipantLink = null; // URI for handling pre and post 2PC phases
if (work == null) {
int id = ++pid;
work = makeWork(txn, info.getAbsolutePath().toString(), String.valueOf(id), txId, enlistUrl, isTwoPhaseAware,
isVolatileParticipant, null, fault);
} else {
Work newWork = makeWork(txn, info.getAbsolutePath().toString(), work.id, txId, enlistUrl, isTwoPhaseAware,
isVolatileParticipant, null, fault);
newWork.oldState = work.oldState;
newWork.newState = work.newState;
work = newWork;
}
if (enlistUrl.indexOf(',') != -1) {
String[] urls = enlistUrl.split(",");
if (urls.length < 2)
throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
enlistUrl = urls[0];
vRegistration = urls[1];
String vParticipant = new StringBuilder(info.getAbsolutePath().toString()).append('/').append(work.id).append('/')
.append(txId).append('/').append("vp").toString();
vParticipantLink = txn.addLink2(new StringBuilder(), TxLinkNames.VOLATILE_PARTICIPANT, vParticipant, true)
.toString();
}
try {
// enlist TestResource in the transaction as a participant
work.recoveryUrl = txn.enlistParticipant(enlistUrl, work.pLinks);
if (vParticipantLink != null)
txn.enlistVolatileParticipant(vRegistration, vParticipantLink);
} catch (HttpResponseException e) {
throw new WebApplicationException(e.getActualResponse());
}
work.status = TxStatus.TransactionActive.name();
work.start();
faults.put(work.id, work);
return work.id;
}
@PUT
@Path("{pId}/{tId}/vp")
public Response directSynchronizations(@PathParam("pId") @DefaultValue("") String pId,
@PathParam("tId") @DefaultValue("") String tId, String content) {
return synchronizations(pId, tId, content);
}
@PUT
@Path("{pId}/{tId}/volatile-participant")
public Response synchronizations(@PathParam("pId") @DefaultValue("") String pId,
@PathParam("tId") @DefaultValue("") String tId, String content) {
Work work = faults.get(pId);
TxStatus txStatus;
int vStatus;
if (work == null)
return Response.ok().build();
txStatus = content != null ? TxStatus.fromStatus(content) : TxStatus.TransactionStatusUnknown;
vStatus = txStatus.equals(TxStatus.TransactionStatusUnknown) ? 1 : 2;
if (vStatus == 2 && work.vStatus == 0) {
// afterCompletion but coordinator never called beforeCompletion
return Response.status(HttpURLConnection.HTTP_BAD_REQUEST).build();
}
work.vStatus = vStatus;
work.syncCount += 1;
if (vStatus == 1 && "V_PREPARE".equals(work.fault))
return Response.status(HttpURLConnection.HTTP_CONFLICT).build();
else if (vStatus == 2 && "V_COMMIT".equals(work.fault))
return Response.status(HttpURLConnection.HTTP_CONFLICT).build();
return Response.ok().build();
}
@PUT
@Path("{pId}/{tId}/terminator")
public Response terminate(@PathParam("pId") @DefaultValue("") String pId, @PathParam("tId") @DefaultValue("") String tId,
String content) {
TxStatus status = TxSupport.toTxStatus(content);
// String status = TxSupport.getStatus(content);
Work work = faults.get(pId);
if (work == null)
return Response.status(HttpURLConnection.HTTP_NOT_FOUND).build();
String fault = work.fault;
if (status.isPrepare()) {
if ("READONLY".equals(fault)) {
// faults.remove(pId);
work.status = TxStatus.TransactionReadOnly.name();
} else if ("PREPARE_FAIL".equals(fault)) {
// faults.remove(pId);
return Response.status(HttpURLConnection.HTTP_CONFLICT).build();
// throw new WebApplicationException(HttpURLConnection.HTTP_CONFLICT);
} else {
if ("PDELAY".equals(fault)) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
work.status = TxStatus.TransactionPrepared.name();
}
} else if (status.isCommit() || status.isCommitOnePhase()) {
if ("H_HAZARD".equals(fault))
work.status = TxStatus.TransactionHeuristicHazard.name();
else if ("H_ROLLBACK".equals(fault))
work.status = TxStatus.TransactionHeuristicRollback.name();
else if ("H_MIXED".equals(fault))
work.status = TxStatus.TransactionHeuristicMixed.name();
else {
if ("CDELAY".equals(fault)) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// ok
}
}
work.status = status.isCommitOnePhase() ? TxStatus.TransactionCommittedOnePhase.name()
: TxStatus.TransactionCommitted.name();
work.end(true);
}
} else if (status.isAbort()) {
if ("H_HAZARD".equals(fault))
work.status = TxStatus.TransactionHeuristicHazard.name();
else if ("H_COMMIT".equals(fault))
work.status = TxStatus.TransactionHeuristicCommit.name();
else if ("H_MIXED".equals(fault))
work.status = TxStatus.TransactionHeuristicMixed.name();
else {
if ("ADELAY".equals(fault)) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// ok
}
}
work.status = TxStatus.TransactionRolledBack.name();
work.end(false);
// faults.remove(pId);
}
} else {
return Response.status(HttpURLConnection.HTTP_BAD_REQUEST).build();
// throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
}
// return TxSupport.toStatusContent(work.status);
return Response.ok(TxSupport.toStatusContent(work.status)).build();
}
@PUT
@Path("{pId}/{tId}/prepare")
public Response prepare(@PathParam("pId") @DefaultValue("") String pId, @PathParam("tId") @DefaultValue("") String tId,
String content) {
Work work = faults.get(pId);
if (work != null)
work.prepareCnt += 1;
return terminate(pId, tId, TxStatusMediaType.TX_PREPARED);
}
@PUT
@Path("{pId}/{tId}/commit")
public Response commit(@PathParam("pId") @DefaultValue("") String pId, @PathParam("tId") @DefaultValue("") String tId,
String content) {
Work work = faults.get(pId);
if (work != null)
work.commitCnt += 1;
return terminate(pId, tId, TxStatusMediaType.TX_COMMITTED);
}
@PUT
@Path("{pId}/{tId}/rollback")
public Response rollback(@PathParam("pId") @DefaultValue("") String pId, @PathParam("tId") @DefaultValue("") String tId,
String content) {
Work work = faults.get(pId);
if (work != null)
work.rollbackCnt += 1;
return terminate(pId, tId, TxStatusMediaType.TX_ROLLEDBACK);
}
@PUT
@Path("{pId}/{tId}/commit-one-phase")
public Response commmitOnePhase(@PathParam("pId") @DefaultValue("") String pId,
@PathParam("tId") @DefaultValue("") String tId, String content) {
Work work = faults.get(pId);
if (work != null)
work.commmitOnePhaseCnt += 1;
return terminate(pId, tId, TxStatusMediaType.TX_COMMITTED_ONE_PHASE);
}
@HEAD
@Path("{pId}/{tId}/participant")
public Response getTerminator(@Context UriInfo info, @PathParam("pId") @DefaultValue("") String pId,
@PathParam("tId") @DefaultValue("") String tId) {
Work work = faults.get(pId);
if (work == null)
return Response.status(HttpURLConnection.HTTP_BAD_REQUEST).build();
Response.ResponseBuilder builder = Response.ok();
builder.header("Link", work.pLinks);
return builder.build();
}
@GET
@Path("{pId}/{tId}/participant")
public String getStatus(@PathParam("pId") @DefaultValue("") String pId, @PathParam("tId") @DefaultValue("") String tId) {
Work work = faults.get(pId);
if (work == null)
throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
return TxSupport.toStatusContent(work.status);
}
@DELETE
@Path("{pId}/{tId}/participant")
public void forgetWork(@PathParam("pId") String pId, @PathParam("tId") String tId) {
Work work = faults.get(pId);
if (work == null)
throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
faults.remove(pId);
}
public Work makeWork(TxSupport txn, String baseURI, String id, String txId, String enlistUrl, boolean twoPhaseAware,
boolean isVolatile, String recoveryUrl, String fault) {
String linkHeader = twoPhaseAware ? txn.makeTwoPhaseAwareParticipantLinkHeader(baseURI, isVolatile, id, txId) : txn
.makeTwoPhaseUnAwareParticipantLinkHeader(baseURI, isVolatile, id, txId, true);
return new Work(id, txId, baseURI + '/' + id, linkHeader, enlistUrl, recoveryUrl, fault);
}
}
| 15,469 | 37.675 | 126 |
java
|
null |
wildfly-main/testsuite/integration/rts/src/test/java/org/wildfly/test/extension/rts/common/InboundBridgeResourceEjb.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2020, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.test.extension.rts.common;
import org.jboss.logging.Logger;
import jakarta.annotation.Resource;
import jakarta.ejb.Stateless;
import jakarta.json.Json;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path(InboundBridgeResourceEjb.URL_SEGMENT)
@Stateless
public class InboundBridgeResourceEjb {
private static final Logger LOG = Logger.getLogger(LoggingRestATResource.class);
public static final String URL_SEGMENT = "inbound-bridge-resource-ejb";
private static LoggingXAResource loggingXAResource;
@Resource(lookup = "java:/TransactionManager")
jakarta.transaction.TransactionManager transactionManager;
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getInvocations() {
LOG.tracef("getInvocations() for resource '%s'", loggingXAResource);
if (loggingXAResource == null) {
throw new WebApplicationException(409);
}
return Json.createArrayBuilder(loggingXAResource.getInvocations()).build().toString();
}
@POST
public Response enlistXAResource() {
LOG.tracef("enlistXAResource() of resource '%s'", loggingXAResource);
try {
loggingXAResource = new LoggingXAResource();
transactionManager.getTransaction().enlistResource(loggingXAResource);
} catch (Exception e) {
LOG.warnf(e, "Cannot enlist XAResource '%s'", loggingXAResource);
return Response.serverError().build();
}
return Response.ok().build();
}
@PUT
public Response resetXAResource() {
LOG.tracef("resetXAResource() of resource", loggingXAResource);
if (loggingXAResource != null) {
loggingXAResource.resetInvocations();
}
return Response.ok().build();
}
}
| 3,025 | 34.186047 | 94 |
java
|
null |
wildfly-main/testsuite/integration/rbac/src/test/java/org/jboss/as/test/integration/mgmt/access/ReadFullModelTestCase.java
|
/*
* Copyright 2023 JBoss by Red Hat.
*
* 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.jboss.as.test.integration.mgmt.access;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.USERNAME;
import static org.jboss.as.test.integration.management.rbac.RbacUtil.ADMINISTRATOR_USER;
import static org.jboss.as.test.integration.management.rbac.RbacUtil.AUDITOR_USER;
import static org.jboss.as.test.integration.management.rbac.RbacUtil.DEPLOYER_USER;
import static org.jboss.as.test.integration.management.rbac.RbacUtil.MAINTAINER_USER;
import static org.jboss.as.test.integration.management.rbac.RbacUtil.MONITOR_USER;
import static org.jboss.as.test.integration.management.rbac.RbacUtil.OPERATOR_USER;
import static org.jboss.as.test.integration.management.rbac.RbacUtil.SUPERUSER_USER;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.test.integration.management.rbac.Outcome;
import org.jboss.as.test.integration.management.rbac.RbacUtil;
import org.jboss.dmr.ModelNode;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author Emmanuel Hugonnet (c) 2022 Red Hat, Inc.
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ReadFullModelTestCase extends AbstractRbacTestCase {
@Test
public void testMonitor() throws Exception {
ModelControllerClient client = getClientForUser(MONITOR_USER);
whoami(client, MONITOR_USER);
readWholeConfig(client, Outcome.SUCCESS);
}
@Test
public void testOperator() throws Exception {
ModelControllerClient client = getClientForUser(OPERATOR_USER);
whoami(client, OPERATOR_USER);
readWholeConfig(client, Outcome.SUCCESS);
}
@Test
public void testMaintainer() throws Exception {
ModelControllerClient client = getClientForUser(MAINTAINER_USER);
whoami(client, MAINTAINER_USER);
readWholeConfig(client, Outcome.SUCCESS);
}
@Test
public void testDeployer() throws Exception {
ModelControllerClient client = getClientForUser(DEPLOYER_USER);
whoami(client, DEPLOYER_USER);
readWholeConfig(client, Outcome.SUCCESS);
}
@Test
public void testAdministrator() throws Exception {
ModelControllerClient client = getClientForUser(ADMINISTRATOR_USER);
whoami(client, ADMINISTRATOR_USER);
readWholeConfig(client, Outcome.SUCCESS);
}
@Test
public void testAuditor() throws Exception {
ModelControllerClient client = getClientForUser(AUDITOR_USER);
whoami(client, AUDITOR_USER);
readWholeConfig(client, Outcome.SUCCESS);
}
@Test
public void testSuperUser() throws Exception {
ModelControllerClient client = getClientForUser(SUPERUSER_USER);
whoami(client, SUPERUSER_USER);
readWholeConfig(client, Outcome.SUCCESS);
}
private static void whoami(ModelControllerClient client, String expectedUsername) throws IOException {
ModelNode op = createOpNode(null, "whoami");
op.get("verbose").set(true);
ModelNode result = RbacUtil.executeOperation(client, op, Outcome.SUCCESS);
System.out.println("whomai " + result);
String returnedUsername = result.get(RESULT, "identity", USERNAME).asString();
assertEquals(expectedUsername, returnedUsername);
}
private void readWholeConfig(ModelControllerClient client, Outcome expectedOutcome) throws IOException {
ModelNode op = createOpNode("/", READ_RESOURCE_OPERATION);
op.get("include-runtime").set(true);
op.get("recursive").set(true);
RbacUtil.executeOperation(client, op, expectedOutcome);
}
}
| 4,658 | 39.513043 | 108 |
java
|
null |
wildfly-main/testsuite/integration/rbac/src/test/java/org/jboss/as/test/integration/mgmt/access/CustomLoadableExtension.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.mgmt.access;
import org.jboss.arquillian.core.spi.LoadableExtension;
/**
* Custom arquillian extension to allow us register notifications about server lifecycle.
*/
public class CustomLoadableExtension implements LoadableExtension {
@Override
public void register(ExtensionBuilder builder) {
builder.observer(ServerLifecycleObserver.class);
}
}
| 1,432 | 37.72973 | 89 |
java
|
null |
wildfly-main/testsuite/integration/rbac/src/test/java/org/jboss/as/test/integration/mgmt/access/ServerLifecycleObserver.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.mgmt.access;
import java.io.IOException;
import org.jboss.arquillian.container.spi.event.container.AfterStop;
import org.jboss.arquillian.container.spi.event.container.BeforeStart;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.as.test.module.util.TestModule;
import org.wildfly.test.installationmanager.TestInstallationManager;
import org.wildfly.test.installationmanager.TestInstallationManagerFactory;
/**
* Observers container lifecycle events to prepare the server with an test implementation of an installation manager.
*/
public class ServerLifecycleObserver {
private static final String MODULE_NAME = "org.jboss.prospero";
private TestModule testModule;
public void containerBeforeStart(@Observes BeforeStart event) throws IOException {
createTestModule();
}
public void containerAfterStop(@Observes AfterStop event) throws IOException {
testModule.remove();
}
private void createTestModule() throws IOException {
testModule = new TestModule(MODULE_NAME, "org.wildfly.installation-manager.api");
testModule.addResource("test-mock-installation-manager.jar").addClass(TestInstallationManager.class)
.addClass(TestInstallationManagerFactory.class)
.addAsManifestResource("META-INF/services/org.wildfly.installationmanager.spi.InstallationManagerFactory",
"services/org.wildfly.installationmanager.spi.InstallationManagerFactory");
testModule.create(true);
}
}
| 2,593 | 42.966102 | 122 |
java
|
null |
wildfly-main/testsuite/integration/rbac/src/test/java/org/jboss/as/test/integration/mgmt/access/AccessConstraintUtilizationTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.mgmt.access;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATIONS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_RESOURCES_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import java.io.IOException;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.access.management.AccessConstraintKey;
import org.jboss.as.controller.access.management.ApplicationTypeAccessConstraintDefinition;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.management.rbac.Outcome;
import org.jboss.as.test.integration.management.rbac.RbacUtil;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.Property;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test of the access constraint utilization resources.
*
* @author Brian Stansberry (c) 2013 Red Hat Inc.
*/
@RunWith(Arquillian.class)
@RunAsClient
public class AccessConstraintUtilizationTestCase extends AbstractRbacTestCase {
private static class ExpectedDef {
private final AccessConstraintKey key;
private final boolean expectResource;
private final boolean expectAttributes;
private final boolean expectOps;
private ExpectedDef(AccessConstraintKey key, boolean expectResource, boolean expectAttributes, boolean expectOps) {
this.key = key;
this.expectResource = expectResource;
this.expectAttributes = expectAttributes;
this.expectOps = expectOps;
}
}
private static final String ADDR_FORMAT =
"core-service=management/access=authorization/constraint=%s/type=%s/classification=%s";
private static final ExpectedDef[] EXPECTED_DEFS = {
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.ACCESS_CONTROL.getKey(), true, true, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.CREDENTIAL.getKey(), false, true, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.EXTENSIONS.getKey(), true, false, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.MANAGEMENT_INTERFACES.getKey(), true, false, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.MODULE_LOADING.getKey(), true, false, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.PATCHING.getKey(), true, false, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.READ_WHOLE_CONFIG.getKey(), false, false, true),
//new ExpectedDef(SensitiveTargetAccessConstraintDefinition.SECURITY_DOMAIN.getKey(), true, false, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.SECURITY_DOMAIN_REF.getKey(), false, true, false),
//new ExpectedDef(SensitiveTargetAccessConstraintDefinition.SECURITY_REALM.getKey(), true, false, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.SECURITY_REALM_REF.getKey(), false, true, false),
//new ExpectedDef(SensitiveTargetAccessConstraintDefinition.SECURITY_VAULT.getKey(), true, false, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.SERVICE_CONTAINER.getKey(), true, false, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF.getKey(), false, true, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.SOCKET_CONFIG.getKey(), true, true, true),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.SNAPSHOTS.getKey(), false, false, true),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.SYSTEM_PROPERTY.getKey(), true, true, true),
// A few subsystem ones
new ExpectedDef(getSensKey("undertow", "web-access-log"), true, false, false),
new ExpectedDef(getSensKey("datasources", "data-source-security"), false, true, false),
new ExpectedDef(getSensKey("resource-adapters", "resource-adapter-security"), false, true, false),
new ExpectedDef(getSensKey("jdr", "jdr"), false, false, true),
new ExpectedDef(getSensKey("messaging-activemq", "messaging-management"), false, true, false),
/* N/A on standalone
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.DOMAIN_CONTROLLER, false, true, true),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.DOMAIN_NAMES, false, true, false),
new ExpectedDef(SensitiveTargetAccessConstraintDefinition.JVM, false, true, true),
*/
new ExpectedDef(ApplicationTypeAccessConstraintDefinition.DEPLOYMENT.getKey(), true, false, true),
new ExpectedDef(getAppKey("datasources", "data-source"), true, false, false),
new ExpectedDef(getAppKey("datasources", "xa-data-source"), true, false, false),
new ExpectedDef(getAppKey("datasources", "jdbc-driver"), true, false, false),
new ExpectedDef(getAppKey("messaging-activemq", "queue"), true, false, false),
new ExpectedDef(getAppKey("messaging-activemq", "jms-queue"), true, false, false),
new ExpectedDef(getAppKey("messaging-activemq", "jms-topic"), true, false, false),
// Agroal
new ExpectedDef(getAppKey("datasources-agroal", "datasource"), true, false, false),
new ExpectedDef(getAppKey("datasources-agroal", "xa-datasource"), true, false, false),
new ExpectedDef(getAppKey("datasources-agroal", "driver"), true, false, false)
};
@ContainerResource
private ManagementClient managementClient;
@Before
public void addAgroal() throws IOException {
ModelNode addOp = Util.createAddOperation(PathAddress.pathAddress(EXTENSION, "org.wildfly.extension.datasources-agroal"));
ModelNode response = managementClient.getControllerClient().execute(addOp);
Assert.assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());
}
@After
public void removeAgroal() throws IOException {
ModelNode removeOp = Util.createRemoveOperation(PathAddress.pathAddress(EXTENSION, "org.wildfly.extension.datasources-agroal"));
ModelNode response = managementClient.getControllerClient().execute(removeOp);
Assert.assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());
}
@Test
public void testConstraintUtilization() throws Exception {
ModelControllerClient client = managementClient.getControllerClient();
for (ExpectedDef expectedDef : EXPECTED_DEFS) {
AccessConstraintKey acdKey = expectedDef.key;
String constraint = ModelDescriptionConstants.SENSITIVE.equals(acdKey.getType())
? ModelDescriptionConstants.SENSITIVITY_CLASSIFICATION
: ModelDescriptionConstants.APPLICATION_CLASSIFICATION;
String acdType = acdKey.isCore() ? "core" : acdKey.getSubsystemName();
String path = String.format(ADDR_FORMAT, acdKey.getType(), acdType, acdKey.getName());
ModelNode op = createOpNode(path, READ_CHILDREN_RESOURCES_OPERATION);
op.get(ModelDescriptionConstants.CHILD_TYPE).set(ModelDescriptionConstants.APPLIES_TO);
//System.out.println("Testing " + acdKey);
ModelNode result = RbacUtil.executeOperation(client, op, Outcome.SUCCESS).get(ModelDescriptionConstants.RESULT);
Assert.assertTrue(acdKey + "result is defined", result.isDefined());
Assert.assertTrue(acdKey + "result has content", result.asInt() > 0);
boolean foundResource = false;
boolean foundAttr = false;
boolean foundOps = false;
for (Property prop : result.asPropertyList()) {
ModelNode pathResult = prop.getValue();
if (pathResult.get(ModelDescriptionConstants.ENTIRE_RESOURCE).asBoolean()) {
Assert.assertTrue(acdKey + " -- " + prop.getName() + " resource", expectedDef.expectResource);
foundResource = true;
}
ModelNode attrs = pathResult.get(ATTRIBUTES);
if (attrs.isDefined() && attrs.asInt() > 0) {
Assert.assertTrue(acdKey + " -- " + prop.getName() + " attributes = " + attrs.asString(), expectedDef.expectAttributes);
foundAttr = true;
}
ModelNode ops = pathResult.get(OPERATIONS);
if (ops.isDefined() && ops.asInt() > 0) {
Assert.assertTrue(acdKey + " -- " + prop.getName() + " operations = " + ops.asString(), expectedDef.expectOps);
foundOps = true;
}
}
Assert.assertEquals(acdKey + " -- resource", expectedDef.expectResource, foundResource);
Assert.assertEquals(acdKey + " -- attributes", expectedDef.expectAttributes, foundAttr);
Assert.assertEquals(acdKey + " -- operations", expectedDef.expectOps, foundOps);
}
}
private static AccessConstraintKey getAppKey(String subsystemName, String name) {
return new AccessConstraintKey(ModelDescriptionConstants.APPLICATION_CLASSIFICATION, false, subsystemName, name);
}
private static AccessConstraintKey getSensKey(String subsystemName, String name) {
return new AccessConstraintKey(ModelDescriptionConstants.SENSITIVITY_CLASSIFICATION, false, subsystemName, name);
}
}
| 11,363 | 58.1875 | 140 |
java
|
null |
wildfly-main/testsuite/integration/rbac/src/test/java/org/jboss/as/test/integration/mgmt/access/PermissionsCoverageTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.mgmt.access;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.test.integration.management.rbac.PermissionsCoverageTestUtil.assertTheEntireDomainTreeHasPermissionsDefined;
import java.io.IOException;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Ladislav Thon <[email protected]>
*/
@RunWith(Arquillian.class)
public class PermissionsCoverageTestCase {
@ContainerResource
private ManagementClient managementClient;
@Before
public void addAgroal() throws IOException {
ModelNode addOp = Util.createAddOperation(PathAddress.pathAddress(EXTENSION, "org.wildfly.extension.datasources-agroal"));
ModelNode response = managementClient.getControllerClient().execute(addOp);
Assert.assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());
}
@After
public void removeAgroal() throws IOException {
ModelNode removeOp = Util.createRemoveOperation(PathAddress.pathAddress(EXTENSION, "org.wildfly.extension.datasources-agroal"));
ModelNode response = managementClient.getControllerClient().execute(removeOp);
Assert.assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());
}
@Test
public void testTheEntireDomainTreeHasPermissionsDefined() throws Exception {
ModelControllerClient client = managementClient.getControllerClient();
assertTheEntireDomainTreeHasPermissionsDefined(client);
}
}
| 3,183 | 42.616438 | 136 |
java
|
null |
wildfly-main/testsuite/integration/rbac/src/test/java/org/jboss/as/test/integration/mgmt/access/AbstractRbacTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.mgmt.access;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.ModelControllerClientConfiguration;
import org.jboss.as.test.integration.management.rbac.RbacAdminCallbackHandler;
import org.junit.AfterClass;
/**
* Base class for RBAC tests.
*
* @author Brian Stansberry (c) 2013 Red Hat Inc.
*/
public class AbstractRbacTestCase {
private static final Map<String, ModelControllerClient> clients = new HashMap<String, ModelControllerClient>();
private static final Map<String, String> SASL_OPTIONS = Collections.singletonMap("SASL_DISALLOWED_MECHANISMS", "JBOSS-LOCAL-USER");
@AfterClass
public static void cleanUpClients() {
for (ModelControllerClient client : clients.values()) {
try {
client.close();
} catch (Exception e) {
}
}
clients.clear();
}
@ContainerResource
private ManagementClient managementClient;
public ModelControllerClient getClientForUser(String userName) throws UnknownHostException {
ModelControllerClient result = clients.get(userName);
if (result == null) {
result = createClient(userName);
clients.put(userName, result);
}
return result;
}
private ModelControllerClient createClient(String userName) {
return ModelControllerClient.Factory.create(
new ModelControllerClientConfiguration.Builder()
.setHandler(new RbacAdminCallbackHandler(userName))
.setProtocol(managementClient.getMgmtProtocol())
.setHostName(managementClient.getMgmtAddress())
.setPort(managementClient.getMgmtPort())
.setSaslOptions(SASL_OPTIONS)
.build());
}
public static void removeClientForUser(String userName) throws IOException {
ModelControllerClient client = clients.remove(userName);
if (client != null) {
client.close();
}
}
protected ManagementClient getManagementClient() {
return managementClient;
}
}
| 3,499 | 34.714286 | 135 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/TestBase.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.wildfly.test.integration.vdx.utils.server.ServerBase;
import org.wildfly.test.integration.vdx.utils.server.Server;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Do not inherit from this class as it's common for standalone and domain tests! For standalone tests inherit from
*/
public class TestBase {
public static final String STANDALONE_ARQUILLIAN_CONTAINER = "jboss";
public static final String DOMAIN_ARQUILLIAN_CONTAINER = "jboss-domain";
static final Logger log = Logger.getLogger(TestBase.class);
@ArquillianResource private ContainerController controller;
@Rule public TestName testName = new TestName();
/*
* Path to root directory where server.log and xml configuration for each test is archived
*/
private Path testArchiveDirectory;
public Server container() {
return ServerBase.getOrCreateServer(controller);
}
@Before public void setUp() throws Exception {
log.debug("----------------------------------------- Start " +
this.getClass().getSimpleName() + " - " + testName.getMethodName() + " -----------------------------------------");
testArchiveDirectory = Paths.get("target", "test-output", this.getClass().getSimpleName(), testName.getMethodName());
createAndSetTestArchiveDirectoryToContainer(testArchiveDirectory);
}
@After public void tearDown() throws Exception {
log.debug("----------------------------------------- Stop " +
this.getClass().getSimpleName() + " - " + testName.getMethodName() + " -----------------------------------------");
archiveServerLogAndDeleteIt(testArchiveDirectory);
}
protected static void assertContains(String errorMessages, String expectedMessage) {
assertTrue("log doesn't contain '" + expectedMessage + "'", errorMessages.contains(expectedMessage));
}
protected static void assertDoesNotContain(String errorMessages, String expectedMessage) {
assertFalse("log contains '" + expectedMessage + "'", errorMessages.contains(expectedMessage));
}
private void archiveServerLogAndDeleteIt(Path pathToArchiveDirectory) throws Exception {
// if no log then return
if (Files.notExists(container().getServerLogPath())) {
return;
}
// copy server.log files for standalone or host-controller.log for domain
Files.copy(container().getServerLogPath(), pathToArchiveDirectory.resolve(container().getServerLogPath().getFileName()), StandardCopyOption.REPLACE_EXISTING);
Files.delete(container().getServerLogPath());
}
private void createAndSetTestArchiveDirectoryToContainer(Path testArchiveDirectory) throws Exception {
// create directory with name of the test in target directory
if (Files.notExists(testArchiveDirectory)) {
Files.createDirectories(testArchiveDirectory);
}
container().setTestArchiveDirectory(testArchiveDirectory);
}
}
| 4,107 | 39.27451 | 166 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/transformations/DoNothing.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.transformations;
/**
* Created by mnovak on 10/26/16.
*/
public class DoNothing {
}
| 762 | 27.259259 | 75 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/standalone/MissingClosingTagTestCase.java
|
/*
* Copyright 2017 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.standalone;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.StandaloneTests;
import org.wildfly.test.integration.vdx.utils.server.Server;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.util.Scanner;
/**
* Tests for missing closing tag in configuration files
*
* Created by rsvoboda on 1/20/17.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(StandaloneTests.class)
public class MissingClosingTagTestCase extends TestBase {
private static final Path standaloneXml = Server.CONFIGURATION_PATH.resolve("standalone.xml");
private static final String STANDALONE_MISSING_CLOSING_TAG_XML = "standalone-missingClosingTag.xml";
private static final String STANDALONE_COMMENT_IS_NOT_CLOSED_XML = "standalone-commentIsNotClosed.xml";
private static final String STANDALONE_NOT_EXPECTED_CLOSING_TAG_XML = "standalone-notExpectedClosingTag.xml";
private static final Path missingClosingTagStandaloneXml = Server.CONFIGURATION_PATH.resolve(STANDALONE_MISSING_CLOSING_TAG_XML);
private static final Path commentIsNotClosedStandaloneXml = Server.CONFIGURATION_PATH.resolve(STANDALONE_COMMENT_IS_NOT_CLOSED_XML);
private static final Path notExpectedClosingTagStandaloneXml = Server.CONFIGURATION_PATH.resolve(STANDALONE_NOT_EXPECTED_CLOSING_TAG_XML);
private static final String missingClosingTag =
" <subsystem xmlns=\"urn:jboss:domain:webservices:2.0\">\n"
+ " <wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host>\n"
+ " <modify-wsdl-address>true</modify-wsdl-address>\n"
+ " <endpoint-config name=\"Standard-Endpoint-Config\"/>\n"
+ " <endpoint-config name=\"Recording-Endpoint-Config\">\n"
+ " <pre-handler-chain name=\"recording-handlers\" protocol-bindings=\"##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM\">\n"
+ " <handler name=\"RecordingHandler\" class=\"org.jboss.ws.common.invocation.RecordingServerHandler\"/>\n"
+ " </pre-handler-chain>\n"
+ " </endpoint-config>\n"
+ " <client-config name=\"Standard-Client-Config\"/>\n"
// + " </subsystem>"; // <-- missing closing tag
;
private static final String commentIsNotClosed =
" <subsystem xmlns=\"urn:jboss:domain:webservices:2.0\">\n"
+ " <wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host>\n"
+ " <modify-wsdl-address>true</modify-wsdl-address> <!-- some important comment \n" // <-- not closed comment
+ " <endpoint-config name=\"Standard-Endpoint-Config\"/>\n"
+ " <endpoint-config name=\"Recording-Endpoint-Config\">\n"
+ " <pre-handler-chain name=\"recording-handlers\" protocol-bindings=\"##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM\">\n"
+ " <handler name=\"RecordingHandler\" class=\"org.jboss.ws.common.invocation.RecordingServerHandler\"/>\n"
+ " </pre-handler-chain>\n"
+ " </endpoint-config>\n"
+ " <client-config name=\"Standard-Client-Config\"/>\n"
+ " </subsystem>";
private static final String notExpectedClosingTag =
" <subsystem xmlns=\"urn:jboss:domain:webservices:2.0\" />\n" // <-- closing tag / is here
+ " <wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host>\n"
+ " <modify-wsdl-address>true</modify-wsdl-address>\n"
+ " <endpoint-config name=\"Standard-Endpoint-Config\"/>\n"
+ " <endpoint-config name=\"Recording-Endpoint-Config\">\n"
+ " <pre-handler-chain name=\"recording-handlers\" protocol-bindings=\"##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM\">\n"
+ " <handler name=\"RecordingHandler\" class=\"org.jboss.ws.common.invocation.RecordingServerHandler\"/>\n"
+ " </pre-handler-chain>\n"
+ " </endpoint-config>\n"
+ " <client-config name=\"Standard-Client-Config\"/>\n"
+ " </subsystem>";
@BeforeClass
public static void prepareBrokenConfiguration() throws IOException {
try (Scanner scanner = new Scanner(standaloneXml);
PrintWriter missingClosingTagStandaloneXmlPrintWriter = new PrintWriter(missingClosingTagStandaloneXml.toFile());
PrintWriter commentIsNotClosedStandaloneXmlPrintWriter = new PrintWriter(commentIsNotClosedStandaloneXml.toFile());
PrintWriter notExpectedClosingTagStandaloneXmlPrintWriter = new PrintWriter(notExpectedClosingTagStandaloneXml.toFile())) {
boolean inWSSubsystem = false;
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.contains("<subsystem xmlns=\"urn:jboss:domain:webservices")) {
inWSSubsystem = true;
} else if (!inWSSubsystem) {
missingClosingTagStandaloneXmlPrintWriter.println(line);
commentIsNotClosedStandaloneXmlPrintWriter.println(line);
notExpectedClosingTagStandaloneXmlPrintWriter.println(line);
} else if (line.contains("</subsystem>")) {
missingClosingTagStandaloneXmlPrintWriter.println(missingClosingTag);
commentIsNotClosedStandaloneXmlPrintWriter.println(commentIsNotClosed);
notExpectedClosingTagStandaloneXmlPrintWriter.println(notExpectedClosingTag);
inWSSubsystem = false;
}
}
}
}
/*
* There is missing closing tag (for example </subsystem> tag is missing)
*/
@Test
@ServerConfig(configuration = STANDALONE_MISSING_CLOSING_TAG_XML)
public void missingClosingTag()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "XMLStreamException:");
assertContains(errorLog, "WFLYCTL0198: Unexpected element '{urn:jboss:domain:weld:");
assertContains(errorLog, "WFLYCTL0085: Failed to parse configuration");
}
/*
* Comments - what happens if there is missing closing --> in <!-- comment here -->
*/
@Test
@ServerConfig(configuration = STANDALONE_COMMENT_IS_NOT_CLOSED_XML)
public void commentIsNotClosed()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in " + STANDALONE_COMMENT_IS_NOT_CLOSED_XML);
if (errorLog.contains("input block")) {
// Apache JAXP impl
assertContains(errorLog, "^^^^ Unexpected end of input block in comment");
} else {
// JDK JAXP impl
assertContains(errorLog, "^^^^ XML document structures must start and end within the same entity");
}
assertContains(errorLog, "WFLYCTL0085: Failed to parse configuration");
}
/*
* Not expected closing tag - for example <subsystem ... /> ... </subsystem>
*/
@Test
@ServerConfig(configuration = STANDALONE_NOT_EXPECTED_CLOSING_TAG_XML)
public void notExpectedClosingTag()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone-notExpectedClosingTag.xml");
assertContains(errorLog, "^^^^ 'wsdl-host' isn't an allowed element here");
assertContains(errorLog, "WFLYCTL0198: Unexpected element");
}
}
| 9,339 | 53.302326 | 177 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/standalone/LoggingTestCase.java
|
/*
* Copyright 2017 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.standalone;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.GroovyXmlTransform;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.Subtree;
import org.wildfly.extras.creaper.core.offline.OfflineCommand;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.StandaloneTests;
import org.wildfly.test.integration.vdx.transformations.DoNothing;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
/**
*
* Created by rsvoboda on 08/24/17.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(StandaloneTests.class)
public class LoggingTestCase extends TestBase {
/*
* Duplicate logger category
*/
@Test
@ServerConfig()
public void duplicateLoggerCategory() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class, "AddElement.groovy")
.subtree("path", Subtree.subsystem("logging")).parameter("elementXml",
" <logger category=\"sun.rmi\">\n" +
" <level name=\"WARN\"/>\n" +
" </logger>")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone.xml");
assertContains(errorLog, "^^^^ 'logger' with a name of 'sun.rmi' can't appear more than once");
assertContains(errorLog, "An element of this type named 'sun.rmi' has");
assertContains(errorLog, "WFLYCTL0073");
}
/*
* No package specified, just empty sting in category attribute
*/
@Test
@ServerConfig()
public void invalidLoggerCategoryValue() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class, "AddElement.groovy")
.subtree("path", Subtree.subsystem("logging")).parameter("elementXml",
" <logger category=\"\">\n" +
" <level name=\"WARN\"/>\n" +
" </logger>")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone.xml");
assertContains(errorLog, "^^^^ '' isn't a valid value for the 'category' attribute");
assertContains(errorLog, "WFLYCTL0106: Invalid value '' for attribute 'category'");
}
/*
* No category attribute specified
*/
@Test
@ServerConfig()
public void noLoggerCategory() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class, "AddElement.groovy")
.subtree("path", Subtree.subsystem("logging")).parameter("elementXml",
" <logger>\n" +
" <level name=\"WARN\"/>\n" +
" </logger>")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "WFLYCTL0133: Missing required attribute(s): CATEGORY");
}
}
| 4,407 | 43.08 | 116 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/standalone/JBossWSStringReplaceTestCase.java
|
package org.wildfly.test.integration.vdx.standalone;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.StandaloneTests;
import org.wildfly.test.integration.vdx.utils.server.Server;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.util.Scanner;
/**
*
* Created by rsvoboda on 12/14/16.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(StandaloneTests.class)
public class JBossWSStringReplaceTestCase extends TestBase {
private static final Path standaloneXml = Server.CONFIGURATION_PATH.resolve("standalone.xml");
private static final Path patchedStandaloneXml = Server.CONFIGURATION_PATH.resolve("standalone-ws-broken.xml");
private static final String brokenWSSubsystemDefinition =
" <subsystem xmlns=\"urn:jboss:domain:webservices:2.0\">\n"
+ " <wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host>\n"
+ " <mmodify-wsdl-address>true</modify-wsdl-address>\n"
+ " <endpoint-config name=\"Standard-Endpoint-Config\"/>\n"
+ " <endpoint-config name=\"Recording-Endpoint-Config\">\n"
+ " <pre-handler-chain name=\"recording-handlers\" protocol-bindings=\"##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM\">\n"
+ " <handler name=\"RecordingHandler\" class=\"org.jboss.ws.common.invocation.RecordingServerHandler\"/>\n"
+ " </pre-handler-chain>\n"
+ " </endpoint-config>\n"
+ " <client-config name=\"Standard-Client-Config\"/>\n"
+ " </subsystem>";
@BeforeClass
public static void prepareBrokenConfiguration() throws IOException {
try (Scanner scanner = new Scanner(standaloneXml);
PrintWriter printWriter = new PrintWriter(patchedStandaloneXml.toFile())) {
boolean inWSSubsystem = false;
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.contains("<subsystem xmlns=\"urn:jboss:domain:webservices")) {
inWSSubsystem = true;
} else if (!inWSSubsystem) {
printWriter.println(line);
} else if (line.contains("</subsystem>")) {
printWriter.println(brokenWSSubsystemDefinition);
inWSSubsystem = false;
}
}
printWriter.flush();
printWriter.close();
}
}
/*
* <mmodify-wsdl-address>true</modify-wsdl-address> instead of <modify-wsdl-address>true</modify-wsdl-address>
*/
@Test
@ServerConfig(configuration = "standalone-ws-broken.xml")
public void incorrectValueOfModifyWsdlAddressOpeningElement()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone-ws-broken.xml");
assertContains(errorLog, "<mmodify-wsdl-address>true</modify-wsdl-address>");
assertContains(errorLog, "^^^^ 'mmodify-wsdl-address' isn't an allowed element here");
assertContains(errorLog, "matching end-tag \"</mmodify-wsdl-address>");
}
}
| 3,702 | 44.158537 | 169 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/standalone/SmokeStandaloneTestCase.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.standalone;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.StandaloneTests;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
import java.nio.file.Files;
/**
* Smoke test case - it tests whether WildFly/EAP test automation is working and basic VDX functionality.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(StandaloneTests.class)
public class SmokeStandaloneTestCase extends TestBase {
@Test
@ServerConfig(configuration = "duplicate-attribute.xml")
public void testWithExistingConfigInResources() throws Exception {
container().tryStartAndWaitForFail();
ensureDuplicateAttribute(container().getErrorMessageFromServerStart());
}
public static void ensureDuplicateAttribute(String errorMessages) {
assertContains(errorMessages, "OPVDX001: Validation error in duplicate-attribute.xml");
assertContains(errorMessages, "<jdbc data-source=\"foo\"");
assertContains(errorMessages, "data-source=\"bar\"/>");
if (errorMessages.contains("first appears")) {
// Apache JAXP impl
assertContains(errorMessages, "^^^^ 'data-source' can't appear more than once on this element");
assertContains(errorMessages, "A 'data-source' attribute first appears here:");
} else {
// JDK JAXP impl
assertContains(errorMessages, "^^^^ http://www.w3.org/TR/1999/REC-xml-names-19990114#AttributeNotUnique?jdbc&data-source");
}
}
@Test
@ServerConfig(configuration = "standalone-full-ha-to-damage.xml", xmlTransformationGroovy = "TypoInExtensions.groovy")
public void typoInExtensionsWithConfigInResources() throws Exception {
container().tryStartAndWaitForFail();
ensureTypoInExtensions(container().getErrorMessageFromServerStart());
}
public static void ensureTypoInExtensions(String errorMessages) {
assertContains(errorMessages, "WFLYCTL0197: Unexpected attribute 'modules' encountered");
}
@Test
@ServerConfig(configuration = "standalone-full-ha.xml", xmlTransformationGroovy = "AddNonExistentElementToMessagingSubsystem.groovy",
subtreeName = "messaging", subsystemName = "messaging-activemq")
public void addNonExistingElementToMessagingSubsystem() throws Exception {
// WildFly Preview doesn't configure a messaging broker
AssumeTestGroupUtil.assumeNotWildFlyPreview();
container().tryStartAndWaitForFail();
ensureNonExistingElementToMessagingSubsystem(container().getErrorMessageFromServerStart());
}
public static void ensureNonExistingElementToMessagingSubsystem(String errorMessages) {
assertContains(errorMessages, "^^^^ 'id' isn't an allowed attribute for the 'cluster' element");
assertContains(errorMessages, "| 'id' is allowed on elements:");
assertContains(errorMessages, "resource-adapters > resource-adapter");
assertContains(errorMessages, "resource-adapters > resource-adapter > module");
}
@Test
@ServerConfig(configuration = "empty.xml")
public void emptyConfigFile() throws Exception {
container().tryStartAndWaitForFail();
assertContains( String.join("\n", Files.readAllLines(container().getServerLogPath())),
"OPVDX004: Failed to pretty print validation error: empty.xml has no content");
}
}
| 4,358 | 45.37234 | 137 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/standalone/InvalidCharactersTestCase.java
|
/*
* Copyright 2017 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.standalone;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.GroovyXmlTransform;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.Subtree;
import org.wildfly.extras.creaper.core.offline.OfflineCommand;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.StandaloneTests;
import org.wildfly.test.integration.vdx.transformations.DoNothing;
import org.wildfly.test.integration.vdx.utils.server.Server;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.util.Scanner;
/**
*
* Tests for invalid characters in configuration files
*
* Created by rsvoboda on 1/18/17.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(StandaloneTests.class)
public class InvalidCharactersTestCase extends TestBase {
private static final Path standaloneXml = Server.CONFIGURATION_PATH.resolve("standalone.xml");
private static final String STANDALONE_MISSING_START_OF_ELEMENT_XML = "standalone-missingStartOfElement.xml";
private static final String STANDALONE_SPACE_IN_XML_DECLARATION_XML = "standalone-spaceInXmlDeclaration.xml";
private static final String STANDALONE_MISSING_LAST_QUOTE_XML = "standalone-missingLastQuote.xml";
private static final Path missingStartOfElementStandaloneXml = Server.CONFIGURATION_PATH.resolve(STANDALONE_MISSING_START_OF_ELEMENT_XML);
private static final Path spaceInXmlDeclarationStandaloneXml = Server.CONFIGURATION_PATH.resolve(STANDALONE_SPACE_IN_XML_DECLARATION_XML);
private static final Path missingLastQuoteStandaloneXml = Server.CONFIGURATION_PATH.resolve(STANDALONE_MISSING_LAST_QUOTE_XML);
private static final String missingStartOfElement =
" <subsystem xmlns=\"urn:jboss:domain:webservices:2.0\">\n"
+ " <wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host>\n"
+ " modify-wsdl-address>true</modify-wsdl-address>\n" // <-- on this line is the missing start <
+ " <endpoint-config name=\"Standard-Endpoint-Config\"/>\n"
+ " <endpoint-config name=\"Recording-Endpoint-Config\">\n"
+ " <pre-handler-chain name=\"recording-handlers\" protocol-bindings=\"##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM\">\n"
+ " <handler name=\"RecordingHandler\" class=\"org.jboss.ws.common.invocation.RecordingServerHandler\"/>\n"
+ " </pre-handler-chain>\n"
+ " </endpoint-config>\n"
+ " <client-config name=\"Standard-Client-Config\"/>\n"
+ " </subsystem>";
private static final String missingLastQuote =
" <subsystem xmlns=\"urn:jboss:domain:webservices:2.0\">\n"
+ " <wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host>\n"
+ " <modify-wsdl-address>true</modify-wsdl-address>\n"
+ " <endpoint-config name=\"Standard-Endpoint-Config/>\n" // <-- here is the missing end quote
+ " <endpoint-config name=\"Recording-Endpoint-Config\">\n"
+ " <pre-handler-chain name=\"recording-handlers\" protocol-bindings=\"##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM\">\n"
+ " <handler name=\"RecordingHandler\" class=\"org.jboss.ws.common.invocation.RecordingServerHandler\"/>\n"
+ " </pre-handler-chain>\n"
+ " </endpoint-config>\n"
+ " <client-config name=\"Standard-Client-Config\"/>\n"
+ " </subsystem>";
private String elementWithNationalCharacters = "<řebříček>obecný</řebříček>";
@BeforeClass
public static void prepareBrokenConfiguration() throws IOException {
try (Scanner scanner = new Scanner(standaloneXml);
PrintWriter missingStartOfElementStandaloneXmlPrintWriter = new PrintWriter(missingStartOfElementStandaloneXml.toFile());
PrintWriter spaceInXmlDeclarationStandaloneXmlPrintWriter = new PrintWriter(spaceInXmlDeclarationStandaloneXml.toFile());
PrintWriter missingLastQuoteStandaloneXmlPrintWriter = new PrintWriter(missingLastQuoteStandaloneXml.toFile())) {
boolean inWSSubsystem = false;
boolean wasInFirstLine = false;
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (wasInFirstLine) {
spaceInXmlDeclarationStandaloneXmlPrintWriter.println(line);
} else {
wasInFirstLine = true;
spaceInXmlDeclarationStandaloneXmlPrintWriter.println(" " + line);
}
if (line.contains("<subsystem xmlns=\"urn:jboss:domain:webservices")) {
inWSSubsystem = true;
} else if (!inWSSubsystem) {
missingStartOfElementStandaloneXmlPrintWriter.println(line);
missingLastQuoteStandaloneXmlPrintWriter.println(line);
} else if (line.contains("</subsystem>")) {
missingStartOfElementStandaloneXmlPrintWriter.println(missingStartOfElement);
missingLastQuoteStandaloneXmlPrintWriter.println(missingLastQuote);
inWSSubsystem = false;
}
}
}
}
/*
* Add space before xml declaration - <space><?xml version='1.0' encoding='UTF-8'?>
*/
@Test
@ServerConfig(configuration = STANDALONE_SPACE_IN_XML_DECLARATION_XML)
public void spaceInXmlDeclaration()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
if (errorLog.contains("is reserved")) {
// Apache JAXP impl
assertContains(errorLog, " ^^^^ Illegal processing instruction target (\"xml\"); xml (case insensitive)");
assertContains(errorLog, "is reserved by the specs");
} else {
// JDK JAXP impl
assertContains(errorLog, "^^^^ The processing instruction target matching \"[xX][mM][lL]\" is not");
}
}
/*
* There is bad character in xml (for example < is missing)
*/
@Test
@ServerConfig(configuration = STANDALONE_MISSING_START_OF_ELEMENT_XML)
public void missingStartOfElement()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, " modify-wsdl-address>true</modify-wsdl-address>");
if (errorLog.contains("CDATA")) {
// Apache JAXP impl
assertContains(errorLog, "^^^^ Received non-all-whitespace CHARACTERS or CDATA event in nextTag()");
} else {
// JDK JAXP impl
assertContains(errorLog, "^^^^ found: CHARACTERS, expected START_ELEMENT or END_ELEMENT");
}
}
/*
* There is missing last quote " in <element name="foobar>
*/
@Test
@ServerConfig(configuration = STANDALONE_MISSING_LAST_QUOTE_XML)
public void missingLastQuoteStandaloneXml()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "<endpoint-config name=\"Standard-Endpoint-Config/>");
if (errorLog.contains("(code 60)")) {
// Apache JAXP impl
assertContains(errorLog, "^^^^ Unexpected character '<' (code 60) in attribute value");
} else {
// JDK JAXP impl
assertContains(errorLog, "^^^^ The value of attribute \"name\" associated with an element type");
assertContains(errorLog, "\"endpoint-config\" must not contain the '<' character");
}
}
/*
* Element with national characters - e.g. <řebříček>obecný</řebříček>
*/
@Test
@ServerConfig()
public void elementWithNationalCharacters()throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class, "AddElement.groovy")
.subtree("path", Subtree.subsystem("webservices")).parameter("elementXml", elementWithNationalCharacters)
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "isn't an allowed element here");
}
}
| 9,767 | 49.350515 | 177 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/standalone/JBossWSTestCase.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.standalone;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.GroovyXmlTransform;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.Subtree;
import org.wildfly.extras.creaper.core.offline.OfflineCommand;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.StandaloneTests;
import org.wildfly.test.integration.vdx.transformations.DoNothing;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
/**
*
* Created by rsvoboda on 11/30/16.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(StandaloneTests.class)
public class JBossWSTestCase extends TestBase {
/*
* <modify-wsdl-address /> instead of <modify-wsdl-address>true</modify-wsdl-address>
*/
@Test
@ServerConfig(configuration = "standalone.xml", xmlTransformationGroovy = "webservices/AddModifyWsdlAddressElementWithNoValue.groovy",
subtreeName = "webservices", subsystemName = "webservices")
public void modifyWsdlAddressElementWithNoValue()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone.xml");
assertContains(errorLog, "<modify-wsdl-address/>");
assertContains(errorLog, " ^^^^ Wrong type for 'modify-wsdl-address'. Expected [BOOLEAN] but was");
assertContains(errorLog, "STRING");
}
/*
* <mmodify-wsdl-address>true</mmodify-wsdl-address> instead of <modify-wsdl-address>true</modify-wsdl-address>
*/
@Test
@ServerConfig(configuration = "standalone.xml", xmlTransformationGroovy = "webservices/AddIncorrectlyNamedModifyWsdlAddressElement.groovy",
subtreeName = "webservices", subsystemName = "webservices")
public void incorrectlyNamedModifyWsdlAddressElement()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone.xml");
assertContains(errorLog, "<mmodify-wsdl-address>true</mmodify-wsdl-address>");
assertContains(errorLog, "^^^^ 'mmodify-wsdl-address' isn't an allowed element here");
}
/*
* <modify-wsdl-address>ttrue</modify-wsdl-address> instead of <modify-wsdl-address>true</modify-wsdl-address>
*/
@Test
@ServerConfig(configuration = "standalone.xml", xmlTransformationGroovy = "webservices/AddModifyWsdlAddressElementWithIncorrectValue.groovy",
subtreeName = "webservices", subsystemName = "webservices")
public void incorrectValueOfModifyWsdlAddressElement()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone.xml");
assertContains(errorLog, "<modify-wsdl-address>ttrue</modify-wsdl-address>");
assertContains(errorLog, " ^^^^ Wrong type for 'modify-wsdl-address'. Expected [BOOLEAN] but was");
assertContains(errorLog, " STRING");
}
/*
* use webservices:1.1 instead of webservices:2.0 schema
*/
@Test
@ServerConfig(configuration = "standalone.xml", xmlTransformationGroovy = "ModifySubsystemConfiguration.groovy",
subtreeName = "subsystem", subsystemName = "webservices",
parameterName = "configurationXml",
parameterValue =
" <subsystem xmlns=\"urn:jboss:domain:webservices:1.1\">\n"
+ " <wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host>\n"
+ " <endpoint-config name=\"Standard-Endpoint-Config\"/>\n"
+ " <endpoint-config name=\"Recording-Endpoint-Config\">\n"
+ " <pre-handler-chain name=\"recording-handlers\" protocol-bindings=\"##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM\">\n"
+ " <handler name=\"RecordingHandler\" class=\"org.jboss.ws.common.invocation.RecordingServerHandler\"/>\n"
+ " </pre-handler-chain>\n"
+ " </endpoint-config>\n"
+ " <client-config name=\"Standard-Client-Config\"/>\n"
+ " </subsystem>"
)
public void oldSubsystemVersionOnNewerConfiguration()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone.xml");
assertContains(errorLog, "^^^^ 'client-config' isn't an allowed element here");
}
/*
* duplicate wsdl-host element
*/
@Test
@ServerConfig()
public void duplicateWsdlHostElement() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class, "AddElement.groovy")
.subtree("path", Subtree.subsystem("webservices")).parameter("elementXml", "<wsdl-host>127.0.0.1</wsdl-host>")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone.xml");
}
}
| 6,349 | 47.106061 | 173 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/standalone/NoSchemaTestCase.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.standalone;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.StandaloneTests;
import org.wildfly.test.integration.vdx.utils.server.Server;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import static org.junit.Assert.fail;
/**
* Tests to check behavior when $JBOSS_HOME/docs/schema is not available
*
* Created by rsvoboda on 11/30/16.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(StandaloneTests.class)
public class NoSchemaTestCase extends TestBase {
private static final Path docs = Paths.get(Server.JBOSS_HOME, "docs");
private static final Path docsx = Paths.get(Server.JBOSS_HOME, "docsx");
@BeforeClass
public static void moveDocsAway() {
try {
Files.move(docs, docsx, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
fail("Couldn't move docs directory (" + docs + ")");
}
}
@AfterClass
public static void returnDocs() throws Exception {
try {
Files.move(docsx, docs, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
fail("Couldn't move docs directory back after finished testing");
}
}
/*
* remove $JBOSS_HOME/docs and use <modify-wsdl-address /> instead of <modify-wsdl-address>true</modify-wsdl-address>
* only stacktrace based error messages are available
*/
@Test
@ServerConfig(configuration = "standalone.xml", xmlTransformationGroovy = "webservices/AddModifyWsdlAddressElementWithNoValue.groovy",
subtreeName = "webservices", subsystemName = "webservices")
public void addWsdlAddressElementWithNoValueNoSchemaAvailable()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertDoesNotContain(errorLog,"OPVDX001: Validation error in standalone.xml");
assertDoesNotContain(errorLog,"<modify-wsdl-address/>");
assertDoesNotContain(errorLog," ^^^^ Wrong type for 'modify-wsdl-address'. Expected [BOOLEAN] but was");
assertDoesNotContain(errorLog,"| STRING");
assertContains(errorLog,"WFLYCTL0097");
assertContains(errorLog,"Wrong type for 'modify-wsdl-address'. Expected [BOOLEAN] but was STRING");
}
/*
* ensure something like '22:35:00,342 INFO [org.jboss.as.controller] (Controller Boot Thread) OPVDX003: No schemas available
* from /path/to/server/docs/schema - disabling validation error pretty printing' is available in the log
*/
@Test
@ServerConfig(configuration = "standalone.xml", xmlTransformationGroovy = "webservices/AddModifyWsdlAddressElementWithNoValue.groovy",
subtreeName = "webservices", subsystemName = "webservices")
public void ensureNoSchemasAvailableMessage()throws Exception {
container().tryStartAndWaitForFail();
String serverLog = String.join("\n", Files.readAllLines(container().getServerLogPath()));
assertContains(serverLog, "OPVDX003: No schemas available");
assertContains(serverLog, "disabling validation error pretty printing");
}
}
| 4,373 | 39.5 | 138 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/standalone/MessagingTestCase.java
|
/*
* Copyright 2017 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.standalone;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.GroovyXmlTransform;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.Subtree;
import org.wildfly.extras.creaper.core.offline.OfflineCommand;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.StandaloneTests;
import org.wildfly.test.integration.vdx.transformations.DoNothing;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
/**
* Tests for messaging subsystem in standalone mode
*
* Created by rsvoboda on 12/13/16.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(StandaloneTests.class)
public class MessagingTestCase extends TestBase {
@BeforeClass
public static void noPreview() {
// WildFly Preview doesn't configure a messaging broker
AssumeTestGroupUtil.assumeNotWildFlyPreview();
}
/*
* append invalid element to subsystem definition
* check that all elements are listed
*/
@Test
@ServerConfig(configuration = "standalone-full-ha.xml", xmlTransformationGroovy = "messaging/AddFooBar.groovy",
subtreeName = "messaging", subsystemName = "messaging-activemq")
public void modifyWsdlAddressElementWithNoValue() throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertDoesNotContain(errorLog, "more)"); // something like '(and 24 more)' shouldn't be in the log
assertContains(errorLog, "<foo>bar</foo>");
assertContains(errorLog, "^^^^ 'foo' isn't an allowed element here");
assertContains(errorLog, "Elements allowed here are: ");
assertContains(errorLog, "acceptor");
assertContains(errorLog, "address-setting");
assertContains(errorLog, "bindings-directory");
assertContains(errorLog, "bridge");
assertContains(errorLog, "broadcast-group");
assertContains(errorLog, "cluster-connection");
assertContains(errorLog, "connection-factory");
assertContains(errorLog, "connector");
assertContains(errorLog, "connector-service");
assertContains(errorLog, "discovery-group");
assertContains(errorLog, "divert");
assertContains(errorLog, "grouping-handler");
assertContains(errorLog, "http-acceptor");
assertContains(errorLog, "http-connector");
assertContains(errorLog, "in-vm-acceptor");
assertContains(errorLog, "in-vm-connector");
assertContains(errorLog, "jms-queue");
assertContains(errorLog, "jms-topic");
assertContains(errorLog, "journal-directory");
assertContains(errorLog, "large-messages-directory");
assertContains(errorLog, "legacy-connection-factory");
assertContains(errorLog, "live-only");
assertContains(errorLog, "paging-directory");
assertContains(errorLog, "pooled-connection-factory");
assertContains(errorLog, "queue");
assertContains(errorLog, "remote-acceptor");
assertContains(errorLog, "remote-connector");
assertContains(errorLog, "replication-colocated");
assertContains(errorLog, "replication-primary");
assertContains(errorLog, "replication-secondary");
assertContains(errorLog, "security-setting");
assertContains(errorLog, "shared-store-colocated");
assertContains(errorLog, "shared-store-primary");
assertContains(errorLog, "shared-store-secondary");
}
/*
* provide invalid value to address-full-policy which is enum - only allowed are PAGE,BLOCK,FAIL,DROP, try to use "PAGES"
*/
@Test
@ServerConfig(configuration = "standalone-full-ha.xml", xmlTransformationGroovy = "messaging/InvalidAddressSettingFullPolicy.groovy",
subtreeName = "messaging", subsystemName = "messaging-activemq")
public void testInvalidEnumValueInAddressSettingsFullPolicy() throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "^^^^ Invalid value PAGES for address-full-policy; legal values are [BLOCK");
assertContains(errorLog, "PAGE, FAIL, DROP]");
assertContains(errorLog, "\"WFLYCTL0248: Invalid value PAGES for address-full-policy");
}
/*
* provide invalid type to server-id to in-vm-acceptor - put string to int
*/
@Test
@ServerConfig(configuration = "standalone-full-ha.xml")
public void testInvalidTypeForServerIdInAcceptor() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class, "messaging/InvalidTypeForServerIdInAcceptor.groovy")
.subtree("messaging", Subtree.subsystem("messaging-activemq")).parameter("parameter", "not-int-value")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone-full-ha.xml ---------------------------");
assertContains(errorLog, "<in-vm-acceptor name=\"in-vm\" server-id=\"not-int-value\"/>");
assertContains(errorLog, "^^^^ Wrong type for 'server-id'. Expected [INT] but was STRING. Couldn't");
assertContains(errorLog, "convert \\\"not-int-value\\\" to [INT]");
}
/*
* provide invalid type to server-id to in-vm-acceptor - put long to int
*/
@Test
@ServerConfig(configuration = "standalone-full-ha.xml")
public void testLongInIntServerIdInAcceptor() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class, "messaging/InvalidTypeForServerIdInAcceptor.groovy")
.subtree("messaging", Subtree.subsystem("messaging-activemq")).parameter("parameter", "214748364700")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone-full-ha.xml ---------------------------");
assertContains(errorLog, "<in-vm-acceptor name=\"in-vm\" server-id=\"214748364700\"/>");
assertContains(errorLog, "^^^^ Wrong type for 'server-id'. Expected [INT] but was STRING. Couldn't");
assertContains(errorLog, "convert \\\"214748364700\\\" to [INT]");
}
/*
* provide invalid type - too long value to long type
*/
@Test
@ServerConfig(configuration = "standalone-full-ha.xml")
public void testTooLongValueForLongTypeInMaxSizeBytes() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class,
"messaging/InvalidValueForMaxSizeBytesInAddressSettings.groovy")
.subtree("messaging", Subtree.subsystem("messaging-activemq"))
.parameter("parameter", "1048576000000000000000000000000000000000")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone-full-ha.xml");
assertContains(errorLog, "<address-setting name=\"#\" dead-letter-address=\"jms.queue.DLQ\" " +
"expiry-address=\"jms.queue.ExpiryQueue\" max-size-bytes=\"1048576000000000000000000000000000000000\" " +
"page-size-bytes=\"2097152\" message-counter-history-day-limit=\"10\" redistribution-delay=\"1000\" " +
"address-full-policy=\"PAGE\"/>");
assertContains(errorLog, " ^^^^ Wrong type for 'max-size-bytes'. Expected [LONG] but was STRING.");
assertContains(errorLog, "Couldn't convert \\\"1048576000000000000000000000000000000000\\\" to");
assertContains(errorLog, "[LONG]");
}
/*
* provide invalid type - test double in long
*/
@Test
@ServerConfig(configuration = "standalone-full-ha.xml")
public void testDoubleInLongTypeInMaxSizeBytes() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class,
"messaging/InvalidValueForMaxSizeBytesInAddressSettings.groovy")
.subtree("messaging", Subtree.subsystem("messaging-activemq")).parameter("parameter", "0.12345678")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone-full-ha.xml ---------------------------");
assertContains(errorLog, "<address-setting name=\"#\" dead-letter-address=\"jms.queue.DLQ\" " +
"expiry-address=\"jms.queue.ExpiryQueue\" max-size-bytes=\"0.12345678\" page-size-bytes=\"2097152\" " +
"message-counter-history-day-limit=\"10\" redistribution-delay=\"1000\" address-full-policy=\"PAGE\"/>");
assertContains(errorLog, "^^^^ Wrong type for 'max-size-bytes'. Expected [LONG] but was STRING.");
assertContains(errorLog, "Couldn't convert \\\"0.12345678\\\" to [LONG]");
}
/*
* invalid order of elements - append security element to end of messaging-activemq subsystem
*/
@Test
@ServerConfig(configuration = "standalone-full-ha.xml", xmlTransformationGroovy = "messaging/AddSecurityElementToEndOfSubsystem.groovy",
subtreeName = "messaging", subsystemName = "messaging-activemq")
public void testWrongOrderOfElements() throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone-full-ha.xml ---------------------------");
assertContains(errorLog, "<security enabled=\"false\"/>");
assertContains(errorLog, "^^^^ 'security' isn't an allowed element here");
assertContains(errorLog, "Elements allowed here are:");
assertContains(errorLog, "acceptor journal-directory");
assertContains(errorLog, "address-setting large-messages-directory");
assertContains(errorLog, "bindings-directory legacy-connection-factory");
assertContains(errorLog, "bridge live-only");
assertContains(errorLog, "cluster-connection paging-directory");
assertContains(errorLog, "connection-factory pooled-connection-factory");
assertContains(errorLog, "connector queue");
assertContains(errorLog, "connector-service remote-acceptor");
assertContains(errorLog, "divert remote-connector");
assertContains(errorLog, "grouping-handler replication-colocated");
assertContains(errorLog, "http-acceptor replication-primary");
assertContains(errorLog, "http-connector replication-secondary");
assertContains(errorLog, "in-vm-acceptor security-setting");
assertContains(errorLog, "in-vm-connector shared-store-colocated");
assertContains(errorLog, "jgroups-broadcast-group shared-store-primary");
assertContains(errorLog, "jgroups-discovery-group shared-store-secondary");
assertContains(errorLog, "jms-queue socket-broadcast-group");
assertContains(errorLog, "jms-topic socket-discovery-group");
assertContains(errorLog, "'security' is allowed in elements:");
assertContains(errorLog, "- server > profile > {urn:jboss:domain:messaging-activemq:");
assertContains(errorLog, "subsystem > server");
}
/*
* missing required attribute in element - missing name in connector
* Reported Issue: https://issues.jboss.org/browse/JBEAP-8437
*/
@Test
@ServerConfig(configuration = "standalone-full-ha.xml", xmlTransformationGroovy = "messaging/AddConnectorWithoutName.groovy",
subtreeName = "messaging", subsystemName = "messaging-activemq")
public void testFirstMissingRequiredAttributeInElement() throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone-full-ha.xml ---------------------------");
assertContains(errorLog, "<http-connector socket-binding=\"http\" endpoint=\"http-acceptor\"/>");
assertContains(errorLog, "^^^^ Missing required attribute(s): name");
assertContains(errorLog, "WFLYCTL0133: Missing required attribute(s): name");
}
}
| 13,840 | 55.264228 | 148 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/standalone/ElytronTestCase.java
|
/*
* Copyright 2017 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.standalone;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.StandaloneTests;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
/**
* Test cases for Elytron subsystem configuration
*
* Created by rsvoboda on 2/4/17.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(StandaloneTests.class)
public class ElytronTestCase extends TestBase {
/*
* misplaced 'plain-text' attribute for properties-realm definition
*/
@Test
@ServerConfig(configuration = "standalone.xml", xmlTransformationGroovy = "elytron/MisplacedAttributeForPropertiesRealm.groovy",
subtreeName = "elytron", subsystemName = "elytron")
public void misplacedAttributeForPropertiesRealm()throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in standalone.xml");
assertContains(errorLog, "^^^^ 'plain-text' isn't an allowed attribute for the 'properties-realm'");
assertContains(errorLog, "Attributes allowed here are: ");
assertContains(errorLog, "groups-attribute");
assertContains(errorLog, "name");
assertContains(errorLog, "groups-properties");
assertContains(errorLog, "hash-charset");
assertContains(errorLog, "hash-encoding");
assertContains(errorLog, "users-properties");
assertContains(errorLog, "'plain-text' is allowed on elements:");
assertContains(errorLog, "server > profile > {urn:wildfly:elytron");
assertContains(errorLog, "subsystem > security-realms > properties-realm > users-properties");
}
}
| 2,613 | 39.84375 | 132 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/category/DomainTests.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.category;
/**
* Category which is specified in all domain tests.
*/
public interface DomainTests {
}
| 777 | 30.12 | 75 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/category/StandaloneTests.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.category;
/**
* Parent class for all standalone tests.
*/
public interface StandaloneTests {
}
| 772 | 28.730769 | 75 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/domain/JBossWSDomainTestCase.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.domain;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.DomainTests;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
/**
*
* Created by rsvoboda on 12/15/16.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(DomainTests.class)
public class JBossWSDomainTestCase extends TestBase {
/*
* <modify-wsdl-address /> instead of <modify-wsdl-address>true</modify-wsdl-address> in domain profiles
*/
private void startAndCheckLogsForWsdlAddressElementWithNoValue() throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "<modify-wsdl-address/>");
assertContains(errorLog, " ^^^^ Wrong type for 'modify-wsdl-address'. Expected [BOOLEAN] but was");
assertContains(errorLog, "STRING");
}
@Test
@ServerConfig(configuration = "domain.xml", xmlTransformationGroovy = "webservices/AddModifyWsdlAddressElementWithNoValue.groovy",
subtreeName = "webservices", subsystemName = "webservices", profileName = "default")
public void modifyWsdlAddressElementWithNoValue()throws Exception {
startAndCheckLogsForWsdlAddressElementWithNoValue();
}
@Test
@ServerConfig(configuration = "domain.xml", xmlTransformationGroovy = "webservices/AddModifyWsdlAddressElementWithNoValue.groovy",
subtreeName = "webservices", subsystemName = "webservices", profileName = "ha")
public void modifyWsdlAddressElementWithNoValueHa()throws Exception {
startAndCheckLogsForWsdlAddressElementWithNoValue();
}
@Test
@ServerConfig(configuration = "domain.xml", xmlTransformationGroovy = "webservices/AddModifyWsdlAddressElementWithNoValue.groovy",
subtreeName = "webservices", subsystemName = "webservices", profileName = "full")
public void modifyWsdlAddressElementWithNoValueFull()throws Exception {
startAndCheckLogsForWsdlAddressElementWithNoValue();
}
@Test
@ServerConfig(configuration = "domain.xml", xmlTransformationGroovy = "webservices/AddModifyWsdlAddressElementWithNoValue.groovy",
subtreeName = "webservices", subsystemName = "webservices", profileName = "full-ha")
public void modifyWsdlAddressElementWithNoValueFullHa()throws Exception {
startAndCheckLogsForWsdlAddressElementWithNoValue();
}
/*
* <mmodify-wsdl-address>true</mmodify-wsdl-address> instead of <modify-wsdl-address>true</modify-wsdl-address>
*/
private void startAndCheckLogsForIncorrectlyNamedWsdlAddressElementWithNoValue() throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "<mmodify-wsdl-address>true</mmodify-wsdl-address>");
assertContains(errorLog, "'mmodify-wsdl-address' isn't an allowed element here");
assertContains(errorLog, "WFLYCTL0198: Unexpected element");
assertContains(errorLog, "'{urn:jboss:domain:webservices:2.0}mmodify-wsdl-address' encountered");
}
@Test
@ServerConfig(configuration = "domain.xml", xmlTransformationGroovy = "webservices/AddIncorrectlyNamedModifyWsdlAddressElement.groovy",
subtreeName = "webservices", subsystemName = "webservices", profileName = "default")
public void incorrectlyNamedModifyWsdlAddressElement()throws Exception {
startAndCheckLogsForIncorrectlyNamedWsdlAddressElementWithNoValue();
}
@Test
@ServerConfig(configuration = "domain.xml", xmlTransformationGroovy = "webservices/AddIncorrectlyNamedModifyWsdlAddressElement.groovy",
subtreeName = "webservices", subsystemName = "webservices", profileName = "ha")
public void incorrectlyNamedModifyWsdlAddressElementHa()throws Exception {
startAndCheckLogsForIncorrectlyNamedWsdlAddressElementWithNoValue();
}
@Test
@ServerConfig(configuration = "domain.xml", xmlTransformationGroovy = "webservices/AddIncorrectlyNamedModifyWsdlAddressElement.groovy",
subtreeName = "webservices", subsystemName = "webservices", profileName = "full")
public void incorrectlyNamedModifyWsdlAddressElementFull()throws Exception {
startAndCheckLogsForIncorrectlyNamedWsdlAddressElementWithNoValue();
}
@Test
@ServerConfig(configuration = "domain.xml", xmlTransformationGroovy = "webservices/AddIncorrectlyNamedModifyWsdlAddressElement.groovy",
subtreeName = "webservices", subsystemName = "webservices", profileName = "full-ha")
public void incorrectlyNamedModifyWsdlAddressElementFullHa()throws Exception {
startAndCheckLogsForIncorrectlyNamedWsdlAddressElementWithNoValue();
}
}
| 5,679 | 46.333333 | 139 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/domain/SmokeDomainTestCase.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.domain;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.DomainTests;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
import java.nio.file.Files;
import static org.wildfly.test.integration.vdx.standalone.SmokeStandaloneTestCase.*;
/**
*
* Created by mnovak on 11/28/16.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(DomainTests.class)
public class SmokeDomainTestCase extends TestBase {
@Test
@ServerConfig(configuration = "duplicate-attribute.xml")
public void testWithExistingConfigInResources() throws Exception {
container().tryStartAndWaitForFail();
ensureDuplicateAttribute(container().getErrorMessageFromServerStart());
}
@Test
@ServerConfig(configuration = "domain-to-damage.xml", xmlTransformationGroovy = "TypoInExtensions.groovy")
public void typoInExtensionsWithConfigInResources() throws Exception {
container().tryStartAndWaitForFail();
ensureTypoInExtensions(container().getErrorMessageFromServerStart());
}
@Test
@ServerConfig(configuration = "domain.xml", xmlTransformationGroovy = "AddNonExistentElementToMessagingSubsystem.groovy",
subtreeName = "messaging", subsystemName = "messaging-activemq", profileName = "full-ha")
public void addNonExistingElementToMessagingSubsystem() throws Exception {
// WildFly Preview doesn't configure a messaging broker
AssumeTestGroupUtil.assumeNotWildFlyPreview();
container().tryStartAndWaitForFail();
ensureNonExistingElementToMessagingSubsystem(container().getErrorMessageFromServerStart());
}
@Test
@ServerConfig(configuration = "empty.xml")
public void emptyDCConfigFile() throws Exception {
container().tryStartAndWaitForFail();
assertContains( String.join("\n", Files.readAllLines(container().getServerLogPath())),
"OPVDX004: Failed to pretty print validation error: empty.xml has no content");
}
@Test
@ServerConfig(configuration = "domain.xml", hostConfig = "empty.xml")
public void emptyHCConfigFile() throws Exception {
container().tryStartAndWaitForFail();
assertContains( String.join("\n", Files.readAllLines(container().getServerLogPath())),
"OPVDX004: Failed to pretty print validation error: empty.xml has no content");
}
}
| 3,345 | 39.804878 | 125 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/domain/HostXmlSmokeTestCase.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.domain;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.GroovyXmlTransform;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.Subtree;
import org.wildfly.extras.creaper.core.offline.OfflineCommand;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.DomainTests;
import org.wildfly.test.integration.vdx.transformations.DoNothing;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
/**
*
* Created by rsvoboda on 12/15/16.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(DomainTests.class)
public class HostXmlSmokeTestCase extends TestBase {
private final String simpleXmlElement = "unexpectedElement";
private final String simpleXmlValue = "valueXYZ";
private final String simpleXml = "<" + simpleXmlElement + ">" + simpleXmlValue + "</" + simpleXmlElement + ">\n";
@Test
@ServerConfig(configuration = "host.xml", xmlTransformationGroovy = "host/ManagementAuditLogElement.groovy")
public void addManagementAuditLogElement() throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "^^^^ 'foo' isn't an allowed element here");
}
@Test
@ServerConfig(configuration = "host.xml", xmlTransformationGroovy = "host/EmptyManagementInterfaces.groovy")
public void emptyManagementInterfaces() throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "Must include one of the following elements:");
assertContains(errorLog, "HTTP_INTERFACE, NATIVE_INTERFACE");
}
@Test
@ServerConfig(configuration = "host.xml")
public void noManagementElement() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class, "RemoveElement.groovy")
.subtree("path", Subtree.management()).build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "WFLYCTL0134: Missing required element(s): MANAGEMENT");
}
private String addElementAndStart(Subtree subtree, String elementXml) throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class, "AddElement.groovy")
.subtree("path", subtree).parameter("elementXml", elementXml)
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "^^^^ '" + simpleXmlElement + "' isn't an allowed element here");
return errorLog;
}
@Test
@ServerConfig(configuration = "host.xml")
public void appendElementInJvms() throws Exception {
String errorLog = addElementAndStart( Subtree.jvms(), simpleXml);
assertContains(errorLog, "'unexpectedElement' isn't an allowed element here");
assertContains(errorLog, "WFLYCTL0198: Unexpected element");
assertContains(errorLog, "unexpectedElement' encountered");
}
@Test
@ServerConfig(configuration = "host.xml")
public void appendElementInServers() throws Exception {
String errorLog = addElementAndStart( Subtree.servers(), simpleXml);
assertContains(errorLog, "'unexpectedElement' isn't an allowed element here");
assertContains(errorLog, "WFLYCTL0198: Unexpected element");
assertContains(errorLog, "unexpectedElement' encountered");
}
@Test
@ServerConfig(configuration = "host.xml")
public void appendElementInDC() throws Exception {
String errorLog = addElementAndStart( Subtree.domainController(), simpleXml);
assertContains(errorLog, "'unexpectedElement' isn't an allowed element here");
assertContains(errorLog, "WFLYCTL0198: Unexpected element");
assertContains(errorLog, "unexpectedElement' encountered");
}
@Test
@ServerConfig(configuration = "host.xml")
public void appendElementInInterfaces() throws Exception {
String errorLog = addElementAndStart( Subtree.interfaces(), simpleXml);
assertContains(errorLog, "'unexpectedElement' isn't an allowed element here");
assertContains(errorLog, "WFLYCTL0198: Unexpected element");
assertContains(errorLog, "unexpectedElement' encountered");
}
@Test
@ServerConfig(configuration = "host.xml")
public void appendElementInManagement() throws Exception {
String errorLog = addElementAndStart( Subtree.management(), simpleXml);
assertContains(errorLog, "'unexpectedElement' isn't an allowed element here");
assertContains(errorLog, "WFLYCTL0198: Unexpected element");
assertContains(errorLog, "unexpectedElement' encountered");
}
@Test
@ServerConfig(configuration = "host.xml")
public void appendElementInExtensions() throws Exception {
String errorLog = addElementAndStart( Subtree.extensions(), simpleXml);
assertContains(errorLog, "'unexpectedElement' isn't an allowed element here");
assertContains(errorLog, "WFLYCTL0198: Unexpected element");
assertContains(errorLog, "unexpectedElement' encountered");
}
@Test
@ServerConfig(configuration = "host.xml")
public void appendElementInProperties() throws Exception {
String errorLog = addElementAndStart( Subtree.systemProperties(), simpleXml);
assertContains(errorLog, "'unexpectedElement' isn't an allowed element here");
assertContains(errorLog, "WFLYCTL0198: Unexpected element");
assertContains(errorLog, "unexpectedElement' encountered");
}
}
| 6,729 | 43.569536 | 119 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/domain/MessagingDomainTestCase.java
|
/*
* Copyright 2017 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.domain;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.GroovyXmlTransform;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.Subtree;
import org.wildfly.extras.creaper.core.offline.OfflineCommand;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.category.DomainTests;
import org.wildfly.test.integration.vdx.transformations.DoNothing;
import org.wildfly.test.integration.vdx.utils.server.ServerConfig;
/**
* Tests for messaging subsystem in domain mode
*
* Created by mnovak on 1/19/17.
*/
@RunAsClient
@RunWith(Arquillian.class)
@Category(DomainTests.class)
public class MessagingDomainTestCase extends TestBase {
@BeforeClass
public static void noPreview() {
// WildFly Preview doesn't configure a messaging broker
AssumeTestGroupUtil.assumeNotWildFlyPreview();
}
/*
* provide invalid value to address-full-policy which is enum - only allowed are PAGE,BLOCK,FAIL,DROP, try to use "PAGES"
*/
@Test
@ServerConfig(configuration = "domain.xml", xmlTransformationGroovy = "messaging/InvalidAddressSettingFullPolicy.groovy",
subtreeName = "messaging", subsystemName = "messaging-activemq", profileName = "full-ha")
public void testInvalidEnumValueInAddressSettingsFullPolicy() throws Exception {
container().tryStartAndWaitForFail();
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "^^^^ Invalid value PAGES for address-full-policy; legal values are [BLOCK");
assertContains(errorLog, "PAGE, FAIL, DROP]");
assertContains(errorLog, "\"WFLYCTL0248: Invalid value PAGES for address-full-policy");
}
/*
* provide invalid type to server-id to in-vm-acceptor - put string to int
*/
@Test
@ServerConfig(configuration = "domain.xml", profileName = "full-ha")
public void testInvalidTypeForServerIdInAcceptor() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class,
"messaging/InvalidTypeForServerIdInAcceptor.groovy")
.subtree("messaging", Subtree.subsystemInProfile("full-ha", "messaging-activemq"))
.parameter("parameter", "not-int-value")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in domain.xml ---------------------------");
assertContains(errorLog, "<in-vm-acceptor name=\"in-vm\" server-id=\"not-int-value\"/>");
assertContains(errorLog, "^^^^ Wrong type for 'server-id'. Expected [INT] but was STRING. Couldn't");
assertContains(errorLog, "convert \\\"not-int-value\\\" to [INT]");
}
/*
* provide invalid type to server-id to in-vm-acceptor - put long to int
*/
@Test
@ServerConfig(configuration = "domain.xml", profileName = "full-ha")
public void testLongInIntServerIdInAcceptor() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class,
"messaging/InvalidTypeForServerIdInAcceptor.groovy")
.subtree("messaging", Subtree.subsystemInProfile("full-ha", "messaging-activemq"))
.parameter("parameter", "214748364700")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in domain.xml ---------------------------");
assertContains(errorLog, "<in-vm-acceptor name=\"in-vm\" server-id=\"214748364700\"/>");
assertContains(errorLog, "^^^^ Wrong type for 'server-id'. Expected [INT] but was STRING. Couldn't");
assertContains(errorLog, "convert \\\"214748364700\\\" to [INT]");
}
/*
* provide invalid type - too long value to long type
*/
@Test
@ServerConfig(configuration = "domain.xml", profileName = "full-ha")
public void testTooLongValueForLongTypeInMaxSizeBytes() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class,
"messaging/InvalidValueForMaxSizeBytesInAddressSettings.groovy")
.subtree("messaging", Subtree.subsystemInProfile("full-ha", "messaging-activemq"))
.parameter("parameter", "1048576000000000000000000000000000000000")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in domain.xml");
assertContains(errorLog, "<address-setting name=\"#\" dead-letter-address=\"jms.queue.DLQ\" " +
"expiry-address=\"jms.queue.ExpiryQueue\" max-size-bytes=\"1048576000000000000000000000000000000000\" " +
"page-size-bytes=\"2097152\" message-counter-history-day-limit=\"10\" redistribution-delay=\"1000\" " +
"address-full-policy=\"PAGE\"/>");
assertContains(errorLog, " ^^^^ Wrong type for 'max-size-bytes'. Expected [LONG] but was STRING.");
assertContains(errorLog, "Couldn't convert \\\"1048576000000000000000000000000000000000\\\" to");
assertContains(errorLog, "[LONG]");
}
/*
* provide invalid type - test double in long
*/
@Test
@ServerConfig(configuration = "domain.xml")
public void testDoubleInLongTypeInMaxSizeBytes() throws Exception {
container().tryStartAndWaitForFail(
(OfflineCommand) ctx -> ctx.client.apply(GroovyXmlTransform.of(DoNothing.class,
"messaging/InvalidValueForMaxSizeBytesInAddressSettings.groovy")
.subtree("messaging", Subtree.subsystemInProfile("full-ha", "messaging-activemq")).parameter("parameter", "0.12345678")
.build()));
String errorLog = container().getErrorMessageFromServerStart();
assertContains(errorLog, "OPVDX001: Validation error in domain.xml ---------------------------");
assertContains(errorLog, "<address-setting name=\"#\" dead-letter-address=\"jms.queue.DLQ\" " +
"expiry-address=\"jms.queue.ExpiryQueue\" max-size-bytes=\"0.12345678\" page-size-bytes=\"2097152\" " +
"message-counter-history-day-limit=\"10\" redistribution-delay=\"1000\" address-full-policy=\"PAGE\"/>");
assertContains(errorLog, "^^^^ Wrong type for 'max-size-bytes'. Expected [LONG] but was STRING.");
assertContains(errorLog, "Couldn't convert \\\"0.12345678\\\" to [LONG]");
}
}
| 7,811 | 52.142857 | 143 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/utils/FileUtils.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.utils;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class FileUtils {
public static void copyFileFromResourcesToServer(String resourceFile, Path targetDirectory, boolean override) throws Exception {
if (resourceFile == null || "".equals(resourceFile)) {
return;
}
Path sourcePath = Paths.get(ClassLoader.getSystemResource(resourceFile).toURI());
Path targetPath = Paths.get(targetDirectory.toString(), sourcePath.getFileName().toString());
if (override || Files.notExists(targetPath)) {
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
}
}
}
| 1,412 | 32.642857 | 132 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/utils/server/ServerBase.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.utils.server;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.logging.Logger;
import org.junit.Assert;
import org.wildfly.extras.creaper.commands.foundation.offline.ConfigurationFileBackup;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.GroovyXmlTransform;
import org.wildfly.extras.creaper.commands.foundation.offline.xml.Subtree;
import org.wildfly.extras.creaper.core.offline.OfflineCommand;
import org.wildfly.extras.creaper.core.offline.OfflineManagementClient;
import org.wildfly.test.integration.vdx.transformations.DoNothing;
import org.wildfly.test.integration.vdx.utils.FileUtils;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public abstract class ServerBase implements Server {
protected Path testArchiveDirectory = null;
private ConfigurationFileBackup configurationFileBackup = new ConfigurationFileBackup();
private static Server server = null;
private OfflineManagementClient managementClient;
static final Logger log = Logger.getLogger(ServerBase.class);
@Override
public void tryStartAndWaitForFail(OfflineCommand... offlineCommands) throws Exception {
boolean modifyConfiguration = (offlineCommands != null) || (! getServerConfig().xmlTransformationGroovy().equals(""));
// stop server if running
stop();
// copy logging.properties
copyLoggingPropertiesToConfiguration();
// if configuration file is not in configuration directory then copy from resources directory (never override)
copyConfigFilesFromResourcesIfItDoesNotExist();
if (modifyConfiguration) {
managementClient = getOfflineManagementClient();
// backup config
backupConfiguration();
// apply transformation(s)
if (offlineCommands == null) {
applyXmlTransformation();
} else {
managementClient.apply(offlineCommands);
}
} else {
managementClient = null; // to see NPE when trying unexpected use-case
}
// archive configuration used during server start
archiveModifiedUsedConfig();
try {
// tryStartAndWaitForFail - this must throw exception due invalid xml
startServer();
// fail the test if server starts
Assert.fail("Server started successfully - probably xml was not invalidated/damaged correctly.");
} catch (Exception ex) {
log.debug("Start of the server failed. This is expected.");
} finally {
// restore original config if it exists
if (modifyConfiguration) {
restoreConfigIfBackupExists();
}
}
}
@Override
public void tryStartAndWaitForFail() throws Exception {
tryStartAndWaitForFail(null);
}
@Override
public abstract Path getServerLogPath();
/**
* Copies custom logging.properties to server configuration.
* This will log ERROR messages to target/errors.log file
*
* @throws Exception when copy fails
*/
protected void copyLoggingPropertiesToConfiguration() throws Exception {
String loggingPropertiesInResources = RESOURCES_DIRECTORY + LOGGING_PROPERTIES_FILE_NAME;
FileUtils.copyFileFromResourcesToServer(loggingPropertiesInResources, CONFIGURATION_PATH, true);
}
/**
* This will copy config file from resources directory to configuration directory of application server
* This never overrides existing files, so the file with the same name in configuration directory of server has precedence
*
* @throws Exception when copy operation
*/
protected abstract void copyConfigFilesFromResourcesIfItDoesNotExist() throws Exception;
protected abstract OfflineManagementClient getOfflineManagementClient() throws Exception;
protected abstract void startServer() throws Exception;
@Override
public String getErrorMessageFromServerStart() throws Exception {
return String.join("\n", Files.readAllLines(Paths.get(ERRORS_LOG_FILE_NAME), Charset.forName(System.getProperty("file.encoding", "UTF-8"))));
}
private void backupConfiguration() throws Exception {
// destroy any existing backup config
managementClient.apply(configurationFileBackup.destroy());
// backup any existing config
managementClient.apply(configurationFileBackup.backup());
}
private void restoreConfigIfBackupExists() throws Exception {
if (configurationFileBackup == null) {
throw new Exception("Backup config is null. This can happen if this method is called before " +
"startServer() call. Check tryStartAndWaitForFail() sequence that backupConfiguration() was called.");
}
log.debug("Restoring server configuration. Configuration to be restored " + getServerConfig());
managementClient.apply(configurationFileBackup.restore());
}
private void archiveModifiedUsedConfig() throws Exception {
Files.copy(CONFIGURATION_PATH.resolve(getServerConfig().configuration()),
testArchiveDirectory.resolve(getServerConfig().configuration()), StandardCopyOption.REPLACE_EXISTING);
}
/**
* Damages xml config file only if config file has valid syntax. This relies on well-formed xml.
*
* @throws Exception if not valid xml transformation
*/
@SuppressWarnings("deprecation")
private void applyXmlTransformation() throws Exception {
ServerConfig serverConfig = getServerConfig();
if (serverConfig.subtreeName().equals("")) { // standalone or domain case without subtree
managementClient.apply(GroovyXmlTransform.of(DoNothing.class, serverConfig.xmlTransformationGroovy())
.parameter(serverConfig.parameterName(), serverConfig.parameterValue())
.build());
return;
}
if (serverConfig.profileName().equals("")) { // standalone case with subtree
managementClient.apply(GroovyXmlTransform.of(DoNothing.class, serverConfig.xmlTransformationGroovy())
.subtree(serverConfig.subtreeName(), Subtree.subsystem(serverConfig.subsystemName()))
.parameter(serverConfig.parameterName(), serverConfig.parameterValue())
.build());
} else { // domain case with subtree
managementClient.apply(GroovyXmlTransform.of(DoNothing.class, serverConfig.xmlTransformationGroovy())
.subtree(serverConfig.subtreeName(), Subtree.subsystemInProfile(serverConfig.profileName(), serverConfig.subsystemName()))
.parameter(serverConfig.parameterName(), serverConfig.parameterValue())
.build());
}
}
/**
* @return returns Search stacktrace for @ServerConfig annotation and return it, returns null if there is none
*/
static ServerConfig getServerConfig() {
Throwable t = new Throwable();
StackTraceElement[] elements = t.getStackTrace();
String callerMethodName;
String callerClassName;
ServerConfig serverConfig = null;
for (int level = 1; level < elements.length; level++) {
try {
callerClassName = elements[level].getClassName();
callerMethodName = elements[level].getMethodName();
Method method = Class.forName(callerClassName).getMethod(callerMethodName);
serverConfig = method.getAnnotation(ServerConfig.class);
if (serverConfig != null) {
break;
}
} catch (Exception e) {
// ignore
}
}
return serverConfig;
}
/**
* Creates instance of server. If -Ddomain=true system property is specified it will be domain server,
* otherwise standalone server will be used.
*
* @param controller arquillian container controller
* @return Server instance - standalone by default or domain if -Ddomain=true is set
*/
public static Server getOrCreateServer(ContainerController controller) {
if (server == null) {
if (Server.isDomain()) {
server = new ServerDomain(controller);
} else {
server = new ServerStandalone(controller);
}
}
return server;
}
@Override
public void setTestArchiveDirectory(Path testArchiveDirectory) {
this.testArchiveDirectory = testArchiveDirectory;
}
}
| 9,534 | 39.922747 | 150 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/utils/server/ServerDomain.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.utils.server;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.wildfly.extras.creaper.core.ManagementClient;
import org.wildfly.extras.creaper.core.offline.OfflineManagementClient;
import org.wildfly.extras.creaper.core.offline.OfflineOptions;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.utils.FileUtils;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class ServerDomain extends ServerBase {
ContainerController controller;
protected ServerDomain(ContainerController controller) {
this.controller = controller;
}
@Override
public void startServer() {
ServerConfig serverConfig = getServerConfig();
Map<String, String> containerProperties = new HashMap<>();
if (serverConfig != null) {
if (serverConfig.configuration().startsWith("host")) { // for modifications in host.xml, see HostXmlSmokeTestCase
containerProperties.put("domainConfig", DEFAULT_SERVER_CONFIG);
containerProperties.put("hostConfig", serverConfig.configuration());
} else {
containerProperties.put("domainConfig", serverConfig.configuration());
containerProperties.put("hostConfig", serverConfig.hostConfig());
}
} else { // if no server config was specified return arquillian to default // todo take this from arquillian.xml
containerProperties.put("domainConfig", DEFAULT_SERVER_CONFIG);
containerProperties.put("hostConfig", DEFAULT_HOST_CONFIG);
}
controller.start(TestBase.DOMAIN_ARQUILLIAN_CONTAINER, containerProperties);
}
@Override
public Path getServerLogPath() {
return Paths.get(JBOSS_HOME, SERVER_MODE, "log", "host-controller.log");
}
@Override
protected void copyConfigFilesFromResourcesIfItDoesNotExist() throws Exception {
if (Files.notExists(CONFIGURATION_PATH.resolve(getServerConfig().configuration()))) {
FileUtils.copyFileFromResourcesToServer(RESOURCES_DIRECTORY + getServerConfig().configuration(),
CONFIGURATION_PATH, false);
}
if (Files.notExists(CONFIGURATION_PATH.resolve(getServerConfig().hostConfig()))) {
FileUtils.copyFileFromResourcesToServer(RESOURCES_DIRECTORY + getServerConfig().hostConfig(),
CONFIGURATION_PATH, false);
}
}
@Override
protected OfflineManagementClient getOfflineManagementClient() throws Exception {
return ManagementClient.offline(OfflineOptions
.domain().build().rootDirectory(new File(JBOSS_HOME))
.configurationFile(getServerConfig() == null ? DEFAULT_SERVER_CONFIG : getServerConfig().configuration())
.build());
}
@Override
public void stop() {
controller.stop(TestBase.DOMAIN_ARQUILLIAN_CONTAINER);
}
}
| 3,727 | 38.242105 | 126 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/utils/server/ServerStandalone.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.utils.server;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.wildfly.extras.creaper.core.ManagementClient;
import org.wildfly.extras.creaper.core.offline.OfflineManagementClient;
import org.wildfly.extras.creaper.core.offline.OfflineOptions;
import org.wildfly.test.integration.vdx.TestBase;
import org.wildfly.test.integration.vdx.utils.FileUtils;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class ServerStandalone extends ServerBase {
private ContainerController controller;
protected ServerStandalone(ContainerController controller) {
this.controller = controller;
}
protected void startServer() throws Exception {
ServerConfig serverConfig = getServerConfig();
Map<String, String> containerProperties = new HashMap<>();
if (serverConfig != null) {
containerProperties.put("serverConfig", serverConfig.configuration());
} else { // if no server config was specified return arquillian to default
containerProperties.put("serverConfig", DEFAULT_SERVER_CONFIG);
}
controller.start(TestBase.STANDALONE_ARQUILLIAN_CONTAINER, containerProperties);
}
@Override
protected OfflineManagementClient getOfflineManagementClient() throws Exception {
return ManagementClient.offline(OfflineOptions
.standalone()
.rootDirectory(new File(JBOSS_HOME))
.configurationFile(getServerConfig() == null ? DEFAULT_SERVER_CONFIG : getServerConfig().configuration())
.build());
}
@Override
public Path getServerLogPath() {
return Paths.get(JBOSS_HOME, SERVER_MODE, "log", "server.log");
}
@Override
protected void copyConfigFilesFromResourcesIfItDoesNotExist() throws Exception {
if (Files.notExists(CONFIGURATION_PATH.resolve(getServerConfig().configuration()))) {
FileUtils.copyFileFromResourcesToServer(RESOURCES_DIRECTORY + getServerConfig().configuration(),
CONFIGURATION_PATH, false);
}
}
@Override
public void stop() {
controller.stop(TestBase.STANDALONE_ARQUILLIAN_CONTAINER);
}
}
| 2,983 | 34.52381 | 121 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/utils/server/ServerConfig.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.utils.server;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation which specifies server config file from resources directory with which server should be started.
* <p>
* If domain is tested then it allows to specify host.xml file to be used. Otherwise it's ignored.
* <p>
* Used during tryStartAndWaitForFail of @see Server#tryStartAndWaitForFail()
* <p>
* Created by mnovak on 10/24/16.
*/
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ServerConfig {
/**
* Specifies with which configuration option server will be started.
* <p>
* Default value for standalone mode is "standalone.xml"
* Default value for domain mode is "domain.xml"
*/
String configuration() default "standalone.xml";
/**
* Optional - will be applied only in domain mode. Same as --host-config=...
* <p>
* Default is host.xml
*/
String hostConfig() default "host.xml";
String xmlTransformationGroovy() default "";
//for things like subtree("webservices", Subtree.subsystemInProfile("profileXY", "webservices")).build());
/**
* subtree name used in .groovy file
*/
String subtreeName() default "";
// mapping to server configuration .xml file
/**
* server's subsystem
*/
String subsystemName() default "";
/**
* server's profile, applicable only for domain
*/
String profileName() default "";
// provide variable name and value for transformation script
/**
* variable name for transformation script
*/
String parameterName() default "foo";
/**
* variable value for transformation script
*/
String parameterValue() default "bar";
}
| 2,524 | 28.705882 | 110 |
java
|
null |
wildfly-main/testsuite/integration/vdx/src/test/java/org/wildfly/test/integration/vdx/utils/server/Server.java
|
/*
* Copyright 2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.test.integration.vdx.utils.server;
import org.wildfly.extras.creaper.core.offline.OfflineCommand;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public interface Server {
String JBOSS_HOME = System.getProperty("jboss.home", "jboss-as");
String SERVER_MODE = isDomain() ? "domain" : "standalone";
String DEFAULT_SERVER_CONFIG = SERVER_MODE + ".xml"; // domain.xml or standalone.xml
String DEFAULT_HOST_CONFIG = "host.xml";
Path CONFIGURATION_PATH = Paths.get(JBOSS_HOME, SERVER_MODE, "configuration");
String RESOURCES_DIRECTORY = "configurations" + File.separator + SERVER_MODE + File.separator;
String LOGGING_PROPERTIES_FILE_NAME = "logging.properties";
String ERRORS_LOG_FILE_NAME = "target/errors.log";
/**
* Starts the server. If @ServerConfig annotation is present on method in calling stacktrace (for example test method) then
* it's applied before the server is started.
*
* Start of the server is expected to fail due to xml syntac error. It does not throw any exception when tryStartAndWaitForFail of server fails.
*
* @throws Exception when something unexpected happens
*/
void tryStartAndWaitForFail() throws Exception;
void tryStartAndWaitForFail(OfflineCommand... offlineCommands) throws Exception;
/**
* Stops server.
*/
void stop();
/**
*
* @return true if started server is in domain mode. false if it's standalone mode.
*/
static boolean isDomain() {
return Boolean.parseBoolean(System.getProperty("domain", "false"));
}
Path getServerLogPath();
/**
* Reads file with ERROR log output from server start.
* @return all error logs output
* @throws Exception
*/
String getErrorMessageFromServerStart() throws Exception;
void setTestArchiveDirectory(Path testArchiveDirectory);
}
| 2,553 | 32.605263 | 149 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/WrapThreadContextClassLoader.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD})
public @interface WrapThreadContextClassLoader {
}
| 1,371 | 39.352941 | 70 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/SimpleWebserviceEndpointIface.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws;
import jakarta.jws.WebService;
import jakarta.jws.soap.SOAPBinding;
/**
* Webservice endpoint interface.
*
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
@WebService
@SOAPBinding
public interface SimpleWebserviceEndpointIface {
String echo(String s);
}
| 1,352 | 32.825 | 70 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/SimpleWebserviceEndpointImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.jws.WebService;
import jakarta.xml.ws.WebServiceContext;
/**
* Webservice endpoint implementation.
*
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
@WebService(
endpointInterface = "org.jboss.as.test.integration.ws.SimpleWebserviceEndpointIface",
targetNamespace = "org.jboss.as.test.integration.ws",
serviceName = "SimpleService"
)
public class SimpleWebserviceEndpointImpl {
@Resource
WebServiceContext ctx;
// method driven injection, with default name to be computed
private String string1;
@Resource(name = "string2")
private String string2;
// XML driven injection
private String string3;
@Resource
private void setString1(final String s) {
string1 = s;
}
private boolean postConstructCalled;
@PostConstruct
private void init() {
postConstructCalled = true;
}
public String echo(final String s) {
if (!postConstructCalled) { throw new RuntimeException("@PostConstruct not called"); }
if (!"Ahoj 1".equals(string1)) { throw new RuntimeException("@Resource String with default name not injected"); }
if (!"Ahoj 2".equals(string2)) { throw new RuntimeException("@Resource String with explicit name not injected"); }
if (!"Ahoj 2".equals(string3)) { throw new RuntimeException("@Resource String with DD driven injection not injected"); }
if (ctx == null) { throw new RuntimeException("@Resource WebServiceContext not injected"); }
return s;
}
}
| 2,695 | 35.432432 | 128 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/SimpleWebserviceEndpointTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws;
import java.net.URL;
import org.jboss.logging.Logger;
import javax.xml.namespace.QName;
import jakarta.xml.ws.Service;
import jakarta.xml.ws.spi.Provider;
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.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests simple stateless web service endpoint invocation.
*
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
@RunWith(Arquillian.class)
public class SimpleWebserviceEndpointTestCase {
@ArquillianResource
URL baseUrl;
private static final Logger log = Logger.getLogger(SimpleWebserviceEndpointTestCase.class.getName());
@Deployment
public static WebArchive createDeployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, "ws-endpoint-example.war");
war.addPackage(SimpleWebserviceEndpointImpl.class.getPackage());
war.addClass(SimpleWebserviceEndpointImpl.class);
war.addAsWebInfResource(SimpleWebserviceEndpointTestCase.class.getPackage(), "web.xml", "web.xml");
return war;
}
@Test
public void testJBossWSIntegrationIsInPlace() {
String p = Provider.provider().getClass().getName();
Assert.assertTrue(p + " is not a JBossWS implementation of jakarta.xml.ws.spi.Provider", p.startsWith("org.jboss."));
}
@Test
@RunAsClient
public void testSimpleStatelessWebserviceEndpoint() throws Exception {
final QName serviceName = new QName("org.jboss.as.test.integration.ws", "SimpleService");
final URL wsdlURL = new URL(baseUrl, "/ws-endpoint-example/SimpleService?wsdl");
final Service service = Service.create(wsdlURL, serviceName);
final SimpleWebserviceEndpointIface port = service.getPort(SimpleWebserviceEndpointIface.class);
final String result = port.echo("hello");
Assert.assertEquals("hello", result);
}
}
| 3,236 | 37.535714 | 125 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/EJBEncryptServiceImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse;
import jakarta.ejb.Stateless;
import jakarta.jws.WebService;
import org.jboss.ws.api.annotation.EndpointConfig;
import org.jboss.ws.api.annotation.WebContext;
@Stateless
@WebService
(
portName = "EJBEncryptSecurityServicePort",
serviceName = "EJBEncryptSecurityService",
wsdlLocation = "META-INF/wsdl/SecurityService.wsdl",
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy",
endpointInterface = "org.jboss.as.test.integration.ws.wsse.ServiceIface"
)
@WebContext(
urlPattern = "/EJBEncryptSecurityService"
)
@EndpointConfig(configFile = "META-INF/jaxws-endpoint-config.xml", configName = "Custom WS-Security Endpoint")
public class EJBEncryptServiceImpl implements ServiceIface {
public String sayHello() {
return "Secure Hello World!";
}
}
| 1,973 | 39.285714 | 110 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/ElytronUsernameTokenImpl.java
|
/*
* Copyright 2021 Red Hat, Inc.
*
* 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.jboss.as.test.integration.ws.wsse;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ejb.Stateless;
import jakarta.jws.WebService;
import org.apache.cxf.annotations.EndpointProperties;
import org.apache.cxf.annotations.EndpointProperty;
import org.apache.cxf.interceptor.InInterceptors;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.SecurityIdentity;
/**
* <p>Implementation for the ServiceIface that obtains the current elytron
* security identity and checks that it is correctly filled (roles and
* attributes are not empty). It is only allowed for users with role
* <em>Users</em>.</p>
*
* @author rmartinc
*/
@Stateless
@RolesAllowed("Users")
@WebService(
portName = "UsernameTokenPort",
serviceName = "UsernameToken",
wsdlLocation = "WEB-INF/wsdl/UsernameToken.wsdl",
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy",
endpointInterface = "org.jboss.as.test.integration.ws.wsse.ServiceIface"
)
@EndpointProperties(value = {
@EndpointProperty(key = "ws-security.validate.token", value = "false")
})
@InInterceptors(interceptors = {
"org.jboss.wsf.stack.cxf.security.authentication.SubjectCreatingPolicyInterceptor"
})
public class ElytronUsernameTokenImpl implements ServiceIface {
@Override
public String sayHello() {
String username = "World";
boolean roles = false, attributes = false;
SecurityDomain sd = SecurityDomain.getCurrent();
if (sd != null && sd.getCurrentSecurityIdentity() != null) {
SecurityIdentity si = sd.getCurrentSecurityIdentity();
username = si.getPrincipal().getName();
roles = !si.getRoles().isEmpty();
attributes = !si.getAttributes().isEmpty();
}
return new StringBuilder("Hello ")
.append(username)
.append(roles? " with roles" : " without roles")
.append(attributes? " and with attributes" : " and without attributes")
.append("!")
.toString();
}
}
| 2,730 | 36.930556 | 88 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/GenerateJKSAndPropertiesFiles.java
|
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* 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.jboss.as.test.integration.ws.wsse;
import java.io.File;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;
import org.wildfly.security.x500.cert.BasicConstraintsExtension;
import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey;
/**
* Generates the jks and properties files needed for some ws tests
* @author <a href="mailto:[email protected]">Justin Cook</a>
*/
public class GenerateJKSAndPropertiesFiles {
private static final char[] ACTAS_PASSWORD = "aapass".toCharArray();
private static final char[] SERVICE_PASSWORD = "sspass".toCharArray();
private static final char[] STS_PASSWORD = "stsspass".toCharArray();
private static final char[] CLIENT_STORE_PASSWORD = "cspass".toCharArray();
private static final char[] ACTAS_KEY_PASSWORD = "aspass".toCharArray();
private static final char[] SERVICE_KEY_PASSWORD = "skpass".toCharArray();
private static final char[] STS_KEY_PASSWORD = "stskpass".toCharArray();
private static final char[] CLIENT_KEY_PASSWORD = "ckpass".toCharArray();
private static final String ACTAS_ALIAS = "myactaskey";
private static final String ACTAS_ALIAS_TRUST = "actasclient";
private static final String SERVICE_ALIAS = "myservicekey";
private static final String STS_ALIAS = "mystskey";
private static final String LOCALHOST_ALIAS = "mytomcatkey";
private static final String CLIENT_ALIAS = "myclientkey";
private static final String WEB_INF_WORKING_DIRECTORY_LOCATION = GenerateJKSAndPropertiesFiles.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "org/jboss/as/test/integration/ws/wsse/trust/WEB-INF";
private static final String META_INF_WORKING_DIRECTORY_LOCATION = GenerateJKSAndPropertiesFiles.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "org/jboss/as/test/integration/ws/wsse/trust/META-INF";
private static final String ACTAS_JKS_NAME = "actasstore.jks";
private static final String SERVICE_JKS_NAME = "servicestore.jks";
private static final String STS_JKS_NAME = "stsstore.jks";
private static final String CLIENT_STORE_JKS_NAME = "clientstore.jks";
private static final File ACTAS_JKS_FILE = new File(WEB_INF_WORKING_DIRECTORY_LOCATION, ACTAS_JKS_NAME);
private static final File SERVICE_JKS_FILE = new File(WEB_INF_WORKING_DIRECTORY_LOCATION, SERVICE_JKS_NAME);
private static final File STS_JKS_FILE = new File(WEB_INF_WORKING_DIRECTORY_LOCATION, STS_JKS_NAME);
private static final File CLIENT_STORE_JKS_FILE = new File(META_INF_WORKING_DIRECTORY_LOCATION, CLIENT_STORE_JKS_NAME);
private static final String ACTAS_DN = "CN=www.actas.com, OU=IT Department, O=Sample ActAs Web Service -- NOT FOR PRODUCTION, L=Dayton, ST=Ohio, C=US";
private static final String SERVICE_DN = "[email protected], CN=www.service.com, OU=IT Department, O=Sample Web Service Provider -- NOT FOR PRODUCTION, L=Buffalo, ST=New York, C=US";
private static final String STS_DN = "[email protected], CN=www.sts.com, OU=IT Department, O=Sample STS -- NOT FOR PRODUCTION, L=Baltimore, ST=Maryland, C=US";
private static final String LOCALHOST_DN = "CN=localhost";
private static final String CLIENT_DN = "[email protected], CN=www.client.com, OU=IT Department, O=Sample Client -- NOT FOR PRODUCTION, L=Niagara Falls, ST=New York, C=US";
private static final String SHA_1_RSA = "SHA1withRSA";
private static final String SHA_256_RSA = "SHA256withRSA";
private static KeyStore loadKeyStore() throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
return ks;
}
private static SelfSignedX509CertificateAndSigningKey createBasicSelfSigned(String DN, String signatureAlgorithmName, int keySize) {
return SelfSignedX509CertificateAndSigningKey.builder()
.setDn(new X500Principal(DN))
.setKeyAlgorithmName("RSA")
.setSignatureAlgorithmName(signatureAlgorithmName)
.setKeySize(keySize)
.build();
}
private static SelfSignedX509CertificateAndSigningKey createExtensionSelfSigned(String DN) {
return SelfSignedX509CertificateAndSigningKey.builder()
.setDn(new X500Principal(DN))
.setKeyAlgorithmName("RSA")
.setSignatureAlgorithmName(SHA_1_RSA)
.setKeySize(1024)
.addExtension(new BasicConstraintsExtension(false, true, 2147483647))
.build();
}
private static KeyStore createKeyStore(SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey, String alias, char[] password) throws Exception {
KeyStore keyStore = loadKeyStore();
X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
keyStore.setKeyEntry(alias, selfSignedX509CertificateAndSigningKey.getSigningKey(), password, new X509Certificate[]{certificate});
return keyStore;
}
private static void createTemporaryKeyStoreFile(KeyStore keyStore, File outputFile, char[] password) throws Exception {
try (FileOutputStream fos = new FileOutputStream(outputFile)){
keyStore.store(fos, password);
}
}
private static void setUpKeyStores() throws Exception {
File workingDir = new File(WEB_INF_WORKING_DIRECTORY_LOCATION);
if (workingDir.exists() == false) {
workingDir.mkdirs();
}
SelfSignedX509CertificateAndSigningKey actasSelfSignedX509CertificateAndSigningKey = createBasicSelfSigned(ACTAS_DN, SHA_256_RSA, 2048);
SelfSignedX509CertificateAndSigningKey serviceSelfSignedX509CertificateAndSigningKey = createExtensionSelfSigned(SERVICE_DN);
SelfSignedX509CertificateAndSigningKey stsSelfSignedX509CertificateAndSigningKey = createExtensionSelfSigned(STS_DN);
SelfSignedX509CertificateAndSigningKey localhostSelfSignedX509CertificateAndSigningKey = createBasicSelfSigned(LOCALHOST_DN, SHA_1_RSA, 1024);
SelfSignedX509CertificateAndSigningKey clientSelfSignedX509CertificateAndSigningKey = createExtensionSelfSigned(CLIENT_DN);
KeyStore actasKeyStore = createKeyStore(actasSelfSignedX509CertificateAndSigningKey, ACTAS_ALIAS, ACTAS_KEY_PASSWORD);
actasKeyStore.setCertificateEntry(STS_ALIAS, stsSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate());
KeyStore serviceKeyStore = createKeyStore(serviceSelfSignedX509CertificateAndSigningKey, SERVICE_ALIAS, SERVICE_KEY_PASSWORD);
serviceKeyStore.setCertificateEntry(STS_ALIAS, stsSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate());
serviceKeyStore.setCertificateEntry(LOCALHOST_ALIAS, localhostSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate());
KeyStore stsKeyStore = createKeyStore(stsSelfSignedX509CertificateAndSigningKey, STS_ALIAS, STS_KEY_PASSWORD);
stsKeyStore.setCertificateEntry(SERVICE_ALIAS, serviceSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate());
stsKeyStore.setCertificateEntry(CLIENT_ALIAS, clientSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate());
stsKeyStore.setCertificateEntry(ACTAS_ALIAS_TRUST, actasSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate());
KeyStore clientStoreKeyStore = createKeyStore(clientSelfSignedX509CertificateAndSigningKey, CLIENT_ALIAS, CLIENT_KEY_PASSWORD);
clientStoreKeyStore.setCertificateEntry(ACTAS_ALIAS, actasSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate());
clientStoreKeyStore.setCertificateEntry(STS_ALIAS, stsSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate());
clientStoreKeyStore.setCertificateEntry(SERVICE_ALIAS, serviceSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate());
clientStoreKeyStore.setCertificateEntry(LOCALHOST_ALIAS, localhostSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate());
createTemporaryKeyStoreFile(actasKeyStore, ACTAS_JKS_FILE, ACTAS_PASSWORD);
createTemporaryKeyStoreFile(serviceKeyStore, SERVICE_JKS_FILE, SERVICE_PASSWORD);
createTemporaryKeyStoreFile(stsKeyStore, STS_JKS_FILE, STS_PASSWORD);
createTemporaryKeyStoreFile(clientStoreKeyStore, CLIENT_STORE_JKS_FILE, CLIENT_STORE_PASSWORD);
}
public static void main(String[] args) throws Exception {
setUpKeyStores();
}
}
| 9,306 | 59.435065 | 225 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/GenerateSignEncryptFiles.java
|
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* 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.jboss.as.test.integration.ws.wsse;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.security.auth.x500.X500Principal;
import org.wildfly.security.x500.GeneralName;
import org.wildfly.security.x500.cert.BasicConstraintsExtension;
import org.wildfly.security.x500.cert.IssuerAlternativeNamesExtension;
import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey;
import org.wildfly.security.x500.cert.SubjectAlternativeNamesExtension;
import org.wildfly.security.x500.cert.X509CertificateBuilder;
/**
* Generates the jks and properties files needed for SignEncrypt tests
* @author <a href="mailto:[email protected]">Justin Cook</a>
*/
public class GenerateSignEncryptFiles {
private static final char[] GENERATED_KEYSTORE_PASSWORD = "password".toCharArray();
private static final String ALICE_ALIAS = "alice";
private static final String BOB_ALIAS = "bob";
private static final String JOHN_ALIAS = "john";
private static final String MAX_ALIAS = "max";
private static final String WORKING_DIRECTORY_LOCATION = GenerateWSKeyStores.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "org/jboss/as/test/integration/ws/wsse";
private static final File ALICE_JKS_FILE = new File(WORKING_DIRECTORY_LOCATION, "alice.jks");
private static final File BOB_JKS_FILE = new File(WORKING_DIRECTORY_LOCATION, "bob.jks");
private static final File JOHN_JKS_FILE = new File(WORKING_DIRECTORY_LOCATION, "john.jks");
private static final File MAX_JKS_FILE = new File(WORKING_DIRECTORY_LOCATION, "max.jks");
private static final String ALICE_DN = "CN=alice, OU=eng, O=apache.org";
private static final String BOB_DN = "CN=bob, OU=eng, O=apache.org";
private static final String JOHN_DN = "CN=John, OU=Test, O=Test, L=Test, ST=Test, C=IT";
private static final String MAX_DN = "CN=Max, OU=Test, O=Test, L=Test, ST=Test, C=CZ";
private static final String CXFCA_DN = "CN=cxfca, OU=eng, O=apache.org";
private static final String ALICE_SERIAL_NUMBER = "49546001";
private static final String BOB_SERIAL_NUMBER = "49546002";
private static final String SHA_1_RSA = "SHA1withRSA";
private static final String SHA_256_RSA = "SHA256withRSA";
private static KeyStore loadKeyStore() throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
return ks;
}
private static SelfSignedX509CertificateAndSigningKey createBasicSelfSigned(String DN, String signatureAlgorithmName) {
return SelfSignedX509CertificateAndSigningKey.builder()
.setDn(new X500Principal(DN))
.setKeyAlgorithmName("RSA")
.setSignatureAlgorithmName(signatureAlgorithmName)
.setKeySize(1024)
.build();
}
private static SelfSignedX509CertificateAndSigningKey createExtensionSelfSigned() {
return SelfSignedX509CertificateAndSigningKey.builder()
.setDn(new X500Principal(CXFCA_DN))
.setKeyAlgorithmName("RSA")
.setSignatureAlgorithmName(SHA_1_RSA)
.setKeySize(1024)
.addExtension(new BasicConstraintsExtension(true, true, 2147483647))
.addExtension(false, "IssuerAlternativeName","DNS:NOT_FOR_PRODUCTION_USE")
.build();
}
private static X509Certificate createCertificate(SelfSignedX509CertificateAndSigningKey issuerSelfSignedX509CertificateAndSigningKey, PublicKey publicKey, String subjectDN, String serialNumber) throws Exception {
List<GeneralName> issuerAltName = new ArrayList<>();
issuerAltName.add(new GeneralName.DNSName("NOT_FOR_PRODUCTION_USE"));
List<GeneralName> subjectAltName = new ArrayList<>();
subjectAltName.add(new GeneralName.DNSName("localhost"));
return new X509CertificateBuilder()
.setIssuerDn(issuerSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate().getIssuerX500Principal())
.setSubjectDn(new X500Principal(subjectDN))
.setSignatureAlgorithmName(SHA_1_RSA)
.setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey())
.setPublicKey(publicKey)
.addExtension(new IssuerAlternativeNamesExtension(false, issuerAltName))
.addExtension(new SubjectAlternativeNamesExtension(false, subjectAltName))
.setSerialNumber(new BigInteger(serialNumber))
.build();
}
private static KeyStore createSelfSignedKeyStore(SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey, String alias) throws Exception {
KeyStore keyStore = loadKeyStore();
X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
keyStore.setKeyEntry(alias, selfSignedX509CertificateAndSigningKey.getSigningKey(), GENERATED_KEYSTORE_PASSWORD, new X509Certificate[]{certificate});
return keyStore;
}
private static KeyStore createChainedKeyStore(SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey, X509Certificate subjectCertificate, PrivateKey signingKey, String alias) throws Exception {
KeyStore keyStore = loadKeyStore();
X509Certificate issuerCertificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
keyStore.setKeyEntry(alias, signingKey, GENERATED_KEYSTORE_PASSWORD, new X509Certificate[]{subjectCertificate, issuerCertificate});
return keyStore;
}
private static void createTemporaryKeyStoreFile(KeyStore keyStore, File outputFile) throws Exception {
try (FileOutputStream fos = new FileOutputStream(outputFile)){
keyStore.store(fos, GENERATED_KEYSTORE_PASSWORD);
}
}
private static void setUpKeyStores() throws Exception {
File workingDir = new File(WORKING_DIRECTORY_LOCATION);
if (workingDir.exists() == false) {
workingDir.mkdirs();
}
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair aliceKeys = keyPairGenerator.generateKeyPair();
PrivateKey aliceSigningKey = aliceKeys.getPrivate();
PublicKey alicePublicKey = aliceKeys.getPublic();
KeyPair bobKeys = keyPairGenerator.generateKeyPair();
PrivateKey bobSigningKey = bobKeys.getPrivate();
PublicKey bobPublicKey = bobKeys.getPublic();
SelfSignedX509CertificateAndSigningKey cxfcaSelfSignedX509CertificateAndSigningKey = createExtensionSelfSigned();
SelfSignedX509CertificateAndSigningKey johnSelfSignedX509CertificateAndSigningKey = createBasicSelfSigned(JOHN_DN, SHA_256_RSA);
SelfSignedX509CertificateAndSigningKey maxSelfSignedX509CertificateAndSigningKey = createBasicSelfSigned(MAX_DN, SHA_1_RSA);
X509Certificate aliceCertificate = createCertificate(cxfcaSelfSignedX509CertificateAndSigningKey, alicePublicKey, ALICE_DN, ALICE_SERIAL_NUMBER);
X509Certificate bobCertificate = createCertificate(cxfcaSelfSignedX509CertificateAndSigningKey, bobPublicKey, BOB_DN, BOB_SERIAL_NUMBER);
KeyStore aliceKeyStore = createChainedKeyStore(cxfcaSelfSignedX509CertificateAndSigningKey, aliceCertificate, aliceSigningKey, ALICE_ALIAS);
aliceKeyStore.setCertificateEntry(BOB_ALIAS, bobCertificate);
KeyStore bobKeyStore = createChainedKeyStore(cxfcaSelfSignedX509CertificateAndSigningKey, bobCertificate, bobSigningKey, BOB_ALIAS);
bobKeyStore.setCertificateEntry(ALICE_ALIAS, aliceCertificate);
bobKeyStore.setCertificateEntry(JOHN_ALIAS, johnSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate());
KeyStore johnKeyStore = createSelfSignedKeyStore(johnSelfSignedX509CertificateAndSigningKey, JOHN_ALIAS);
johnKeyStore.setCertificateEntry(BOB_ALIAS, bobCertificate);
KeyStore maxKeyStore = createSelfSignedKeyStore(maxSelfSignedX509CertificateAndSigningKey, MAX_ALIAS);
maxKeyStore.setCertificateEntry(BOB_ALIAS, bobCertificate);
createTemporaryKeyStoreFile(aliceKeyStore, ALICE_JKS_FILE);
createTemporaryKeyStoreFile(bobKeyStore, BOB_JKS_FILE);
createTemporaryKeyStoreFile(johnKeyStore, JOHN_JKS_FILE);
createTemporaryKeyStoreFile(maxKeyStore, MAX_JKS_FILE);
}
public static void main(String[] args) throws Exception {
setUpKeyStores();
}
}
| 9,472 | 50.483696 | 220 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/EJBServiceImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse;
import jakarta.ejb.Stateless;
import jakarta.jws.WebService;
import org.jboss.ws.api.annotation.EndpointConfig;
import org.jboss.ws.api.annotation.WebContext;
@Stateless
@WebService
(
portName = "EJBSecurityServicePort",
serviceName = "EJBSecurityService",
wsdlLocation = "META-INF/wsdl/SecurityService.wsdl",
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy",
endpointInterface = "org.jboss.as.test.integration.ws.wsse.ServiceIface"
)
@WebContext(
urlPattern = "/EJBSecurityService",
contextRoot = "/jaxws-wsse-sign-ejb"
)
@EndpointConfig(configFile = "META-INF/jaxws-endpoint-config.xml", configName = "Custom WS-Security Endpoint")
public class EJBServiceImpl implements ServiceIface {
public String sayHello() {
return "Secure Hello World!";
}
}
| 1,991 | 38.84 | 110 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/ServiceIface.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse;
import jakarta.jws.WebMethod;
import jakarta.jws.WebService;
@WebService
(
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy"
)
public interface ServiceIface {
@WebMethod
String sayHello();
}
| 1,343 | 36.333333 | 95 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/POJOServiceImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse;
import jakarta.jws.WebService;
import org.jboss.ws.api.annotation.EndpointConfig;
@WebService
(
portName = "SecurityServicePort",
serviceName = "SecurityService",
wsdlLocation = "WEB-INF/wsdl/SecurityService.wsdl",
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy",
endpointInterface = "org.jboss.as.test.integration.ws.wsse.ServiceIface"
)
@EndpointConfig(configFile = "WEB-INF/jaxws-endpoint-config.xml", configName = "Custom WS-Security Endpoint")
public class POJOServiceImpl implements ServiceIface {
public String sayHello() {
return "Secure Hello World!";
}
}
| 1,792 | 40.697674 | 109 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/POJOEncryptServiceImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse;
import jakarta.jws.WebService;
import org.jboss.ws.api.annotation.EndpointConfig;
@WebService
(
portName = "EncryptSecurityServicePort",
serviceName = "EncryptSecurityService",
wsdlLocation = "WEB-INF/wsdl/SecurityService.wsdl",
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy",
endpointInterface = "org.jboss.as.test.integration.ws.wsse.ServiceIface"
)
@EndpointConfig(configFile = "WEB-INF/jaxws-endpoint-config.xml", configName = "Custom WS-Security Endpoint")
public class POJOEncryptServiceImpl implements ServiceIface {
public String sayHello() {
return "Secure Hello World!";
}
}
| 1,813 | 41.186047 | 109 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/KeystorePasswordCallback.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse;
import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.wss4j.common.ext.WSPasswordCallback;
public class KeystorePasswordCallback implements CallbackHandler {
private Map<String, String> passwords = new HashMap<String, String>();
public KeystorePasswordCallback() {
passwords.put("alice", "password");
passwords.put("bob", "password");
passwords.put("john", "password");
passwords.put("max", "password");
}
/**
* It attempts to get the password from the private alias/passwords map.
*/
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
String pass = passwords.get(pc.getIdentifier());
if (pass != null) {
pc.setPassword(pass);
return;
}
}
}
/**
* Add an alias/password pair to the callback mechanism.
*/
public void setAliasPassword(String alias, String password) {
passwords.put(alias, password);
}
}
| 2,431 | 35.848485 | 95 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/GenerateWSKeyStores.java
|
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* 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.jboss.as.test.integration.ws.wsse;
import java.io.File;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;
import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey;
/**
* Generates the keystores and truststore needed for the ws tests
* @author <a href="mailto:[email protected]">Justin Cook</a>
*/
public class GenerateWSKeyStores {
private static final char[] GENERATED_KEYSTORE_PASSWORD = "changeit".toCharArray();
private static final String CLIENT_KEYSTORE_ALIAS = "client";
private static final String CLIENT_TRUSTSTORE_ALIAS = "myclientkey";
private static final String TEST_KEYSTORE_ALIAS = "tomcat";
private static final String TEST_TRUSTSTORE_ALIAS = "mykey";
private static final String WORKING_DIRECTORY_LOCATION = GenerateWSKeyStores.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "org/jboss/as/test/integration/ws/wsse/trust";
private static final File CLIENT_KEY_STORE_FILE = new File(WORKING_DIRECTORY_LOCATION, "client.keystore");
private static final File TEST_KEY_STORE_FILE = new File(WORKING_DIRECTORY_LOCATION, "test.keystore");
private static final File TRUST_STORE_FILE = new File(WORKING_DIRECTORY_LOCATION, "test.truststore");
private static KeyStore loadKeyStore() throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
return ks;
}
private static SelfSignedX509CertificateAndSigningKey createSelfSigned() {
X500Principal DN = new X500Principal("CN=Alessio, OU=JBoss, O=Red Hat, L=Milan, ST=MI, C=IT");
return SelfSignedX509CertificateAndSigningKey.builder()
.setDn(DN)
.setKeyAlgorithmName("RSA")
.setSignatureAlgorithmName("SHA256withRSA")
.build();
}
private static KeyStore createKeyStore(SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey, String alias) throws Exception {
KeyStore keyStore = loadKeyStore();
X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
keyStore.setKeyEntry(alias, selfSignedX509CertificateAndSigningKey.getSigningKey(), GENERATED_KEYSTORE_PASSWORD, new X509Certificate[]{certificate});
return keyStore;
}
private static void addCertEntry(SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey, KeyStore trustStore, String alias) throws Exception {
X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();
trustStore.setCertificateEntry(alias, certificate);
}
private static void createTemporaryKeyStoreFile(KeyStore keyStore, File outputFile) throws Exception {
try (FileOutputStream fos = new FileOutputStream(outputFile)){
keyStore.store(fos, GENERATED_KEYSTORE_PASSWORD);
}
}
private static void setUpKeyStores() throws Exception {
File workingDir = new File(WORKING_DIRECTORY_LOCATION);
if (workingDir.exists() == false) {
workingDir.mkdirs();
}
KeyStore trustStore = loadKeyStore();
SelfSignedX509CertificateAndSigningKey alessio1SelfSignedX509CertificateAndSigningKey = createSelfSigned();
SelfSignedX509CertificateAndSigningKey alessio2SelfSignedX509CertificateAndSigningKey = createSelfSigned();
KeyStore clientKeyStore = createKeyStore(alessio1SelfSignedX509CertificateAndSigningKey, CLIENT_KEYSTORE_ALIAS);
KeyStore testKeyStore = createKeyStore(alessio2SelfSignedX509CertificateAndSigningKey, TEST_KEYSTORE_ALIAS);
addCertEntry(alessio1SelfSignedX509CertificateAndSigningKey, trustStore, CLIENT_TRUSTSTORE_ALIAS);
addCertEntry(alessio2SelfSignedX509CertificateAndSigningKey, trustStore, TEST_TRUSTSTORE_ALIAS);
createTemporaryKeyStoreFile(clientKeyStore, CLIENT_KEY_STORE_FILE);
createTemporaryKeyStoreFile(testKeyStore, TEST_KEY_STORE_FILE);
createTemporaryKeyStoreFile(trustStore, TRUST_STORE_FILE);
}
public static void main(String[] args) throws Exception {
setUpKeyStores();
}
}
| 4,958 | 44.916667 | 197 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/sign/SignTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.sign;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import jakarta.xml.ws.BindingProvider;
import jakarta.xml.ws.Service;
import org.junit.Assert;
import org.apache.cxf.ws.security.SecurityConstants;
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.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jboss.as.test.integration.ws.wsse.KeystorePasswordCallback;
import org.jboss.as.test.integration.ws.wsse.ServiceIface;
import org.jboss.as.test.integration.ws.wsse.POJOServiceImpl;
/**
* Test WS sign capability
* <p>
* Certificates can ge generated using keytool -genkey -keyalg RSA -storetype JKS
* Public key can be extracted using keytool -export
* Public key can be imported using keytool -import
* Keystore can be listed using keytool -list -v
*
* @author Rostislav Svoboda
*/
@RunWith(Arquillian.class)
@RunAsClient
public class SignTestCase {
private static Logger log = Logger.getLogger(SignTestCase.class.getName());
@ArquillianResource
URL baseUrl;
@Deployment
public static Archive<?> deployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "jaxws-wsse-sign.war").
addAsManifestResource(new StringAsset("Dependencies: org.apache.ws.security\n"), "MANIFEST.MF").
addClasses(ServiceIface.class, POJOServiceImpl.class, KeystorePasswordCallback.class).
addAsResource(ServiceIface.class.getPackage(), "bob.jks", "bob.jks").
addAsResource(ServiceIface.class.getPackage(), "bob.properties", "bob.properties").
addAsWebInfResource(ServiceIface.class.getPackage(), "wsdl/SecurityService-sign.wsdl", "wsdl/SecurityService.wsdl").
addAsWebInfResource(ServiceIface.class.getPackage(), "wsdl/SecurityService_schema1.xsd", "wsdl/SecurityService_schema1.xsd").
addAsWebInfResource(SignTestCase.class.getPackage(), "jaxws-endpoint-config.xml", "jaxws-endpoint-config.xml");
return war;
}
@Test
public void signedRequest() throws Exception {
QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy", "SecurityService");
URL wsdlURL = new URL(baseUrl.toString() + "SecurityService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
ServiceIface proxy = (ServiceIface) service.getPort(ServiceIface.class);
setupWsse(proxy);
Assert.assertEquals("Secure Hello World!", proxy.sayHello());
}
private void setupWsse(ServiceIface proxy) throws MalformedURLException {
((BindingProvider) proxy).getRequestContext().put(SecurityConstants.CALLBACK_HANDLER, new KeystorePasswordCallback());
((BindingProvider) proxy).getRequestContext().put(SecurityConstants.SIGNATURE_PROPERTIES, "org/jboss/as/test/integration/ws/wsse/alice.properties");
}
}
| 4,374 | 44.572917 | 156 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/sign/EJBSignTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.sign;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import jakarta.xml.ws.BindingProvider;
import jakarta.xml.ws.Service;
import org.junit.Assert;
import org.apache.cxf.ws.security.SecurityConstants;
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.test.integration.ws.wsse.EJBServiceImpl;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jboss.as.test.integration.ws.wsse.KeystorePasswordCallback;
import org.jboss.as.test.integration.ws.wsse.ServiceIface;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
/**
* Test WS sign capability
* <p>
* Certificates can ge generated using keytool -genkey -keyalg RSA -storetype JKS
* Public key can be extracted using keytool -export
* Public key can be imported using keytool -import
* Keystore can be listed using keytool -list -v
*
* @author Rostislav Svoboda
*/
@RunWith(Arquillian.class)
@RunAsClient
public class EJBSignTestCase {
@ArquillianResource
URL baseUrl;
@Deployment(testable = false)
public static Archive<?> deployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "jaxws-wsse-sign.jar").
addAsManifestResource(new StringAsset("Dependencies: org.apache.ws.security\n"), "MANIFEST.MF").
addClasses(ServiceIface.class, EJBServiceImpl.class, KeystorePasswordCallback.class).
addAsResource(ServiceIface.class.getPackage(), "bob.jks", "bob.jks").
addAsResource(ServiceIface.class.getPackage(), "bob.properties", "bob.properties").
addAsManifestResource(ServiceIface.class.getPackage(), "wsdl/SecurityService-ejb-sign.wsdl", "wsdl/SecurityService.wsdl").
addAsManifestResource(ServiceIface.class.getPackage(), "wsdl/SecurityService_schema1.xsd", "wsdl/SecurityService_schema1.xsd").
addAsManifestResource(EJBSignTestCase.class.getPackage(), "jaxws-endpoint-config.xml", "jaxws-endpoint-config.xml");
return jar;
}
@Test
public void signedRequest() throws Exception {
QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy", "EJBSecurityService");
URL wsdlURL = new URL(baseUrl, "/jaxws-wsse-sign-ejb/EJBSecurityService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
ServiceIface proxy = (ServiceIface) service.getPort(ServiceIface.class);
setupWsse(proxy);
Assert.assertEquals("Secure Hello World!", proxy.sayHello());
}
private void setupWsse(ServiceIface proxy) throws MalformedURLException {
((BindingProvider) proxy).getRequestContext().put(SecurityConstants.CALLBACK_HANDLER, new KeystorePasswordCallback());
((BindingProvider) proxy).getRequestContext().put(SecurityConstants.SIGNATURE_PROPERTIES, "org/jboss/as/test/integration/ws/wsse/alice.properties");
}
}
| 4,311 | 44.87234 | 156 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/WSTrustTestCaseElytronSecuritySetupTask.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PORT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLBACK_ON_RUNTIME_FAILURE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SSL_CONTEXT;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import java.util.ArrayList;
import java.util.List;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.management.util.ModelUtil;
import org.jboss.as.test.integration.security.common.CoreUtils;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.dmr.ModelNode;
public class WSTrustTestCaseElytronSecuritySetupTask implements ServerSetupTask {
public static final String SECURITY_DOMAIN_NAME = "ApplicationDomain";
public static final String HTTPS_LISTENER_NAME = "jbossws-https-listener";
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
List<ModelNode> operations = new ArrayList<>();
addSSLContext(operations);
addHttpsListener(operations);
addElytronSecurityDomain(operations);
ModelNode updateOp = Util.createCompositeOperation(operations);
updateOp.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
CoreUtils.applyUpdate(updateOp, managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
List<ModelNode> operations = new ArrayList<>();
removeHttpsListener(operations);
removeSSLContext(operations);
removeElytronSecurityDomain(operations);
ModelNode updateOp = Util.createCompositeOperation(operations);
updateOp.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false);
updateOp.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
CoreUtils.applyUpdate(updateOp, managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
private void addSSLContext(List<ModelNode> operations) throws Exception {
addKeyManager(operations);
final ModelNode addOp = createOpNode("subsystem=elytron/server-ssl-context=TestContext", ADD);
addOp.get("key-manager").set("TestManager");
operations.add(addOp);
}
private void addKeyManager(List<ModelNode> operations) throws Exception {
addKeyStore(operations);
final ModelNode addOp = createOpNode("subsystem=elytron/key-manager=TestManager", ADD);
ModelNode credentialReference = new ModelNode();
credentialReference.get("clear-text").set("changeit");
addOp.get("credential-reference").set(credentialReference);
addOp.get("key-store").set("TestStore");
operations.add(addOp);
}
private void addKeyStore(List<ModelNode> operations) throws Exception {
final ModelNode addOp = createOpNode("subsystem=elytron/key-store=TestStore", ADD);
addOp.get("path").set(WSTrustTestCaseElytronSecuritySetupTask.class.getResource("test.keystore").getPath());
ModelNode credentialReference = new ModelNode();
credentialReference.get("clear-text").set("changeit");
addOp.get("credential-reference").set(credentialReference);
operations.add(addOp);
}
private void removeSSLContext(List<ModelNode> operations) {
operations.add(createOpNode("subsystem=elytron/server-ssl-context=TestContext", REMOVE));
operations.add(createOpNode("subsystem=elytron/key-manager=TestManager", REMOVE));
operations.add(createOpNode("subsystem=elytron/key-store=TestStore", REMOVE));
}
/**
* Add https listner like this:
* <p/>
* <subsystem xmlns="urn:jboss:domain:undertow:3.0"> <server name="default-server"> <https-listener
* name="jbws-test-https-listener" socket-binding="https" security-realm="jbws-test-https-realm"/> .... </server> ...
* <subsystem>
*/
private void addHttpsListener(List<ModelNode> operations) throws Exception {
ModelNode addOp = createOpNode("socket-binding-group=standard-sockets/socket-binding=https2", ADD);
addOp.get(PORT).set("8444");
operations.add(addOp);
addOp = createOpNode("subsystem=undertow/server=default-server/https-listener=" + HTTPS_LISTENER_NAME, ADD);
addOp.get(SOCKET_BINDING).set("https2");
addOp.get(SSL_CONTEXT).set("TestContext");
operations.add(addOp);
}
private void removeHttpsListener(List<ModelNode> operations) throws Exception {
ModelNode removeOp = createOpNode("socket-binding-group=standard-sockets/socket-binding=https2", REMOVE);
operations.add(removeOp);
removeOp = createOpNode("subsystem=undertow/server=default-server/https-listener=" + HTTPS_LISTENER_NAME, REMOVE);
operations.add(removeOp);
}
private void addElytronSecurityDomain(List<ModelNode> operations) throws Exception {
final ModelNode elytronHttpAuthOp = ModelUtil.createOpNode(
"subsystem=elytron/http-authentication-factory=ws-http-authentication", ADD);
elytronHttpAuthOp.get("http-server-mechanism-factory").set("global");
elytronHttpAuthOp.get("security-domain").set(SECURITY_DOMAIN_NAME);
operations.add(elytronHttpAuthOp);
final ModelNode addUndertowDomainOp = ModelUtil.createOpNode("subsystem=undertow/application-security-domain="
+ SECURITY_DOMAIN_NAME, ADD);
addUndertowDomainOp.get("http-authentication-factory").set("ws-http-authentication");
operations.add(addUndertowDomainOp);
final ModelNode addEJbDomainOp = ModelUtil.createOpNode("subsystem=ejb3/application-security-domain="
+ SECURITY_DOMAIN_NAME, ADD);
addEJbDomainOp.get("security-domain").set(SECURITY_DOMAIN_NAME);
operations.add(addEJbDomainOp);
}
private void removeElytronSecurityDomain(List<ModelNode> operations) throws Exception {
final ModelNode removeElytronHttpAuthOp = ModelUtil.createOpNode(
"subsystem=elytron/http-authentication-factory=ws-http-authentication", REMOVE);
operations.add(removeElytronHttpAuthOp);
final ModelNode removeUndertowDomainOp = ModelUtil.createOpNode(
"subsystem=undertow/application-security-domain=" + SECURITY_DOMAIN_NAME, REMOVE);
operations.add(removeUndertowDomainOp);
final ModelNode removeEjbDomainOp = ModelUtil.createOpNode(
"subsystem=ejb3/application-security-domain=" + SECURITY_DOMAIN_NAME, REMOVE);
operations.add(removeEjbDomainOp);
}
}
| 8,490 | 48.947059 | 122 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/ContextProviderBean.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.ejb.Remote;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Stateless;
@Stateless
@PermitAll
@Remote(ContextProvider.class)
public class ContextProviderBean implements ContextProvider{
@Resource SessionContext context;
public String getEjbCallerPrincipalName() {
return context.getCallerPrincipal().getName();
}
}
| 1,528 | 36.292683 | 70 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/WSTrustTestCaseSecuritySetupTask.java
|
package org.jboss.as.test.integration.ws.wsse.trust;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PORT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLBACK_ON_RUNTIME_FAILURE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SSL_CONTEXT;
import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode;
import java.util.ArrayList;
import java.util.List;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.security.common.CoreUtils;
import org.jboss.as.test.shared.ServerReload;
import org.jboss.dmr.ModelNode;
public class WSTrustTestCaseSecuritySetupTask implements ServerSetupTask {
public static final String HTTPS_LISTENER_NAME = "jbws-test-https-listener";
@Override
public void setup(ManagementClient managementClient, String containerId) throws Exception {
List<ModelNode> operations = new ArrayList<>();
addSSLContext(operations);
addHttpsListener(operations);
ModelNode updateOp = Util.createCompositeOperation(operations);
updateOp.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
CoreUtils.applyUpdate(updateOp, managementClient.getControllerClient());
}
@Override
public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
List<ModelNode> operations = new ArrayList<>();
removeHttpsListener(operations);
removeSSLContext(operations);
ModelNode updateOp = Util.createCompositeOperation(operations);
updateOp.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false);
updateOp.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true);
CoreUtils.applyUpdate(updateOp, managementClient.getControllerClient());
ServerReload.reloadIfRequired(managementClient);
}
private void addSSLContext(List<ModelNode> operations) throws Exception {
addKeyManager(operations);
final ModelNode addOp = createOpNode("subsystem=elytron/server-ssl-context=TestContext", ADD);
addOp.get("key-manager").set("TestManager");
operations.add(addOp);
}
private void addKeyManager(List<ModelNode> operations) throws Exception {
addKeyStore(operations);
final ModelNode addOp = createOpNode("subsystem=elytron/key-manager=TestManager", ADD);
ModelNode credentialReference = new ModelNode();
credentialReference.get("clear-text").set("changeit");
addOp.get("credential-reference").set(credentialReference);
addOp.get("key-store").set("TestStore");
operations.add(addOp);
}
private void addKeyStore(List<ModelNode> operations) throws Exception {
final ModelNode addOp = createOpNode("subsystem=elytron/key-store=TestStore", ADD);
addOp.get("path").set(WSTrustTestCaseElytronSecuritySetupTask.class.getResource("test.keystore").getPath());
ModelNode credentialReference = new ModelNode();
credentialReference.get("clear-text").set("changeit");
addOp.get("credential-reference").set(credentialReference);
operations.add(addOp);
}
private void removeSSLContext(List<ModelNode> operations) {
operations.add(createOpNode("subsystem=elytron/server-ssl-context=TestContext", REMOVE));
operations.add(createOpNode("subsystem=elytron/key-manager=TestManager", REMOVE));
operations.add(createOpNode("subsystem=elytron/key-store=TestStore", REMOVE));
}
/**
* Add https listner like this:
* <p/>
* <subsystem xmlns="urn:jboss:domain:undertow:3.0">
* <server name="default-server">
* <https-listener name="jbws-test-https-listener" socket-binding="https" security-realm="jbws-test-https-realm"/>
* ....
* </server>
* ...
* </subsystem>
*/
private void addHttpsListener(List<ModelNode> operations) throws Exception {
ModelNode addOp = createOpNode("socket-binding-group=standard-sockets/socket-binding=https2", ADD);
addOp.get(PORT).set("8444");
operations.add(addOp);
addOp = createOpNode("subsystem=undertow/server=default-server/https-listener=" + HTTPS_LISTENER_NAME, ADD);
addOp.get(SOCKET_BINDING).set("https2");
addOp.get(SSL_CONTEXT).set("TestContext");
operations.add(addOp);
}
private void removeHttpsListener(List<ModelNode> operations) throws Exception {
ModelNode removeOp = createOpNode("socket-binding-group=standard-sockets/socket-binding=https2", REMOVE);
operations.add(removeOp);
removeOp = createOpNode("subsystem=undertow/server=default-server/https-listener=" + HTTPS_LISTENER_NAME, REMOVE);
operations.add(removeOp);
}
}
| 5,414 | 45.681034 | 122 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/ContextProvider.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust;
public interface ContextProvider {
String getEjbCallerPrincipalName();
}
| 1,163 | 40.571429 | 70 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/WSTrustTestUtils.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust;
import org.apache.cxf.Bus;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.trust.STSClient;
import org.jboss.as.test.integration.ws.wsse.trust.service.ServiceIface;
import org.jboss.as.test.integration.ws.wsse.trust.shared.ClientCallbackHandler;
import org.jboss.as.test.integration.ws.wsse.trust.shared.UsernameTokenCallbackHandler;
import javax.xml.namespace.QName;
import jakarta.xml.ws.BindingProvider;
import java.util.Map;
/**
* Some client util methods for WS-Trust testcases
*
* @author [email protected]
* @since 08-May-2012
*/
public class WSTrustTestUtils {
public static void setupWsseAndSTSClient(ServiceIface proxy, Bus bus, String stsWsdlLocation, QName stsService, QName stsPort) {
Map<String, Object> ctx = ((BindingProvider) proxy).getRequestContext();
setServiceContextAttributes(ctx);
ctx.put(SecurityConstants.STS_CLIENT, createSTSClient(bus, stsWsdlLocation, stsService, stsPort));
}
public static void setupWsse(ServiceIface proxy, Bus bus) {
Map<String, Object> ctx = ((BindingProvider) proxy).getRequestContext();
setServiceContextAttributes(ctx);
ctx.put(appendIssuedTokenSuffix(SecurityConstants.USERNAME), "alice");
ctx.put(appendIssuedTokenSuffix(SecurityConstants.CALLBACK_HANDLER), new ClientCallbackHandler());
ctx.put(appendIssuedTokenSuffix(SecurityConstants.ENCRYPT_PROPERTIES), Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(appendIssuedTokenSuffix(SecurityConstants.ENCRYPT_USERNAME), "mystskey");
ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_USERNAME), "myclientkey");
ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_PROPERTIES), Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO), "true");
}
/**
* A PASSWORD is provided in place of the ClientCallbackHandler in the
* STSClient. A USERNAME and PASSWORD is required by CXF in the msg.
*
* @param proxy
* @param bus
* @param stsWsdlLocation
* @param stsService
* @param stsPort
* @see org.apache.cxf.ws.security.SecurityConstants#PASSWORD
*/
public static void setupWsseAndSTSClientNoCallbackHandler(ServiceIface proxy, Bus bus, String stsWsdlLocation, QName stsService, QName stsPort) {
Map<String, Object> ctx = ((BindingProvider) proxy).getRequestContext();
setServiceContextAttributes(ctx);
STSClient stsClient = new STSClient(bus);
if (stsWsdlLocation != null) {
stsClient.setWsdlLocation(stsWsdlLocation);
stsClient.setServiceQName(stsService);
stsClient.setEndpointQName(stsPort);
}
Map<String, Object> props = stsClient.getProperties();
props.put(SecurityConstants.USERNAME, "alice");
props.put(SecurityConstants.PASSWORD, "clarinet");
props.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
props.put(SecurityConstants.ENCRYPT_USERNAME, "mystskey");
props.put(SecurityConstants.STS_TOKEN_USERNAME, "myclientkey");
props.put(SecurityConstants.STS_TOKEN_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
props.put(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO, "true");
ctx.put(SecurityConstants.STS_CLIENT, stsClient);
}
/**
* Uses the SIGNATURE_PROPERTIES keystore's "alias name" as the SIGNATURE_USERNAME when
* USERNAME and SIGNATURE_USERNAME is not provided.
*
* @param proxy
* @param bus
* @param stsWsdlLocation
* @param stsService
* @param stsPort
* @see org.apache.cxf.ws.security.SecurityConstants#SIGNATURE_PROPERTIES
*/
public static void setupWsseAndSTSClientNoSignatureUsername(ServiceIface proxy, Bus bus, String stsWsdlLocation, QName stsService, QName stsPort) {
Map<String, Object> ctx = ((BindingProvider) proxy).getRequestContext();
ctx.put(SecurityConstants.CALLBACK_HANDLER, new ClientCallbackHandler());
ctx.put(SecurityConstants.SIGNATURE_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.ENCRYPT_USERNAME, "myservicekey");
ctx.put(SecurityConstants.STS_CLIENT, createSTSClient(bus, stsWsdlLocation, stsService, stsPort));
}
/**
* Request a security token that allows it to act as if it were somebody else.
*
* @param proxy
* @param bus
*/
public static void setupWsseAndSTSClientActAs(BindingProvider proxy, Bus bus) {
Map<String, Object> ctx = proxy.getRequestContext();
ctx.put(SecurityConstants.CALLBACK_HANDLER, new ClientCallbackHandler());
ctx.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.ENCRYPT_USERNAME, "myactaskey");
ctx.put(SecurityConstants.SIGNATURE_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.SIGNATURE_USERNAME, "myclientkey");
UsernameTokenCallbackHandler ch = new UsernameTokenCallbackHandler();
String str = ch.getUsernameTokenString("alice", "clarinet");
ctx.put(SecurityConstants.STS_TOKEN_ACT_AS, str);
STSClient stsClient = new STSClient(bus);
Map<String, Object> props = stsClient.getProperties();
props.put(SecurityConstants.USERNAME, "bob");
props.put(SecurityConstants.CALLBACK_HANDLER, new ClientCallbackHandler());
props.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
props.put(SecurityConstants.ENCRYPT_USERNAME, "mystskey");
props.put(SecurityConstants.STS_TOKEN_USERNAME, "myclientkey");
props.put(SecurityConstants.STS_TOKEN_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
props.put(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO, "true");
ctx.put(SecurityConstants.STS_CLIENT, stsClient);
}
/**
* Request a security token that allows it to act on the behalf of somebody else.
*
* @param proxy
* @param bus
*/
public static void setupWsseAndSTSClientOnBehalfOf(BindingProvider proxy, Bus bus) {
Map<String, Object> ctx = proxy.getRequestContext();
ctx.put(SecurityConstants.CALLBACK_HANDLER, new ClientCallbackHandler());
ctx.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.ENCRYPT_USERNAME, "myactaskey");
ctx.put(SecurityConstants.SIGNATURE_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.SIGNATURE_USERNAME, "myclientkey");
ctx.put(SecurityConstants.USERNAME, "alice");
ctx.put(SecurityConstants.PASSWORD, "clarinet");
STSClient stsClient = new STSClient(bus);
stsClient.setOnBehalfOf(new UsernameTokenCallbackHandler());
Map<String, Object> props = stsClient.getProperties();
props.put(SecurityConstants.CALLBACK_HANDLER, new ClientCallbackHandler());
props.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
props.put(SecurityConstants.ENCRYPT_USERNAME, "mystskey");
props.put(SecurityConstants.STS_TOKEN_USERNAME, "myclientkey");
props.put(SecurityConstants.STS_TOKEN_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
props.put(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO, "true");
ctx.put(SecurityConstants.STS_CLIENT, stsClient);
}
public static void setupWsseAndSTSClientBearer(BindingProvider proxy, Bus bus) {
Map<String, Object> ctx = proxy.getRequestContext();
STSClient stsClient = new STSClient(bus);
ctx.put(SecurityConstants.CALLBACK_HANDLER, new ClientCallbackHandler());
ctx.put(SecurityConstants.SIGNATURE_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.SIGNATURE_USERNAME, "myclientkey");
ctx.put(SecurityConstants.ENCRYPT_USERNAME, "myservicekey");
ctx.put(appendIssuedTokenSuffix(SecurityConstants.USERNAME), "alice");
ctx.put(appendIssuedTokenSuffix(SecurityConstants.CALLBACK_HANDLER), new ClientCallbackHandler());
ctx.put(appendIssuedTokenSuffix(SecurityConstants.ENCRYPT_PROPERTIES), Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(appendIssuedTokenSuffix(SecurityConstants.ENCRYPT_USERNAME), "mystskey");
ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_USERNAME), "myclientkey");
ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_PROPERTIES), Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO), "true");
ctx.put(SecurityConstants.STS_CLIENT, stsClient);
}
public static void setupWsseAndSTSClientHolderOfKey(BindingProvider proxy, Bus bus) {
Map<String, Object> ctx = proxy.getRequestContext();
STSClient stsClient = new STSClient(bus);
ctx.put(SecurityConstants.CALLBACK_HANDLER, new ClientCallbackHandler());
ctx.put(SecurityConstants.SIGNATURE_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.SIGNATURE_USERNAME, "myclientkey");
ctx.put(SecurityConstants.ENCRYPT_USERNAME, "myservicekey");
ctx.put(appendIssuedTokenSuffix(SecurityConstants.USERNAME), "alice");
ctx.put(appendIssuedTokenSuffix(SecurityConstants.CALLBACK_HANDLER), new ClientCallbackHandler());
ctx.put(appendIssuedTokenSuffix(SecurityConstants.ENCRYPT_PROPERTIES), Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(appendIssuedTokenSuffix(SecurityConstants.ENCRYPT_USERNAME), "mystskey");
ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_USERNAME), "myclientkey");
ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_PROPERTIES), Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO), "true");
ctx.put(SecurityConstants.STS_CLIENT, stsClient);
}
private static String appendIssuedTokenSuffix(String prop) {
return prop + ".it";
}
/**
* Create and configure an STSClient for use by service ServiceImpl.
* <p/>
* Whenever an "<sp:IssuedToken>" policy is configured on a WSDL port, as is the
* case for ServiceImpl, a STSClient must be created and configured in
* order for the service to connect to the STS-server to obtain a token.
*
* @param bus
* @param stsWsdlLocation
* @param stsService
* @param stsPort
* @return
*/
private static STSClient createSTSClient(Bus bus, String stsWsdlLocation, QName stsService, QName stsPort) {
STSClient stsClient = new STSClient(bus);
if (stsWsdlLocation != null) {
stsClient.setWsdlLocation(stsWsdlLocation);
stsClient.setServiceQName(stsService);
stsClient.setEndpointQName(stsPort);
}
Map<String, Object> props = stsClient.getProperties();
props.put(SecurityConstants.USERNAME, "alice");
props.put(SecurityConstants.CALLBACK_HANDLER, new ClientCallbackHandler());
props.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
props.put(SecurityConstants.ENCRYPT_USERNAME, "mystskey");
props.put(SecurityConstants.STS_TOKEN_USERNAME, "myclientkey");
props.put(SecurityConstants.STS_TOKEN_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
props.put(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO, "true");
return stsClient;
}
private static void setServiceContextAttributes(Map<String, Object> ctx) {
ctx.put(SecurityConstants.CALLBACK_HANDLER, new ClientCallbackHandler());
ctx.put(SecurityConstants.SIGNATURE_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.SIGNATURE_USERNAME, "myclientkey");
ctx.put(SecurityConstants.ENCRYPT_USERNAME, "myservicekey");
}
}
| 15,156 | 55.137037 | 179 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/SayHelloResponse.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;
@XmlRootElement(name = "sayHelloResponse", namespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sayHelloResponse", namespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy")
public class SayHelloResponse {
@XmlElement(name = "return", namespace = "")
private String _return;
public String getReturn() {
return this._return;
}
public void setReturn(String _return) {
this._return = _return;
}
}
| 1,862 | 38.638298 | 117 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/WSTrustTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust;
import org.apache.commons.io.IOUtils;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
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.ServerSetup;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.network.NetworkUtils;
import org.jboss.as.test.integration.ws.WrapThreadContextClassLoader;
import org.jboss.as.test.integration.ws.wsse.trust.actas.ActAsServiceIface;
import org.jboss.as.test.integration.ws.wsse.trust.bearer.BearerIface;
import org.jboss.as.test.integration.ws.wsse.trust.holderofkey.HolderOfKeyIface;
import org.jboss.as.test.integration.ws.wsse.trust.onbehalfof.OnBehalfOfServiceIface;
import org.jboss.as.test.integration.ws.wsse.trust.service.ServiceIface;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import javax.xml.namespace.QName;
import jakarta.xml.ws.BindingProvider;
import jakarta.xml.ws.Service;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.util.StringTokenizer;
import static org.junit.Assert.assertEquals;
/**
* WS-Trust test case
* This is basically the Apache CXF STS demo (from distribution samples)
* ported to jbossws-cxf for running over JBoss Application Server.
*
* @author [email protected]
* @author [email protected]
* @since 08-Feb-2012
*/
@RunWith(Arquillian.class)
@ServerSetup(WSTrustTestCaseSecuritySetupTask.class)
@FixMethodOrder
public class WSTrustTestCase {
private static final String STS_DEP = "jaxws-samples-wsse-policy-trust-sts";
private static final String SERVER_DEP = "jaxws-samples-wsse-policy-trust";
private static final String ACT_AS_SERVER_DEP = "jaxws-samples-wsse-policy-trust-actas";
private static final String ON_BEHALF_OF_SERVER_DEP = "jaxws-samples-wsse-policy-trust-onbehalfof";
private static final String HOLDER_OF_KEY_STS_DEP = "jaxws-samples-wsse-policy-trust-sts-holderofkey";
private static final String HOLDER_OF_KEY_SERVER_DEP = "jaxws-samples-wsse-policy-trust-holderofkey";
private static final String BEARER_STS_DEP = "jaxws-samples-wsse-policy-trust-sts-bearer";
private static final String BEARER_SERVER_DEP = "jaxws-samples-wsse-policy-trust-bearer";
@Rule
public TestRule watcher = new WrapThreadContextClassLoaderWatcher();
@ArquillianResource
private URL serviceURL;
@Deployment(name = STS_DEP, testable = false)
public static WebArchive createSTSDeployment() {
WebArchive archive = ShrinkWrap.create(WebArchive.class, STS_DEP + ".war");
archive
.setManifest(new StringAsset("Manifest-Version: 1.0\n"
+ "Dependencies: org.jboss.ws.cxf.jbossws-cxf-client,org.jboss.ws.cxf.sts export services\n"))
.addClass(org.jboss.as.test.integration.ws.wsse.trust.sts.STSCallbackHandler.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.sts.SampleSTS.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.shared.WSTrustAppUtils.class)
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/jboss-web.xml", "jboss-web.xml")
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/ws-trust-1.4-service.wsdl"), "wsdl/ws-trust-1.4-service.wsdl")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/stsstore.jks", "classes/stsstore.jks")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/stsKeystore.properties", "classes/stsKeystore.properties")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "WEB-INF/permissions.xml", "permissions.xml")
.setWebXML(WSTrustTestCase.class.getPackage(), "WEB-INF/web.xml");
return archive;
}
@Deployment(name = SERVER_DEP, testable = false)
public static WebArchive createServerDeployment() {
WebArchive archive = ShrinkWrap.create(WebArchive.class, SERVER_DEP + ".war");
archive
.setManifest(new StringAsset("Manifest-Version: 1.0\n"
+ "Dependencies: org.jboss.ws.cxf.jbossws-cxf-client\n"))
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHello.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHelloResponse.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.service.ServerCallbackHandler.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.service.ServiceIface.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.service.ServiceImpl.class)
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/SecurityService.wsdl"), "wsdl/SecurityService.wsdl")
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/SecurityService_schema1.xsd"), "wsdl/SecurityService_schema1.xsd")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/servicestore.jks", "classes/servicestore.jks")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/serviceKeystore.properties", "classes/serviceKeystore.properties")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "WEB-INF/permissions.xml", "permissions.xml");
return archive;
}
@Deployment(name = ACT_AS_SERVER_DEP, testable = false)
public static WebArchive createActAsServerDeployment() {
WebArchive archive = ShrinkWrap.create(WebArchive.class, ACT_AS_SERVER_DEP + ".war");
archive
.setManifest(new StringAsset("Manifest-Version: 1.0\n"
+ "Dependencies: org.jboss.ws.cxf.jbossws-cxf-client, org.jboss.ws.cxf.sts\n"))
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHello.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHelloResponse.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.actas.ActAsCallbackHandler.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.actas.ActAsServiceIface.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.actas.ActAsServiceImpl.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.service.ServiceIface.class)
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/ActAsService.wsdl"), "wsdl/ActAsService.wsdl")
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/ActAsService_schema1.xsd"), "wsdl/ActAsService_schema1.xsd")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/actasstore.jks", "classes/actasstore.jks")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/actasKeystore.properties", "classes/actasKeystore.properties")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/clientstore.jks", "clientstore.jks")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/clientKeystore.properties", "clientKeystore.properties")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/permissions.xml", "permissions.xml");
return archive;
}
@Deployment(name = ON_BEHALF_OF_SERVER_DEP, testable = false)
public static WebArchive createOnBehalfOfServerDeployment() {
WebArchive archive = ShrinkWrap.create(WebArchive.class, ON_BEHALF_OF_SERVER_DEP + ".war");
archive
.setManifest(new StringAsset("Manifest-Version: 1.0\n"
+ "Dependencies: org.jboss.ws.cxf.jbossws-cxf-client, org.jboss.ws.cxf.sts\n"))
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHello.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHelloResponse.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.onbehalfof.OnBehalfOfCallbackHandler.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.onbehalfof.OnBehalfOfServiceIface.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.onbehalfof.OnBehalfOfServiceImpl.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.service.ServiceIface.class)
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/OnBehalfOfService.wsdl"), "wsdl/OnBehalfOfService.wsdl")
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/OnBehalfOfService_schema1.xsd"), "wsdl/OnBehalfOfService_schema1.xsd")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/actasstore.jks", "classes/actasstore.jks")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/actasKeystore.properties", "classes/actasKeystore.properties")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/clientstore.jks", "clientstore.jks")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/clientKeystore.properties", "clientKeystore.properties")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/permissions.xml", "permissions.xml");
return archive;
}
@Deployment(name = HOLDER_OF_KEY_STS_DEP, testable = false)
public static WebArchive createHolderOfKeySTSDeployment() {
WebArchive archive = ShrinkWrap.create(WebArchive.class, HOLDER_OF_KEY_STS_DEP + ".war");
archive
.setManifest(new StringAsset("Manifest-Version: 1.0\n"
+ "Dependencies: org.jboss.ws.cxf.jbossws-cxf-client,org.jboss.ws.cxf.sts annotations\n"))
.addClass(org.jboss.as.test.integration.ws.wsse.trust.stsholderofkey.STSHolderOfKeyCallbackHandler.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.stsholderofkey.SampleSTSHolderOfKey.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.shared.WSTrustAppUtils.class)
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/jboss-web.xml", "jboss-web.xml")
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/holderofkey-ws-trust-1.4-service.wsdl"), "wsdl/holderofkey-ws-trust-1.4-service.wsdl")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/stsstore.jks", "classes/stsstore.jks")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/stsKeystore.properties", "classes/stsKeystore.properties")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "WEB-INF/permissions.xml", "permissions.xml")
.setWebXML(WSTrustTestCase.class.getPackage(), "WEB-INF/holderofkey/web.xml");
return archive;
}
@Deployment(name = HOLDER_OF_KEY_SERVER_DEP, testable = false)
public static WebArchive createHolderOfKeyServerDeployment() {
WebArchive archive = ShrinkWrap.create(WebArchive.class, HOLDER_OF_KEY_SERVER_DEP + ".war");
archive
.setManifest(new StringAsset("Manifest-Version: 1.0\n"
+ "Dependencies: org.jboss.ws.cxf.jbossws-cxf-client\n"))
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHello.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHelloResponse.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.holderofkey.HolderOfKeyCallbackHandler.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.holderofkey.HolderOfKeyIface.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.holderofkey.HolderOfKeyImpl.class)
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/HolderOfKeyService.wsdl"), "wsdl/HolderOfKeyService.wsdl")
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/HolderOfKeyService_schema1.xsd"), "wsdl/HolderOfKeyService_schema1.xsd")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/servicestore.jks", "classes/servicestore.jks")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/serviceKeystore.properties", "classes/serviceKeystore.properties");
return archive;
}
@Deployment(name = BEARER_STS_DEP, testable = false)
public static WebArchive createBearerSTSDeployment() {
WebArchive archive = ShrinkWrap.create(WebArchive.class, BEARER_STS_DEP + ".war");
archive
.setManifest(new StringAsset("Manifest-Version: 1.0\n"
+ "Dependencies: org.jboss.ws.cxf.jbossws-cxf-client,org.jboss.ws.cxf.sts annotations\n"))
.addClass(org.jboss.as.test.integration.ws.wsse.trust.stsbearer.STSBearerCallbackHandler.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.stsbearer.SampleSTSBearer.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.shared.WSTrustAppUtils.class)
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/jboss-web.xml", "jboss-web.xml")
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/bearer-ws-trust-1.4-service.wsdl"), "wsdl/bearer-ws-trust-1.4-service.wsdl")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/stsstore.jks", "classes/stsstore.jks")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/stsKeystore.properties", "classes/stsKeystore.properties")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/permissions.xml", "permissions.xml")
.setWebXML(WSTrustTestCase.class.getPackage(), "WEB-INF/bearer/web.xml");
return archive;
}
@Deployment(name = BEARER_SERVER_DEP, testable = false)
public static WebArchive createBearerServerDeployment() {
WebArchive archive = ShrinkWrap.create(WebArchive.class, BEARER_SERVER_DEP + ".war");
archive
.setManifest(new StringAsset("Manifest-Version: 1.0\n"
+ "Dependencies: org.jboss.ws.cxf.jbossws-cxf-client\n"))
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHello.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHelloResponse.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.bearer.BearerIface.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.bearer.BearerImpl.class)
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/BearerService.wsdl"), "wsdl/BearerService.wsdl")
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/BearerService_schema1.xsd"), "wsdl/BearerService_schema1.xsd")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/servicestore.jks", "classes/servicestore.jks")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/serviceKeystore.properties", "classes/serviceKeystore.properties");
return archive;
}
/**
* @return comma- or space-separated list of absolute paths to client jars
*/
private String getClientJarPaths() throws IOException {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "jaxws-samples-wsse-policy-trust-client.jar");
jar.addManifest()
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/clientKeystore.properties", "clientKeystore.properties")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/clientstore.jks", "clientstore.jks");
File jarFile = new File(TestSuiteEnvironment.getTmpDir(), "jaxws-samples-wsse-policy-trust-client.jar");
jar.as(ZipExporter.class).exportTo(jarFile, true);
return jarFile.getAbsolutePath();
}
@Test
@OperateOnDeployment(HOLDER_OF_KEY_STS_DEP)
@RunAsClient
public void testReadDeploymentResource(@ArquillianResource ManagementClient client) throws Exception {
final ModelNode address = Operations.createAddress("deployment", HOLDER_OF_KEY_STS_DEP + ".war");
final ModelNode op = Operations.createReadResourceOperation(address);
op.get("include-runtime").set(true);
op.get("recursive").set(true);
final ModelNode result = client.getControllerClient().execute(op);
if (!Operations.isSuccessfulOutcome(result)) {
Assert.fail("Expected to be able to read the resource at deployment=" + HOLDER_OF_KEY_STS_DEP + ".war: "
+ Operations.getFailureDescription(result).asString());
}
}
/**
* WS-Trust test with the STS information programmatically provided
*
* @throws Exception
*/
@Test
@RunAsClient
@OperateOnDeployment(SERVER_DEP)
@WrapThreadContextClassLoader
public void test() throws Exception {
Bus bus = BusFactory.newInstance().createBus();
try {
BusFactory.setThreadDefaultBus(bus);
final QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy", "SecurityService");
final URL wsdlURL = new URL(serviceURL + "SecurityService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
ServiceIface proxy = (ServiceIface) service.getPort(ServiceIface.class);
final QName stsServiceName = new QName("http://docs.oasis-open.org/ws-sx/ws-trust/200512/", "SecurityTokenService");
final QName stsPortName = new QName("http://docs.oasis-open.org/ws-sx/ws-trust/200512/", "UT_Port");
URL stsURL = new URL(serviceURL.getProtocol(), serviceURL.getHost(), serviceURL.getPort(), "/jaxws-samples-wsse-policy-trust-sts/SecurityTokenService?wsdl");
WSTrustTestUtils.setupWsseAndSTSClient(proxy, bus, stsURL.toString(), stsServiceName, stsPortName);
try {
assertEquals("WS-Trust Hello World!", proxy.sayHello());
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} finally {
bus.shutdown(true);
}
}
/**
* WS-Trust test with the STS information coming from EPR specified in service endpoint contract policy
*
* @throws Exception
*/
@Test
@RunAsClient
@OperateOnDeployment(SERVER_DEP)
@WrapThreadContextClassLoader
public void testUsingEPR() throws Exception {
Bus bus = BusFactory.newInstance().createBus();
try {
BusFactory.setThreadDefaultBus(bus);
final QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy", "SecurityService");
final URL wsdlURL = new URL(serviceURL + "SecurityService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
ServiceIface proxy = (ServiceIface) service.getPort(ServiceIface.class);
WSTrustTestUtils.setupWsse(proxy, bus);
try {
assertEquals("WS-Trust Hello World!", proxy.sayHello());
} catch (Exception e) {
throw e;
}
} finally {
bus.shutdown(true);
}
}
/**
* No CallbackHandler is provided in STSCLient. Username and password provided instead.
*
* @throws Exception
*/
@Test
@RunAsClient
@OperateOnDeployment(SERVER_DEP)
@WrapThreadContextClassLoader
public void testNoClientCallback() throws Exception {
Bus bus = BusFactory.newInstance().createBus();
try {
BusFactory.setThreadDefaultBus(bus);
final QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy", "SecurityService");
final URL wsdlURL = new URL(serviceURL + "SecurityService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
ServiceIface proxy = (ServiceIface) service.getPort(ServiceIface.class);
final QName stsServiceName = new QName("http://docs.oasis-open.org/ws-sx/ws-trust/200512/", "SecurityTokenService");
final QName stsPortName = new QName("http://docs.oasis-open.org/ws-sx/ws-trust/200512/", "UT_Port");
URL stsURL = new URL(serviceURL.getProtocol(), serviceURL.getHost(), serviceURL.getPort(), "/jaxws-samples-wsse-policy-trust-sts/SecurityTokenService?wsdl");
WSTrustTestUtils.setupWsseAndSTSClientNoCallbackHandler(proxy, bus, stsURL.toString(), stsServiceName, stsPortName);
assertEquals("WS-Trust Hello World!", proxy.sayHello());
} finally {
bus.shutdown(true);
}
}
/**
* No SIGNATURE_USERNAME is provided to the service. Service will use the
* client's keystore alias in its place.
*
* @throws Exception
*/
@Test
@RunAsClient
@OperateOnDeployment(SERVER_DEP)
@WrapThreadContextClassLoader
public void testNoSignatureUsername() throws Exception {
Bus bus = BusFactory.newInstance().createBus();
try {
BusFactory.setThreadDefaultBus(bus);
final QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy", "SecurityService");
final URL wsdlURL = new URL(serviceURL + "SecurityService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
ServiceIface proxy = (ServiceIface) service.getPort(ServiceIface.class);
final QName stsServiceName = new QName("http://docs.oasis-open.org/ws-sx/ws-trust/200512/", "SecurityTokenService");
final QName stsPortName = new QName("http://docs.oasis-open.org/ws-sx/ws-trust/200512/", "UT_Port");
URL stsURL = new URL(serviceURL.getProtocol(), serviceURL.getHost(), serviceURL.getPort(), "/jaxws-samples-wsse-policy-trust-sts/SecurityTokenService?wsdl");
WSTrustTestUtils.setupWsseAndSTSClientNoSignatureUsername(proxy, bus, stsURL.toString(), stsServiceName, stsPortName);
assertEquals("WS-Trust Hello World!", proxy.sayHello());
} finally {
bus.shutdown(true);
}
}
/**
* Request a security token that allows it to act as if it were somebody else.
*
* @throws Exception
*/
@Test
@RunAsClient
@OperateOnDeployment(ACT_AS_SERVER_DEP)
@WrapThreadContextClassLoader
public void testActAs() throws Exception {
Bus bus = BusFactory.newInstance().createBus();
try {
BusFactory.setThreadDefaultBus(bus);
final QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/actaswssecuritypolicy", "ActAsService");
final URL wsdlURL = new URL(serviceURL + "ActAsService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
ActAsServiceIface proxy = (ActAsServiceIface) service.getPort(ActAsServiceIface.class);
WSTrustTestUtils.setupWsseAndSTSClientActAs((BindingProvider) proxy, bus);
assertEquals("ActAs WS-Trust Hello World!", proxy.sayHello(serviceURL.getHost(), String.valueOf(serviceURL.getPort())));
} finally {
bus.shutdown(true);
}
}
/**
* Request a security token that allows it to act on behalf of somebody else.
*
* @throws Exception
*/
@Test
@RunAsClient
@OperateOnDeployment(ON_BEHALF_OF_SERVER_DEP)
@WrapThreadContextClassLoader
public void testOnBehalfOf() throws Exception {
Bus bus = BusFactory.newInstance().createBus();
try {
BusFactory.setThreadDefaultBus(bus);
final QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/onbehalfofwssecuritypolicy", "OnBehalfOfService");
final URL wsdlURL = new URL(serviceURL + "OnBehalfOfService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
OnBehalfOfServiceIface proxy = (OnBehalfOfServiceIface) service.getPort(OnBehalfOfServiceIface.class);
WSTrustTestUtils.setupWsseAndSTSClientOnBehalfOf((BindingProvider) proxy, bus);
assertEquals("OnBehalfOf WS-Trust Hello World!", proxy.sayHello(serviceURL.getHost(), String.valueOf(serviceURL.getPort())));
} finally {
bus.shutdown(true);
}
}
@Test
@RunAsClient
@OperateOnDeployment(HOLDER_OF_KEY_SERVER_DEP)
@WrapThreadContextClassLoader
public void testHolderOfKey() throws Exception {
Bus bus = BusFactory.newInstance().createBus();
try {
BusFactory.setThreadDefaultBus(bus);
final QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/holderofkeywssecuritypolicy", "HolderOfKeyService");
final URL wsdlURL = new URL("https", serviceURL.getHost(), serviceURL.getPort() - 8080 + 8444, "/jaxws-samples-wsse-policy-trust-holderofkey/HolderOfKeyService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
HolderOfKeyIface proxy = (HolderOfKeyIface) service.getPort(HolderOfKeyIface.class);
WSTrustTestUtils.setupWsseAndSTSClientHolderOfKey((BindingProvider) proxy, bus);
assertEquals("Holder-Of-Key WS-Trust Hello World!", proxy.sayHello());
} finally {
bus.shutdown(true);
}
}
@Test
@RunAsClient
@OperateOnDeployment(BEARER_SERVER_DEP)
@WrapThreadContextClassLoader
public void testBearer() throws Exception {
Bus bus = BusFactory.newInstance().createBus();
try {
BusFactory.setThreadDefaultBus(bus);
final QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/bearerwssecuritypolicy", "BearerService");
Service service = Service.create(new URL(serviceURL + "BearerService?wsdl"), serviceName);
BearerIface proxy = (BearerIface) service.getPort(BearerIface.class);
WSTrustTestUtils.setupWsseAndSTSClientBearer((BindingProvider) proxy, bus);
assertEquals("Bearer WS-Trust Hello World!", proxy.sayHello());
} catch (Exception e) {
throw e;
} finally {
bus.shutdown(true);
}
}
private static String replaceNodeAddress(String resourceName) {
String content = null;
try {
content = IOUtils.toString(WSTrustTestCase.class.getResourceAsStream(resourceName), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException("Exception during replacing node address in resource", e);
}
return content.replaceAll("@node0@", NetworkUtils.formatPossibleIpv6Address(System.getProperty("node0", "127.0.0.1")));
}
private static StringAsset createFilteredAsset(String resourceName) {
return new StringAsset(replaceNodeAddress(resourceName));
}
class WrapThreadContextClassLoaderWatcher extends TestWatcher {
private ClassLoader classLoader = null;
protected void starting(Description description) {
try {
final String cjp = getClientJarPaths();
if (cjp == null || cjp.trim().isEmpty()) {
return;
}
if (description.getAnnotation(WrapThreadContextClassLoader.class) != null) {
classLoader = Thread.currentThread().getContextClassLoader();
StringTokenizer st = new StringTokenizer(cjp, ", ");
URL[] archives = new URL[st.countTokens()];
for (int i = 0; i < archives.length; i++) {
archives[i] = new File(st.nextToken()).toURI().toURL();
}
URLClassLoader cl = new URLClassLoader(archives, classLoader);
Thread.currentThread().setContextClassLoader(cl);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void finished(Description description) {
if (classLoader != null && description.getAnnotation(WrapThreadContextClassLoader.class) != null) {
Thread.currentThread().setContextClassLoader(classLoader);
}
}
}
}
| 30,366 | 53.323792 | 179 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/SayHello.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;
@XmlRootElement(name = "sayHello", namespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sayHello", namespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy")
public class SayHello {
}
| 1,561 | 44.941176 | 109 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/WSBearerElytronSecurityPropagationTestCase.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust;
import static org.junit.Assert.assertEquals;
import org.apache.commons.io.IOUtils;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.StringTokenizer;
import javax.xml.namespace.QName;
import jakarta.xml.ws.BindingProvider;
import jakarta.xml.ws.Service;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
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.ServerSetup;
import org.jboss.as.network.NetworkUtils;
import org.jboss.as.test.integration.ws.WrapThreadContextClassLoader;
import org.jboss.as.test.integration.ws.wsse.trust.bearer.BearerIface;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
/**
* Test for WFLY-10480 with Elytron security domain
*
*/
@RunWith(Arquillian.class)
@ServerSetup(WSTrustTestCaseElytronSecuritySetupTask.class)
public class WSBearerElytronSecurityPropagationTestCase {
private static final String BEARER_STS_DEP = "jaxws-samples-wsse-policy-trust-sts-bearer";
private static final String BEARER_SERVER_DEP = "jaxws-samples-wsse-policy-trust-bearer";
@Rule
public TestRule watcher = new WrapThreadContextClassLoaderWatcher();
@ArquillianResource
private URL serviceURL;
@Deployment(name = BEARER_STS_DEP, testable = false)
public static WebArchive createBearerSTSDeployment() {
WebArchive archive = ShrinkWrap.create(WebArchive.class, BEARER_STS_DEP + ".war");
archive
.setManifest(new StringAsset("Manifest-Version: 1.0\n"
+ "Dependencies: org.jboss.ws.cxf.jbossws-cxf-client,org.jboss.ws.cxf.sts export services\n"))
.addClass(org.jboss.as.test.integration.ws.wsse.trust.stsbearer.STSBearerCallbackHandler.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.stsbearer.SampleSTSBearer.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.shared.WSTrustAppUtils.class)
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/bearer-ws-trust-1.4-service.wsdl"), "wsdl/bearer-ws-trust-1.4-service.wsdl")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/stsstore.jks", "classes/stsstore.jks")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/stsKeystore.properties", "classes/stsKeystore.properties")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/permissions.xml", "permissions.xml")
.setWebXML(WSTrustTestCase.class.getPackage(), "WEB-INF/bearer/web.xml");
return archive;
}
@Deployment(name = BEARER_SERVER_DEP, testable = false)
public static WebArchive createBearerServerDeployment() {
WebArchive archive = ShrinkWrap.create(WebArchive.class, BEARER_SERVER_DEP + ".war");
archive
.setManifest(new StringAsset("Manifest-Version: 1.0\n"
+ "Dependencies: org.jboss.ws.cxf.jbossws-cxf-client,org.apache.cxf.impl\n"))
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHello.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SayHelloResponse.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.bearer.BearerIface.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.bearer.BearerEJBImpl.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.SamlSecurityContextInInterceptor.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.ContextProvider.class)
.addClass(org.jboss.as.test.integration.ws.wsse.trust.ContextProviderBean.class)
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/jboss-web-elytron.xml", "jboss-web.xml")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/jboss-ejb3-elytron.xml", "jboss-ejb3.xml")
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/BearerService.wsdl"), "wsdl/BearerService.wsdl")
.addAsWebInfResource(createFilteredAsset("WEB-INF/wsdl/BearerService_schema1.xsd"), "wsdl/BearerService_schema1.xsd")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/servicestore.jks", "classes/servicestore.jks")
.addAsWebInfResource(WSTrustTestCase.class.getPackage(), "WEB-INF/serviceKeystore.properties", "classes/serviceKeystore.properties");
return archive;
}
@Test
@RunAsClient
@OperateOnDeployment(BEARER_SERVER_DEP)
@WrapThreadContextClassLoader
public void testBearer() throws Exception {
Bus bus = BusFactory.newInstance().createBus();
try {
BusFactory.setThreadDefaultBus(bus);
final QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/bearerwssecuritypolicy", "BearerService");
Service service = Service.create(new URL(serviceURL + "BearerService?wsdl"), serviceName);
BearerIface proxy = (BearerIface) service.getPort(BearerIface.class);
WSTrustTestUtils.setupWsseAndSTSClientBearer((BindingProvider) proxy, bus);
assertEquals("alice&alice", proxy.sayHello());
} catch (Exception e) {
throw e;
} finally {
bus.shutdown(true);
}
}
private static String replaceNodeAddress(String resourceName) {
String content = null;
try {
content = IOUtils.toString(WSTrustTestCase.class.getResourceAsStream(resourceName), "UTF-8");
} catch (IOException e) {
throw new RuntimeException("Exception during replacing node address in resource", e);
}
return content.replaceAll("@node0@", NetworkUtils.formatPossibleIpv6Address(System.getProperty("node0", "127.0.0.1")));
}
private static StringAsset createFilteredAsset(String resourceName) {
return new StringAsset(replaceNodeAddress(resourceName));
}
/**
* @return comma- or space-separated list of absolute paths to client jars
*/
private String getClientJarPaths() throws IOException {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "jaxws-samples-wsse-policy-trust-client.jar");
jar.addManifest()
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/clientKeystore.properties", "clientKeystore.properties")
.addAsManifestResource(WSTrustTestCase.class.getPackage(), "META-INF/clientstore.jks", "clientstore.jks");
File jarFile = new File(TestSuiteEnvironment.getTmpDir(), "jaxws-samples-wsse-policy-trust-client.jar");
jar.as(ZipExporter.class).exportTo(jarFile, true);
return jarFile.getAbsolutePath();
}
class WrapThreadContextClassLoaderWatcher extends TestWatcher {
private ClassLoader classLoader = null;
protected void starting(Description description) {
try {
final String cjp = getClientJarPaths();
if (cjp == null || cjp.trim().isEmpty()) {
return;
}
if (description.getAnnotation(WrapThreadContextClassLoader.class) != null) {
classLoader = Thread.currentThread().getContextClassLoader();
StringTokenizer st = new StringTokenizer(cjp, ", ");
URL[] archives = new URL[st.countTokens()];
for (int i = 0; i < archives.length; i++) {
archives[i] = new File(st.nextToken()).toURI().toURL();
}
URLClassLoader cl = new URLClassLoader(archives, classLoader);
Thread.currentThread().setContextClassLoader(cl);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void finished(Description description) {
if (classLoader != null && description.getAnnotation(WrapThreadContextClassLoader.class) != null) {
Thread.currentThread().setContextClassLoader(classLoader);
}
}
}
}
| 9,968 | 48.351485 | 149 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/SamlSecurityContextInInterceptor.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2018, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.common.security.SimplePrincipal;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.security.DefaultSecurityContext;
import org.apache.cxf.security.SecurityContext;
import org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JInInterceptor;
import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
import org.jboss.wsf.spi.deployment.Endpoint;
import org.jboss.wsf.spi.security.SecurityDomainContext;
import javax.security.auth.Subject;
import java.security.Principal;
import java.util.Collections;
public class SamlSecurityContextInInterceptor extends WSS4JInInterceptor {
public SamlSecurityContextInInterceptor() {
super();
getAfter().add(PolicyBasedWSS4JInInterceptor.class.getName());
}
@Override
public void handleMessage(SoapMessage message) throws Fault {
final SecurityContext securityContext = message.get(SecurityContext.class);
final Principal principal = securityContext.getUserPrincipal();
final String name = principal.getName();
final Endpoint endpoint = message.getExchange().get(Endpoint.class);
final SecurityDomainContext securityDomainContext = endpoint.getSecurityDomainContext();
Principal simplePrincipal = new SimplePrincipal(name);
Subject subject = new Subject(false, Collections.singleton(simplePrincipal), Collections.emptySet(), Collections.emptySet());
securityDomainContext.pushSubjectContext(subject, simplePrincipal, null);
message.put(SecurityContext.class, new DefaultSecurityContext(simplePrincipal, subject));
}
}
| 2,716 | 45.050847 | 131 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/stsbearer/SampleSTSBearer.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.stsbearer;
import org.apache.cxf.annotations.EndpointProperties;
import org.apache.cxf.annotations.EndpointProperty;
import org.apache.cxf.sts.StaticSTSProperties;
import org.apache.cxf.sts.operation.TokenIssueOperation;
import org.apache.cxf.sts.service.ServiceMBean;
import org.apache.cxf.sts.service.StaticService;
import org.apache.cxf.sts.token.provider.SAMLTokenProvider;
import org.apache.cxf.ws.security.sts.provider.SecurityTokenServiceProvider;
import org.jboss.as.test.integration.ws.wsse.trust.shared.WSTrustAppUtils;
import jakarta.xml.ws.WebServiceProvider;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
@WebServiceProvider(serviceName = "SecurityTokenService",
portName = "UT_Port",
targetNamespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/",
wsdlLocation = "WEB-INF/wsdl/bearer-ws-trust-1.4-service.wsdl")
//be sure to have dependency on org.apache.cxf module when on AS7, otherwise Apache CXF annotations are ignored
@EndpointProperties(value = {
@EndpointProperty(key = "ws-security.signature.username", value = "mystskey"),
@EndpointProperty(key = "ws-security.signature.properties", value = "stsKeystore.properties"),
@EndpointProperty(key = "ws-security.callback-handler", value = "org.jboss.as.test.integration.ws.wsse.trust.stsbearer.STSBearerCallbackHandler")
})
public class SampleSTSBearer extends SecurityTokenServiceProvider {
public SampleSTSBearer() throws Exception {
super();
StaticSTSProperties props = new StaticSTSProperties();
props.setSignatureCryptoProperties("stsKeystore.properties");
props.setSignatureUsername("mystskey");
props.setCallbackHandlerClass(STSBearerCallbackHandler.class.getName());
props.setEncryptionCryptoProperties("stsKeystore.properties");
props.setEncryptionUsername("myservicekey");
props.setIssuer("DoubleItSTSIssuer");
List<ServiceMBean> services = new LinkedList<ServiceMBean>();
StaticService service = new StaticService();
String serverHostRegexp = WSTrustAppUtils.getServerHost().replace("[", "\\[").replace("]", "\\]").replace("127.0.0.1", "localhost");
service.setEndpoints(Arrays.asList(
"https://" + serverHostRegexp + ":(\\d)*/jaxws-samples-wsse-policy-trust-bearer/BearerService"
));
services.add(service);
TokenIssueOperation issueOperation = new TokenIssueOperation();
issueOperation.getTokenProviders().add(new SAMLTokenProvider());
issueOperation.setServices(services);
issueOperation.setStsProperties(props);
this.setIssueOperation(issueOperation);
}
}
| 3,790 | 48.233766 | 153 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/stsbearer/STSBearerCallbackHandler.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.stsbearer;
import org.jboss.wsf.stack.cxf.extensions.security.PasswordCallbackHandler;
import java.util.HashMap;
import java.util.Map;
public class STSBearerCallbackHandler extends PasswordCallbackHandler {
public STSBearerCallbackHandler() {
super(getInitMap());
}
private static Map<String, String> getInitMap() {
Map<String, String> passwords = new HashMap<String, String>();
passwords.put("mystskey", "stskpass");
passwords.put("alice", "clarinet");
return passwords;
}
}
| 1,620 | 38.536585 | 75 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/service/ServerCallbackHandler.java
|
/**
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.jboss.as.test.integration.ws.wsse.trust.service;
import org.jboss.wsf.stack.cxf.extensions.security.PasswordCallbackHandler;
import java.util.HashMap;
import java.util.Map;
public class ServerCallbackHandler extends PasswordCallbackHandler {
public ServerCallbackHandler() {
super(getInitMap());
}
private static Map<String, String> getInitMap() {
Map<String, String> passwords = new HashMap<String, String>();
passwords.put("myservicekey", "skpass");
return passwords;
}
}
| 1,352 | 34.605263 | 75 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/service/ServiceImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.service;
import org.apache.cxf.annotations.EndpointProperties;
import org.apache.cxf.annotations.EndpointProperty;
import jakarta.jws.WebService;
@WebService
(
portName = "SecurityServicePort",
serviceName = "SecurityService",
wsdlLocation = "WEB-INF/wsdl/SecurityService.wsdl",
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy",
endpointInterface = "org.jboss.as.test.integration.ws.wsse.trust.service.ServiceIface"
)
@EndpointProperties(value = {
@EndpointProperty(key = "ws-security.signature.username", value = "myservicekey"),
@EndpointProperty(key = "ws-security.signature.properties", value = "serviceKeystore.properties"),
@EndpointProperty(key = "ws-security.encryption.properties", value = "serviceKeystore.properties"),
@EndpointProperty(key = "ws-security.callback-handler", value = "org.jboss.as.test.integration.ws.wsse.trust.service.ServerCallbackHandler")
})
public class ServiceImpl implements ServiceIface {
public String sayHello() {
return "WS-Trust Hello World!";
}
}
| 2,250 | 45.895833 | 148 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/service/ServiceIface.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.service;
import jakarta.jws.WebMethod;
import jakarta.jws.WebService;
@WebService
(
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy"
)
public interface ServiceIface {
@WebMethod
String sayHello();
}
| 1,356 | 37.771429 | 95 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/holderofkey/HolderOfKeyImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.holderofkey;
import org.apache.cxf.annotations.EndpointProperties;
import org.apache.cxf.annotations.EndpointProperty;
import jakarta.jws.WebService;
@WebService
(
portName = "HolderOfKeyServicePort",
serviceName = "HolderOfKeyService",
wsdlLocation = "WEB-INF/wsdl/HolderOfKeyService.wsdl",
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/holderofkeywssecuritypolicy",
endpointInterface = "org.jboss.as.test.integration.ws.wsse.trust.holderofkey.HolderOfKeyIface"
)
@EndpointProperties(value = {
@EndpointProperty(key = "ws-security.is-bsp-compliant", value = "false"),
@EndpointProperty(key = "ws-security.signature.properties", value = "serviceKeystore.properties"),
@EndpointProperty(key = "ws-security.callback-handler", value = "org.jboss.as.test.integration.ws.wsse.trust.holderofkey.HolderOfKeyCallbackHandler")
})
public class HolderOfKeyImpl implements HolderOfKeyIface {
public String sayHello() {
return "Holder-Of-Key WS-Trust Hello World!";
}
}
| 2,196 | 45.744681 | 157 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/holderofkey/HolderOfKeyIface.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.holderofkey;
import jakarta.jws.WebMethod;
import jakarta.jws.WebService;
@WebService
(
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/holderofkeywssecuritypolicy"
)
public interface HolderOfKeyIface {
@WebMethod
String sayHello();
}
| 1,375 | 38.314286 | 106 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/holderofkey/HolderOfKeyCallbackHandler.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.holderofkey;
import org.jboss.wsf.stack.cxf.extensions.security.PasswordCallbackHandler;
import java.util.HashMap;
import java.util.Map;
/**
* User: rsearls
* Date: 3/14/14
*/
public class HolderOfKeyCallbackHandler extends PasswordCallbackHandler {
public HolderOfKeyCallbackHandler() {
super(getInitMap());
}
private static Map<String, String> getInitMap() {
Map<String, String> passwords = new HashMap<String, String>();
passwords.put("myservicekey", "skpass");
return passwords;
}
}
| 1,628 | 34.413043 | 75 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/shared/ClientCallbackHandler.java
|
/**
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.jboss.as.test.integration.ws.wsse.trust.shared;
import org.apache.wss4j.common.ext.WSPasswordCallback;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;
public class ClientCallbackHandler implements CallbackHandler {
public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof WSPasswordCallback) {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
if ("myclientkey".equals(pc.getIdentifier())) {
pc.setPassword("ckpass");
break;
} else if ("alice".equals(pc.getIdentifier())) {
pc.setPassword("clarinet");
break;
} else if ("bob".equals(pc.getIdentifier())) {
pc.setPassword("trombone");
break;
} else if ("myservicekey".equals(pc.getIdentifier())) { // rls test added for bearer test
pc.setPassword("skpass");
break;
}
}
}
}
}
| 2,133 | 40.038462 | 107 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/shared/WSTrustAppUtils.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.shared;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* User: rsearls
* Date: 2/5/14
*/
public class WSTrustAppUtils {
public static String getServerHost() {
final String host = System.getProperty("node0", "localhost");
return toIPv6URLFormat(host);
}
private static String toIPv6URLFormat(final String host) {
try {
if (host.startsWith("[") || host.startsWith(":")) {
if (System.getProperty("java.net.preferIPv4Stack") == null) {
throw new IllegalStateException("always provide java.net.preferIPv4Stack JVM property when using IPv6 address format");
}
if (System.getProperty("java.net.preferIPv6Addresses") == null) {
throw new IllegalStateException("always provide java.net.preferIPv6Addresses JVM property when using IPv6 address format");
}
}
final boolean isIPv6Address = InetAddress.getByName(host) instanceof Inet6Address;
final boolean isIPv6Formatted = isIPv6Address && host.startsWith("[");
return isIPv6Address && !isIPv6Formatted ? "[" + host + "]" : host;
} catch (final UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
| 2,425 | 41.561404 | 143 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/shared/UsernameTokenCallbackHandler.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.shared;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.message.Message;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.trust.delegation.DelegationCallback;
import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.message.token.UsernameToken;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;
import java.util.Map;
/**
* A utility to provide the 3 different input parameter types for jaxws property
* "ws-security.sts.token.act-as" and "ws-security.sts.token.on-behalf-of".
* This implementation obtains a username and password via the jaxws property
* "ws-security.username" and "ws-security.password" respectively, as defined
* in SecurityConstants. It creates a wss UsernameToken to be used as the
* delegation token.
* <p/>
* User: rsearls
* Date: 2/3/14
*/
public class UsernameTokenCallbackHandler implements CallbackHandler {
public void handle(Callback[] callbacks)
throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof DelegationCallback) {
DelegationCallback callback = (DelegationCallback) callbacks[i];
Message message = callback.getCurrentMessage();
String username =
(String) message.getContextualProperty(SecurityConstants.USERNAME);
String password =
(String) message.getContextualProperty(SecurityConstants.PASSWORD);
if (username != null) {
Node contentNode = message.getContent(Node.class);
Document doc = null;
if (contentNode != null) {
doc = contentNode.getOwnerDocument();
} else {
doc = DOMUtils.createDocument();
}
UsernameToken usernameToken = createWSSEUsernameToken(username, password, doc);
callback.setToken(usernameToken.getElement());
}
} else {
throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
}
}
}
/**
* Provide UsernameToken as a string.
*
* @param ctx
* @return
*/
public String getUsernameTokenString(Map<String, Object> ctx) {
Document doc = DOMUtils.createDocument();
String result = null;
String username = (String) ctx.get(SecurityConstants.USERNAME);
String password = (String) ctx.get(SecurityConstants.PASSWORD);
if (username != null) {
UsernameToken usernameToken = createWSSEUsernameToken(username, password, doc);
result = toString(usernameToken.getElement().getFirstChild().getParentNode());
}
return result;
}
/**
* @param username
* @param password
* @return
*/
public String getUsernameTokenString(String username, String password) {
Document doc = DOMUtils.createDocument();
String result = null;
if (username != null) {
UsernameToken usernameToken = createWSSEUsernameToken(username, password, doc);
result = toString(usernameToken.getElement().getFirstChild().getParentNode());
}
return result;
}
/**
* Provide UsernameToken as a DOM Element.
*
* @param ctx
* @return
*/
public Element getUsernameTokenElement(Map<String, Object> ctx) {
Document doc = DOMUtils.createDocument();
Element result = null;
UsernameToken usernameToken = null;
String username = (String) ctx.get(SecurityConstants.USERNAME);
String password = (String) ctx.get(SecurityConstants.PASSWORD);
if (username != null) {
usernameToken = createWSSEUsernameToken(username, password, doc);
result = usernameToken.getElement();
}
return result;
}
/**
* @param username
* @param password
* @return
*/
public Element getUsernameTokenElement(String username, String password) {
Document doc = DOMUtils.createDocument();
Element result = null;
UsernameToken usernameToken = null;
if (username != null) {
usernameToken = createWSSEUsernameToken(username, password, doc);
result = usernameToken.getElement();
}
return result;
}
private UsernameToken createWSSEUsernameToken(String username, String password, Document doc) {
UsernameToken usernameToken = new UsernameToken(true, doc,
(password == null) ? null : WSConstants.PASSWORD_TEXT);
usernameToken.setName(username);
usernameToken.addWSUNamespace();
usernameToken.addWSSENamespace();
usernameToken.setID("id-" + username);
if (password != null) {
usernameToken.setPassword(password);
}
return usernameToken;
}
private String toString(Node node) {
String str = null;
if (node != null) {
DOMImplementationLS lsImpl = (DOMImplementationLS)
node.getOwnerDocument().getImplementation().getFeature("LS", "3.0");
LSSerializer serializer = lsImpl.createLSSerializer();
serializer.getDomConfig().setParameter("xml-declaration", false); //by default its true, so set it to false to get String without xml-declaration
str = serializer.writeToString(node);
}
return str;
}
}
| 6,984 | 37.379121 | 157 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/actas/ActAsCallbackHandler.java
|
/**
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.jboss.as.test.integration.ws.wsse.trust.actas;
import org.jboss.wsf.stack.cxf.extensions.security.PasswordCallbackHandler;
import java.util.HashMap;
import java.util.Map;
/**
* User: [email protected]
* Date: 1/26/14
*/
public class ActAsCallbackHandler extends PasswordCallbackHandler {
public ActAsCallbackHandler() {
super(getInitMap());
}
private static Map<String, String> getInitMap() {
Map<String, String> passwords = new HashMap<String, String>();
passwords.put("myactaskey", "aspass");
passwords.put("alice", "clarinet");
return passwords;
}
}
| 1,444 | 31.840909 | 75 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/actas/ActAsServiceIface.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.actas;
import jakarta.jws.WebMethod;
import jakarta.jws.WebService;
/**
* User: [email protected]
* Date: 1/26/14
*/
@WebService
(
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/actaswssecuritypolicy"
)
public interface ActAsServiceIface {
@WebMethod
String sayHello(String host, String port);
}
| 1,441 | 35.974359 | 100 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/actas/ActAsServiceImpl.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.actas;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.annotations.EndpointProperties;
import org.apache.cxf.annotations.EndpointProperty;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.trust.STSClient;
import org.jboss.as.test.integration.ws.wsse.trust.service.ServiceIface;
import jakarta.jws.WebService;
import javax.xml.namespace.QName;
import jakarta.xml.ws.BindingProvider;
import jakarta.xml.ws.Service;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
/**
* User: [email protected]
* Date: 1/26/14
*/
@WebService
(
portName = "ActAsServicePort",
serviceName = "ActAsService",
wsdlLocation = "WEB-INF/wsdl/ActAsService.wsdl",
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/actaswssecuritypolicy",
endpointInterface = "org.jboss.as.test.integration.ws.wsse.trust.actas.ActAsServiceIface"
)
@EndpointProperties(value = {
@EndpointProperty(key = "ws-security.signature.username", value = "myactaskey"),
@EndpointProperty(key = "ws-security.signature.properties", value = "actasKeystore.properties"),
@EndpointProperty(key = "ws-security.encryption.properties", value = "actasKeystore.properties"),
@EndpointProperty(key = "ws-security.callback-handler", value = "org.jboss.as.test.integration.ws.wsse.trust.actas.ActAsCallbackHandler")
})
public class ActAsServiceImpl implements ActAsServiceIface {
public String sayHello(String host, String port) {
Bus bus = BusFactory.newInstance().createBus();
try {
BusFactory.setThreadDefaultBus(bus);
final String serviceURL = "http://" + host + ":" + port + "/jaxws-samples-wsse-policy-trust/SecurityService";
final QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/wssecuritypolicy", "SecurityService");
final URL wsdlURL = new URL(serviceURL + "?wsdl");
Service service = Service.create(wsdlURL, serviceName);
ServiceIface proxy = (ServiceIface) service.getPort(ServiceIface.class);
Map<String, Object> ctx = ((BindingProvider) proxy).getRequestContext();
ctx.put(SecurityConstants.CALLBACK_HANDLER, new ActAsCallbackHandler());
ctx.put(SecurityConstants.SIGNATURE_PROPERTIES,
Thread.currentThread().getContextClassLoader().getResource("actasKeystore.properties"));
ctx.put(SecurityConstants.SIGNATURE_USERNAME, "myactaskey");
ctx.put(SecurityConstants.ENCRYPT_PROPERTIES,
Thread.currentThread().getContextClassLoader().getResource("../../META-INF/clientKeystore.properties"));
ctx.put(SecurityConstants.ENCRYPT_USERNAME, "myservicekey");
STSClient stsClient = new STSClient(bus);
Map<String, Object> props = stsClient.getProperties();
props.put(SecurityConstants.USERNAME, "alice");
props.put(SecurityConstants.ENCRYPT_USERNAME, "mystskey");
props.put(SecurityConstants.STS_TOKEN_USERNAME, "myactaskey");
props.put(SecurityConstants.STS_TOKEN_PROPERTIES,
Thread.currentThread().getContextClassLoader().getResource("actasKeystore.properties"));
props.put(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO, "true");
ctx.put(SecurityConstants.STS_CLIENT, stsClient);
return "ActAs " + proxy.sayHello();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} finally {
bus.shutdown(true);
}
}
}
| 4,828 | 45.432692 | 145 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/onbehalfof/OnBehalfOfCallbackHandler.java
|
/**
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.jboss.as.test.integration.ws.wsse.trust.onbehalfof;
import org.jboss.wsf.stack.cxf.extensions.security.PasswordCallbackHandler;
import java.util.HashMap;
import java.util.Map;
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
/**
* User: [email protected]
* Date: 1/26/14
*/
public class OnBehalfOfCallbackHandler extends PasswordCallbackHandler {
public OnBehalfOfCallbackHandler() {
super(getInitMap());
}
private static Map<String, String> getInitMap() {
Map<String, String> passwords = new HashMap<String, String>();
passwords.put("myactaskey", "aspass");
passwords.put("alice", "clarinet");
passwords.put("bob", "trombone");
return passwords;
}
}
| 2,534 | 36.835821 | 75 |
java
|
null |
wildfly-main/testsuite/integration/ws/src/test/java/org/jboss/as/test/integration/ws/wsse/trust/onbehalfof/OnBehalfOfServiceIface.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ws.wsse.trust.onbehalfof;
import jakarta.jws.WebMethod;
import jakarta.jws.WebService;
/**
* User: [email protected]
* Date: 1/26/14
*/
@WebService
(
targetNamespace = "http://www.jboss.org/jbossws/ws-extensions/onbehalfofwssecuritypolicy"
)
public interface OnBehalfOfServiceIface {
@WebMethod
String sayHello(String host, String port);
}
| 1,456 | 36.358974 | 105 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.