diff --git a/appserver/admingui/jms-plugin/src/main/java/org/glassfish/admingui/plugin/jms/JmsHandlers.java b/appserver/admingui/jms-plugin/src/main/java/org/glassfish/admingui/plugin/jms/JmsHandlers.java index 3167649c272..4024b7518e8 100644 --- a/appserver/admingui/jms-plugin/src/main/java/org/glassfish/admingui/plugin/jms/JmsHandlers.java +++ b/appserver/admingui/jms-plugin/src/main/java/org/glassfish/admingui/plugin/jms/JmsHandlers.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -138,7 +139,7 @@ public static void getPhysicalDestination(HandlerContext handlerCtx) { Map valueMap = new HashMap(); try { String objectName = getJmsDestinationObjectName(SUBTYPE_CONFIG, name, type); - AttributeList attributes = (AttributeList) JMXUtil.getMBeanServer().getAttributes(new ObjectName(objectName), ATTRS_CONFIG); + AttributeList attributes = JMXUtil.getMBeanServer().getAttributes(new ObjectName(objectName), ATTRS_CONFIG); for (Attribute attribute : attributes.asList()) { valueMap.put(attribute.getName(), (attribute.getValue() != null) ? attribute.getValue().toString() : null); } @@ -168,7 +169,7 @@ public static void getPhysicalDestinationStats(HandlerContext handlerCtx) { insureJmsBrokerIsRunning(); String objectName = getJmsDestinationObjectName(SUBTYPE_MONITOR, name, type); - AttributeList attributes = (AttributeList) getMBeanServerConnection(target).getAttributes(new ObjectName(objectName), ATTRS_MONITOR); + AttributeList attributes = getMBeanServerConnection(target).getAttributes(new ObjectName(objectName), ATTRS_MONITOR); ResourceBundle bundle = GuiUtil.getBundle("org.glassfish.jms.admingui.Strings"); statsList.add(createRow("Name", name, "")); statsList.add(createRow("Type", type.substring(0, 1).toUpperCase(GuiUtil.guiLocale) + type.substring(1), "")); @@ -208,12 +209,12 @@ public static void getPhysicalDestinations(HandlerContext handlerCtx) { List selectedList = (List) handlerCtx.getInputValue("selectedRows"); boolean hasOrig = (selectedList == null || selectedList.size() == 0) ? false : true; - for (int i = 0; i < objectNames.length; i++) { + for (ObjectName objectName : objectNames) { // getAttributes for the given objectName... HashMap oneRow = new HashMap(); - oneRow.put("name", objectNames[i].getKeyProperty(PROP_NAME).replaceAll("\"", "")); - oneRow.put("type", "t".equals(objectNames[i].getKeyProperty(PROP_DEST_TYPE)) ? "topic" : "queue"); - oneRow.put("selected", (hasOrig) ? isSelected(objectNames[i].getKeyProperty(PROP_NAME), selectedList) : false); + oneRow.put("name", objectName.getKeyProperty(PROP_NAME).replaceAll("\"", "")); + oneRow.put("type", "t".equals(objectName.getKeyProperty(PROP_DEST_TYPE)) ? "topic" : "queue"); + oneRow.put("selected", (hasOrig) ? isSelected(objectName.getKeyProperty(PROP_NAME), selectedList) : false); result.add(oneRow); } @@ -287,7 +288,7 @@ public static void updatePhysicalDestination(HandlerContext handlerCtx) { public static void deleteJMSDest(HandlerContext handlerCtx) { // String configName = ((String) handlerCtx.getInputValue("targetName")); List obj = (List) handlerCtx.getInputValue("selectedRows"); - List selectedRows = (List) obj; + List selectedRows = obj; try { for (Map oneRow : selectedRows) { String name = (String) oneRow.get("name"); @@ -403,7 +404,7 @@ protected static void buildAttributeList(AttributeList list, Map attrMap, String list.add(new Attribute(ATTR_MAX_NUM_MSGS, Long.parseLong((String) attrMap.get(ATTR_MAX_NUM_MSGS)))); list.add(new Attribute(ATTR_MAX_BYTES_PER_MSG, Long.parseLong((String) attrMap.get(ATTR_MAX_BYTES_PER_MSG)))); list.add(new Attribute(ATTR_MAX_TOTAL_MSG_BYTES, Long.parseLong((String) attrMap.get(ATTR_MAX_TOTAL_MSG_BYTES)))); - list.add(new Attribute(ATTR_LIMIT_BEHAVIOR, (String) attrMap.get(ATTR_LIMIT_BEHAVIOR))); + list.add(new Attribute(ATTR_LIMIT_BEHAVIOR, attrMap.get(ATTR_LIMIT_BEHAVIOR))); list.add(new Attribute(ATTR_MAX_NUM_PRODUCERS, Integer.parseInt((String) attrMap.get(ATTR_MAX_NUM_PRODUCERS)))); if ("queue".equals(type)) { list.add(new Attribute(ATTR_MAX_NUM_ACTIVE_CONSUMERS, Integer.parseInt((String) attrMap.get(ATTR_MAX_NUM_ACTIVE_CONSUMERS)))); @@ -413,7 +414,7 @@ protected static void buildAttributeList(AttributeList list, Map attrMap, String list.add(new Attribute(ATTR_CONSUMER_FLOW_LIMIT, Long.parseLong((String) attrMap.get(ATTR_CONSUMER_FLOW_LIMIT)))); list.add(new Attribute(ATTR_USE_DMQ, Boolean.valueOf((String) attrMap.get(ATTR_USE_DMQ)))); list.add(new Attribute(ATTR_VALIDATE_XML_SCHEMA_ENABLED, Boolean.valueOf((String) attrMap.get(ATTR_VALIDATE_XML_SCHEMA_ENABLED)))); - list.add(new Attribute(ATTR_XML_SCHEMA_URI_LIST, (String) attrMap.get(ATTR_XML_SCHEMA_URI_LIST))); + list.add(new Attribute(ATTR_XML_SCHEMA_URI_LIST, attrMap.get(ATTR_XML_SCHEMA_URI_LIST))); } protected static void insureJmsBrokerIsRunning() throws ConnectorRuntimeException { @@ -444,14 +445,15 @@ private static MBeanServerConnection getMBeanServerConnection(String target) thr } PhysicalDestinations pd = new PhysicalDestinations(); - MQJMXConnectorInfo mqInfo = pd.getConnectorInfo(target, configRef, habitat, domain); - - return mqInfo.getMQMBeanServerConnection(); + try (MQJMXConnectorInfo mqInfo = pd.createConnectorInfo(target, configRef, habitat, domain)) { + // fyi, the connection is just a description, not closeable. + return mqInfo.getMQMBeanServerConnection(); + } } private static class PhysicalDestinations extends JMSDestination { - public MQJMXConnectorInfo getConnectorInfo(String target, String configName, ServiceLocator habitat, Domain domain) throws Exception { - return getMQJMXConnectorInfo(target, domain.getConfigNamed(configName), habitat.getService(ServerContext.class), + public MQJMXConnectorInfo createConnectorInfo(String target, String configName, ServiceLocator habitat, Domain domain) throws Exception { + return createMQJMXConnectorInfo(target, domain.getConfigNamed(configName), habitat.getService(ServerContext.class), domain, habitat.getService(ConnectorRuntime.class)); } } diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainer.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainer.java index e5e6a93b74d..3789d0930c9 100644 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainer.java +++ b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/AppClientContainer.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -236,7 +237,7 @@ public static AppClientContainer.Builder newBuilder( private URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); - private Collection emfs = null; + private final Collection emfs = null; // private boolean isJWS = false; @@ -354,7 +355,7 @@ private void completePreparation(final Instrumentation inst) throws * Allow pre-destroy handling to work on the main class during clean-up. */ cleanup.setInjectionManager(injectionManager, - clientMainClassSetting.clientMainClass); + ClientMainClassSetting.clientMainClass); /* * If this app client contains persistence unit refs, then initialize @@ -459,9 +460,10 @@ public Map run() { private void cleanupWhenSafe() { if (isEDTRunning()) { - final AtomicReference edt = new AtomicReference(); + final AtomicReference edt = new AtomicReference<>(); try { SwingUtilities.invokeAndWait(new Runnable() { + @Override public void run() { edt.set(Thread.currentThread()); } @@ -498,7 +500,7 @@ private Method getMainMethod() throws NoSuchMethodException, // String[] as the only argument Method result = null; - result = clientMainClassSetting.getClientMainClass( + result = ClientMainClassSetting.getClientMainClass( classLoader, injectionManager, invocationManager, @@ -729,14 +731,14 @@ void setClassLoader(ACCClassLoader classLoader) { */ public interface Builder { - public AppClientContainer newContainer(URI archiveURI) throws Exception, UserError; + AppClientContainer newContainer(URI archiveURI) throws Exception, UserError; - public AppClientContainer newContainer(URI archiveURI, + AppClientContainer newContainer(URI archiveURI, CallbackHandler callbackHandler, String mainClassName, String appName) throws Exception, UserError; - public AppClientContainer newContainer(URI archiveURI, + AppClientContainer newContainer(URI archiveURI, CallbackHandler callbackHandler, String mainClassName, String appName, @@ -744,9 +746,9 @@ public AppClientContainer newContainer(URI archiveURI, - public AppClientContainer newContainer(Class mainClass) throws Exception, UserError; + AppClientContainer newContainer(Class mainClass) throws Exception, UserError; - public TargetServer[] getTargetServers(); + TargetServer[] getTargetServers(); /** * Adds an optional {@link MessageSecurityConfig} setting. @@ -754,9 +756,9 @@ public AppClientContainer newContainer(URI archiveURI, * @param msConfig the new MessageSecurityConfig * @return the Builder instance */ - public Builder addMessageSecurityConfig(final MessageSecurityConfig msConfig); + Builder addMessageSecurityConfig(final MessageSecurityConfig msConfig); - public List getMessageSecurityConfig(); + List getMessageSecurityConfig(); /** * Sets the optional authentication realm for the ACC. @@ -767,9 +769,9 @@ public AppClientContainer newContainer(URI archiveURI, * @param className name of the class which implements the realm * @return the Builder instance */ - public Builder authRealm(final String className); + Builder authRealm(final String className); - public AuthRealm getAuthRealm(); + AuthRealm getAuthRealm(); // /** // * Sets the callback handler the ACC will use when authentication is @@ -802,9 +804,9 @@ public AppClientContainer newContainer(URI archiveURI, * @param password password valid in the default realm on the server for the username * @return the Builder instance */ - public Builder clientCredentials(final String user, final char[] password); + Builder clientCredentials(final String user, final char[] password); - public ClientCredential getClientCredential(); + ClientCredential getClientCredential(); /** * Sets the optional client credentials and server-side realm to be used during @@ -819,7 +821,7 @@ public AppClientContainer newContainer(URI archiveURI, * @param realmName name of the realm on the server within which the credentials are valid * @return the Builder instance */ - public Builder clientCredentials(final String user, final char[] password, final String realm); + Builder clientCredentials(final String user, final char[] password, final String realm); /** * Sets the container-level Properties. @@ -827,7 +829,7 @@ public AppClientContainer newContainer(URI archiveURI, * @param containerProperties * @return */ - public Builder containerProperties(final Properties containerProperties); + Builder containerProperties(final Properties containerProperties); /** * Sets the container-level properties. @@ -838,13 +840,13 @@ public AppClientContainer newContainer(URI archiveURI, * @param containerProperties Property objects to use in setting the properties * @return */ - public Builder containerProperties(final List containerProperties); + Builder containerProperties(final List containerProperties); /** * Returns the container-level Properties. * @return container-level properties */ - public Properties getContainerProperties(); + Properties getContainerProperties(); /** * Sets the logger which the ACC should use as it runs. @@ -852,9 +854,9 @@ public AppClientContainer newContainer(URI archiveURI, * @param logger * @return */ - public Builder logger(final Logger logger); + Builder logger(final Logger logger); - public Logger getLogger(); + Logger getLogger(); /** * Sets whether the ACC should send the password to the server during @@ -863,9 +865,9 @@ public AppClientContainer newContainer(URI archiveURI, * @param sendPassword * @return */ - public Builder sendPassword(final boolean sendPassword); + Builder sendPassword(final boolean sendPassword); - public boolean getSendPassword(); + boolean getSendPassword(); } diff --git a/appserver/common/container-common/src/main/java/org/glassfish/ha/commands/ListPersistenceTypesCommand.java b/appserver/common/container-common/src/main/java/org/glassfish/ha/commands/ListPersistenceTypesCommand.java index 8cadb03839c..f26bd4ed3be 100644 --- a/appserver/common/container-common/src/main/java/org/glassfish/ha/commands/ListPersistenceTypesCommand.java +++ b/appserver/common/container-common/src/main/java/org/glassfish/ha/commands/ListPersistenceTypesCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -17,7 +18,14 @@ package org.glassfish.ha.commands; import com.sun.enterprise.config.serverbeans.Domain; -import java.util.*; + +import jakarta.validation.constraints.Pattern; + +import java.util.ArrayList; +import java.util.Properties; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; import org.glassfish.api.ActionReport; import org.glassfish.api.I18n; @@ -25,15 +33,11 @@ import org.glassfish.api.admin.AdminCommand; import org.glassfish.api.admin.AdminCommandContext; import org.glassfish.api.admin.CommandLock; - -import org.jvnet.hk2.annotations.Service; -import org.glassfish.hk2.api.PerLookup; - -import jakarta.validation.constraints.Pattern; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.glassfish.api.admin.*; +import org.glassfish.api.admin.RestEndpoint; +import org.glassfish.api.admin.RestEndpoints; import org.glassfish.ha.store.spi.BackingStoreFactoryRegistry; +import org.glassfish.hk2.api.PerLookup; +import org.jvnet.hk2.annotations.Service; /** * The list-persistence-types command lists different kinds of persistence options for session data @@ -51,10 +55,12 @@ }) public class ListPersistenceTypesCommand implements AdminCommand { - @Param(name="type", optional=false, primary=false) + private static final String CONTAINER_TYPES = "(ejb|web)"; + + @Param(name = "type", optional = false, primary = false) @I18n("list.persistence.types.container") - @Pattern(regexp = "(ejb|web)") - private String containerType = ""; + @Pattern(regexp = CONTAINER_TYPES, message = "Valid values: " + CONTAINER_TYPES) + private final String containerType = ""; private Logger logger; private static final String EOL = "\n"; @@ -89,7 +95,7 @@ public void execute(AdminCommandContext context) { output = output.substring(0, output.length()-1); } Properties extraProperties = new Properties(); - extraProperties.put("types", new ArrayList(allPersistenceTypes)); + extraProperties.put("types", new ArrayList<>(allPersistenceTypes)); report.setExtraProperties(extraProperties); report.setMessage(output); diff --git a/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/ResourceAdapterConfig.java b/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/ResourceAdapterConfig.java index 27a841d97fc..c3a0decd983 100644 --- a/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/ResourceAdapterConfig.java +++ b/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/ResourceAdapterConfig.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -17,26 +18,27 @@ package org.glassfish.connectors.config; import com.sun.enterprise.config.serverbeans.Resource; -import org.glassfish.resourcebase.resources.ResourceDeploymentOrder; -import org.glassfish.resourcebase.resources.ResourceTypeOrder; -import org.jvnet.hk2.config.*; + +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; import java.util.List; +import org.glassfish.api.admin.RestRedirect; +import org.glassfish.api.admin.RestRedirects; import org.glassfish.api.admin.config.PropertiesDesc; +import org.glassfish.quality.ToDo; +import org.glassfish.resourcebase.resources.ResourceDeploymentOrder; +import org.glassfish.resourcebase.resources.ResourceTypeOrder; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.DuckTyped; +import org.jvnet.hk2.config.Element; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import org.glassfish.api.admin.RestRedirects; -import org.glassfish.api.admin.RestRedirect; -import static org.glassfish.config.support.Constants.NAME_REGEX; - -import org.glassfish.quality.ToDo; -import jakarta.validation.constraints.Pattern; -/** - * - */ +import static org.glassfish.config.support.Constants.NAME_REGEX; /* @XmlType(name = "", propOrder = { "property" @@ -56,6 +58,8 @@ @ResourceTypeOrder(deploymentOrder= ResourceDeploymentOrder.RESOURCEADAPTERCONFIG_RESOURCE) public interface ResourceAdapterConfig extends ConfigBeanProxy, Resource, PropertyBag { + String PATTERN_RA_NAME = "[^',][^',\\\\]*"; + /** * Gets the value of the name property. * @@ -63,16 +67,16 @@ public interface ResourceAdapterConfig extends ConfigBeanProxy, Resource, Proper * {@link String } */ @Attribute - @Pattern(regexp=NAME_REGEX) - public String getName(); + @Pattern(regexp = NAME_REGEX, message = "Pattern: " + NAME_REGEX) + String getName(); /** * Sets the value of the name property. * * @param value allowed object is - * {@link String } + * {@link String } */ - public void setName(String value) throws PropertyVetoException; + void setName(String value) throws PropertyVetoException; /** * Gets the value of the threadPoolIds property. @@ -81,15 +85,15 @@ public interface ResourceAdapterConfig extends ConfigBeanProxy, Resource, Proper * {@link String } */ @Attribute - public String getThreadPoolIds(); + String getThreadPoolIds(); /** * Sets the value of the threadPoolIds property. * * @param value allowed object is - * {@link String } + * {@link String } */ - public void setThreadPoolIds(String value) throws PropertyVetoException; + void setThreadPoolIds(String value) throws PropertyVetoException; /** * Gets the value of the resourceAdapterName property. @@ -97,31 +101,34 @@ public interface ResourceAdapterConfig extends ConfigBeanProxy, Resource, Proper * @return possible object is * {@link String } */ - @Attribute(key=true) - @Pattern(regexp="[^',][^',\\\\]*") - public String getResourceAdapterName(); + @Attribute(key = true) + @Pattern(regexp = PATTERN_RA_NAME, message = "Pattern: " + PATTERN_RA_NAME) + String getResourceAdapterName(); /** * Sets the value of the resourceAdapterName property. * * @param value allowed object is - * {@link String } + * {@link String } */ - public void setResourceAdapterName(String value) throws PropertyVetoException; + void setResourceAdapterName(String value) throws PropertyVetoException; /** - Properties as per {@link org.jvnet.hk2.config.types.PropertyBag} + * Properties as per {@link org.jvnet.hk2.config.types.PropertyBag} */ - @ToDo(priority=ToDo.Priority.IMPORTANT, details="Provide PropertyDesc for legal props" ) - @PropertiesDesc(props={}) + @Override + @ToDo(priority = ToDo.Priority.IMPORTANT, details = "Provide PropertyDesc for legal props") + @PropertiesDesc(props = {}) @Element List getProperty(); + @Override @DuckTyped String getIdentity(); class Duck { - public static String getIdentity(ResourceAdapterConfig resource){ + + public static String getIdentity(ResourceAdapterConfig resource) { return resource.getResourceAdapterName(); } } diff --git a/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/SecurityMap.java b/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/SecurityMap.java index f5adfdaee38..99566fec4d9 100644 --- a/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/SecurityMap.java +++ b/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/SecurityMap.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,17 +17,18 @@ package org.glassfish.connectors.config; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.Element; -import org.jvnet.hk2.config.ConfigBeanProxy; -import static org.glassfish.config.support.Constants.NAME_REGEX; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; import java.util.List; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.Element; + +import static org.glassfish.config.support.Constants.NAME_REGEX; /** * Perform mapping from principal received during Servlet/EJB authentication, @@ -49,18 +51,18 @@ public interface SecurityMap extends ConfigBeanProxy { * @return possible object is * {@link String } */ - @Attribute(key=true) + @Attribute(key = true) @NotNull - @Pattern(regexp=NAME_REGEX) - public String getName(); + @Pattern(regexp = NAME_REGEX, message = "Pattern: " + NAME_REGEX) + String getName(); /** * Sets the value of the name property. * * @param value allowed object is - * {@link String } + * {@link String } */ - public void setName(String value) throws PropertyVetoException; + void setName(String value) throws PropertyVetoException; /** * Gets the value of the backendPrincipal property. @@ -68,33 +70,34 @@ public interface SecurityMap extends ConfigBeanProxy { * @return possible object is * {@link BackendPrincipal } */ - @Element(required=true) - public BackendPrincipal getBackendPrincipal(); + @Element(required = true) + BackendPrincipal getBackendPrincipal(); /** * Sets the value of the backendPrincipal property. * * @param value allowed object is - * {@link BackendPrincipal } + * {@link BackendPrincipal } */ - public void setBackendPrincipal(BackendPrincipal value) throws PropertyVetoException; + void setBackendPrincipal(BackendPrincipal value) throws PropertyVetoException; /** * get the list of principals to be mapped to backend-principal + * * @return list of principals */ @Element - public List getPrincipal(); + List getPrincipal(); void setPrincipal(List principals) throws PropertyVetoException; - /** * get the list of user-groups to be mapped to backend principal + * * @return list of user-groups */ @Element - public List getUserGroup(); + List getUserGroup(); void setUserGroup(List userGroups) throws PropertyVetoException; } diff --git a/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/WorkSecurityMap.java b/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/WorkSecurityMap.java index 437f5fdc35e..e6fd47f2c60 100644 --- a/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/WorkSecurityMap.java +++ b/appserver/connectors/connectors-internal-api/src/main/java/org/glassfish/connectors/config/WorkSecurityMap.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,19 +17,27 @@ package org.glassfish.connectors.config; -import com.sun.enterprise.config.serverbeans.*; -import org.glassfish.resourcebase.resources.ResourceDeploymentOrder; -import org.glassfish.resourcebase.resources.ResourceTypeOrder; -import org.jvnet.hk2.config.*; +import com.sun.enterprise.config.serverbeans.Resource; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Pattern; + import java.beans.PropertyVetoException; import java.util.List; +import org.glassfish.resourcebase.resources.ResourceDeploymentOrder; +import org.glassfish.resourcebase.resources.ResourceTypeOrder; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.DuckTyped; +import org.jvnet.hk2.config.Element; + @Configured -@ResourceTypeOrder(deploymentOrder= ResourceDeploymentOrder.WORKSECURITYMAP_RESOURCE) -public interface WorkSecurityMap extends /*Named,*/ ConfigBeanProxy, Resource { +@ResourceTypeOrder(deploymentOrder = ResourceDeploymentOrder.WORKSECURITYMAP_RESOURCE) +public interface WorkSecurityMap extends ConfigBeanProxy, Resource { + + String PATTERN_RA_NAME = "[^',][^',\\\\]*"; /** * Gets the value of the enabled property. @@ -36,14 +45,14 @@ public interface WorkSecurityMap extends /*Named,*/ ConfigBeanProxy, Resource { * @return possible object is * {@link String } */ - @Attribute (defaultValue="true",dataType=Boolean.class) + @Attribute(defaultValue = "true", dataType = Boolean.class) String getEnabled(); /** * Sets the value of the enabled property. * * @param value allowed object is - * {@link String } + * {@link String } */ void setEnabled(String value) throws PropertyVetoException; @@ -60,11 +69,10 @@ public interface WorkSecurityMap extends /*Named,*/ ConfigBeanProxy, Resource { * Sets the value of the description property. * * @param value allowed object is - * {@link String } + * {@link String } */ void setDescription(String value) throws PropertyVetoException; - /** * Gets the value of the ra name * @@ -73,53 +81,55 @@ public interface WorkSecurityMap extends /*Named,*/ ConfigBeanProxy, Resource { */ @Attribute @NotNull - @Pattern(regexp="[^',][^',\\\\]*") - public String getResourceAdapterName(); + @Pattern(regexp = PATTERN_RA_NAME, message = "Pattern: " + PATTERN_RA_NAME) + String getResourceAdapterName(); /** * Sets the value of the ra name * * @param value allowed object is - * {@link String } + * {@link String } */ - public void setResourceAdapterName(String value) throws PropertyVetoException; + void setResourceAdapterName(String value) throws PropertyVetoException; /** * Gets the group map - * @return group map * + * @return group map */ @Element @NotNull - public List getGroupMap(); + List getGroupMap(); /** * gets the principal map + * * @return principal map */ @Element @NotNull - public List getPrincipalMap(); + List getPrincipalMap(); /** - * Name of the configured object + * Name of the configured object * * @return name of the configured object */ - @Attribute(required=true, key=true) - @Pattern(regexp="[^',][^',\\\\]*") + @Attribute(required = true, key = true) + @Pattern(regexp = PATTERN_RA_NAME, message = "Pattern: " + PATTERN_RA_NAME) @NotNull - public String getName(); + String getName(); - public void setName(String value) throws PropertyVetoException; + void setName(String value) throws PropertyVetoException; + @Override @DuckTyped String getIdentity(); class Duck { - public static String getIdentity(WorkSecurityMap wsm){ - return ("resource-adapter : " + wsm.getResourceAdapterName() - + " : security-map : " + wsm.getName()); + + public static String getIdentity(WorkSecurityMap wsm) { + return ("resource-adapter : " + wsm.getResourceAdapterName() + " : security-map : " + wsm.getName()); } } } diff --git a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/SaxParserHandler.java b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/SaxParserHandler.java index d5f625cccf2..264d1bf0f5a 100644 --- a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/SaxParserHandler.java +++ b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/node/SaxParserHandler.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -22,8 +23,28 @@ import com.sun.enterprise.deployment.xml.TagNames; import com.sun.enterprise.util.LocalStringManagerImpl; -import org.jvnet.hk2.annotations.Service; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EmptyStackException; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Stack; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.logging.Level; + import org.glassfish.hk2.api.PerLookup; +import org.jvnet.hk2.annotations.Service; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -31,13 +52,6 @@ import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.NamespaceSupport; -import java.io.*; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.logging.Level; - /** * This class implements all the callbacks for the SAX Parser in JAXP 1.1 @@ -57,8 +71,8 @@ public class SaxParserHandler extends DefaultHandler { private static final String FALSE_STR = "false"; private static final class MappingStuff { - public final ConcurrentMap mBundleRegistrationStatus = new ConcurrentHashMap(); - public final ConcurrentMap mMapping = new ConcurrentHashMap(); + public final ConcurrentMap mBundleRegistrationStatus = new ConcurrentHashMap<>(); + public final ConcurrentMap mMapping = new ConcurrentHashMap<>(); private final ConcurrentMap mRootNodesMutable; public final Map mRootNodes; @@ -72,33 +86,33 @@ private static final class MappingStuff { private final Map> mVersionUpgrades; MappingStuff() { - mRootNodesMutable = new ConcurrentHashMap(); + mRootNodesMutable = new ConcurrentHashMap<>(); mRootNodes = Collections.unmodifiableMap( mRootNodesMutable ); - mElementsAllowingEmptyValuesMutable = new CopyOnWriteArraySet(); + mElementsAllowingEmptyValuesMutable = new CopyOnWriteArraySet<>(); mElementsAllowingEmptyValues = Collections.unmodifiableSet(mElementsAllowingEmptyValuesMutable); - mElementsPreservingWhiteSpaceMutable = new CopyOnWriteArraySet(); + mElementsPreservingWhiteSpaceMutable = new CopyOnWriteArraySet<>(); mElementsPreservingWhiteSpace = Collections.unmodifiableSet(mElementsPreservingWhiteSpaceMutable); - mVersionUpgradeClasses = new ConcurrentHashMap>(); - mVersionUpgrades = new ConcurrentHashMap>(); + mVersionUpgradeClasses = new ConcurrentHashMap<>(); + mVersionUpgrades = new ConcurrentHashMap<>(); } } private static final MappingStuff _mappingStuff = new MappingStuff(); - private final List nodes = new ArrayList(); + private final List nodes = new ArrayList<>(); public XMLNode topNode = null; - protected String publicID=null; - private StringBuffer elementData=null; - private Map prefixMapping=null; + protected String publicID = null; + private StringBuffer elementData = null; + private Map prefixMapping = null; private boolean stopOnXMLErrors = false; private boolean pushedNamespaceContext=false; - private NamespaceSupport namespaces = new NamespaceSupport(); + private final NamespaceSupport namespaces = new NamespaceSupport(); - private Stack elementStack = new Stack(); + private final Stack elementStack = new Stack(); private static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(SaxParserHandler.class); @@ -112,9 +126,10 @@ protected static List getVersionUpgrades(String key) { return versionUpgradeList; } List classList = _mappingStuff.mVersionUpgradeClasses.get(key); - if (classList == null) + if (classList == null) { return null; - versionUpgradeList = new ArrayList(); + } + versionUpgradeList = new ArrayList<>(); for (int n = 0; n < classList.size(); ++n) { VersionUpgrade versionUpgrade = null; try { @@ -154,8 +169,8 @@ public static void registerBundleNode(BundleNode bn, String bundleTagName) { return; } - final HashMap dtdMapping = new HashMap(); - final Map> versionUpgrades = new HashMap>(); + final HashMap dtdMapping = new HashMap<>(); + final Map> versionUpgrades = new HashMap<>(); String rootNodeKey = bn.registerBundle(dtdMapping); _mappingStuff.mRootNodesMutable.putIfAbsent(rootNodeKey, bn.getClass()); @@ -199,6 +214,7 @@ public static void registerBundleNode(BundleNode bn, String bundleTagName) { _mappingStuff.mBundleRegistrationStatus.put(rootNodeKey, Boolean.TRUE); } + @Override public InputSource resolveEntity(String publicID, String systemID) throws SAXException { try { if(DOLUtils.getDefaultLogger().isLoggable(Level.FINE)) { @@ -229,7 +245,7 @@ public InputSource resolveEntity(String publicID, String systemID) throws SAXExc "Requested schema is not found in local repository, please ensure that there are no typos in the XML namespace declaration.")); } if (DOLUtils.getDefaultLogger().isLoggable(Level.FINE)) { - DOLUtils.getDefaultLogger().fine("Resolved to " + fileName);; + DOLUtils.getDefaultLogger().fine("Resolved to " + fileName); } return new InputSource(fileName); } @@ -251,8 +267,9 @@ public void setStopOnError(boolean stop) { } + @Override public void error(SAXParseException spe) throws SAXParseException { - DOLUtils.getDefaultLogger().log(Level.SEVERE, "enterprise.deployment.backend.invalidDescriptorFailure", + DOLUtils.getDefaultLogger().log(Level.SEVERE, DOLUtils.INVALILD_DESCRIPTOR, new Object[] {errorReportingString, String.valueOf(spe.getLineNumber()), String.valueOf(spe.getColumnNumber()), spe.getLocalizedMessage()}); if (stopOnXMLErrors) { @@ -261,8 +278,9 @@ public void error(SAXParseException spe) throws SAXParseException { } + @Override public void fatalError(SAXParseException spe) throws SAXParseException { - DOLUtils.getDefaultLogger().log(Level.SEVERE, "enterprise.deployment.backend.invalidDescriptorFailure", + DOLUtils.getDefaultLogger().log(Level.SEVERE, DOLUtils.INVALILD_DESCRIPTOR, new Object[] {errorReportingString, String.valueOf(spe.getLineNumber()), String.valueOf(spe.getColumnNumber()), spe.getLocalizedMessage()}); if (stopOnXMLErrors) { @@ -327,8 +345,7 @@ public static File getSchemaFileFor(String schemaSystemID) throws IOException { */ public static String resolveSchemaNamespace(String systemID) { List namespaces = DOLUtils.getProprietarySchemaNamespaces(); - for (int n = 0; n < namespaces.size(); ++n) { - String namespace = namespaces.get(n); + for (String namespace : namespaces) { if (systemID.startsWith(namespace)) { return systemID.substring(namespace.length()); } @@ -346,8 +363,7 @@ public static String resolveSchemaNamespace(String systemID) { */ public static String resolvePublicID(String publicID, String dtd) { List dtdStarts = DOLUtils.getProprietaryDTDStart(); - for (int n = 0; n < dtdStarts.size(); ++n) { - String dtdStart = dtdStarts.get(n); + for (String dtdStart : dtdStarts) { if (dtd.startsWith(dtdStart)) { return dtd.substring(dtdStart.length()); } @@ -355,6 +371,7 @@ public static String resolvePublicID(String publicID, String dtd) { return null; } + @Override public void notationDecl(java.lang.String name, java.lang.String publicId, java.lang.String systemId) @@ -365,12 +382,13 @@ public void notationDecl(java.lang.String name, } + @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { if (prefixMapping==null) { - prefixMapping = new HashMap(); + prefixMapping = new HashMap<>(); } // We need one namespace context per element, but any prefix mapping @@ -385,6 +403,7 @@ public void startPrefixMapping(String prefix, } + @Override public void startElement(String uri, String localName, String qName, Attributes attributes) { if (!pushedNamespaceContext) { // We need one namespae context per element, so push a context @@ -405,8 +424,7 @@ public void startElement(String uri, String localName, String qName, Attributes rootElement = localName; versionUpgradeList = getVersionUpgrades(rootElement); if (versionUpgradeList != null) { - for (int n = 0; n < versionUpgradeList.size(); ++n) { - VersionUpgrade versionUpgrade = versionUpgradeList.get(n); + for (VersionUpgrade versionUpgrade : versionUpgradeList) { versionUpgrade.init(); } } @@ -417,8 +435,7 @@ public void startElement(String uri, String localName, String qName, Attributes } if (versionUpgradeList != null) { - for (int n = 0; n < versionUpgradeList.size(); ++n) { - VersionUpgrade versionUpgrade = versionUpgradeList.get(n); + for (VersionUpgrade versionUpgrade : versionUpgradeList) { if (VersionUpgrade.UpgradeType.REMOVE_ELEMENT == versionUpgrade.getUpgradeType()) { Map matchXPath = versionUpgrade.getMatchXPath(); int entriesMatched = 0; @@ -495,6 +512,7 @@ public void startElement(String uri, String localName, String qName, Attributes } } + @Override public void endElement(String uri, String localName, String qName) { String lastElement = null; @@ -521,8 +539,7 @@ public void endElement(String uri, String localName, String qName) { String replacementName = null; String replacementValue = null; if (versionUpgradeList != null) { - for (int n = 0; n < versionUpgradeList.size(); ++n) { - VersionUpgrade versionUpgrade = versionUpgradeList.get(n); + for (VersionUpgrade versionUpgrade : versionUpgradeList) { if (VersionUpgrade.UpgradeType.REPLACE_ELEMENT == versionUpgrade.getUpgradeType()) { Map matchXPath = versionUpgrade.getMatchXPath(); int entriesMatched = 0; @@ -612,6 +629,7 @@ public void endElement(String uri, String localName, String qName) { } } + @Override public void characters(char[] ch, int start, int stop) { if (elementData!=null) { elementData = elementData.append(ch,start, stop); diff --git a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/util/DOLUtils.java b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/util/DOLUtils.java index d047c210d34..8d153edefc5 100644 --- a/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/util/DOLUtils.java +++ b/appserver/deployment/dol/src/main/java/com/sun/enterprise/deployment/util/DOLUtils.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -92,8 +93,7 @@ public class DOLUtils { public final static String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; public final static String SCHEMA_LOCATION_TAG = "xsi:schemaLocation"; - private static LocalStringManagerImpl localStrings = - new LocalStringManagerImpl(DOLUtils.class); + private static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(DOLUtils.class); @LogMessagesResourceBundle private static final String SHARED_LOGMESSAGE_RESOURCE = "org.glassfish.deployment.LogMessages"; @@ -103,24 +103,30 @@ public class DOLUtils { @LoggerInfo(subsystem = "DEPLOYMENT", description="Deployment logger for dol module", publish=true) private static final String DEPLOYMENT_LOGGER = "jakarta.enterprise.system.tools.deployment.dol"; - public static final Logger deplLogger = - Logger.getLogger(DEPLOYMENT_LOGGER, SHARED_LOGMESSAGE_RESOURCE); + public static final Logger deplLogger = Logger.getLogger(DEPLOYMENT_LOGGER, SHARED_LOGMESSAGE_RESOURCE); @LogMessageInfo(message = "Ignore {0} in archive {1}, as WLS counterpart runtime xml {2} is present in the same archive.", level="WARNING") - private static final String COUNTERPART_CONFIGDD_EXISTS = "AS-DEPLOYMENT-00001"; + private static final String COUNTERPART_CONFIGDD_EXISTS = "AS-DEPLOYMENT-00001"; @LogMessageInfo(message = "Exception caught: {0}.", level="WARNING") - private static final String EXCEPTION_CAUGHT = "AS-DEPLOYMENT-00002"; + private static final String EXCEPTION_CAUGHT = "AS-DEPLOYMENT-00002"; @LogMessageInfo(message = "{0} module [{1}] contains characteristics of other module type: {2}.", level="WARNING") - private static final String INCOMPATIBLE_TYPE = "AS-DEPLOYMENT-00003"; + private static final String INCOMPATIBLE_TYPE = "AS-DEPLOYMENT-00003"; @LogMessageInfo(message = "Unsupported deployment descriptors element {0} value {1}.", level="WARNING") - public static final String INVALID_DESC_MAPPING = "AS-DEPLOYMENT-00015"; + public static final String INVALID_DESC_MAPPING = "AS-DEPLOYMENT-00015"; @LogMessageInfo(message = "DOLUtils: converting EJB to web bundle id {0}.", level="FINER") private static final String CONVERT_EJB_TO_WEB_ID = "AS-DEPLOYMENT-00017"; + @LogMessageInfo(message = "DOLUtils: Invalid Deployment Descriptors in {0} \nLine {1} Column {2} -- {3}.", level="SEVERE", + cause = "Failed to find the resource specified in the deployment descriptor. May be because of wrong specification in the descriptor", + action = "Ensure that the resource specified is present. Ensure that there is no typo in the resource specified in the descriptor" + ) + public static final String INVALILD_DESCRIPTOR = "AS-DEPLOYMENT-00118"; + + // The system property to control the precedence between GF DD // and WLS DD when they are both present. When this property is // set to true, GF DD will have higher precedence over WLS DD. @@ -146,64 +152,58 @@ public static synchronized Logger getDefaultLogger() { public static boolean equals(Object a, Object b) { return ((a == null && b == null) || - (a != null && a.equals(b))); + (a != null && a.equals(b))); } public static List getLibraryJarURIs(BundleDescriptor bundleDesc, ReadableArchive archive) throws Exception { if (bundleDesc == null) { return Collections.emptyList(); } - ModuleDescriptor moduleDesc = ((BundleDescriptor)bundleDesc).getModuleDescriptor(); + ModuleDescriptor moduleDesc = bundleDesc.getModuleDescriptor(); Application app = ((BundleDescriptor)moduleDesc.getDescriptor()).getApplication(); return getLibraryJarURIs(app, archive); } public static List getLibraryJarURIs(Application app, ReadableArchive archive) throws Exception { - List libraryURLs = new ArrayList(); - List libraryURIs = new ArrayList(); + List libraryURLs = new ArrayList<>(); + List libraryURIs = new ArrayList<>(); // add libraries referenced through manifest libraryURLs.addAll(DeploymentUtils.getManifestLibraries(archive)); - ReadableArchive parentArchive = archive.getParentArchive(); - if (parentArchive == null) { return Collections.emptyList(); } File appRoot = new File(parentArchive.getURI()); - // add libraries jars inside application lib directory - libraryURLs.addAll(ASClassLoaderUtil.getAppLibDirLibrariesAsList( - appRoot, app.getLibraryDirectory(), null)); - + libraryURLs.addAll(ASClassLoaderUtil.getAppLibDirLibrariesAsList(appRoot, app.getLibraryDirectory(), null)); for (URL url : libraryURLs) { libraryURIs.add(Util.toURI(url)); } return libraryURIs; } - public static BundleDescriptor getCurrentBundleForContext( - DeploymentContext context) { - ExtendedDeploymentContext ctx = (ExtendedDeploymentContext)context; - Application application = context.getModuleMetaData(Application.class); - if (application == null) return null; // this can happen for non-JavaEE type deployment. e.g., issue 15869 - if (ctx.getParentContext() == null) { - if (application.isVirtual()) { - // standalone module - return application.getStandaloneBundleDescriptor(); - } else { - // top level - return application; - } - } else { - // a sub module of ear - return application.getModuleByUri(ctx.getModuleUri()); - } - } - - public static boolean isRAConnectionFactory(ServiceLocator habitat, - String type, Application thisApp) { + public static BundleDescriptor getCurrentBundleForContext(DeploymentContext context) { + ExtendedDeploymentContext ctx = (ExtendedDeploymentContext)context; + Application application = context.getModuleMetaData(Application.class); + if (application == null) { + // this can happen for non-JavaEE type deployment. e.g., issue 15869 + return null; + } + if (ctx.getParentContext() == null) { + if (application.isVirtual()) { + // standalone module + return application.getStandaloneBundleDescriptor(); + } + // top level + return application; + } + // a sub module of ear + return application.getModuleByUri(ctx.getModuleUri()); + } + + public static boolean isRAConnectionFactory(ServiceLocator habitat, String type, Application thisApp) { // first check if this is a connection factory defined in a resource // adapter in this application if (isRAConnectionFactory(type, thisApp)) { @@ -218,8 +218,9 @@ public static boolean isRAConnectionFactory(ServiceLocator habitat, ApplicationRegistry appRegistry = habitat.getService(ApplicationRegistry.class); for (com.sun.enterprise.config.serverbeans.Application raApp : raApps) { ApplicationInfo appInfo = appRegistry.get(raApp.getName()); - if (appInfo == null) + if (appInfo == null) { continue; + } if (isRAConnectionFactory(type, appInfo.getMetaData(Application.class))) { return true; } @@ -314,7 +315,7 @@ private static List sortConfigurationDDFi sunConfDD = ddFile; } } - List sortedConfDDFiles = new ArrayList(); + List sortedConfDDFiles = new ArrayList<>(); // if there is external runtime alternate deployment descriptor // specified, just use that @@ -385,7 +386,7 @@ public static List processConfigurationDD // specified, the config DD files are already processed return sortConfigurationDDFiles(ddFiles, archiveType, archive); } - List processedConfDDFiles = new ArrayList(); + List processedConfDDFiles = new ArrayList<>(); for (ConfigurationDeploymentDescriptorFile ddFile : sortConfigurationDDFiles(ddFiles, archiveType, archive)) { if (archive.exists(ddFile.getDeploymentDescriptorPath())) { processedConfDDFiles.add(ddFile); @@ -471,19 +472,19 @@ public static void readRuntimeDeploymentDescriptor(List getSniffersForModule(ServiceLocator habitat, String [] incompatibleTypes = mainSniffer.getIncompatibleSnifferTypes(); List allIncompatTypes = addAdditionalIncompatTypes(mainSniffer, incompatibleTypes); - List sniffersToRemove = new ArrayList(); + List sniffersToRemove = new ArrayList<>(); for (Sniffer sniffer : sniffers) { for (String incompatType : allIncompatTypes) { if (sniffer.getModuleType().equals(incompatType)) { - deplLogger.log(Level.WARNING, - INCOMPATIBLE_TYPE, - new Object[] { type, - md.getArchiveUri(), - incompatType }); + deplLogger.log(Level.WARNING, + INCOMPATIBLE_TYPE, + new Object[] { type, + md.getArchiveUri(), + incompatType }); sniffersToRemove.add(sniffer); } @@ -590,7 +591,7 @@ private static String getTypeFromModuleType(ArchiveType moduleType) { // this is to add additional incompatible sniffers at ear level where // we have information to determine what is the main sniffer private static List addAdditionalIncompatTypes(Sniffer mainSniffer, String[] incompatTypes) { - List allIncompatTypes = new ArrayList(); + List allIncompatTypes = new ArrayList<>(); for (String incompatType : incompatTypes) { allIncompatTypes.add(incompatType); } @@ -603,7 +604,7 @@ private static List addAdditionalIncompatTypes(Sniffer mainSniffer, Stri } public static List getConfigurationDeploymentDescriptorFiles(ServiceLocator habitat, String containerType) { - List confDDFiles = new ArrayList(); + List confDDFiles = new ArrayList<>(); for (ServiceHandle serviceHandle : habitat.getAllServiceHandles(ConfigurationDeploymentDescriptorFileFor.class)) { ActiveDescriptor descriptor = serviceHandle.getActiveDescriptor(); String indexedType = descriptor.getMetadata().get(ConfigurationDeploymentDescriptorFileFor.DESCRIPTOR_FOR).get(0); @@ -622,29 +623,33 @@ public static List getConfigurationDeploy * @param value it's associated value */ public static boolean setElementValue(XMLElement element, - String value, - Object o) { + String value, + Object o) { if (SCHEMA_LOCATION_TAG.equals(element.getCompleteName())) { // we need to keep all the non j2ee/javaee schemaLocation tags StringTokenizer st = new StringTokenizer(value); StringBuffer sb = new StringBuffer(); while (st.hasMoreElements()) { String namespace = (String) st.nextElement(); - String schema; - if (st.hasMoreElements()) { - schema = (String) st.nextElement(); - } else { - schema = namespace; - namespace = TagNames.JAKARTAEE_NAMESPACE; - } - if (namespace.equals(TagNames.J2EE_NAMESPACE)) + String schema; + if (st.hasMoreElements()) { + schema = (String) st.nextElement(); + } else { + schema = namespace; + namespace = TagNames.JAKARTAEE_NAMESPACE; + } + if (namespace.equals(TagNames.J2EE_NAMESPACE)) { continue; - if (namespace.equals(TagNames.JAVAEE_NAMESPACE)) + } + if (namespace.equals(TagNames.JAVAEE_NAMESPACE)) { continue; - if (namespace.equals(TagNames.JAKARTAEE_NAMESPACE)) + } + if (namespace.equals(TagNames.JAKARTAEE_NAMESPACE)) { continue; - if (namespace.equals(W3C_XML_SCHEMA)) + } + if (namespace.equals(W3C_XML_SCHEMA)) { continue; + } sb.append(namespace); sb.append(" "); sb.append(schema); @@ -665,167 +670,167 @@ public static boolean setElementValue(XMLElement element, return false; } - /* - * Returns a list of the proprietary schema namespaces - */ - public static List getProprietarySchemaNamespaces() { - ArrayList ns = new ArrayList(); - ns.add(DescriptorConstants.WLS_SCHEMA_NAMESPACE_BEA); - ns.add(DescriptorConstants.WLS_SCHEMA_NAMESPACE_ORACLE); - return ns; - } - - /* - * Returns a list of the proprietary dtd system IDs - */ - public static List getProprietaryDTDStart() { - ArrayList ns = new ArrayList(); - ns.add(DescriptorConstants.WLS_DTD_SYSTEM_ID_BEA); - return ns; - } - - public static Application getApplicationFromEnv(JndiNameEnvironment env) { - Application app = null; - - if (env instanceof EjbDescriptor) { - // EJB component - EjbDescriptor ejbEnv = (EjbDescriptor) env; - app = ejbEnv.getApplication(); - } else if (env instanceof EjbBundleDescriptor) { - EjbBundleDescriptor ejbBundle = (EjbBundleDescriptor) env; - app = ejbBundle.getApplication(); - } else if (env instanceof WebBundleDescriptor) { - WebBundleDescriptor webEnv = (WebBundleDescriptor) env; - app = webEnv.getApplication(); - } else if (env instanceof ApplicationClientDescriptor) { - ApplicationClientDescriptor appEnv = (ApplicationClientDescriptor) env; - app = appEnv.getApplication(); - } else if (env instanceof ManagedBeanDescriptor) { - ManagedBeanDescriptor mb = (ManagedBeanDescriptor) env; - app = mb.getBundle().getApplication(); - } else if (env instanceof Application) { - app = ((Application) env); - } else { - throw new IllegalArgumentException("IllegalJndiNameEnvironment : env"); - } - - return app; - } - - public static String getApplicationName(JndiNameEnvironment env) { - String appName = ""; - - Application app = getApplicationFromEnv(env); - if (app != null) { - appName = app.getAppName(); - } else { - throw new IllegalArgumentException("IllegalJndiNameEnvironment : env"); - } - - return appName; - } - - public static String getModuleName(JndiNameEnvironment env) { - - String moduleName = null; - - if (env instanceof EjbDescriptor) { - // EJB component - EjbDescriptor ejbEnv = (EjbDescriptor) env; - EjbBundleDescriptor ejbBundle = ejbEnv.getEjbBundleDescriptor(); - moduleName = ejbBundle.getModuleDescriptor().getModuleName(); - } else if (env instanceof EjbBundleDescriptor) { - EjbBundleDescriptor ejbBundle = (EjbBundleDescriptor) env; - moduleName = ejbBundle.getModuleDescriptor().getModuleName(); - } else if (env instanceof WebBundleDescriptor) { - WebBundleDescriptor webEnv = (WebBundleDescriptor) env; - moduleName = webEnv.getModuleName(); - } else if (env instanceof ApplicationClientDescriptor) { - ApplicationClientDescriptor appEnv = (ApplicationClientDescriptor) env; - moduleName = appEnv.getModuleName(); - } else if (env instanceof ManagedBeanDescriptor) { - ManagedBeanDescriptor mb = (ManagedBeanDescriptor) env; - moduleName = mb.getBundle().getModuleName(); - } else { - throw new IllegalArgumentException("IllegalJndiNameEnvironment : env"); - } - - return moduleName; - - } - - public static boolean getTreatComponentAsModule(JndiNameEnvironment env) { - - boolean treatComponentAsModule = false; - - if (env instanceof WebBundleDescriptor) { - treatComponentAsModule = true; - } else { - - if (env instanceof EjbDescriptor) { - - EjbDescriptor ejbDesc = (EjbDescriptor) env; - EjbBundleDescriptor ejbBundle = ejbDesc.getEjbBundleDescriptor(); - if (ejbBundle.getModuleDescriptor().getDescriptor() instanceof WebBundleDescriptor) { - treatComponentAsModule = true; - } - } - - } - - return treatComponentAsModule; - } - - /** - * Generate a unique id name for each J2EE component. - */ - public static String getComponentEnvId(JndiNameEnvironment env) { - String id = null; - - if (env instanceof EjbDescriptor) { - // EJB component - EjbDescriptor ejbEnv = (EjbDescriptor) env; - - // Make jndi name flat so it won't result in the creation of - // a bunch of sub-contexts. - String flattedJndiName = ejbEnv.getJndiName().replace('/', '.'); - - EjbBundleDescriptor ejbBundle = ejbEnv.getEjbBundleDescriptor(); - Descriptor d = ejbBundle.getModuleDescriptor().getDescriptor(); - // if this EJB is in a war file, use the same component ID - // as the web bundle, because they share the same JNDI namespace - if (d instanceof WebBundleDescriptor) { - // copy of code below - WebBundleDescriptor webEnv = (WebBundleDescriptor) d; - id = webEnv.getApplication().getName() + ID_SEPARATOR - + webEnv.getContextRoot(); - if (deplLogger.isLoggable(Level.FINER)) { - deplLogger.log(Level.FINER, CONVERT_EJB_TO_WEB_ID, id); - } - - } else { - id = ejbEnv.getApplication().getName() + ID_SEPARATOR - + ejbBundle.getModuleDescriptor().getArchiveUri() + ID_SEPARATOR - + ejbEnv.getName() + ID_SEPARATOR + flattedJndiName - + ejbEnv.getUniqueId(); - } - } else if (env instanceof WebBundleDescriptor) { - WebBundleDescriptor webEnv = (WebBundleDescriptor) env; - id = webEnv.getApplication().getName() + ID_SEPARATOR - + webEnv.getContextRoot(); - } else if (env instanceof ApplicationClientDescriptor) { - ApplicationClientDescriptor appEnv = (ApplicationClientDescriptor) env; - id = "client" + ID_SEPARATOR + appEnv.getName() + ID_SEPARATOR - + appEnv.getMainClassName(); - } else if (env instanceof ManagedBeanDescriptor) { - id = ((ManagedBeanDescriptor) env).getGlobalJndiName(); - } else if (env instanceof EjbBundleDescriptor) { - EjbBundleDescriptor ejbBundle = (EjbBundleDescriptor) env; - id = "__ejbBundle__" + ID_SEPARATOR - + ejbBundle.getApplication().getName() + ID_SEPARATOR - + ejbBundle.getModuleName(); - } - - return id; - } + /* + * Returns a list of the proprietary schema namespaces + */ + public static List getProprietarySchemaNamespaces() { + ArrayList ns = new ArrayList<>(); + ns.add(DescriptorConstants.WLS_SCHEMA_NAMESPACE_BEA); + ns.add(DescriptorConstants.WLS_SCHEMA_NAMESPACE_ORACLE); + return ns; + } + + /* + * Returns a list of the proprietary dtd system IDs + */ + public static List getProprietaryDTDStart() { + ArrayList ns = new ArrayList<>(); + ns.add(DescriptorConstants.WLS_DTD_SYSTEM_ID_BEA); + return ns; + } + + public static Application getApplicationFromEnv(JndiNameEnvironment env) { + Application app = null; + + if (env instanceof EjbDescriptor) { + // EJB component + EjbDescriptor ejbEnv = (EjbDescriptor) env; + app = ejbEnv.getApplication(); + } else if (env instanceof EjbBundleDescriptor) { + EjbBundleDescriptor ejbBundle = (EjbBundleDescriptor) env; + app = ejbBundle.getApplication(); + } else if (env instanceof WebBundleDescriptor) { + WebBundleDescriptor webEnv = (WebBundleDescriptor) env; + app = webEnv.getApplication(); + } else if (env instanceof ApplicationClientDescriptor) { + ApplicationClientDescriptor appEnv = (ApplicationClientDescriptor) env; + app = appEnv.getApplication(); + } else if (env instanceof ManagedBeanDescriptor) { + ManagedBeanDescriptor mb = (ManagedBeanDescriptor) env; + app = mb.getBundle().getApplication(); + } else if (env instanceof Application) { + app = ((Application) env); + } else { + throw new IllegalArgumentException("IllegalJndiNameEnvironment : env"); + } + + return app; + } + + public static String getApplicationName(JndiNameEnvironment env) { + String appName = ""; + + Application app = getApplicationFromEnv(env); + if (app != null) { + appName = app.getAppName(); + } else { + throw new IllegalArgumentException("IllegalJndiNameEnvironment : env"); + } + + return appName; + } + + public static String getModuleName(JndiNameEnvironment env) { + + String moduleName = null; + + if (env instanceof EjbDescriptor) { + // EJB component + EjbDescriptor ejbEnv = (EjbDescriptor) env; + EjbBundleDescriptor ejbBundle = ejbEnv.getEjbBundleDescriptor(); + moduleName = ejbBundle.getModuleDescriptor().getModuleName(); + } else if (env instanceof EjbBundleDescriptor) { + EjbBundleDescriptor ejbBundle = (EjbBundleDescriptor) env; + moduleName = ejbBundle.getModuleDescriptor().getModuleName(); + } else if (env instanceof WebBundleDescriptor) { + WebBundleDescriptor webEnv = (WebBundleDescriptor) env; + moduleName = webEnv.getModuleName(); + } else if (env instanceof ApplicationClientDescriptor) { + ApplicationClientDescriptor appEnv = (ApplicationClientDescriptor) env; + moduleName = appEnv.getModuleName(); + } else if (env instanceof ManagedBeanDescriptor) { + ManagedBeanDescriptor mb = (ManagedBeanDescriptor) env; + moduleName = mb.getBundle().getModuleName(); + } else { + throw new IllegalArgumentException("IllegalJndiNameEnvironment : env"); + } + + return moduleName; + + } + + public static boolean getTreatComponentAsModule(JndiNameEnvironment env) { + + boolean treatComponentAsModule = false; + + if (env instanceof WebBundleDescriptor) { + treatComponentAsModule = true; + } else { + + if (env instanceof EjbDescriptor) { + + EjbDescriptor ejbDesc = (EjbDescriptor) env; + EjbBundleDescriptor ejbBundle = ejbDesc.getEjbBundleDescriptor(); + if (ejbBundle.getModuleDescriptor().getDescriptor() instanceof WebBundleDescriptor) { + treatComponentAsModule = true; + } + } + + } + + return treatComponentAsModule; + } + + /** + * Generate a unique id name for each J2EE component. + */ + public static String getComponentEnvId(JndiNameEnvironment env) { + String id = null; + + if (env instanceof EjbDescriptor) { + // EJB component + EjbDescriptor ejbEnv = (EjbDescriptor) env; + + // Make jndi name flat so it won't result in the creation of + // a bunch of sub-contexts. + String flattedJndiName = ejbEnv.getJndiName().replace('/', '.'); + + EjbBundleDescriptor ejbBundle = ejbEnv.getEjbBundleDescriptor(); + Descriptor d = ejbBundle.getModuleDescriptor().getDescriptor(); + // if this EJB is in a war file, use the same component ID + // as the web bundle, because they share the same JNDI namespace + if (d instanceof WebBundleDescriptor) { + // copy of code below + WebBundleDescriptor webEnv = (WebBundleDescriptor) d; + id = webEnv.getApplication().getName() + ID_SEPARATOR + + webEnv.getContextRoot(); + if (deplLogger.isLoggable(Level.FINER)) { + deplLogger.log(Level.FINER, CONVERT_EJB_TO_WEB_ID, id); + } + + } else { + id = ejbEnv.getApplication().getName() + ID_SEPARATOR + + ejbBundle.getModuleDescriptor().getArchiveUri() + ID_SEPARATOR + + ejbEnv.getName() + ID_SEPARATOR + flattedJndiName + + ejbEnv.getUniqueId(); + } + } else if (env instanceof WebBundleDescriptor) { + WebBundleDescriptor webEnv = (WebBundleDescriptor) env; + id = webEnv.getApplication().getName() + ID_SEPARATOR + + webEnv.getContextRoot(); + } else if (env instanceof ApplicationClientDescriptor) { + ApplicationClientDescriptor appEnv = (ApplicationClientDescriptor) env; + id = "client" + ID_SEPARATOR + appEnv.getName() + ID_SEPARATOR + + appEnv.getMainClassName(); + } else if (env instanceof ManagedBeanDescriptor) { + id = ((ManagedBeanDescriptor) env).getGlobalJndiName(); + } else if (env instanceof EjbBundleDescriptor) { + EjbBundleDescriptor ejbBundle = (EjbBundleDescriptor) env; + id = "__ejbBundle__" + ID_SEPARATOR + + ejbBundle.getApplication().getName() + ID_SEPARATOR + + ejbBundle.getModuleName(); + } + + return id; + } } diff --git a/appserver/ejb/ejb-connector/src/main/java/org/glassfish/ejb/config/EjbContainer.java b/appserver/ejb/ejb-connector/src/main/java/org/glassfish/ejb/config/EjbContainer.java index 46d11578dc7..e52fdcdc3ff 100644 --- a/appserver/ejb/ejb-connector/src/main/java/org/glassfish/ejb/config/EjbContainer.java +++ b/appserver/ejb/ejb-connector/src/main/java/org/glassfish/ejb/config/EjbContainer.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,24 +17,23 @@ package org.glassfish.ejb.config; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.Element; -import org.jvnet.hk2.config.ConfigBeanProxy; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; import java.util.List; +import org.glassfish.api.admin.config.ConfigExtension; import org.glassfish.api.admin.config.PropertiesDesc; +import org.glassfish.api.admin.config.PropertyDesc; +import org.glassfish.quality.ToDo; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.Element; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import org.glassfish.quality.ToDo; - -import jakarta.validation.constraints.Min; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; -import org.glassfish.api.admin.config.PropertyDesc; -import org.glassfish.api.admin.config.ConfigExtension; /** * Configuration of EJB Container @@ -46,12 +46,15 @@ @Configured public interface EjbContainer extends ConfigBeanProxy, PropertyBag, ConfigExtension { - public static final int DEFAULT_THREAD_CORE_POOL_SIZE = 16; - public static final int DEFAULT_THREAD_MAX_POOL_SIZE = 32; - public static final long DEFAULT_THREAD_KEEP_ALIVE_SECONDS = 60; - public static final int DEFAULT_THREAD_QUEUE_CAPACITY = Integer.MAX_VALUE; - public static final boolean DEFAULT_ALLOW_CORE_THREAD_TIMEOUT = false; - public static final boolean DEFAULT_PRESTART_ALL_CORE_THREADS = false; + + String PATTERN_VICTIM_SELECTION_POLICY = "(nru|fifo|lru)"; + + int DEFAULT_THREAD_CORE_POOL_SIZE = 16; + int DEFAULT_THREAD_MAX_POOL_SIZE = 32; + long DEFAULT_THREAD_KEEP_ALIVE_SECONDS = 60; + int DEFAULT_THREAD_QUEUE_CAPACITY = Integer.MAX_VALUE; + boolean DEFAULT_ALLOW_CORE_THREAD_TIMEOUT = false; + boolean DEFAULT_PRESTART_ALL_CORE_THREADS = false; /** * Gets the value of the steadyPoolSize property. @@ -280,8 +283,8 @@ public interface EjbContainer extends ConfigBeanProxy, PropertyBag, ConfigExtens * @return possible object is * {@link String } */ - @Attribute (defaultValue="nru") - @Pattern(regexp="(nru|fifo|lru)") + @Attribute(defaultValue = "nru") + @Pattern(regexp = PATTERN_VICTIM_SELECTION_POLICY, message = "Pattern: " + PATTERN_VICTIM_SELECTION_POLICY) String getVictimSelectionPolicy(); /** @@ -301,8 +304,8 @@ public interface EjbContainer extends ConfigBeanProxy, PropertyBag, ConfigExtens * @return possible object is * {@link String } */ - @Attribute (defaultValue="B") - @Pattern(regexp="B|C") + @Attribute(defaultValue = "B") + @Pattern(regexp = "B|C", message = "B to enable entity bean caching, C to disable.") String getCommitOption(); /** @@ -358,6 +361,7 @@ public interface EjbContainer extends ConfigBeanProxy, PropertyBag, ConfigExtens /** Properties as per {@link PropertyBag} */ + @Override @ToDo(priority=ToDo.Priority.IMPORTANT, details="Provide PropertyDesc for legal props" ) @PropertiesDesc(props = { @PropertyDesc(name = "disable-nonportable-jndi-names", diff --git a/appserver/jdbc/jdbc-config/src/main/java/org/glassfish/jdbc/config/JdbcConnectionPool.java b/appserver/jdbc/jdbc-config/src/main/java/org/glassfish/jdbc/config/JdbcConnectionPool.java index e65526feddc..ff1784acc36 100644 --- a/appserver/jdbc/jdbc-config/src/main/java/org/glassfish/jdbc/config/JdbcConnectionPool.java +++ b/appserver/jdbc/jdbc-config/src/main/java/org/glassfish/jdbc/config/JdbcConnectionPool.java @@ -1,6 +1,6 @@ /* + * Copyright (c) 2021-2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. - * Copyright (c) 2021 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at @@ -19,6 +19,15 @@ import com.sun.enterprise.config.serverbeans.Resource; import com.sun.enterprise.config.serverbeans.ResourcePool; + +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.Pattern; + +import java.beans.PropertyVetoException; +import java.util.List; + +import org.glassfish.admin.cli.resources.UniqueResourceNameConstraint; import org.glassfish.api.admin.RestRedirect; import org.glassfish.api.admin.RestRedirects; import org.glassfish.api.admin.config.PropertiesDesc; @@ -27,19 +36,16 @@ import org.glassfish.connectors.config.validators.ConnectionPoolErrorMessages; import org.glassfish.jdbc.config.validators.JdbcConnectionPoolConstraint; import org.glassfish.jdbc.config.validators.JdbcConnectionPoolConstraints; -import org.glassfish.admin.cli.resources.UniqueResourceNameConstraint; import org.glassfish.resourcebase.resources.ResourceDeploymentOrder; import org.glassfish.resourcebase.resources.ResourceTypeOrder; -import org.jvnet.hk2.config.*; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.DuckTyped; +import org.jvnet.hk2.config.Element; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import jakarta.validation.constraints.Max; -import jakarta.validation.constraints.Min; -import jakarta.validation.constraints.Pattern; -import java.beans.PropertyVetoException; -import java.util.List; - /** * Defines configuration used to create and manage a pool physical database * connections. Pool definition is named, and can be referred to by multiple @@ -69,8 +75,11 @@ }) @ResourceTypeOrder(deploymentOrder=ResourceDeploymentOrder.JDBC_POOL) @UniqueResourceNameConstraint(message="{resourcename.isnot.unique}", payload=JdbcConnectionPool.class) -public interface JdbcConnectionPool extends ConfigBeanProxy, Resource, ResourcePool, - PropertyBag { +public interface JdbcConnectionPool extends ConfigBeanProxy, Resource, ResourcePool, PropertyBag { + + String CONNECTION_VALIDATION_METHODS = "(auto-commit|meta-data|custom-validation|table)"; + String ISOLATION_LEVELS = "(read-uncommitted|read-committed|repeatable-read|serializable)"; + String RESOURCE_TYPES = "(java.sql.Driver|javax.sql.DataSource|javax.sql.XADataSource|javax.sql.ConnectionPoolDataSource)"; /** * @@ -131,7 +140,7 @@ public interface JdbcConnectionPool extends ConfigBeanProxy, Resource, ResourceP * {@link String } */ @Attribute - @Pattern(regexp="(java.sql.Driver|javax.sql.DataSource|javax.sql.XADataSource|javax.sql.ConnectionPoolDataSource)") + @Pattern(regexp = RESOURCE_TYPES, message = "Valid values: " + RESOURCE_TYPES) String getResType(); /** @@ -274,7 +283,7 @@ public interface JdbcConnectionPool extends ConfigBeanProxy, Resource, ResourceP * {@link String } */ @Attribute - @Pattern(regexp="(read-uncommitted|read-committed|repeatable-read|serializable)") + @Pattern(regexp = ISOLATION_LEVELS, message = "Valid values: " + ISOLATION_LEVELS) String getTransactionIsolationLevel(); /** @@ -299,7 +308,7 @@ public interface JdbcConnectionPool extends ConfigBeanProxy, Resource, ResourceP * @return possible object is * {@link String } */ - @Attribute (defaultValue="true", dataType=Boolean.class) + @Attribute(defaultValue = "true", dataType = Boolean.class) String getIsIsolationLevelGuaranteed(); /** @@ -348,7 +357,7 @@ public interface JdbcConnectionPool extends ConfigBeanProxy, Resource, ResourceP * {@link String } */ @Attribute (defaultValue="table") - @Pattern(regexp="(auto-commit|meta-data|custom-validation|table)") + @Pattern(regexp = CONNECTION_VALIDATION_METHODS, message = "Valid values: " + CONNECTION_VALIDATION_METHODS) String getConnectionValidationMethod(); /** @@ -942,6 +951,7 @@ public interface JdbcConnectionPool extends ConfigBeanProxy, Resource, ResourceP * deployment descriptors. * */ +@Override @PropertiesDesc( props={ @PropertyDesc(name="PortNumber", defaultValue="1527", dataType=Port.class, @@ -966,6 +976,7 @@ public interface JdbcConnectionPool extends ConfigBeanProxy, Resource, ResourceP @Element List getProperty(); + @Override @DuckTyped String getIdentity(); diff --git a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/ChangeMasterBrokerCommand.java b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/ChangeMasterBrokerCommand.java index 15c05d87e4c..ac0f3a6e7ff 100755 --- a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/ChangeMasterBrokerCommand.java +++ b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/ChangeMasterBrokerCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -29,8 +30,6 @@ import java.beans.PropertyVetoException; import java.util.List; -import java.util.logging.Level; - import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; @@ -75,12 +74,12 @@ public class ChangeMasterBrokerCommand extends JMSDestination implements AdminCo final private static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(ChangeMasterBrokerCommand.class); // [usemasterbroker] [availability-enabled] [dbvendor] [dbuser] [dbpassword admin] [jdbcurl] [properties props] clusterName - private static enum BrokerStatusCode { + private enum BrokerStatusCode { BAD_REQUEST(400), NOT_ALLOWED(405), UNAVAILABLE(503), PRECONDITION_FAILED(412); - private int code; + private final int code; - private BrokerStatusCode(int c) { + BrokerStatusCode(int c) { code = c; } @@ -115,6 +114,7 @@ public int getCode() { * * @param context information */ + @Override public void execute(AdminCommandContext context) { final ActionReport report = context.getActionReport(); final String newMB = newMasterBroker; @@ -227,6 +227,7 @@ public void execute(AdminCommandContext context) { }*/ ConfigSupport.apply(new SingleConfigCode() { + @Override public Object run(JmsService param) throws PropertyVetoException, TransactionFailure { param.setMasterBroker(newMB); @@ -249,8 +250,8 @@ private JmsHost getDefaultJmsHost(JmsService jmsService){ JmsHost jmsHost = null; String defaultJmsHostName = jmsService.getDefaultJmsHost(); List jmsHostsList = jmsService.getJmsHost(); - for (int i = 0; i < jmsHostsList.size(); i++) { - JmsHost tmpJmsHost = (JmsHost) jmsHostsList.get(i); + for (Object element : jmsHostsList) { + JmsHost tmpJmsHost = (JmsHost) element; if (tmpJmsHost != null && tmpJmsHost.getName().equals(defaultJmsHostName)) { jmsHost = tmpJmsHost; } @@ -259,68 +260,27 @@ private JmsHost getDefaultJmsHost(JmsService jmsService){ } private CompositeData updateMasterBroker(String serverName, String oldMasterBroker, String newMasterBroker) throws Exception { - MQJMXConnectorInfo mqInfo = getMQJMXConnectorInfo(serverName, config,serverContext, domain, connectorRuntime); - - //MBeanServerConnection mbsc = getMBeanServerConnection(tgtName); - CompositeData result = null; - try { + try (MQJMXConnectorInfo mqInfo = createMQJMXConnectorInfo(serverName, config,serverContext, domain, connectorRuntime)) { MBeanServerConnection mbsc = null; try { mbsc = mqInfo.getMQMBeanServerConnection(); } catch (Exception e) { String emsg = localStrings.getLocalString( "change.master.broker.cannotConnectOldMasterBroker", - "Unable to connect to the current master broker {0}. Likely reasons: the cluster might not be running, the server instance {0} associated with the current master broker or the current master broker might not be running. Please check server logs.", - new String[] {mqInfo.getASInstanceName()} + "Unable to connect to the current master broker {0}. Likely reasons:" + + " the cluster might not be running, the server instance {0} associated with" + + " the current master broker or the current master broker might not be running." + + " Please check server logs.", + mqInfo.getASInstanceName() ); - if (logger.isLoggable(Level.WARNING)) { - logger.log(Level.WARNING, emsg); - } - logAndHandleException(e, emsg); + throw handleException(new Exception(emsg, e)); } ObjectName on = new ObjectName(CLUSTER_CONFIG_MBEAN_NAME); - Object[] params = null; String[] signature = new String[] {"java.lang.String", "java.lang.String"}; - params = new Object [] {oldMasterBroker, newMasterBroker}; - - result = mbsc != null ? (CompositeData) mbsc.invoke(on, "changeMasterBroker", params, signature) : null; + Object[] params = new Object [] {oldMasterBroker, newMasterBroker}; + return mbsc == null ? null : (CompositeData) mbsc.invoke(on, "changeMasterBroker", params, signature); } catch (Exception e) { - logAndHandleException(e, e.getMessage()); - } finally { - try { - if(mqInfo != null) { - mqInfo.closeMQMBeanServerConnection(); - } - } catch (Exception e) { - handleException(e); - } - } - return result; - } - - /** - * This is a copy from the super method except that - * it avoids a NPE in using e.getCause() and ensure - * the exception message is errorMsg not "" - these - * eventually should be incoporated to the super method - * post 5.0 release. - */ - @Override - protected void logAndHandleException(Exception e, String errorMsg) - throws JMSAdminException { - //log JMX Exception trace as WARNING - java.io.StringWriter s = new java.io.StringWriter(); - e.printStackTrace(new java.io.PrintWriter(s)); - String emsg = localStrings.getLocalString(errorMsg, errorMsg); - JMSAdminException je = new JMSAdminException(emsg); - /* Cause will be InvocationTargetException, cause of that - * will be MBeanException and cause of that will be the - * real exception we need - */ - if ((e.getCause() != null) && - (e.getCause().getCause() != null)) { - je.initCause(e.getCause().getCause().getCause()); + throw logAndHandleException(e, e.getMessage()); } - handleException(je); } } diff --git a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/CreateJMSDestination.java b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/CreateJMSDestination.java index 9b652b9e9b7..caddd551a33 100644 --- a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/CreateJMSDestination.java +++ b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/CreateJMSDestination.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,37 +17,44 @@ package org.glassfish.jms.admin.cli; -import javax.security.auth.Subject; -import org.glassfish.api.I18n; -import org.glassfish.api.Param; -import org.glassfish.api.ActionReport; -import org.glassfish.api.admin.CommandRunner; -import org.glassfish.api.admin.ParameterMap; -import org.glassfish.config.support.CommandTarget; -import org.glassfish.config.support.TargetType; -import org.glassfish.internal.api.ServerContext; -import java.util.*; -import java.util.logging.Logger; - +import com.sun.enterprise.config.serverbeans.Cluster; +import com.sun.enterprise.config.serverbeans.Config; +import com.sun.enterprise.config.serverbeans.Domain; +import com.sun.enterprise.config.serverbeans.Server; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.SystemPropertyConstants; -import com.sun.enterprise.config.serverbeans.*; import jakarta.inject.Inject; import jakarta.inject.Named; + +import java.util.Properties; + +import javax.management.AttributeList; import javax.management.MBeanServerConnection; import javax.management.ObjectName; -import javax.management.AttributeList; - -import org.jvnet.hk2.annotations.Service; +import javax.security.auth.Subject; +import org.glassfish.api.ActionReport; +import org.glassfish.api.I18n; +import org.glassfish.api.Param; +import org.glassfish.api.admin.AdminCommand; +import org.glassfish.api.admin.AdminCommandContext; +import org.glassfish.api.admin.CommandRunner; +import org.glassfish.api.admin.ExecuteOn; +import org.glassfish.api.admin.ParameterMap; +import org.glassfish.api.admin.RestEndpoint; +import org.glassfish.api.admin.RestEndpoints; +import org.glassfish.api.admin.RestParam; +import org.glassfish.api.admin.RuntimeType; +import org.glassfish.api.admin.ServerEnvironment; +import org.glassfish.config.support.CommandTarget; +import org.glassfish.config.support.TargetType; import org.glassfish.hk2.api.PerLookup; - -import org.glassfish.api.admin.*; +import org.glassfish.internal.api.ServerContext; +import org.jvnet.hk2.annotations.Service; /** * Create JMS Destination - * */ @Service(name = "create-jmsdest") @PerLookup @@ -104,6 +112,7 @@ public class CreateJMSDestination extends JMSDestination implements AdminCommand @Inject ServerContext serverContext; + @Override public void execute(AdminCommandContext context) { final ActionReport report = context.getActionReport(); @@ -139,13 +148,9 @@ public void execute(AdminCommandContext context) { // create-jmsdest private void createJMSDestination(ActionReport report, final Subject subject) throws Exception { - MQJMXConnectorInfo mqInfo = getMQJMXConnectorInfo(target, config, serverContext, domain, connectorRuntime); - - //MBeanServerConnection mbsc = getMBeanServerConnection(tgtName); - try { + try (MQJMXConnectorInfo mqInfo = createMQJMXConnectorInfo(target, config, serverContext, domain, connectorRuntime)) { MBeanServerConnection mbsc = mqInfo.getMQMBeanServerConnection(); - ObjectName on = new ObjectName( - DESTINATION_MANAGER_CONFIG_MBEAN_NAME); + ObjectName on = new ObjectName(DESTINATION_MANAGER_CONFIG_MBEAN_NAME); String[] signature = null; AttributeList destAttrs = null; Object[] params = null; @@ -182,8 +187,6 @@ private void createJMSDestination(ActionReport report, final Subject subject) th destAttrs = convertProp2Attrs(props); } - // setAppserverDefaults(destAttrs, mqInfo); - if (destType.equalsIgnoreCase(JMS_DEST_TYPE_TOPIC)) { destType = DESTINATION_TYPE_TOPIC; } else if (destType.equalsIgnoreCase(JMS_DEST_TYPE_QUEUE)) { @@ -205,15 +208,7 @@ private void createJMSDestination(ActionReport report, final Subject subject) th mbsc.invoke(on, "create", params, signature); report.setMessage(localStrings.getLocalString("create.jms.destination.success", "JMS Desctination {0} created.", destName)); } catch (Exception e) { - logAndHandleException(e, "admin.mbeans.rmb.error_creating_jms_dest"); - } finally { - try { - if (mqInfo != null) { - mqInfo.closeMQMBeanServerConnection(); - } - } catch (Exception e) { - handleException(e); - } + throw logAndHandleException(e, "admin.mbeans.rmb.error_creating_jms_dest"); } } } diff --git a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/DeleteJMSDestination.java b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/DeleteJMSDestination.java index c27734fe9c4..f8c3e2be8c7 100644 --- a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/DeleteJMSDestination.java +++ b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/DeleteJMSDestination.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,38 +17,41 @@ package org.glassfish.jms.admin.cli; -import org.glassfish.api.I18n; -import org.glassfish.api.Param; -import org.glassfish.api.ActionReport; -import org.glassfish.api.admin.AdminCommand; -import org.glassfish.api.admin.AdminCommandContext; -import org.glassfish.internal.api.ServerContext; - -import java.util.logging.Level; -import java.util.logging.Logger; - +import com.sun.enterprise.config.serverbeans.Cluster; +import com.sun.enterprise.config.serverbeans.Config; +import com.sun.enterprise.config.serverbeans.Domain; +import com.sun.enterprise.config.serverbeans.Server; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.SystemPropertyConstants; -import com.sun.enterprise.connectors.jms.system.ActiveJmsResourceAdapter; -import com.sun.enterprise.config.serverbeans.*; - import jakarta.inject.Inject; import jakarta.inject.Named; -import javax.management.MBeanServerConnection; -import javax.management.ObjectName; -import org.jvnet.hk2.annotations.Service; +import java.util.logging.Level; +import java.util.logging.Logger; -import org.glassfish.hk2.api.PerLookup; +import javax.management.MBeanServerConnection; +import javax.management.ObjectName; -import org.glassfish.api.admin.*; +import org.glassfish.api.ActionReport; +import org.glassfish.api.I18n; +import org.glassfish.api.Param; +import org.glassfish.api.admin.AdminCommand; +import org.glassfish.api.admin.AdminCommandContext; +import org.glassfish.api.admin.ExecuteOn; +import org.glassfish.api.admin.RestEndpoint; +import org.glassfish.api.admin.RestEndpoints; +import org.glassfish.api.admin.RestParam; +import org.glassfish.api.admin.RuntimeType; +import org.glassfish.api.admin.ServerEnvironment; import org.glassfish.config.support.CommandTarget; import org.glassfish.config.support.TargetType; +import org.glassfish.hk2.api.PerLookup; +import org.glassfish.internal.api.ServerContext; +import org.jvnet.hk2.annotations.Service; /** * delete JMS Destination - * */ @Service(name="delete-jmsdest") @PerLookup @@ -73,101 +77,73 @@ public class DeleteJMSDestination extends JMSDestination implements AdminCommand { - private final Logger logger = Logger.getLogger(LogUtils.JMS_ADMIN_LOGGER); - final private static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(DeleteJMSDestination.class); - - @Param(name="destType", shortName="T", optional=false) - String destType; + private final Logger logger = Logger.getLogger(LogUtils.JMS_ADMIN_LOGGER); + private static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(DeleteJMSDestination.class); - @Param(name="dest_name", primary=true) - String destName; + @Param(name="destType", shortName="T", optional=false) + String destType; - @Param(optional=true) - String target = SystemPropertyConstants.DEFAULT_SERVER_INSTANCE_NAME; + @Param(name="dest_name", primary=true) + String destName; - @Inject - com.sun.appserv.connectors.internal.api.ConnectorRuntime connectorRuntime; + @Param(optional=true) + String target = SystemPropertyConstants.DEFAULT_SERVER_INSTANCE_NAME; - @Inject - Domain domain; + @Inject + com.sun.appserv.connectors.internal.api.ConnectorRuntime connectorRuntime; - @Inject @Named(ServerEnvironment.DEFAULT_INSTANCE_NAME) - Config config; + @Inject + Domain domain; - @Inject - ServerContext serverContext; + @Inject @Named(ServerEnvironment.DEFAULT_INSTANCE_NAME) + Config config; + @Inject + ServerContext serverContext; - public void execute(AdminCommandContext context) { + @Override + public void execute(AdminCommandContext context) { final ActionReport report = context.getActionReport(); - logger.entering(getClass().getName(), "deleteJMSDestination", - new Object[] {destName, destType}); + logger.entering(getClass().getName(), "deleteJMSDestination", new Object[] {destName, destType}); - try{ + try { validateJMSDestName(destName); validateJMSDestType(destType); - }catch (IllegalArgumentException e){ + } catch (IllegalArgumentException e) { report.setMessage(e.getMessage()); report.setActionExitCode(ActionReport.ExitCode.FAILURE); return; } try { - deleteJMSDestination(destName, destType, target); - return; + deleteJMSDestination(destName, destType, target); + return; } catch (Exception e) { logger.throwing(getClass().getName(), "deleteJMSDestination", e); - //e.printStackTrace();//handleException(e); report.setMessage(localStrings.getLocalString("delete.jms.dest.noJmsDelete", - "Delete JMS Destination failed. Please verify if the JMS Destination specified for deletion exists")); + "Delete JMS Destination failed. Please verify if the JMS Destination specified for deletion exists")); report.setActionExitCode(ActionReport.ExitCode.FAILURE); } } - // delete-jmsdest - private Object deleteJMSDestination(String destName, String destType, - String tgtName) - throws Exception { - - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "deleteJMSDestination ..."); - } - MQJMXConnectorInfo mqInfo = getMQJMXConnectorInfo(target, config, serverContext, domain, connectorRuntime); - - //MBeanServerConnection mbsc = getMBeanServerConnection(tgtName); - try { + private Object deleteJMSDestination(String destName, String destType, String tgtName) throws Exception { + logger.log(Level.FINE, "deleteJMSDestination ..."); + try (MQJMXConnectorInfo mqInfo = createMQJMXConnectorInfo(target, config, serverContext, domain, connectorRuntime)) { MBeanServerConnection mbsc = mqInfo.getMQMBeanServerConnection(); - ObjectName on = new ObjectName( - DESTINATION_MANAGER_CONFIG_MBEAN_NAME); - String [] signature = null; - Object [] params = null; - - signature = new String [] { - "java.lang.String", - "java.lang.String"}; + ObjectName on = new ObjectName(DESTINATION_MANAGER_CONFIG_MBEAN_NAME); + String[] signature = new String[] {"java.lang.String", "java.lang.String"}; if (destType.equalsIgnoreCase("topic")) { destType = DESTINATION_TYPE_TOPIC; } else if (destType.equalsIgnoreCase("queue")) { destType = DESTINATION_TYPE_QUEUE; } - params = new Object [] {destType, destName}; + Object[] params = new Object[] {destType, destName}; return mbsc.invoke(on, "destroy", params, signature); - } catch (Exception e) { - //log JMX Exception trace as WARNING - logAndHandleException(e, "admin.mbeans.rmb.error_deleting_jms_dest"); - } finally { - try { - if(mqInfo != null) { - mqInfo.closeMQMBeanServerConnection(); - } - } catch (Exception e) { - handleException(e); - } - } - return null; + throw logAndHandleException(e, "admin.mbeans.rmb.error_deleting_jms_dest"); + } } } diff --git a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/FlushJMSDestination.java b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/FlushJMSDestination.java index 6bcd95309d3..a10754f2b3f 100644 --- a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/FlushJMSDestination.java +++ b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/FlushJMSDestination.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -103,11 +104,11 @@ public class FlushJMSDestination extends JMSDestination implements AdminCommand ServerContext serverContext; + @Override public void execute(AdminCommandContext context) { final ActionReport report = context.getActionReport(); - logger.entering(getClass().getName(), "flushJMSDestination", - new Object[] {destName, destType}); + logger.entering(getClass().getName(), "flushJMSDestination", new Object[] {destName, destType}); try{ validateJMSDestName(destName); @@ -120,10 +121,8 @@ public void execute(AdminCommandContext context) { try { flushJMSDestination(destName, destType, target); - return; } catch (Exception e) { logger.throwing(getClass().getName(), "flushJMSDestination", e); - //e.printStackTrace();//handleException(e); report.setMessage(localStrings.getLocalString("flush.jms.dest.failed", "Flush JMS Destination failed", e.getMessage())); report.setActionExitCode(ActionReport.ExitCode.FAILURE); @@ -154,71 +153,58 @@ private void flushJMSDestination(String destName, String destType, String tgtNam * This works because we resolve the port numbers * even for standalone instances in MQAddressList. */ - boolean success = true; - Cluster cluster = null; + Exception failure = new Exception("Purging failed."); + final Cluster cluster; if (ctarget == CommandTarget.CLUSTER){ cluster = Globals.get(Domain.class).getClusterNamed(target); - }else { - List clustersList = Globals.get(Domain.class).getClusters().getCluster(); + } else { + List clustersList = Globals.get(Domain.class).getClusters().getCluster(); cluster = JmsRaUtil.getClusterForServer(clustersList, target); } - List servers =cluster.getInstances(); //target.getServer(); - for (int server = 0; server < servers.size(); server++) { + List servers = cluster.getInstances(); + for (Server server : servers) { try { - purgeJMSDestination(destName, destType, ((Server)servers.get(server)).getName()); + purgeJMSDestination(destName, destType, server.getName()); } catch (Exception e) { - success = false; - //todo: enable localized string - logger.log(Level.SEVERE,/*localStrings.getLocalString("admin.mbeans.rmb.error_purging_jms_dest") +*/ ((Server)servers.get(server)).getName()); + failure.addSuppressed( + new RuntimeException("Purging failed for server of this name: " + server.getName(), e)); } } - if (!success) { - //todo: enable localized string - throw new Exception();//localStrings.getLocalString("admin.mbeans.rmb.error_purging_jms_dest")); + if (failure.getSuppressed().length != 0) { + throw failure; } - } else { purgeJMSDestination(destName, destType, tgtName); } } catch (Exception e) { - logger.throwing(getClass().getName(), "flushJMSDestination", e); - handleException(e); + throw handleException(e); } } - public void purgeJMSDestination(String destName, String destType, String tgtName) - throws Exception { + public void purgeJMSDestination(String destName, String destType, String tgtName) throws Exception { logger.log(Level.FINE, "purgeJMSDestination ..."); - MQJMXConnectorInfo[] mqInfos = getMQJMXConnectorInfos(target, config, serverContext, domain, connectorRuntime); - - if (mqInfos != null && mqInfos.length > 0) { - for (MQJMXConnectorInfo mqInfo : mqInfos){ - try { - - MBeanServerConnection mbsc = mqInfo.getMQMBeanServerConnection(); - - if (destType.equalsIgnoreCase("topic")) { - destType = DESTINATION_TYPE_TOPIC; - } else if (destType.equalsIgnoreCase("queue")) { - destType = DESTINATION_TYPE_QUEUE; - } - ObjectName on = createDestinationConfig(destType, destName); - - mbsc.invoke(on, "purge", null, null); - } catch (Exception e) { - //log JMX Exception trace as WARNING - logAndHandleException(e, "admin.mbeans.rmb.error_purging_jms_dest"); - } finally { - try { - if(mqInfo != null) { - mqInfo.closeMQMBeanServerConnection(); - } - } catch (Exception e) { - handleException(e); - } - } + final MQJMXConnectorInfo mqInfo = createMQJMXConnectorInfo(target, config, serverContext, domain, connectorRuntime); + if (mqInfo == null) { + return; + } + try { + MBeanServerConnection mbsc = mqInfo.getMQMBeanServerConnection(); + if (destType.equalsIgnoreCase("topic")) { + destType = DESTINATION_TYPE_TOPIC; + } else if (destType.equalsIgnoreCase("queue")) { + destType = DESTINATION_TYPE_QUEUE; + } + ObjectName on = createDestinationConfig(destType, destName); + mbsc.invoke(on, "purge", null, null); + } catch (Exception e) { + throw logAndHandleException(e, "admin.mbeans.rmb.error_purging_jms_dest"); + } finally { + try { + mqInfo.close(); + } catch (Exception e) { + throw handleException(e); } } } diff --git a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/GetJmsPhysicalDestinationCommand.java b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/GetJmsPhysicalDestinationCommand.java index 45310d82ffd..85c10755840 100644 --- a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/GetJmsPhysicalDestinationCommand.java +++ b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/GetJmsPhysicalDestinationCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -20,30 +21,38 @@ import com.sun.enterprise.config.serverbeans.Config; import com.sun.enterprise.config.serverbeans.Domain; import com.sun.enterprise.config.serverbeans.Server; -import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.SystemPropertyConstants; + +import jakarta.inject.Inject; +import jakarta.inject.Named; + import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.logging.Level; -import jakarta.inject.Inject; -import jakarta.inject.Named; import javax.management.MBeanAttributeInfo; import javax.management.MBeanServerConnection; import javax.management.ObjectName; + import org.glassfish.api.ActionReport; import org.glassfish.api.Param; -import org.glassfish.api.admin.*; +import org.glassfish.api.admin.AdminCommand; +import org.glassfish.api.admin.AdminCommandContext; +import org.glassfish.api.admin.CommandLock; +import org.glassfish.api.admin.ExecuteOn; +import org.glassfish.api.admin.RestEndpoint; +import org.glassfish.api.admin.RestEndpoints; +import org.glassfish.api.admin.RestParam; +import org.glassfish.api.admin.RuntimeType; +import org.glassfish.api.admin.ServerEnvironment; import org.glassfish.config.support.CommandTarget; import org.glassfish.config.support.TargetType; +import org.glassfish.hk2.api.PerLookup; import org.glassfish.internal.api.ServerContext; - import org.jvnet.hk2.annotations.Service; -import org.glassfish.hk2.api.PerLookup; /** - * * @author jasonlee */ @Service(name = "__get-jmsdest") @@ -68,7 +77,6 @@ }) }) public class GetJmsPhysicalDestinationCommand extends JMSDestination implements AdminCommand { - final private static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(GetJmsPhysicalDestinationCommand.class); @Param(name = "desttype", shortName = "t", optional = false) String destType; @@ -95,14 +103,13 @@ public class GetJmsPhysicalDestinationCommand extends JMSDestination implements @Override public void execute(AdminCommandContext context) { final ActionReport report = context.getActionReport(); - logger.entering(getClass().getName(), "__getJmsPhysicalDestination", - new Object[]{destName, destType}); + logger.entering(getClass().getName(), "__getJmsPhysicalDestination", new Object[] {destName, destType}); try { validateJMSDestName(destName); validateJMSDestType(destType); - Map entity = getJMSDestination(); + Map entity = getJMSDestination(); Properties ep = new Properties(); ep.put("entity", entity); report.setExtraProperties(ep); @@ -110,20 +117,14 @@ public void execute(AdminCommandContext context) { } catch (Exception e) { report.setMessage(e.getMessage()); report.setActionExitCode(ActionReport.ExitCode.FAILURE); - return; } } - protected Map getJMSDestination() - throws Exception { - - logger.log(Level.FINE, "__getJmsPhysicalDestination ..."); - MQJMXConnectorInfo mqInfo = getMQJMXConnectorInfo(target, config, serverContext, domain, connectorRuntime); - Map destAttrs = new HashMap(); - try { + protected Map getJMSDestination() throws Exception { + logger.log(Level.FINE, "getJMSDestination ..."); + try (MQJMXConnectorInfo mqInfo = createMQJMXConnectorInfo(target, config, serverContext, domain, connectorRuntime)) { MBeanServerConnection mbsc = mqInfo.getMQMBeanServerConnection(); - if (destType.equalsIgnoreCase("topic")) { destType = DESTINATION_TYPE_TOPIC; } else if (destType.equalsIgnoreCase("queue")) { @@ -131,22 +132,13 @@ protected Map getJMSDestination() } ObjectName on = new ObjectName(MBEAN_DOMAIN_NAME + ":type=Destination,subtype=Config,desttype=" + destType +",name=\"" + destName + "\""); MBeanAttributeInfo[] attribs = mbsc.getMBeanInfo(on).getAttributes(); + Map destAttrs = new HashMap<>(); for (MBeanAttributeInfo attrib: attribs){ destAttrs.put(attrib.getName(), mbsc.getAttribute(on, attrib.getName())); } return destAttrs; } catch (Exception e) { - //log JMX Exception trace as WARNING - logAndHandleException(e, "admin.mbeans.rmb.error_getting_jms_dest"); - } finally { - try { - if (mqInfo != null) { - mqInfo.closeMQMBeanServerConnection(); - } - } catch (Exception e) { - handleException(e); - } + throw logAndHandleException(e, "admin.mbeans.rmb.error_getting_jms_dest"); } - return destAttrs; } } diff --git a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/JMSAdminException.java b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/JMSAdminException.java index 805351f21b3..f9477c5425b 100644 --- a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/JMSAdminException.java +++ b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/JMSAdminException.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -17,20 +18,18 @@ package org.glassfish.jms.admin.cli; +/** + * JMS Admin command failure. + */ public class JMSAdminException extends Exception { - /** - * Exception reference - **/ - private volatile Exception linkedException; - private String _message = null; + private static final long serialVersionUID = 1L; /** * Constructs an JMSAdminException object */ public JMSAdminException() { super(); - linkedException = null; } @@ -41,53 +40,38 @@ public JMSAdminException() { */ public JMSAdminException(String message) { super(message); - _message = message; - linkedException = null; } /** - * Gets the exception linked to this one + * Constructs an JMSAdminException object * - * @return the linked Exception, null if none - **/ - public Exception getLinkedException() { - return (linkedException); + * @param message Exception message + * @param cause original cause. + */ + public JMSAdminException(String message, Exception cause) { + super(message, cause); } /** - * Adds a linked Exception + * Gets the exception linked to this one * - * @param ex the linked Exception - **/ - public void setLinkedException(Exception ex) { - linkedException = ex; + * @return same as {@link #getCause()} + */ + @Deprecated(forRemoval = true) + public Exception getLinkedException() { + return (Exception) getCause(); } /** - * Returns the message along with the message from any linked exception. - **/ - @Override - public String getMessage() { - String retString = null; - - // Return the message of this exception. - if (_message != null) { - retString = _message; - } - - // Append any message from the linked exception. - Exception localLinkedException = linkedException; - if (localLinkedException != null && localLinkedException.getMessage() != null) { - if (retString != null) { - retString += retString + "\n" + localLinkedException.getMessage(); - } else { - retString = localLinkedException.getMessage(); - } - } - return retString; + * Calls {@link #initCause(Throwable)} + * + * @param ex the linked Exception + */ + @Deprecated(forRemoval = true) + public void setLinkedException(Exception ex) { + super.initCause(ex); } - } diff --git a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/JMSDestination.java b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/JMSDestination.java index d9d74250081..2fd0966e819 100644 --- a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/JMSDestination.java +++ b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/JMSDestination.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -36,48 +37,51 @@ import java.util.logging.Level; import java.util.*; import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedExceptionAction; import java.io.StringWriter; import java.io.PrintWriter; import com.sun.enterprise.config.serverbeans.Cluster; import org.glassfish.internal.api.ServerContext; + +import static com.sun.enterprise.connectors.jms.system.ActiveJmsResourceAdapter.ADMINPASSWORD; +import static com.sun.enterprise.connectors.jms.system.ActiveJmsResourceAdapter.ADMINUSERNAME; + import org.glassfish.internal.api.Globals; import org.glassfish.config.support.CommandTarget; +/** + * Common parent for JMS Destination admin commands + */ public abstract class JMSDestination { protected static final Logger logger = Logger.getLogger(LogUtils.JMS_ADMIN_LOGGER); private static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(CreateJMSDestination.class); - // JMS destination types public static final String JMS_DEST_TYPE_TOPIC = "topic"; public static final String JMS_DEST_TYPE_QUEUE = "queue"; + public static final String DEFAULT_MAX_ACTIVE_CONSUMERS = "-1"; public static final String MAX_ACTIVE_CONSUMERS_ATTRIBUTE = "MaxNumActiveConsumers"; public static final String MAX_ACTIVE_CONSUMERS_PROPERTY = "maxNumActiveConsumers"; public static final String JMXSERVICEURLLIST = "JMXServiceURLList"; public static final String JMXCONNECTORENV = "JMXConnectorEnv"; - // flag to enable the use of JMX for JMS destination commands - // if false uses the old behavior - // The value for DONT_USE_MQ_JMX can be set thru sysproperty - private static final boolean USE_JMX = true;// !(Boolean.getBoolean("DONT_USE_MQ_JMX")); + // Following properties are from com.sun.messaging.jms.management.server.MQObjectName - /* Domain name for MQ MBeans */ + /** Domain name for MQ MBeans */ protected static final String MBEAN_DOMAIN_NAME = "com.sun.messaging.jms.server"; - /* String representation of the ObjectName for the DestinationManager Config MBean. */ - protected static final String DESTINATION_MANAGER_CONFIG_MBEAN_NAME = MBEAN_DOMAIN_NAME + ":type=" - + "DestinationManager" + ",subtype=Config"; - - protected static final String CLUSTER_CONFIG_MBEAN_NAME - = MBEAN_DOMAIN_NAME - + ":type=" + "Cluster" - + ",subtype=Config"; - // Queue destination type + /** String representation of the ObjectName for the DestinationManager Config MBean. */ + protected static final String DESTINATION_MANAGER_CONFIG_MBEAN_NAME = MBEAN_DOMAIN_NAME + + ":type=DestinationManager,subtype=Config"; + + protected static final String CLUSTER_CONFIG_MBEAN_NAME = MBEAN_DOMAIN_NAME + ":type=Cluster,subtype=Config"; + /** Queue destination type */ protected static final String DESTINATION_TYPE_QUEUE= "q"; - //Topic destination type + /** Topic destination type */ protected static final String DESTINATION_TYPE_TOPIC = "t"; - protected void validateJMSDestName(String destName) { + protected void validateJMSDestName(final String destName) { if (destName == null || destName.length() <= 0) { throw new IllegalArgumentException( localStrings.getLocalString("admin.mbeans.rmb.invalid_jms_destname", destName)); @@ -85,143 +89,110 @@ protected void validateJMSDestName(String destName) { } - protected void validateJMSDestType(String destType) { - if (destType == null || destType.length() <= 0) { + protected void validateJMSDestType(final String destType) { + if (destType == null || destType.isEmpty()) { throw new IllegalArgumentException( localStrings.getLocalString("admin.mbeans.rmb.invalid_jms_desttype", destType)); } - if (!destType.equals(JMS_DEST_TYPE_QUEUE) && !destType.equals(JMS_DEST_TYPE_TOPIC)) { + if (!JMS_DEST_TYPE_QUEUE.equals(destType) && !JMS_DEST_TYPE_TOPIC.equals(destType)) { throw new IllegalArgumentException( localStrings.getLocalString("admin.mbeans.rmb.invalid_jms_desttype", destType)); } } - protected MQJMXConnectorInfo getMQJMXConnectorInfo(String target, Config config, ServerContext serverContext, - Domain domain, ConnectorRuntime connectorRuntime) throws Exception { - logger.log(Level.FINE, "getMQJMXConnectorInfo for " + target); - MQJMXConnectorInfo mcInfo = null; - - try { - MQJMXConnectorInfo[] cInfo = getMQJMXConnectorInfos(target, config, serverContext, domain, - connectorRuntime); - if (cInfo.length < 1) { - throw new Exception( - localStrings.getLocalString("admin.mbeans.rmb.error_obtaining_jms", "Error obtaining JMS Info")); - } - mcInfo = cInfo[0]; - - } catch (Exception e) { - handleException(e); - } - return mcInfo; - } - - - protected MQJMXConnectorInfo[] getMQJMXConnectorInfos(final String target, final Config config, - final ServerContext serverContext, final Domain domain, ConnectorRuntime connectorRuntime) - throws ConnectorRuntimeException { + protected MQJMXConnectorInfo createMQJMXConnectorInfo(final String targetName, final Config config, + final ServerContext serverContext, final Domain domain, final ConnectorRuntime connectorRuntime) + throws ConnectorRuntimeException { + logger.log(Level.FINE, "createMQJMXConnectorInfo for {0}", targetName); try { final JmsService jmsService = config.getExtensionByType(JmsService.class); - - ActiveJmsResourceAdapter air = getMQAdapter(connectorRuntime); - final Class mqRAClassName = air.getResourceAdapter().getClass(); - final CommandTarget ctarget = this.getTypeForTarget(target); - MQJMXConnectorInfo mqjmxForServer = (MQJMXConnectorInfo) java.security.AccessController - .doPrivileged(new java.security.PrivilegedExceptionAction() { - - @Override - public java.lang.Object run() throws Exception { - if (ctarget == CommandTarget.CLUSTER || ctarget == CommandTarget.CLUSTERED_INSTANCE) { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "Getting JMX connector for" + " cluster target " + target); - } - return _getMQJMXConnectorInfoForCluster(target, jmsService, mqRAClassName, serverContext); - } else { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "Getting JMX connector for" + " standalone target " + target); - } - return _getMQJMXConnectorInfo(target, jmsService, mqRAClassName, serverContext, config, domain); - } + final ActiveJmsResourceAdapter air = getMQAdapter(connectorRuntime); + final Class mqRAClassName = air.getResourceAdapter().getClass(); + final CommandTarget ctarget = this.getTypeForTarget(targetName); + final PrivilegedExceptionAction action = () -> { + if (ctarget == CommandTarget.CLUSTER || ctarget == CommandTarget.CLUSTERED_INSTANCE) { + if (logger.isLoggable(Level.FINE)) { + logger.log(Level.FINE, "Getting JMX connector for cluster target " + targetName); } - }); - - return new MQJMXConnectorInfo[] {mqjmxForServer}; - } catch (Exception e) { - // e.printStackTrace(); - ConnectorRuntimeException cre = new ConnectorRuntimeException(e.getMessage()); - cre.initCause(e); - throw cre; + return _getMQJMXConnectorInfoForCluster(targetName, jmsService, mqRAClassName, serverContext); + } + if (logger.isLoggable(Level.FINE)) { + logger.log(Level.FINE, "Getting JMX connector for standalone target " + targetName); + } + return createMQJMXConnectorInfo(targetName, jmsService, mqRAClassName, serverContext, config, domain); + }; + return AccessController.doPrivileged(action); + } catch (final Exception e) { + throw new ConnectorRuntimeException(e); } } - protected MQJMXConnectorInfo _getMQJMXConnectorInfo( - String targetName, JmsService jmsService, Class mqRAClassName, ServerContext serverContext, Config config, Domain domain) - throws ConnectorRuntimeException { + private MQJMXConnectorInfo createMQJMXConnectorInfo(final String targetName, final JmsService jmsService, + final Class mqRAClassName, final ServerContext serverContext, final Config config, + final Domain domain) throws ConnectorRuntimeException { try { - //If DAS, use the default address list, else obtain - - String connectionURL = null; - MQAddressList mqadList = new MQAddressList(); - //boolean isDAS = mqadList.isDAS(targetName); + final MQAddressList mqadList = new MQAddressList(); + final String connectionURL; if (getTypeForTarget(targetName) == CommandTarget.DAS) { connectionURL = getDefaultAddressList(jmsService).toString(); } else { - //Standalone server instance - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE,"not in DAS"); - logger.log(Level.FINE," _getMQJMXConnectorInfo - NOT in DAS"); - } - JmsService serverJmsService= getJmsServiceOfStandaloneServerInstance(targetName, config, domain); - //MQAddressList mqadList = new MQAddressList(serverJmsService, targetName); + logger.log(Level.FINEST," _getMQJMXConnectorInfo - standalone JMS service, NOT in DAS"); + final JmsService serverJmsService= getJmsServiceOfStandaloneServerInstance(targetName, config, domain); mqadList.setJmsService(serverJmsService); mqadList.setTargetName(targetName); mqadList.setup(false); connectionURL = mqadList.toString(); } - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, " _getMQJMXConnectorInfo - connection URL " + connectionURL); - } - String adminUserName = null; - String adminPassword = null; - JmsHost jmsHost = mqadList.getDefaultJmsHost(jmsService); - if (jmsHost != null) {//&& jmsHost.isEnabled()) { + logger.log(Level.FINE, " _getMQJMXConnectorInfo - connection URL {0}", connectionURL); + final String adminUserName; + final String adminPassword; + final JmsHost jmsHost = mqadList.getDefaultJmsHost(jmsService); + if (jmsHost == null) { + logger.log(Level.FINE, " _getMQJMXConnectorInfo, using default jms admin user and password "); + adminUserName = null; + adminPassword = null; + } else { adminUserName = jmsHost.getAdminUserName(); adminPassword = JmsRaUtil.getUnAliasedPwd(jmsHost.getAdminPassword()); - } else { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, " _getMQJMXConnectorInfo, using default jms admin user and password "); - } } - ResourceAdapter raInstance = getConfiguredRA(mqRAClassName, - connectionURL, adminUserName, adminPassword); - String jmxServiceURL = null, jmxServiceURLList = null; - Map jmxConnectorEnv = null; - Method[] methds = raInstance.getClass().getMethods(); - for (Method m : methds) { - if (m.getName().equalsIgnoreCase("get" + JMXSERVICEURLLIST)){ - jmxServiceURLList = (String)m.invoke(raInstance, new Object[]{}); - } else if (m.getName().equalsIgnoreCase("get" + JMXCONNECTORENV)){ - jmxConnectorEnv = (Map)m.invoke(raInstance, new Object[]{}); - } - } - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, " _getMQJMXConnectorInfo - jmxServiceURLList " + jmxServiceURLList); - logger.log(Level.FINE, " _getMQJMXConnectorInfo - jmxConnectorEnv " + jmxConnectorEnv); - } - jmxServiceURL = getFirstJMXServiceURL(jmxServiceURLList); - MQJMXConnectorInfo mqInfo = new MQJMXConnectorInfo(targetName, - ActiveJmsResourceAdapter.getBrokerInstanceName(jmsService) , + final ResourceAdapter raInstance = getConfiguredRA(mqRAClassName, connectionURL, adminUserName, adminPassword); + final String jmxServiceURLList = getJmxServiceUrlList(raInstance); + final Map jmxConnectorEnv = getJmxConnectorEnv(raInstance); + logger.log(Level.CONFIG, " _getMQJMXConnectorInfo - jmxServiceURLList {0}", jmxServiceURLList); + logger.log(Level.CONFIG, " _getMQJMXConnectorInfo - jmxConnectorEnv {0}", jmxConnectorEnv); + final String jmxServiceURL = getFirstJMXServiceURL(jmxServiceURLList); + return new MQJMXConnectorInfo(targetName, ActiveJmsResourceAdapter.getBrokerInstanceName(jmsService), jmsService.getType(), jmxServiceURL, jmxConnectorEnv); - return mqInfo; - } catch (Exception e) { - e.printStackTrace(); - ConnectorRuntimeException cre = new ConnectorRuntimeException(e.getMessage()); - cre.initCause(e); - throw cre; + } catch (final Exception e) { + throw new ConnectorRuntimeException(e); + } + } + + + private String getJmxServiceUrlList(final ResourceAdapter raInstance) { + final String methodName = "get" + JMXSERVICEURLLIST; + try { + final Method method = raInstance.getClass().getMethod(methodName); + return (String) method.invoke(raInstance); + } catch (final ReflectiveOperationException e) { + logger.log(Level.INFO, "Invocation of " + methodName + " failed, returning null.", e); + return null; + } + } + + + private Map getJmxConnectorEnv(final ResourceAdapter raInstance) { + final String methodName = "get" + JMXCONNECTORENV; + try { + final Method method = raInstance.getClass().getMethod(methodName); + return (Map) method.invoke(raInstance); + } catch (final ReflectiveOperationException e) { + logger.log(Level.INFO, "Invocation of " + methodName + " failed, returning null.", e); + return null; } } @@ -231,188 +202,95 @@ protected MQJMXConnectorInfo _getMQJMXConnectorInfo( * executed in DAS, an admin API is used to resolve hostnames and ports of * cluster instances for LOCAL type brokers while creating the connectionURL. */ - protected MQJMXConnectorInfo _getMQJMXConnectorInfoForCluster( - String target, JmsService jmsService, Class mqRAClassName, ServerContext serverContext) + protected MQJMXConnectorInfo _getMQJMXConnectorInfoForCluster(final String target, final JmsService jmsService, + final Class mqRAClass, final ServerContext serverContext) throws ConnectorRuntimeException { - // Create a new RA instance. - ResourceAdapter raInstance = null; - // Set the ConnectionURL - MQAddressList list = null; + final ResourceAdapter raInstance; try { + final MQAddressList list; if (jmsService.getType().equalsIgnoreCase(ActiveJmsResourceAdapter.REMOTE)) { list = getDefaultAddressList(jmsService); } else { list = new MQAddressList(); - CommandTarget ctarget = this.getTypeForTarget(target); + final CommandTarget ctarget = this.getTypeForTarget(target); if (ctarget == CommandTarget.CLUSTER) { - Server[] servers = list.getServersInCluster(target); + final Server[] servers = list.getServersInCluster(target); if (servers != null && servers.length > 0) { list.setInstanceName(servers[0].getName()); } - } else if (ctarget == CommandTarget.CLUSTERED_INSTANCE ){ + } else if (ctarget == CommandTarget.CLUSTERED_INSTANCE) { list.setInstanceName(target); } - java.util.Map hostMap = list.getResolvedLocalJmsHostsInMyCluster(true); - - if ( hostMap.size() == 0 ) { - String msg = localStrings.getLocalString("mqjmx.no_jms_hosts", "No JMS Hosts Configured"); + final Map hostMap = list.getResolvedLocalJmsHostsInMyCluster(true); + if (hostMap.isEmpty()) { + final String msg = localStrings.getLocalString("mqjmx.no_jms_hosts", "No JMS Hosts Configured"); throw new ConnectorRuntimeException(msg); } - - for (JmsHost host : hostMap.values()) { + for (final JmsHost host : hostMap.values()) { list.addMQUrl(host); } } - String connectionUrl = list.toString(); - String adminUserName = null; - String adminPassword = null; - JmsHost jmsHost = list.getDefaultJmsHost(jmsService); - if (jmsHost != null){// && jmsHost.isEnabled()) { + final String connectionUrl = list.toString(); + final String adminUserName; + final String adminPassword; + final JmsHost jmsHost = list.getDefaultJmsHost(jmsService); + if (jmsHost == null) { + logger.log(Level.FINE, " _getMQJMXConnectorInfo, using default jms admin user and password "); + adminUserName = null; + adminPassword = null; + } else { adminUserName = jmsHost.getAdminUserName(); adminPassword = JmsRaUtil.getUnAliasedPwd(jmsHost.getAdminPassword()); - } else { - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, " _getMQJMXConnectorInfo, using default jms admin user and password "); - } } - raInstance = getConfiguredRA(mqRAClassName, connectionUrl, adminUserName, adminPassword); - } catch (Exception e) { - e.printStackTrace(); - ConnectorRuntimeException cre = new ConnectorRuntimeException(e.getMessage()); - cre.initCause(e); - throw cre; + raInstance = getConfiguredRA(mqRAClass, connectionUrl, adminUserName, adminPassword); + } catch (final Exception e) { + throw new ConnectorRuntimeException(e); } try { - String jmxServiceURL = null, jmxServiceURLList = null; - Map jmxConnectorEnv = null; - Method[] methds = raInstance.getClass().getMethods(); - for (Method m : methds) { - if (m.getName().equalsIgnoreCase("get" + JMXSERVICEURLLIST)){ - jmxServiceURLList = (String)m.invoke(raInstance, new Object[]{}); - if (jmxServiceURLList != null && !jmxServiceURLList.trim().equals("")){ - jmxServiceURL = getFirstJMXServiceURL(jmxServiceURLList); - } - } else if (m.getName().equalsIgnoreCase("get" + JMXCONNECTORENV)){ - jmxConnectorEnv = (Map)m.invoke(raInstance, new Object[]{}); - } - } - MQJMXConnectorInfo mqInfo = new MQJMXConnectorInfo(target, - ActiveJmsResourceAdapter.getBrokerInstanceName(jmsService), + final String jmxServiceURLList = getJmxServiceUrlList(raInstance); + final Map jmxConnectorEnv = getJmxConnectorEnv(raInstance); + final String jmxServiceURL = getFirstJMXServiceURL(jmxServiceURLList); + return new MQJMXConnectorInfo(target, ActiveJmsResourceAdapter.getBrokerInstanceName(jmsService), jmsService.getType(), jmxServiceURL, jmxConnectorEnv); - return mqInfo; - } catch (Exception e) { - e.printStackTrace(); - ConnectorRuntimeException cre = new ConnectorRuntimeException(e.getMessage()); - cre.initCause(e); - throw cre; + } catch (final Exception e) { + throw new ConnectorRuntimeException(e); } } - /* protected boolean isAConfig(String targetName) throws Exception { - Domain domain = Globals.get(Domain.class); - Configs configs = domain.getConfigs(); - List configsList = configs.getConfig(); - for (int i =0; i < configsList.size(); i++){ - Config config = (Config)configsList.get(i); - if (targetName.equals(config.getName())) - return true; - } - return false; - //ConfigContext con = com.sun.enterprise.admin.server.core.AdminService.getAdminService().getAdminContext().getAdminConfigContext(); - //return ServerHelper.isAConfig(con, targetName); - } */ - - /* protected JmsHost getDefaultJmsHost(JmsService jmsService){ - String defaultJmsHost = jmsService.getDefaultJmsHost(); - JmsHost jmsHost = null; - if (defaultJmsHost == null || defaultJmsHost.equals("")) { - try { - jmsHost = jmsService.getJmsHost().get(0); - }catch (Exception e) { - ; - } - } else { - for (JmsHost defaultHost: jmsService.getJmsHost()) - if(defaultJmsHost.equals(defaultHost.getName())) - jmsHost = defaultHost; - } - return jmsHost; - } */ - - /* protected Map getResolvedLocalJmsHostsInCluster(String clusterName, MQAddressList list) { - Map map = new HashMap (); - - Domain domain = Globals.get(Domain.class); - Clusters clusters = domain.getClusters(); - List clusterList = clusters.getCluster(); - Cluster cluster = null; - for (int i =0; i < clusterList.size(); i++){ - if (clusterName.equals(((Cluster)clusterList.get(i)).getName())) - cluster = (Cluster)clusterList.get(i); - } - - //final String myCluster = ClusterHelper.getClusterByName(domainCC, clusterName).getName(); - final Server[] buddies = this.getServersInCluster(cluster);//ServerHelper.getServersInCluster(domainCC, myCluster); - final Config cfg = getConfigForServer(buddies[0]); - - final String myCluster = ClusterHelper.getClusterByName(domainCC, clusterName).getName(); - final Server[] buddies = ServerHelper.getServersInCluster(domainCC, myCluster); - for (final Server as : buddies) { - try { - final JmsHost copy = getResolvedJmsHost(as); - map.put(as.getName(), copy); - } catch (Exception e) { - // we dont add the host if we cannot get it - ; - } - } - return map; - } */ - /** * Configures an instance of MQ-RA with the connection URL passed in. * This configured RA is then used to obtain the JMXServiceURL/JMXServiceURLList */ - protected ResourceAdapter getConfiguredRA(Class mqRAclassname, String connectionURL, String adminuser, - String adminpasswd) throws Exception { - ResourceAdapter raInstance = (ResourceAdapter) mqRAclassname.newInstance(); - Method setConnectionURL = mqRAclassname.getMethod( + protected ResourceAdapter getConfiguredRA(final Class mqRAclassname, + final String connectionURL, final String adminuser, final String adminpasswd) throws Exception { + final ResourceAdapter raInstance = mqRAclassname.getDeclaredConstructor().newInstance(); + final Method setConnectionURL = mqRAclassname.getMethod( "set" + ActiveJmsResourceAdapter.CONNECTION_URL, new Class[] {String.class}); setConnectionURL.invoke(raInstance, new Object[] {connectionURL}); - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, " getConfiguredRA - set connectionURL as " + connectionURL); - } + logger.log(Level.FINE, "getConfiguredRA - set connectionURL as {0}", connectionURL); if (adminuser != null) { - Method setAdminUser = mqRAclassname.getMethod( - "set" + ActiveJmsResourceAdapter.ADMINUSERNAME, - new Class[] { String.class}); + final Method setAdminUser = mqRAclassname.getMethod("set" + ADMINUSERNAME, new Class[] {String.class}); setAdminUser.invoke(raInstance, new Object[] {adminuser}); - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, " getConfiguredRA - set admin user as " + adminuser); - } + logger.log(Level.FINE, "getConfiguredRA - set admin user as {0}", adminuser); } if (adminpasswd != null) { - Method setAdminPasswd = mqRAclassname.getMethod( - "set" + ActiveJmsResourceAdapter.ADMINPASSWORD, new Class[] {String.class}); + final Method setAdminPasswd = mqRAclassname.getMethod("set" + ADMINPASSWORD, new Class[] {String.class}); setAdminPasswd.invoke(raInstance, new Object[] {adminpasswd}); - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, " getConfiguredRA - set admin passwd as ***** "); - } + logger.log(Level.FINE, "getConfiguredRA - set admin passwd"); } return raInstance; } - private JmsService getJmsServiceOfStandaloneServerInstance(String target, Config cfg, Domain domain) throws Exception { + private JmsService getJmsServiceOfStandaloneServerInstance(final String target, final Config cfg, final Domain domain) throws Exception { if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "getJMSServiceOfSI LL " + target); - //ConfigContext con = com.sun.enterprise.admin.server.core.AdminService.getAdminService().getAdminContext().getAdminConfigContext(); + logger.log(Level.FINE, "getJMSServiceOfSI target: {0}", target); logger.log(Level.FINE, "cfg " + cfg); } - JmsService jmsService = cfg.getExtensionByType(JmsService.class); + final JmsService jmsService = cfg.getExtensionByType(JmsService.class); if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "jmsservice " + jmsService); } @@ -420,42 +298,33 @@ private JmsService getJmsServiceOfStandaloneServerInstance(String target, Config } - protected String getFirstJMXServiceURL(String jmxServiceURLList) { - //If type is REMOTE, MQ RA returns a null jmxServiceURL and a non-null - //jmxServiceURLList for PE also. - if ((jmxServiceURLList == null) || ("".equals(jmxServiceURLList))) { - return jmxServiceURLList; - } else { - StringTokenizer tokenizer = new StringTokenizer(jmxServiceURLList, " "); - return tokenizer.nextToken(); + private String getFirstJMXServiceURL(final String jmxServiceURLList) { + if (jmxServiceURLList == null || jmxServiceURLList.isBlank()) { + return null; } + final StringTokenizer tokenizer = new StringTokenizer(jmxServiceURLList, " "); + return tokenizer.nextToken(); } - protected CommandTarget getTypeForTarget(String target){ - Domain domain = Globals.get(Domain.class); - Config config = domain.getConfigNamed(target); + protected CommandTarget getTypeForTarget(final String target){ + final Domain domain = Globals.get(Domain.class); + final Config config = domain.getConfigNamed(target); if (config != null) { return CommandTarget.CONFIG; } - Server targetServer = domain.getServerNamed(target); - if (targetServer!=null) { - // Clusters clusters = domain.getClusters(); - // List clustersList = clusters.getCluster(); - //if (JmsRaUtil.isServerClustered(clustersList, target)) - // return CommandTarget.CLUSTERED_INSTANCE; + final Server targetServer = domain.getServerNamed(target); + if (targetServer != null) { if (targetServer.isDas()) { return CommandTarget.DAS; - } else { - return CommandTarget.STANDALONE_INSTANCE; } - }//end if (targetServer!=null) - Cluster cluster =domain.getClusterNamed(target); - if (cluster!=null) { + return CommandTarget.STANDALONE_INSTANCE; + } + final Cluster cluster = domain.getClusterNamed(target); + if (cluster != null) { return CommandTarget.CLUSTER; } return CommandTarget.DAS; - } @@ -464,186 +333,143 @@ protected CommandTarget getTypeForTarget(String target){ * performed in DAS. */ protected ActiveJmsResourceAdapter getMQAdapter(final ConnectorRuntime connectorRuntime) throws Exception { - ActiveJmsResourceAdapter air = (ActiveJmsResourceAdapter) java.security.AccessController - .doPrivileged(new java.security.PrivilegedExceptionAction() { - - @Override - public java.lang.Object run() throws Exception { - String module = ConnectorConstants.DEFAULT_JMS_ADAPTER; - String loc = ConnectorsUtil.getSystemModuleLocation(module); - connectorRuntime.createActiveResourceAdapter(loc, module, null); - return ConnectorRegistry.getInstance().getActiveResourceAdapter(module); - } - }); - return air; + PrivilegedExceptionAction action = () -> { + final String module = ConnectorConstants.DEFAULT_JMS_ADAPTER; + final String loc = ConnectorsUtil.getSystemModuleLocation(module); + connectorRuntime.createActiveResourceAdapter(loc, module, null); + return (ActiveJmsResourceAdapter) ConnectorRegistry.getInstance().getActiveResourceAdapter(module); + }; + return AccessController.doPrivileged(action); } - /* private boolean isDAS(String targetName) { - //return true; - if (isAConfig(targetName)) { - return false; - } - return getServerByName(targetName).isDas(); + protected MQAddressList getDefaultAddressList(final JmsService jmsService) throws Exception { + final MQAddressList list = new MQAddressList(jmsService); + list.setup(false); + return list; + } + + + protected final JMSAdminException logAndHandleException(final Exception cause, final String messageKey) + throws JMSAdminException { + return handleException(new Exception(localStrings.getLocalString(messageKey, null), cause)); + } - }*/ - /* private Server getServerByName(String serverName){ - Domain domain = Globals.get(Domain.class); - Servers servers = domain.getServers(); - List serverList = servers.getServer(); - for (int i=0; i < serverList.size(); i++){ - Server server = (Server) serverList.get(i); - if(serverName.equals(server.getName())) - return server; + /** + * @param e original cause; it is not included in the result, because the caller's classloader + * might not know all internal exception. + * @return JMSAdminException to throw + */ + protected final JMSAdminException handleException(final Exception e) { + logger.log(Level.WARNING, "Handling exception to be thrown.", e); + if (e instanceof JMSAdminException) { + return ((JMSAdminException)e); + } + final String msg = e.getMessage(); + if (msg == null) { + try (PrintWriter writer = new PrintWriter(new StringWriter())) { + e.printStackTrace(writer); + return new JMSAdminException(writer.toString()); } - return null; - }*/ - - - protected MQAddressList getDefaultAddressList(JmsService jmsService) throws Exception { - MQAddressList list = new MQAddressList(jmsService); - list.setup(false); - return list; - } - - - protected void logAndHandleException(Exception e, String errorMsg) throws JMSAdminException { - // log JMX Exception trace as WARNING - StringWriter s = new StringWriter(); - e.getCause().printStackTrace(new PrintWriter(s)); - logger.log(Level.WARNING, s.toString()); - JMSAdminException je = new JMSAdminException(localStrings.getLocalString(errorMsg, "")); - - // Cause will be InvocationTargetException, cause of that - // wil be MBeanException and cause of that will be the - // real exception we need - if ((e.getCause() != null) && (e.getCause().getCause() != null)) { - je.initCause(e.getCause().getCause().getCause()); - } - handleException(je); - } - - - protected void handleException(Exception e) throws JMSAdminException { - if (e instanceof JMSAdminException) { - throw ((JMSAdminException)e); - } - - String msg = e.getMessage(); - - JMSAdminException jae; - if (msg == null) { - jae = new JMSAdminException(); - } else { - jae = new JMSAdminException(msg); - } - - /* - * Don't do this for now because the CLI does not include jms.jar - * (at least not yet) in the classpath. Sending over a JMSException - * will cause a class not found exception to be thrown. - */ - //jae.setLinkedException(e); - - throw jae; - } - - - // XXX: To refactor into a Generic attribute type mapper, so that it is extensible later. - protected AttributeList convertProp2Attrs(Properties destProps) { - AttributeList destAttrs = new AttributeList(); - - String propName = null; - String propValue = null; - - for (Enumeration e = destProps.propertyNames(); e.hasMoreElements();) { - propName = (String) e.nextElement(); - if (propName.equals("AutoCreateQueueMaxNumActiveConsumers")) { - destAttrs.add(new Attribute("AutoCreateQueueMaxNumActiveConsumers", - Integer.valueOf(destProps.getProperty("AutoCreateQueueMaxNumActiveConsumers")))); - } else if (propName.equals("maxNumActiveConsumers")) { - destAttrs.add(new Attribute("MaxNumActiveConsumers", - Integer.valueOf(destProps.getProperty("maxNumActiveConsumers")))); - } else if (propName.equals("MaxNumActiveConsumers")) { - destAttrs.add(new Attribute("MaxNumActiveConsumers", - Integer.valueOf(destProps.getProperty("MaxNumActiveConsumers")))); - } else if (propName.equals("AutoCreateQueueMaxNumBackupConsumers")) { - destAttrs.add(new Attribute("AutoCreateQueueMaxNumBackupConsumers", - Integer.valueOf(destProps.getProperty("AutoCreateQueueMaxNumBackupConsumers")))); - } else if (propName.equals("AutoCreateQueues")) { - boolean b = false; - propValue = destProps.getProperty("AutoCreateQueues"); - if (propValue.equalsIgnoreCase("true")) { - b = true; - } - destAttrs.add(new Attribute("AutoCreateQueues", Boolean.valueOf(b))); - } else if (propName.equals("AutoCreateTopics")) { - boolean b = false; - propValue = destProps.getProperty("AutoCreateTopics"); - if (propValue.equalsIgnoreCase("true")) { - b = true; - } - destAttrs.add(new Attribute("AutoCreateTopics", Boolean.valueOf(b))); - } else if (propName.equals("DMQTruncateBody")) { - boolean b = false; - propValue = destProps.getProperty("DMQTruncateBody"); - if (propValue.equalsIgnoreCase("true")) { - b = true; - } - destAttrs.add(new Attribute("DMQTruncateBody", Boolean.valueOf(b))); - } else if (propName.equals("LogDeadMsgs")) { - boolean b = false; - propValue = destProps.getProperty("LogDeadMsgs"); - if (propValue.equalsIgnoreCase("true")) { - b = true; - } - destAttrs.add(new Attribute("LogDeadMsgs", Boolean.valueOf(b))); - } else if (propName.equals("MaxBytesPerMsg")) { - destAttrs.add(new Attribute("MaxBytesPerMsg", - Long.valueOf(destProps.getProperty("MaxBytesPerMsg")))); - } else if (propName.equals("MaxNumMsgs")) { - destAttrs.add(new Attribute("MaxNumMsgs", - Long.valueOf(destProps.getProperty("MaxNumMsgs")))); - } else if (propName.equals("MaxTotalMsgBytes")) { - destAttrs.add(new Attribute("MaxTotalMsgBytes", - Long.valueOf(destProps.getProperty("MaxTotalMsgBytes")))); - } else if (propName.equals("NumDestinations")) { - destAttrs.add(new Attribute("NumDestinations", - Integer.valueOf(destProps.getProperty("NumDestinations")))); - } else if (propName.equals("ConsumerFlowLimit")) { - destAttrs.add(new Attribute("ConsumerFlowLimit", - Long.valueOf(destProps.getProperty("ConsumerFlowLimit")))); - } else if (propName.equals("LocalDeliveryPreferred")) { - destAttrs.add(new Attribute("LocalDeliveryPreferred", - getBooleanValue(destProps.getProperty("LocalDeliveryPreferred")))); - } else if (propName.equals("ValidateXMLSchemaEnabled")) { - destAttrs.add(new Attribute("ValidateXMLSchemaEnabled", - getBooleanValue(destProps.getProperty("ValidateXMLSchemaEnabled")))); - } else if (propName.equals("UseDMQ")) { - destAttrs.add(new Attribute("UseDMQ", - getBooleanValue(destProps.getProperty("UseDMQ")))); - } else if (propName.equals("LocalOnly")) { - destAttrs.add(new Attribute("LocalOnly", - getBooleanValue(destProps.getProperty("LocalOnly")))); - } else if (propName.equals("ReloadXMLSchemaOnFailure")) { - destAttrs.add(new Attribute("ReloadXMLSchemaOnFailure", - getBooleanValue(destProps.getProperty("ReloadXMLSchemaOnFailure")))); - } else if (propName.equals("MaxNumProducers")) { - destAttrs.add(new Attribute("MaxNumProducers", - Integer.valueOf(destProps.getProperty("MaxNumProducers")))); - } else if (propName.equals("MaxNumBackupConsumers")) { - destAttrs.add(new Attribute("MaxNumBackupConsumers", - Integer.valueOf(destProps.getProperty("MaxNumBackupConsumers")))); - } else if (propName.equals("LimitBehavior")) { - destAttrs.add(new Attribute("LimitBehavior", destProps.getProperty("LimitBehavior"))); - } - } - return destAttrs; - } - - private Boolean getBooleanValue(String propValue) { - return propValue.equalsIgnoreCase("true") ? Boolean.TRUE : Boolean.FALSE; -// UseDMQ + } + return new JMSAdminException(msg); + } + + + // XXX: To refactor into a Generic attribute type mapper, so that it is extensible later. + protected AttributeList convertProp2Attrs(final Properties destProps) { + final AttributeList destAttrs = new AttributeList(); + + String propName = null; + String propValue = null; + + for (final Enumeration e = destProps.propertyNames(); e.hasMoreElements();) { + propName = (String) e.nextElement(); + if (propName.equals("AutoCreateQueueMaxNumActiveConsumers")) { + destAttrs.add(new Attribute("AutoCreateQueueMaxNumActiveConsumers", + Integer.valueOf(destProps.getProperty("AutoCreateQueueMaxNumActiveConsumers")))); + } else if (propName.equals("maxNumActiveConsumers")) { + destAttrs.add(new Attribute("MaxNumActiveConsumers", + Integer.valueOf(destProps.getProperty("maxNumActiveConsumers")))); + } else if (propName.equals("MaxNumActiveConsumers")) { + destAttrs.add(new Attribute("MaxNumActiveConsumers", + Integer.valueOf(destProps.getProperty("MaxNumActiveConsumers")))); + } else if (propName.equals("AutoCreateQueueMaxNumBackupConsumers")) { + destAttrs.add(new Attribute("AutoCreateQueueMaxNumBackupConsumers", + Integer.valueOf(destProps.getProperty("AutoCreateQueueMaxNumBackupConsumers")))); + } else if (propName.equals("AutoCreateQueues")) { + boolean b = false; + propValue = destProps.getProperty("AutoCreateQueues"); + if (propValue.equalsIgnoreCase("true")) { + b = true; + } + destAttrs.add(new Attribute("AutoCreateQueues", Boolean.valueOf(b))); + } else if (propName.equals("AutoCreateTopics")) { + boolean b = false; + propValue = destProps.getProperty("AutoCreateTopics"); + if (propValue.equalsIgnoreCase("true")) { + b = true; + } + destAttrs.add(new Attribute("AutoCreateTopics", Boolean.valueOf(b))); + } else if (propName.equals("DMQTruncateBody")) { + boolean b = false; + propValue = destProps.getProperty("DMQTruncateBody"); + if (propValue.equalsIgnoreCase("true")) { + b = true; + } + destAttrs.add(new Attribute("DMQTruncateBody", Boolean.valueOf(b))); + } else if (propName.equals("LogDeadMsgs")) { + boolean b = false; + propValue = destProps.getProperty("LogDeadMsgs"); + if (propValue.equalsIgnoreCase("true")) { + b = true; + } + destAttrs.add(new Attribute("LogDeadMsgs", Boolean.valueOf(b))); + } else if (propName.equals("MaxBytesPerMsg")) { + destAttrs.add(new Attribute("MaxBytesPerMsg", + Long.valueOf(destProps.getProperty("MaxBytesPerMsg")))); + } else if (propName.equals("MaxNumMsgs")) { + destAttrs.add(new Attribute("MaxNumMsgs", + Long.valueOf(destProps.getProperty("MaxNumMsgs")))); + } else if (propName.equals("MaxTotalMsgBytes")) { + destAttrs.add(new Attribute("MaxTotalMsgBytes", + Long.valueOf(destProps.getProperty("MaxTotalMsgBytes")))); + } else if (propName.equals("NumDestinations")) { + destAttrs.add(new Attribute("NumDestinations", + Integer.valueOf(destProps.getProperty("NumDestinations")))); + } else if (propName.equals("ConsumerFlowLimit")) { + destAttrs.add(new Attribute("ConsumerFlowLimit", + Long.valueOf(destProps.getProperty("ConsumerFlowLimit")))); + } else if (propName.equals("LocalDeliveryPreferred")) { + destAttrs.add(new Attribute("LocalDeliveryPreferred", + getBooleanValue(destProps.getProperty("LocalDeliveryPreferred")))); + } else if (propName.equals("ValidateXMLSchemaEnabled")) { + destAttrs.add(new Attribute("ValidateXMLSchemaEnabled", + getBooleanValue(destProps.getProperty("ValidateXMLSchemaEnabled")))); + } else if (propName.equals("UseDMQ")) { + destAttrs.add(new Attribute("UseDMQ", + getBooleanValue(destProps.getProperty("UseDMQ")))); + } else if (propName.equals("LocalOnly")) { + destAttrs.add(new Attribute("LocalOnly", + getBooleanValue(destProps.getProperty("LocalOnly")))); + } else if (propName.equals("ReloadXMLSchemaOnFailure")) { + destAttrs.add(new Attribute("ReloadXMLSchemaOnFailure", + getBooleanValue(destProps.getProperty("ReloadXMLSchemaOnFailure")))); + } else if (propName.equals("MaxNumProducers")) { + destAttrs.add(new Attribute("MaxNumProducers", + Integer.valueOf(destProps.getProperty("MaxNumProducers")))); + } else if (propName.equals("MaxNumBackupConsumers")) { + destAttrs.add(new Attribute("MaxNumBackupConsumers", + Integer.valueOf(destProps.getProperty("MaxNumBackupConsumers")))); + } else if (propName.equals("LimitBehavior")) { + destAttrs.add(new Attribute("LimitBehavior", destProps.getProperty("LimitBehavior"))); + } + } + return destAttrs; + } + + private Boolean getBooleanValue(final String propValue) { + return propValue.equalsIgnoreCase("true") ? Boolean.TRUE : Boolean.FALSE; } } diff --git a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/ListJMSDestinations.java b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/ListJMSDestinations.java index ca5a1cc4b91..4650b167def 100644 --- a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/ListJMSDestinations.java +++ b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/ListJMSDestinations.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,40 +17,47 @@ package org.glassfish.jms.admin.cli; -import org.glassfish.api.I18n; -import org.glassfish.api.Param; -import org.glassfish.api.ActionReport; -import org.glassfish.api.admin.AdminCommand; -import org.glassfish.api.admin.AdminCommandContext; -import org.glassfish.api.admin.CommandLock; -import org.glassfish.internal.api.ServerContext; - -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.sun.enterprise.config.serverbeans.Cluster; +import com.sun.enterprise.config.serverbeans.Config; +import com.sun.enterprise.config.serverbeans.Domain; +import com.sun.enterprise.config.serverbeans.Server; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.SystemPropertyConstants; -import com.sun.enterprise.config.serverbeans.*; - -import org.glassfish.api.admin.ExecuteOn; -import org.glassfish.config.support.CommandTarget; -import org.glassfish.config.support.TargetType; -import org.glassfish.api.admin.RuntimeType; -import org.glassfish.api.admin.ServerEnvironment; import jakarta.inject.Inject; import jakarta.inject.Named; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; + import javax.management.MBeanServerConnection; import javax.management.ObjectName; -import org.jvnet.hk2.annotations.Service; - +import org.glassfish.api.ActionReport; +import org.glassfish.api.I18n; +import org.glassfish.api.Param; +import org.glassfish.api.admin.AdminCommand; +import org.glassfish.api.admin.AdminCommandContext; +import org.glassfish.api.admin.CommandLock; +import org.glassfish.api.admin.ExecuteOn; +import org.glassfish.api.admin.RestEndpoint; +import org.glassfish.api.admin.RestEndpoints; +import org.glassfish.api.admin.RestParam; +import org.glassfish.api.admin.RuntimeType; +import org.glassfish.api.admin.ServerEnvironment; +import org.glassfish.config.support.CommandTarget; +import org.glassfish.config.support.TargetType; import org.glassfish.hk2.api.PerLookup; -import org.glassfish.api.admin.*; +import org.glassfish.internal.api.ServerContext; +import org.jvnet.hk2.annotations.Service; /** * Create JMS Destination - * */ @Service(name="list-jmsdest") @PerLookup @@ -100,6 +108,7 @@ public class ListJMSDestinations extends JMSDestination implements AdminCommand ServerContext serverContext; + @Override public void execute(AdminCommandContext context) { final ActionReport report = context.getActionReport(); @@ -112,7 +121,7 @@ public void execute(AdminCommandContext context) { } report.setExtraProperties(new Properties()); - List jmsDestList = new ArrayList(); + List jmsDestList = new ArrayList<>(); try { List list = listJMSDestinations(target, destType); @@ -120,7 +129,7 @@ public void execute(AdminCommandContext context) { for (JMSDestinationInfo destInfo : list) { final ActionReport.MessagePart part = report.getTopMessagePart().addChild(); part.setMessage(destInfo.getDestinationName()); - Map destMap = new HashMap(); + Map destMap = new HashMap<>(); destMap.put("name", destInfo.getDestinationName()); destMap.put("type", destInfo.getDestinationType()); jmsDestList.add(destMap); @@ -130,88 +139,65 @@ public void execute(AdminCommandContext context) { } catch (Exception e) { logger.throwing(getClass().getName(), "ListJMSDestination", e); - e.printStackTrace();//handleException(e); report.setMessage(localStrings.getLocalString("list.jms.dest.fail", - "Unable to list JMS Destinations. Please ensure that the Message Queue Brokers are running"));// + " " + e.getLocalizedMessage()); + "Unable to list JMS Destinations. Please ensure that the Message Queue Brokers are running")); report.setActionExitCode(ActionReport.ExitCode.FAILURE); report.setFailureCause(e); - return; } } -// list-jmsdest - public List listJMSDestinations(String tgtName, String destType) - throws Exception { - - if (logger.isLoggable(Level.FINE)) { - logger.log(Level.FINE, "listJMSDestination ..."); - } - MQJMXConnectorInfo mqInfo = getMQJMXConnectorInfo(target, config, serverContext, domain, connectorRuntime); - - //MBeanServerConnection mbsc = getMBeanServerConnection(tgtName); - try { + public List listJMSDestinations(String tgtName, String destType) throws Exception { + logger.log(Level.FINE, "listJMSDestinations ..."); + try (MQJMXConnectorInfo mqInfo = createMQJMXConnectorInfo(target, config, serverContext, domain, connectorRuntime)) { MBeanServerConnection mbsc = mqInfo.getMQMBeanServerConnection(); ObjectName on = new ObjectName(DESTINATION_MANAGER_CONFIG_MBEAN_NAME); - - ObjectName [] dests = (ObjectName [])mbsc.invoke(on, "getDestinations", null, null); - if ((dests != null) && (dests.length > 0)) { - List jmsdi = new ArrayList(); - for (int i = 0; i < dests.length; i++) { - on = dests[i]; - - String jdiType = toStringLabel(on.getKeyProperty("desttype")); - String jdiName = on.getKeyProperty("name"); - - // check if the destination name has double quotes at the beginning - // and end, if yes strip them - if ((jdiName != null) && (jdiName.length() > 1)) { - if (jdiName.indexOf('"') == 0) { - jdiName = jdiName.substring(1); - } - if (jdiName.lastIndexOf('"') == (jdiName.length() - 1)) { - jdiName = jdiName.substring(0, jdiName.lastIndexOf('"')); - } + ObjectName[] dests = (ObjectName[]) mbsc.invoke(on, "getDestinations", null, null); + if (dests == null || dests.length <= 0) { + return null; + } + final List jmsdi = new ArrayList<>(); + for (ObjectName dest : dests) { + on = dest; + String jdiType = toStringLabel(on.getKeyProperty("desttype")); + String jdiName = on.getKeyProperty("name"); + + // check if the destination name has double quotes at the beginning + // and end, if yes strip them + if ((jdiName != null) && (jdiName.length() > 1)) { + if (jdiName.indexOf('"') == 0) { + jdiName = jdiName.substring(1); + } + if (jdiName.lastIndexOf('"') == (jdiName.length() - 1)) { + jdiName = jdiName.substring(0, jdiName.lastIndexOf('"')); } + } - JMSDestinationInfo jdi = new JMSDestinationInfo(jdiName, jdiType); + JMSDestinationInfo jdi = new JMSDestinationInfo(jdiName, jdiType); - if (destType == null) { + if (destType == null) { + jmsdi.add(jdi); + } else if (destType.equals(JMS_DEST_TYPE_TOPIC) + || destType.equals(JMS_DEST_TYPE_QUEUE)) { + //Physical Destination Type specific listing + if (jdiType.equalsIgnoreCase(destType)) { jmsdi.add(jdi); - } else if (destType.equals(JMS_DEST_TYPE_TOPIC) - || destType.equals(JMS_DEST_TYPE_QUEUE)) { - //Physical Destination Type specific listing - if (jdiType.equalsIgnoreCase(destType)) { - jmsdi.add(jdi); - } } } - return jmsdi; - //(JMSDestinationInfo[]) jmsdi.toArray(new JMSDestinationInfo[]{}); } + return jmsdi; } catch (Exception e) { - // log JMX Exception trace as WARNING - logAndHandleException(e, "admin.mbeans.rmb.error_listing_jms_dest"); - } finally { - try { - if (mqInfo != null) { - mqInfo.closeMQMBeanServerConnection(); - } - } catch (Exception e) { - handleException(e); - } + throw logAndHandleException(e, "admin.mbeans.rmb.error_listing_jms_dest"); } - - return null; } private String toStringLabel(String type) { if (type.equals(DESTINATION_TYPE_QUEUE)) { - return ("queue"); + return "queue"; } else if (type.equals(DESTINATION_TYPE_TOPIC)) { - return ("topic"); + return "topic"; } else { - return ("unknown"); + return "unknown"; } } diff --git a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/MQJMXConnectorInfo.java b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/MQJMXConnectorInfo.java index 877cf2d0e72..1c618c30653 100644 --- a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/MQJMXConnectorInfo.java +++ b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/MQJMXConnectorInfo.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -36,29 +37,29 @@ * @author Sivakumar Thyagarajan * @since SJSAS 9.0 */ -public class MQJMXConnectorInfo { - private String jmxServiceURL = null; - private Map jmxConnectorEnv = null; - private String asInstanceName = null; - private String brokerInstanceName = null; - private String brokerType = null; +public class MQJMXConnectorInfo implements AutoCloseable { private static final Logger _logger = Logger.getLogger(LogUtils.JMS_ADMIN_LOGGER); - final private static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(MQJMXConnectorInfo.class); - private JMXConnector connector = null; + private static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(MQJMXConnectorInfo.class); - public MQJMXConnectorInfo(String asInstanceName, String brokerInstanceName, - String brokerType, String jmxServiceURL, - Map jmxConnectorEnv) { + private final String jmxServiceURL; + private final Map jmxConnectorEnv; + private final String asInstanceName; + private final String brokerInstanceName; + private final String brokerType; + private JMXConnector connector; + + public MQJMXConnectorInfo(String asInstanceName, String brokerInstanceName, String brokerType, String jmxServiceURL, + Map jmxConnectorEnv) { this.brokerInstanceName = brokerInstanceName; this.asInstanceName = asInstanceName; this.jmxServiceURL = jmxServiceURL; this.brokerType = brokerType; this.jmxConnectorEnv = jmxConnectorEnv; if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, "MQJMXConnectorInfo : brokerInstanceName " + - brokerInstanceName + " ASInstanceName " + asInstanceName + - " jmxServiceURL " + jmxServiceURL + " BrokerType " + brokerType - + " jmxConnectorEnv " + jmxConnectorEnv); + _logger.log(Level.FINE, + "MQJMXConnectorInfo : brokerInstanceName " + brokerInstanceName + " ASInstanceName " + asInstanceName + + " jmxServiceURL " + jmxServiceURL + " BrokerType " + brokerType + " jmxConnectorEnv " + + jmxConnectorEnv); } } @@ -86,9 +87,7 @@ public String getJMXServiceURL(){ } /** - * Returns an MBeanServerConnection representing the MQ broker instance's MBean - * server. - * @return + * @return an MBeanServerConnection representing the MQ broker instance's MBean server. * @throws ConnectorRuntimeException */ //XXX:Enhance to support SSL (once MQ team delivers support in the next drop) @@ -96,37 +95,36 @@ public String getJMXServiceURL(){ //be shared with the consumer of this API public MBeanServerConnection getMQMBeanServerConnection() throws ConnectorRuntimeException { try { - if (getJMXServiceURL() == null || getJMXServiceURL().equals("")) { - String msg = localStrings.getLocalString("error.get.jmsserviceurl", - "Failed to get MQ JMXServiceURL of {0}.", getASInstanceName()); - throw new ConnectorRuntimeException(msg); - } - if (_logger.isLoggable(Level.FINE)) { - _logger.log(Level.FINE, - "creating MBeanServerConnection to MQ JMXServer with "+getJMXServiceURL()); + if (connector == null) { + if (getJMXServiceURL() == null || getJMXServiceURL().isEmpty()) { + String msg = localStrings.getLocalString("error.get.jmsserviceurl", + "Failed to get MQ JMXServiceURL of {0}.", getASInstanceName()); + throw new ConnectorRuntimeException(msg); + } + _logger.log(Level.FINE, "creating MBeanServerConnection to MQ JMXServer with {0}", getJMXServiceURL()); + JMXServiceURL serviceURL = new JMXServiceURL(getJMXServiceURL()); + connector = JMXConnectorFactory.connect(serviceURL, this.jmxConnectorEnv); } - JMXServiceURL jmxServiceURL = new JMXServiceURL(getJMXServiceURL()); - connector = JMXConnectorFactory.connect(jmxServiceURL, this.jmxConnectorEnv); //XXX: Do we need to pass in a Subject? MBeanServerConnection mbsc = connector.getMBeanServerConnection(); return mbsc; } catch (Exception e) { - e.printStackTrace(); - ConnectorRuntimeException cre = new ConnectorRuntimeException(e.getMessage()); - cre.initCause(e); - throw cre; + throw new ConnectorRuntimeException(e.getMessage(), e); } } - public void closeMQMBeanServerConnection() throws ConnectorRuntimeException { + /** + * Closes the connector. + */ + @Override + public void close() throws ConnectorRuntimeException { try { - if (connector != null) { - connector.close(); - } + if (connector != null) { + connector.close(); + connector = null; + } } catch (IOException e) { - ConnectorRuntimeException cre = new ConnectorRuntimeException(e.getMessage()); - cre.initCause(e); - throw cre; + throw new ConnectorRuntimeException(e.getMessage(), e); } } } diff --git a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/UpdateJmsPhysicalDestinationCommand.java b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/UpdateJmsPhysicalDestinationCommand.java index a459195124e..42d7f46ca0f 100644 --- a/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/UpdateJmsPhysicalDestinationCommand.java +++ b/appserver/jms/admin/src/main/java/org/glassfish/jms/admin/cli/UpdateJmsPhysicalDestinationCommand.java @@ -111,17 +111,10 @@ public void execute(AdminCommandContext context) { } protected void updateJMSDestination() throws Exception { - logger.log(Level.FINE, "__updateJmsPhysicalDestination ..."); - MQJMXConnectorInfo mqInfo = getMQJMXConnectorInfo(target, config, serverContext, domain, connectorRuntime); - - try { - MBeanServerConnection mbsc = mqInfo.getMQMBeanServerConnection(); - AttributeList destAttrs = null; - - if (props != null) { - destAttrs = convertProp2Attrs(props); - } - + logger.log(Level.FINE, "updateJMSDestination ..."); + try (MQJMXConnectorInfo mqInfo = createMQJMXConnectorInfo(target, config, serverContext, domain, connectorRuntime)) { + final MBeanServerConnection mbsc = mqInfo.getMQMBeanServerConnection(); + final AttributeList destAttrs = props == null ? null : convertProp2Attrs(props); if (destType.equalsIgnoreCase("topic")) { destType = DESTINATION_TYPE_TOPIC; } else if (destType.equalsIgnoreCase("queue")) { @@ -130,16 +123,7 @@ protected void updateJMSDestination() throws Exception { ObjectName on = new ObjectName(MBEAN_DOMAIN_NAME + ":type=Destination,subtype=Config,desttype=" + destType +",name=\"" + destName + "\""); mbsc.setAttributes(on, destAttrs); } catch (Exception e) { - //log JMX Exception trace as WARNING - logAndHandleException(e, "admin.mbeans.rmb.error_updating_jms_dest"); - } finally { - try { - if (mqInfo != null) { - mqInfo.closeMQMBeanServerConnection(); - } - } catch (Exception e) { - handleException(e); - } + throw logAndHandleException(e, "admin.mbeans.rmb.error_updating_jms_dest"); } } } diff --git a/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsAvailability.java b/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsAvailability.java index e76ccfdcbf6..4c5577b5d97 100644 --- a/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsAvailability.java +++ b/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsAvailability.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -21,7 +22,6 @@ import org.jvnet.hk2.config.Attribute; import org.jvnet.hk2.config.Element; import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.ConfigBeanProxy; import org.jvnet.hk2.config.types.Property; import java.beans.PropertyVetoException; @@ -44,6 +44,9 @@ @Configured public interface JmsAvailability extends ConfigExtension, PropertyBag, AvailabilityServiceExtension { + String PATTERN_BROKER = "(masterbroker|shareddb)"; + String PATTERN_MESSAGE_STORE_TYPE = "(file|jdbc)"; + /** * Gets the value of the availabilityEnabled property. * @@ -87,7 +90,7 @@ public interface JmsAvailability extends ConfigExtension, PropertyBag, Availabil */ @Attribute (defaultValue="masterbroker") - @Pattern(regexp="(masterbroker|shareddb)") + @Pattern(regexp = PATTERN_BROKER, message = "Valid values: " + PATTERN_BROKER) String getConfigStoreType(); @@ -112,8 +115,8 @@ public interface JmsAvailability extends ConfigExtension, PropertyBag, Availabil * {@link String } */ - @Attribute (defaultValue="file") - @Pattern(regexp="(file|jdbc)") + @Attribute(defaultValue = "file") + @Pattern(regexp = PATTERN_MESSAGE_STORE_TYPE, message = "Valid values: " + PATTERN_MESSAGE_STORE_TYPE) String getMessageStoreType(); @@ -144,29 +147,28 @@ public interface JmsAvailability extends ConfigExtension, PropertyBag, Availabil * Sets the value of the DB Vendor property. * * @param value allowed object is - * {@link String } + * {@link String } */ void setDbVendor(String value) throws PropertyVetoException; /** - * Gets the value of the DB User Name property. - * - * This is the DB user Name for the DB used by the MQ broker cluster - * for use in saving persistent JMS messages and other broker - * cluster configuration information. - * - * @return possible object is - * {@link String } - */ + * Gets the value of the DB User Name property. + * This is the DB user Name for the DB used by the MQ broker cluster + * for use in saving persistent JMS messages and other broker + * cluster configuration information. + * + * @return possible object is + * {@link String } + */ @Attribute String getDbUsername(); - /** - * Sets the value of the DB UserName property. - * - * @param value allowed object is - * {@link String } - */ + /** + * Sets the value of the DB UserName property. + * + * @param value allowed object is + * {@link String } + */ void setDbUsername(String value) throws PropertyVetoException; /** @@ -227,10 +229,12 @@ public interface JmsAvailability extends ConfigExtension, PropertyBag, Availabil * {@link String } */ void setMqStorePoolName(String value) throws PropertyVetoException; + /** - Properties as per {@link PropertyBag} + * Properties as per {@link PropertyBag} */ - @ToDo(priority=ToDo.Priority.IMPORTANT, details="Provide PropertyDesc for legal props" ) + @Override + @ToDo(priority = ToDo.Priority.IMPORTANT, details = "Provide PropertyDesc for legal props") @PropertiesDesc(props={}) @Element List getProperty(); diff --git a/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsHost.java b/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsHost.java index 060eb396a18..0195a37e8a9 100644 --- a/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsHost.java +++ b/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsHost.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -20,7 +21,6 @@ import org.jvnet.hk2.config.Attribute; import org.jvnet.hk2.config.Element; import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.ConfigBeanProxy; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; @@ -34,8 +34,6 @@ import org.glassfish.quality.ToDo; import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Min; -import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Pattern; import jakarta.validation.Payload; @@ -54,7 +52,7 @@ }) public interface JmsHost extends ConfigExtension, PropertyBag, Payload { - final static String PORT_PATTERN = "\\$\\{[\\p{L}\\p{N}_][\\p{L}\\p{N}\\-_./;#]*\\}" + String PORT_PATTERN = "\\$\\{[\\p{L}\\p{N}_][\\p{L}\\p{N}\\-_./;#]*\\}" + "|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]" + "|[1-5][0-9][0-9][0-9][0-9]|6[0-4][0-9][0-9][0-9]" + "|65[0-4][0-9][0-9]|655[0-2][0-9]|6553[0-5]"; @@ -104,10 +102,8 @@ public interface JmsHost extends ConfigExtension, PropertyBag, Payload { * @return possible object is * {@link String } */ - @Attribute (defaultValue="7676") - @Pattern(regexp=PORT_PATTERN, - message="{port-pattern}", - payload=JmsHost.class) + @Attribute(defaultValue = "7676") + @Pattern(regexp = PORT_PATTERN, message = "{port-pattern}", payload = JmsHost.class) String getPort(); /** @@ -178,6 +174,7 @@ public interface JmsHost extends ConfigExtension, PropertyBag, Payload { /** Properties as per {@link org.jvnet.hk2.config.types.PropertyBag} */ + @Override @ToDo(priority=ToDo.Priority.IMPORTANT, details="Provide PropertyDesc for legal props" ) @PropertiesDesc(props={}) @Element diff --git a/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsService.java b/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsService.java index 0db3f4f1ad7..938db976a20 100644 --- a/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsService.java +++ b/appserver/jms/gf-jms-connector/src/main/java/com/sun/enterprise/connectors/jms/config/JmsService.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -18,6 +19,15 @@ import com.sun.enterprise.config.modularity.annotation.CustomConfiguration; import com.sun.enterprise.config.modularity.annotation.HasCustomizationTokens; + +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; + +import java.beans.PropertyVetoException; +import java.util.List; + import org.glassfish.api.admin.config.ConfigExtension; import org.glassfish.api.admin.config.Container; import org.glassfish.api.admin.config.PropertiesDesc; @@ -28,13 +38,6 @@ import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import jakarta.validation.constraints.Max; -import jakarta.validation.constraints.Min; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; -import java.beans.PropertyVetoException; -import java.util.List; - /** * The jms-service element specifies information about the bundled/built-in * JMS service that is managed by Application Server @@ -50,6 +53,11 @@ @CustomConfiguration(baseConfigurationFileName = "jms-module-conf.xml") public interface JmsService extends ConfigExtension, PropertyBag, Container { + String ADDRESS_LIST_SELECTIONS = "(random|priority)"; + String SERVICE_TYPES = "(LOCAL|EMBEDDED|REMOTE)"; + String MQ_SCHEMES = "(mq||http)"; + String MQ_SERVICES = "(ssljms||jms)"; + /** * Gets the value of the initTimeoutInSeconds property. * @@ -83,7 +91,7 @@ public interface JmsService extends ConfigExtension, PropertyBag, Container { */ @Attribute @NotNull - @Pattern(regexp="(LOCAL|EMBEDDED|REMOTE)") + @Pattern(regexp = SERVICE_TYPES, message = "Valid values: " + SERVICE_TYPES) String getType(); /** @@ -134,14 +142,14 @@ public interface JmsService extends ConfigExtension, PropertyBag, Container { */ void setDefaultJmsHost(String value) throws PropertyVetoException; - @Attribute + @Attribute String getMasterBroker(); /** * Sets the value of the MasterBroker property. * * @param value allowed object is - * {@link String } + * {@link String } */ void setMasterBroker(String value) throws PropertyVetoException; @@ -215,8 +223,8 @@ public interface JmsService extends ConfigExtension, PropertyBag, Container { * @return possible object is * {@link String } */ - @Attribute (defaultValue="random") - @Pattern(regexp="(random|priority)") + @Attribute(defaultValue = "random") + @Pattern(regexp = ADDRESS_LIST_SELECTIONS, message = "Valid values: " + ADDRESS_LIST_SELECTIONS) String getAddresslistBehavior(); /** @@ -259,7 +267,7 @@ public interface JmsService extends ConfigExtension, PropertyBag, Container { * {@link String } */ @Attribute - @Pattern(regexp="(mq||http)") + @Pattern(regexp = MQ_SCHEMES, message = "Valid values: " + MQ_SCHEMES) String getMqScheme(); /** @@ -281,7 +289,7 @@ public interface JmsService extends ConfigExtension, PropertyBag, Container { * {@link String } */ @Attribute - @Pattern(regexp="(ssljms||jms)") + @Pattern(regexp = MQ_SERVICES, message = "Valid values: " + MQ_SERVICES) String getMqService(); /** @@ -315,33 +323,44 @@ public interface JmsService extends ConfigExtension, PropertyBag, Container { @Element List getJmsHost(); - /** - Properties. + /** + * Properties. */ -@PropertiesDesc( - props={ - @PropertyDesc(name="instance-name", defaultValue="imqbroker", - description="The full Sun GlassFish Message Queue broker instance name"), - - @PropertyDesc(name="instance-name-suffix", defaultValue="xxxxxxxxxxxxxxxxxx", - description="A suffix to add to the full Message Queue broker instance name. The suffix is separated " + - "from the instance name by an underscore character (_). For example, if the instance name is 'imqbroker', " + - "appending the suffix 'xyz' changes the instance name to 'imqbroker_xyz'"), - - @PropertyDesc(name="append-version", defaultValue="", - description="If true, appends the major and minor version numbers, preceded by underscore characters (_), " + - "to the full Message Queue broker instance name. For example, if the instance name is 'imqbroker', " + - "appending the version numbers changes the instance name to imqbroker_8_0"), - - @PropertyDesc(name="user-name", defaultValue="xxxxxxxxxxxxxxxxxx", - description="Specifies the user name for creating the JMS connection. Needed only if the default " + - "username/password of guest/guest is not available in the broker"), - - @PropertyDesc(name="password", defaultValue="xxxxxxxxxxxxxxxxxx", - description="Specifies the password for creating the JMS connection. Needed only if the default " + - "username/password of guest/guest is not available in the broker") - } - ) + @Override + @PropertiesDesc( + props = { + @PropertyDesc( + name = "instance-name", + defaultValue = "imqbroker", + description = "The full Sun GlassFish Message Queue broker instance name"), + + @PropertyDesc( + name = "instance-name-suffix", + defaultValue = "xxxxxxxxxxxxxxxxxx", + description = "A suffix to add to the full Message Queue broker instance name. The suffix is separated " + + "from the instance name by an underscore character (_). For example, if the instance name is 'imqbroker', " + + "appending the suffix 'xyz' changes the instance name to 'imqbroker_xyz'"), + + @PropertyDesc( + name = "append-version", + defaultValue = "", + description = "If true, appends the major and minor version numbers, preceded by underscore characters (_), " + + "to the full Message Queue broker instance name. For example, if the instance name is 'imqbroker', " + + "appending the version numbers changes the instance name to imqbroker_8_0"), + + @PropertyDesc( + name = "user-name", + defaultValue = "xxxxxxxxxxxxxxxxxx", + description = "Specifies the user name for creating the JMS connection. Needed only if the default " + + "username/password of guest/guest is not available in the broker"), + + @PropertyDesc( + name = "password", + defaultValue = "xxxxxxxxxxxxxxxxxx", + description = "Specifies the password for creating the JMS connection. Needed only if the default " + + "username/password of guest/guest is not available in the broker") + } + ) @Element List getProperty(); } diff --git a/appserver/jms/jmsra/pom.xml b/appserver/jms/jmsra/pom.xml index 97ff9116360..6940c17733c 100644 --- a/appserver/jms/jmsra/pom.xml +++ b/appserver/jms/jmsra/pom.xml @@ -81,9 +81,10 @@ run - process-resources + generate-resources + + + + + Eclipse OpenMQ(tm) JMS Resource Adapter + Eclipse OpenMQ(tm) Jakarta EE Resource Adapter for JMS + Eclipse Foundation + Jakarta Messaging v3.0 + 6.2.0 + + + + com.sun.messaging.jms.ra.ResourceAdapter + + + + ConnectionURL + + + java.lang.String + + + mq://localhost:7676/ + + + + + UserName + + + java.lang.String + + + guest + + + + + Password + + + java.lang.String + + + guest + + + + + + com.sun.messaging.jms.ra.ManagedConnectionFactory + + + AddressList + java.lang.String + localhost + + + UserName + java.lang.String + guest + + + Password + java.lang.String + guest + + + jakarta.jms.ConnectionFactory + + + com.sun.messaging.jms.ra.ConnectionFactoryAdapter + + + jakarta.jms.QueueConnection + + + com.sun.messaging.jms.ra.ConnectionAdapter + + + + + com.sun.messaging.jms.ra.ManagedConnectionFactory + + + AddressList + java.lang.String + localhost + + + UserName + java.lang.String + guest + + + Password + java.lang.String + guest + + + jakarta.jms.QueueConnectionFactory + + + com.sun.messaging.jms.ra.ConnectionFactoryAdapter + + + jakarta.jms.QueueConnection + + + com.sun.messaging.jms.ra.ConnectionAdapter + + + + + com.sun.messaging.jms.ra.ManagedConnectionFactory + + + AddressList + java.lang.String + localhost + + + UserName + java.lang.String + guest + + + Password + java.lang.String + guest + + + jakarta.jms.TopicConnectionFactory + + + com.sun.messaging.jms.ra.ConnectionFactoryAdapter + + + jakarta.jms.TopicConnection + + + com.sun.messaging.jms.ra.ConnectionAdapter + + + + XATransaction + + + + BasicPassword + + + jakarta.resource.spi.security.PasswordCredential + + + + false + + + + + + + jakarta.jms.MessageListener + + + + com.sun.messaging.jms.ra.ActivationSpec + + + + destination + + + + + destinationType + + + + + + + + jakarta.jms.Queue + + + com.sun.messaging.Queue + + + + Name + + + java.lang.String + + + + + + + Description + + + java.lang.String + + + + + + + + jakarta.jms.Topic + + + com.sun.messaging.Topic + + + + Name + + + java.lang.String + + + + + + + Description + + + java.lang.String + + + + + + + diff --git a/appserver/orb/orb-enabler/src/main/java/org/glassfish/orb/admin/config/IiopListener.java b/appserver/orb/orb-enabler/src/main/java/org/glassfish/orb/admin/config/IiopListener.java index 357b2aa1cf2..17c5efb77de 100644 --- a/appserver/orb/orb-enabler/src/main/java/org/glassfish/orb/admin/config/IiopListener.java +++ b/appserver/orb/orb-enabler/src/main/java/org/glassfish/orb/admin/config/IiopListener.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,6 +17,10 @@ package org.glassfish.orb.admin.config; +import jakarta.validation.Payload; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; + import java.beans.PropertyVetoException; import java.util.List; @@ -31,16 +36,8 @@ import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import jakarta.validation.Payload; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; - import static org.glassfish.config.support.Constants.NAME_REGEX; -/** - * - */ - /* @XmlType(name = "", propOrder = { "ssl", "property" @@ -67,9 +64,9 @@ public interface IiopListener extends ConfigBeanProxy, PropertyBag, Payload { * @return possible object is * {@link String } */ - @Attribute(key=true) + @Attribute(key = true) @NotNull - @Pattern(regexp=NAME_REGEX) + @Pattern(regexp = NAME_REGEX, message = "Pattern: " + NAME_REGEX) String getId(); /** @@ -109,9 +106,7 @@ public interface IiopListener extends ConfigBeanProxy, PropertyBag, Payload { * {@link String } */ @Attribute (defaultValue="1072") - @Pattern(regexp=PORT_PATTERN, - message="{port-pattern}", - payload=IiopListener.class) + @Pattern(regexp = PORT_PATTERN, message = "{port-pattern}", payload = IiopListener.class) String getPort(); /** diff --git a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jmac/config/GFServerConfigProvider.java b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jmac/config/GFServerConfigProvider.java index ea2ce8fb2b9..ca99577f835 100644 --- a/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jmac/config/GFServerConfigProvider.java +++ b/appserver/security/core-ee/src/main/java/com/sun/enterprise/security/jmac/config/GFServerConfigProvider.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -108,7 +109,7 @@ public class GFServerConfigProvider implements AuthConfigProvider { protected AuthConfigFactory factory = null; private WebServicesDelegate wsdelegate = null; - public GFServerConfigProvider(Map properties, AuthConfigFactory factory) { + public GFServerConfigProvider(Map properties, AuthConfigFactory factory) { this.factory = factory; initializeParser(); @@ -376,10 +377,10 @@ static class Entry { private static final Class[] PARAMS = {}; private static final Object[] ARGS = {}; - private String moduleClassName; - private MessagePolicy requestPolicy; - private MessagePolicy responsePolicy; - private Map options; + private final String moduleClassName; + private final MessagePolicy requestPolicy; + private final MessagePolicy responsePolicy; + private final Map options; /** * Construct a ConfigFile entry. @@ -488,11 +489,11 @@ public String getDefaultServerID() { * parsed ID entry */ public static class IDEntry { - private String type; // provider type (client, server, client-server) - private String moduleClassName; - private MessagePolicy requestPolicy; - private MessagePolicy responsePolicy; - private Map options; + private final String type; // provider type (client, server, client-server) + private final String moduleClassName; + private final MessagePolicy requestPolicy; + private final MessagePolicy responsePolicy; + private final Map options; public String getModuleClassName() { return moduleClassName; @@ -527,8 +528,8 @@ public IDEntry(String type, String moduleClassName, MessagePolicy requestPolicy, * A data object contains module object and the corresponding map. */ protected static class ModuleInfo { - private Object module; - private Map map; + private final Object module; + private final Map map; ModuleInfo(Object module, Map map) { this.module = module; @@ -940,11 +941,11 @@ public ClientAuthContext getAuthContext(String authContextID, Subject clientSubj static protected class GFServerAuthContext implements ServerAuthContext { - private GFServerAuthConfig config; - private ServerAuthModule module; - private com.sun.enterprise.security.jauth.ServerAuthModule oldModule; + private final GFServerAuthConfig config; + private final ServerAuthModule module; + private final com.sun.enterprise.security.jauth.ServerAuthModule oldModule; - private Map map; + private final Map map; boolean managesSession = false; GFServerAuthContext(GFServerAuthConfig config, ServerAuthModule module, Map map) { @@ -1068,9 +1069,9 @@ public void cleanSubject(MessageInfo messageInfo, Subject subject) throws AuthEx static protected class GFClientAuthContext implements ClientAuthContext { - private GFClientAuthConfig config; - private ClientAuthModule module; - private com.sun.enterprise.security.jauth.ClientAuthModule oldModule; + private final GFClientAuthConfig config; + private final ClientAuthModule module; + private final com.sun.enterprise.security.jauth.ClientAuthModule oldModule; // private Map map; GFClientAuthContext(GFClientAuthConfig config, ClientAuthModule module, Map map) { diff --git a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java index 29b74ce2149..59967f54c4a 100644 --- a/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java +++ b/appserver/security/jaspic-provider-framework/src/main/java/com/sun/jaspic/config/jaas/JAASAuthConfigProvider.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -36,13 +37,13 @@ public abstract class JAASAuthConfigProvider extends AuthConfigProviderHelper { private static final String DEFAULT_JAAS_APP_NAME = "other"; private static final String ALL_APPS = "*"; - private String configFileName; + private final String configFileName; private ExtendedConfigFile jaasConfig; - private Map properties; - private AuthConfigFactory factory; + private final Map properties; + private final AuthConfigFactory factory; - public JAASAuthConfigProvider(Map properties, AuthConfigFactory factory) { + public JAASAuthConfigProvider(Map properties, AuthConfigFactory factory) { this.properties = properties; this.factory = factory; @@ -62,11 +63,13 @@ public JAASAuthConfigProvider(Map properties, AuthConfigFactory factory) { selfRegister(); } + @Override public Map getProperties() { return properties; } + @Override public AuthConfigFactory getFactory() { return factory; } @@ -85,24 +88,29 @@ private RegistrationContext getRegistrationContext(String id) { final String description = "JAAS AuthConfig: " + appContext; + @Override public String getMessageLayer() { return layer; } + @Override public String getAppContext() { return appContext; } + @Override public String getDescription() { return description; } + @Override public boolean isPersistent() { return false; } }; } + @Override public AuthConfigFactory.RegistrationContext[] getSelfRegistrationContexts() { final String[] appContexts = jaasConfig.getAppNames(getModuleTypes()); RegistrationContext[] rvalue = new RegistrationContext[appContexts.length]; @@ -112,6 +120,7 @@ public AuthConfigFactory.RegistrationContext[] getSelfRegistrationContexts() { return rvalue; } + @Override public AuthContextHelper getAuthContextHelper(String appContext, boolean returnNullContexts) throws AuthException { return new JAASAuthContextHelper(getLoggerName(), returnNullContexts, diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/osgi.bundle b/appserver/tests/admin/admin-extension/osgi.bundle similarity index 100% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/osgi.bundle rename to appserver/tests/admin/admin-extension/osgi.bundle diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/pom.xml b/appserver/tests/admin/admin-extension/pom.xml similarity index 58% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/pom.xml rename to appserver/tests/admin/admin-extension/pom.xml index bfcb847c278..11648ba174d 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/pom.xml +++ b/appserver/tests/admin/admin-extension/pom.xml @@ -21,60 +21,37 @@ 4.0.0 org.glassfish.main.tests - nucleus-tests - @project.version@ - ../../../../../pom.xml + admin-tests-parent + 6.2.6-SNAPSHOT - test-progress-status-commands - Progress status - Test Commands + test-progress-admin-extension glassfish-jar - - - - - - - src/main/java - - **/*.properties - - - - src/main/resources - - **/*.1 - **/*.xml - **/*.properties - - - - - + GlassFish Admin Tests - Progress Admin Extension org.glassfish.main.common glassfish-api ${project.version} + provided org.glassfish.main.common common-util ${project.version} + provided - - org.glassfish.main.admin - config-api - ${project.version} - + org.glassfish.hk2 - hk2 + hk2-api + provided - org.glassfish.hk2 - hk2-junitrunner + jakarta.inject + jakarta.inject-api + provided diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressComplexCommand.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressComplexCommand.java similarity index 95% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressComplexCommand.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressComplexCommand.java index 8f61b6fa779..7e095aec37b 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressComplexCommand.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressComplexCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,24 +17,22 @@ package com.sun.enterprise.tests.progress; -import com.sun.enterprise.config.serverbeans.Domain; import com.sun.logging.LogDomains; -import java.util.logging.Level; + import java.util.logging.Logger; + import org.glassfish.api.I18n; -import org.glassfish.api.Param; import org.glassfish.api.admin.AdminCommand; import org.glassfish.api.admin.AdminCommandContext; import org.glassfish.api.admin.CommandLock; import org.glassfish.api.admin.ManagedJob; import org.glassfish.api.admin.Progress; import org.glassfish.api.admin.ProgressStatus; -import org.glassfish.api.admin.RestEndpoint; -import org.glassfish.api.admin.RestEndpoints; import org.glassfish.hk2.api.PerLookup; import org.jvnet.hk2.annotations.Service; -/** Basic progress status example. +/** + * Basic progress status example. * Contains 10 steps * * @author mmares @@ -137,6 +136,7 @@ public ProgressRunnable(ProgressStatus ps, int count, long interval, String mess this.message = message; } + @Override public void run() { doProgress(ps, count, interval, message); } diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressCustomCommand.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressCustomCommand.java similarity index 94% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressCustomCommand.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressCustomCommand.java index 974c6f125dc..7d30c49a4c4 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressCustomCommand.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressCustomCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -19,6 +20,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.regex.Pattern; + import org.glassfish.api.ActionReport; import org.glassfish.api.I18n; import org.glassfish.api.Param; @@ -31,7 +33,6 @@ import org.jvnet.hk2.annotations.Service; /** - * * @author mmares */ @Service(name = "progress-custom") @@ -51,14 +52,14 @@ public class ProgressCustomCommand implements AdminCommand { private static class Interval { private boolean valid = true; - private String origInteval; + private String origInterval; private int multiplicator = 1; private int minSec = -1; private int maxSec = 0; private boolean spin = false; private Interval(String interval) { - origInteval = interval; + origInterval = interval; try { if (!keyPattern.matcher(interval).matches()) { valid = false; @@ -99,13 +100,8 @@ public boolean isSpin() { public int getMultiplicator() { if (valid) { return multiplicator; - } else { - return 1; } - } - - public String getOrigInteval() { - return origInteval; + return 1; } public boolean isValid() { @@ -128,7 +124,7 @@ public long getMilis() { @Override public String toString() { - return origInteval; + return origInterval; } } @@ -149,7 +145,7 @@ private int getStepCount() { @Override public void execute(AdminCommandContext context) { ProgressStatus ps = context.getProgressStatus(); - parsedIntervals = new ArrayList(intervals != null ? intervals.length : 0); + parsedIntervals = new ArrayList<>(intervals != null ? intervals.length : 0); ActionReport report = context.getActionReport(); for (String interval : intervals) { parsedIntervals.add(new Interval(interval)); diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressDoubleTotalsCommand.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressDoubleTotalsCommand.java similarity index 95% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressDoubleTotalsCommand.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressDoubleTotalsCommand.java index 08d5ba70024..698a113bf17 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressDoubleTotalsCommand.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressDoubleTotalsCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -26,7 +27,8 @@ import org.glassfish.hk2.api.PerLookup; import org.jvnet.hk2.annotations.Service; -/** Basic progress status example. +/** + * Basic progress status example. * Contains 10 steps * * @author mmares diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressExecOtherCommand.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressExecOtherCommand.java similarity index 84% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressExecOtherCommand.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressExecOtherCommand.java index 042eaf9e3bd..1ef602ee4c4 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressExecOtherCommand.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressExecOtherCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -55,15 +56,11 @@ public void execute(AdminCommandContext context) { } // Execute other command - commandRunner.getCommandInvocation( - "progress-simple", - context.getActionReport() - .addSubActionsReport(), + // Number 20 is little bit tricky. Please see javadoc of ProgressStatus + commandRunner.getCommandInvocation("progress-simple", + context.getActionReport().addSubActionsReport(), context.getSubject()) - .progressStatusChild( - // Number 20 is little bit tricky. Please see javadoc of ProgressStatus - progressStatus.createChild("subcommand", 20)) - .execute(); + .progressStatusChild(progressStatus.createChild("subcommand", 20)).execute(); // Do some after logic progressStatus.progress("Finishing outer command"); @@ -73,8 +70,6 @@ public void execute(AdminCommandContext context) { } progressStatus.complete("Finished outer command"); - - System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } private void doSomeLogic() { diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressFailInHalfCommand.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressFailInHalfCommand.java similarity index 95% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressFailInHalfCommand.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressFailInHalfCommand.java index 969c2982d2f..eae97507349 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressFailInHalfCommand.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressFailInHalfCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -27,7 +28,8 @@ import org.glassfish.hk2.api.PerLookup; import org.jvnet.hk2.annotations.Service; -/** Basic progress status example. +/** + * Basic progress status example. * Contains 10 steps * * @author mmares diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressFullAnnotCommand.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressFullAnnotCommand.java similarity index 96% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressFullAnnotCommand.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressFullAnnotCommand.java index 84c4e07b467..f19189f0147 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressFullAnnotCommand.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressFullAnnotCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -42,5 +43,4 @@ public void execute(AdminCommandContext context) { cmd.noTotalSteps = true; cmd.execute(context); } - } diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressPayloadCommand.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressPayloadCommand.java similarity index 94% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressPayloadCommand.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressPayloadCommand.java index 4892191b575..09f2e607ca3 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressPayloadCommand.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressPayloadCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -18,10 +19,12 @@ import com.sun.enterprise.util.StringUtils; import com.sun.logging.LogDomains; + import java.io.File; import java.io.IOException; import java.net.URI; import java.util.logging.Logger; + import org.glassfish.api.ActionReport; import org.glassfish.api.I18n; import org.glassfish.api.Param; @@ -35,7 +38,8 @@ import org.glassfish.hk2.api.PerLookup; import org.jvnet.hk2.annotations.Service; -/** Doing progress and send some payload. +/** + * Doing progress and send some payload. * * @author mmares */ @@ -47,8 +51,7 @@ @ManagedJob public class ProgressPayloadCommand implements AdminCommand { - private final static Logger logger = - LogDomains.getLogger(ProgressPayloadCommand.class, LogDomains.ADMIN_LOGGER); + private final static Logger logger = LogDomains.getLogger(ProgressPayloadCommand.class, LogDomains.ADMIN_LOGGER); @Param(name = "down", multiple = false, primary = true, optional = true) String down; diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressSimpleCommand.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressSimpleCommand.java similarity index 97% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressSimpleCommand.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressSimpleCommand.java index 41b0df81a80..c6e81cb8127 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressSimpleCommand.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressSimpleCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressStepBackCommand.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressStepBackCommand.java similarity index 95% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressStepBackCommand.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressStepBackCommand.java index 614d59d57f3..27fd174bc39 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressStepBackCommand.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressStepBackCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -26,7 +27,8 @@ import org.glassfish.hk2.api.PerLookup; import org.jvnet.hk2.annotations.Service; -/** Basic progress status example. +/** + * Basic progress status example. * Contains 10 steps * * @author mmares diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressWithSupplementCommand.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressWithSupplementCommand.java similarity index 88% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressWithSupplementCommand.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressWithSupplementCommand.java index 37273cccefa..c49b1e7a47b 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/ProgressWithSupplementCommand.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/ProgressWithSupplementCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,7 +17,6 @@ package com.sun.enterprise.tests.progress; -import com.sun.enterprise.universal.i18n.LocalStringsImpl; import org.glassfish.api.I18n; import org.glassfish.api.admin.AdminCommand; import org.glassfish.api.admin.AdminCommandContext; @@ -26,7 +26,8 @@ import org.glassfish.hk2.api.PerLookup; import org.jvnet.hk2.annotations.Service; -/** Same as {@code ProgressSimpleCommand} but this one has supplements. +/** + * Same as {@code ProgressSimpleCommand} but this one has supplements. * It also does not specify totalStepCount in annotation but using API. * Percentage can be printed after {@code SupplementBefore} will be done. * @@ -38,12 +39,9 @@ @PerLookup @CommandLock(CommandLock.LockType.NONE) @I18n("progress") -@Progress() +@Progress public class ProgressWithSupplementCommand implements AdminCommand { - private static final LocalStringsImpl strings = - new LocalStringsImpl(ProgressWithSupplementCommand.class); - @Override public void execute(AdminCommandContext context) { ProgressStatus ps = context.getProgressStatus(); diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/SupplementAfter.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/SupplementAfter.java similarity index 96% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/SupplementAfter.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/SupplementAfter.java index f24e8761184..f094f548ce2 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/SupplementAfter.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/SupplementAfter.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the diff --git a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/SupplementBefore.java b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/SupplementBefore.java similarity index 96% rename from nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/SupplementBefore.java rename to appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/SupplementBefore.java index 2faed1d56a5..f0f68665c2a 100644 --- a/nucleus/tests/admin/src/addon/modules/test-progress-status-commands/src/main/java/com/sun/enterprise/tests/progress/SupplementBefore.java +++ b/appserver/tests/admin/admin-extension/src/main/java/com/sun/enterprise/tests/progress/SupplementBefore.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the diff --git a/appserver/tests/admin/pom.xml b/appserver/tests/admin/pom.xml new file mode 100755 index 00000000000..153f9790246 --- /dev/null +++ b/appserver/tests/admin/pom.xml @@ -0,0 +1,38 @@ + + + + + 4.0.0 + + + org.glassfish.main.tests + tests + 6.2.6-SNAPSHOT + + + admin-tests-parent + pom + + GlassFish Admin Tests - Parent + + + admin-extension + tests + + diff --git a/appserver/tests/admin/tests/pom.xml b/appserver/tests/admin/tests/pom.xml new file mode 100644 index 00000000000..3a64f8479e0 --- /dev/null +++ b/appserver/tests/admin/tests/pom.xml @@ -0,0 +1,135 @@ + + + + + 4.0.0 + + + org.glassfish.main.tests + admin-tests-parent + 6.2.6-SNAPSHOT + + + admin-tests + + GlassFish Admin Tests + + + + + org.glassfish.jersey.core + jersey-client + test + + + + org.glassfish.jersey.inject + jersey-hk2 + test + + + org.glassfish.main.admin + rest-client + ${project.version} + test + + + org.glassfish.main.common + common-util + ${project.version} + test + + + org.glassfish.main.security + security + ${project.version} + test + + + org.glassfish.main.security + security-ee + ${project.version} + test + + + jakarta.servlet + jakarta.servlet-api + test + + + + org.glassfish.main.distributions + glassfish + zip + ${project.version} + test + + + org.glassfish.main.tests + test-progress-admin-extension + ${project.version} + test + + + + org.junit.jupiter + junit-jupiter-engine + + + org.hamcrest + hamcrest + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-impl-maven-archive + + + + + + + maven-dependency-plugin + + + unpack-glassfish + + unpack-dependencies + + + glassfish + true + ${project.build.directory} + + + + copy-addon + + copy-dependencies + + + test-progress-admin-extension + true + ${project.build.directory}/glassfish6/glassfish/modules + + + + + + + diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/ClusterITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/ClusterITest.java new file mode 100644 index 00000000000..97946190713 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/ClusterITest.java @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2012, 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.net.URL; +import java.net.URLConnection; + +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; +import org.glassfish.main.admin.test.tool.asadmin.Asadmin; +import org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static org.glassfish.main.admin.test.tool.AsadminResultMatcher.asadminOK; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.stringContainsInOrder; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * @author Tom Mueller + */ +@TestMethodOrder(OrderAnnotation.class) +public class ClusterITest { + + private static final String PORT1 = "55123"; + private static final String PORT2 = "55124"; + private static final String CLUSTER_NAME = "eec1"; + private static final String INSTANCE_NAME_1 = "eein1-with-a-very-very-very-long-name"; + private static final String INSTANCE_NAME_2 = "eein2"; + private static final String URL1 = "http://localhost:" + PORT1; + private static final String URL2 = "http://localhost:" + PORT2; + private static final Asadmin ASADMIN = GlassFishTestEnvironment.getAsadmin(); + + @Test + @Order(1) + public void createClusterTest() { + assertThat(ASADMIN.exec("create-cluster", CLUSTER_NAME), asadminOK()); + } + + @Test + @Order(2) + public void createInstancesTest() { + assertThat( + ASADMIN.exec("create-local-instance", "--cluster", CLUSTER_NAME, "--systemproperties", + "HTTP_LISTENER_PORT=" + PORT1 + + ":HTTP_SSL_LISTENER_PORT=18181" + + ":IIOP_SSL_LISTENER_PORT=13800" + + ":IIOP_LISTENER_PORT=13700" + + ":JMX_SYSTEM_CONNECTOR_PORT=17676" + + ":IIOP_SSL_MUTUALAUTH_PORT=13801" + + ":JMS_PROVIDER_PORT=18686" + + ":ASADMIN_LISTENER_PORT=14848", + INSTANCE_NAME_1), asadminOK()); + + assertThat( + ASADMIN.exec("create-local-instance", "--cluster", CLUSTER_NAME, "--systemproperties", + "HTTP_LISTENER_PORT=" + PORT2 + + ":HTTP_SSL_LISTENER_PORT=28181" + + ":IIOP_SSL_LISTENER_PORT=23800" + + ":IIOP_LISTENER_PORT=23700" + + ":JMX_SYSTEM_CONNECTOR_PORT=27676" + + ":IIOP_SSL_MUTUALAUTH_PORT=23801" + + ":JMS_PROVIDER_PORT=28686" + + ":ASADMIN_LISTENER_PORT=24848", + INSTANCE_NAME_2), asadminOK()); + } + + + @Test + @Order(3) + public void startInstancesTest() { + assertThat(ASADMIN.exec(30_000, false, "start-local-instance", INSTANCE_NAME_1), asadminOK()); + assertThat(ASADMIN.exec(30_000, false, "start-local-instance", INSTANCE_NAME_2), asadminOK()); + } + + @Test + @Order(4) + public void checkClusterTest() { + assertThat(ASADMIN.exec("list-instances"), asadminOK()); + assertThat(getURL(URL1), stringContainsInOrder("GlassFish Server")); + assertThat(getURL(URL2), stringContainsInOrder("GlassFish Server")); + } + + @Test + @Order(5) + public void stopInstancesTest() { + assertThat(ASADMIN.exec("stop-local-instance", "--kill", INSTANCE_NAME_1), asadminOK()); + assertThat(ASADMIN.exec("stop-local-instance", "--kill", INSTANCE_NAME_2), asadminOK()); + } + + @Test + @Order(6) + public void deleteInstancesTest() { + assertThat(ASADMIN.exec("delete-local-instance", INSTANCE_NAME_1), asadminOK()); + assertThat(ASADMIN.exec("delete-local-instance", INSTANCE_NAME_2), asadminOK()); + } + + @Test + @Order(7) + public void deleteClusterTest() { + assertThat(ASADMIN.exec("delete-cluster", CLUSTER_NAME), asadminOK()); + } + + + /** + * This methods opens a connection to the given URL and + * returns the string that is returned from that URL. This + * is useful for simple servlet retrieval + * + * @param urlstr The URL to connect to + * @return The string returned from that URL, or empty + * string if there was a problem contacting the URL + */ + public static String getURL(String urlstr) { + URLConnection urlc = openConnection(urlstr); + try ( + BufferedReader ir = new BufferedReader(new InputStreamReader(urlc.getInputStream(), ISO_8859_1)); + StringWriter ow = new StringWriter(); + ) { + String line; + while ((line = ir.readLine()) != null) { + ow.write(line); + ow.write("\n"); + } + return ow.getBuffer().toString(); + } catch (IOException ex) { + return fail(ex); + } + } + + private static URLConnection openConnection(String url) { + try { + return new URL(url).openConnection(); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/MiscCommandsITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/MiscCommandsITest.java new file mode 100644 index 00000000000..330638eefdd --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/MiscCommandsITest.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test; + +import org.glassfish.main.admin.test.tool.asadmin.Asadmin; +import org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; + +import static org.glassfish.main.admin.test.tool.AsadminResultMatcher.asadminOK; + +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.hamcrest.MatcherAssert.assertThat; + + +/** + * @author Tom Mueller + */ +@TestMethodOrder(OrderAnnotation.class) +public class MiscCommandsITest { + + private static final Asadmin ASADMIN = GlassFishTestEnvironment.getAsadmin(); + + @AfterAll + public static void startDomainAgain() { + assertThat(ASADMIN.exec("start-domain"), asadminOK()); + } + + @Test + @Order(1) + public void uptime() { + assertThat(ASADMIN.exec("uptime"), asadminOK()); + } + + @Test + @Order(1) + public void version1() { + assertThat(ASADMIN.exec("version"), asadminOK()); + } + + @Test + @Order(100) + public void version2() { + assertThat(ASADMIN.exec("stop-domain"), asadminOK()); + assertThat(ASADMIN.exec("version", "--local"), asadminOK()); + } +} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/OSGiCommandsTest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/OSGiCommandsITest.java similarity index 51% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/OSGiCommandsTest.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/OSGiCommandsITest.java index 36faf61368d..81c74afeec2 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/OSGiCommandsTest.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/OSGiCommandsITest.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -14,95 +15,79 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package org.glassfish.nucleus.admin; +package org.glassfish.main.admin.test; -import org.glassfish.api.admin.AccessRequired; -import org.glassfish.tests.utils.NucleusTestUtils; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.*; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -import static org.glassfish.tests.utils.NucleusTestUtils.nadmin; -import static org.glassfish.tests.utils.NucleusTestUtils.nadminWithOutput; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertTrue; +import org.glassfish.main.admin.test.tool.asadmin.Asadmin; +import org.glassfish.main.admin.test.tool.asadmin.AsadminResult; +import org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment; +import org.hamcrest.collection.IsEmptyCollection; +import org.junit.jupiter.api.Test; + +import static org.glassfish.main.admin.test.tool.AsadminResultMatcher.asadminOK; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author sanjeeb.sahoo@oracle.com */ -@Test -public class OSGiCommandsTest { - - public void basicOsgiCmd() { - assertTrue(nadmin("osgi", "lb")); - } +public class OSGiCommandsITest { - private List runCmd(String... cmd) throws Exception { - NucleusTestUtils.NadminReturn value = nadminWithOutput(cmd); - if (!value.returnValue) { - throw new Exception("Cmd failed: \n" + value.outAndErr); - } - List output = new ArrayList(); - for (String line : value.out.split("\\n")) { - line = line.trim(); - if (line.isEmpty() || line.startsWith("nadmin") || line.startsWith("Command")) continue; - output.add(line); - } - return output; - } + private static final Asadmin ASADMIN = GlassFishTestEnvironment.getAsadmin(); - private String newCmdSession() throws Exception { - List value = runCmd("osgi", "--session", "new"); - if (value.size() != 1) { - throw new Exception("Unexpected output: \n " + value); - } - return value.get(0); + @Test + public void basicOsgiCmd() { + assertThat(ASADMIN.exec("osgi", "lb"), asadminOK()); } - private Set listCmdSessions() throws Exception { - List sessions = runCmd("osgi", "--session", "list"); - return new HashSet(sessions); - } /** * Tests functionality of session handling of osgi command. * It creates sessions, lists them, executes commands against each session and finally stops them. * @throws Exception */ + @Test public void osgiCmdSession() throws Exception { // Create some sessions - Set sessions = new HashSet(); - for (int i = 0 ; i < 3; ++i) { + Set sessions = new HashSet<>(); + for (int i = 0; i < 3; ++i) { sessions.add(newCmdSession()); } // Let's list them to make sure list operation works. final Set actual = listCmdSessions(); - assertEquals("listed sessions do not match with created sessions", sessions, actual); + assertEquals(sessions, actual, "listed sessions do not match with created sessions"); - // Let's set the same variable in each command session with a different value and make sure the variables - // are scoped to sessions. + // Let's set the same variable in each command session with a different value and make sure + // the variables are scoped to sessions. for (String sessionId : sessions) { - runCmd("osgi", "--session", "execute", "--session-id", sessionId, "var=" + sessionId); + List result = runCmd("osgi", "--session", "execute", "--session-id", sessionId, "var=" + sessionId); + assertThat(result, IsEmptyCollection.empty()); } for (String sessionId : sessions) { - String value = runCmd("osgi", "--session", "execute", "--session-id", sessionId, "echo $var").get(0); - assertEquals(sessionId, value); + List result = runCmd("osgi", "--session", "execute", "--session-id", sessionId, "echo $var"); + assertThat(result, not(IsEmptyCollection.empty())); + assertEquals(sessionId, result.get(0)); } // Let's stop all sessions. for (String sessionId : sessions) { - runCmd("osgi", "--session", "stop", "--session-id", sessionId); + List result = runCmd("osgi", "--session", "stop", "--session-id", sessionId); + assertThat(result, IsEmptyCollection.empty()); } sessions = listCmdSessions(); - assertTrue("Not all sessions closed properly: " + sessions, sessions.isEmpty()); + assertTrue(sessions.isEmpty(), "Not all sessions closed properly: " + sessions); } /** @@ -110,21 +95,44 @@ public void osgiCmdSession() throws Exception { * a list of shell commands to be executed. * @throws IOException */ + @Test public void osgiShell() throws IOException { File cmdFile = File.createTempFile("osgi-commands", ".txt"); cmdFile.deleteOnExit(); - PrintStream ps = new PrintStream(new FileOutputStream(cmdFile)); - try { + try (PrintStream ps = new PrintStream(new FileOutputStream(cmdFile))) { ps.println("help"); ps.println("lb"); - NucleusTestUtils.NadminReturn value = nadminWithOutput("osgi-shell", "--file", cmdFile.getAbsolutePath()); - assertTrue(value.out.contains("System Bundle")); - } finally { - try { - ps.close(); - } catch (Exception e) { - // ignore + AsadminResult value = ASADMIN.exec("osgi-shell", "--file", cmdFile.getAbsolutePath()); + assertTrue(value.getStdOut().contains("System Bundle")); + } + } + + + private String newCmdSession() throws Exception { + List value = runCmd("osgi", "--session", "new"); + if (value.size() != 1) { + throw new Exception("Unexpected output: \n " + value); + } + return value.get(0); + } + + private Set listCmdSessions() throws Exception { + List sessions = runCmd("osgi", "--session", "list"); + return new HashSet<>(sessions); + } + + + private List runCmd(String... cmd) throws Exception { + AsadminResult value = ASADMIN.exec(cmd); + assertThat(value, asadminOK()); + List output = new ArrayList<>(); + for (String line : value.getStdOut().split("\\n")) { + line = line.trim(); + if (line.isEmpty() || line.startsWith(ASADMIN.getCommandName()) || line.startsWith("Command")) { + continue; } + output.add(line); } + return output; } } diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/RestITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/RestITest.java new file mode 100644 index 00000000000..43945ef3353 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/RestITest.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.HttpURLConnection; + +import org.junit.jupiter.api.Test; + +import static org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment.openConnection; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class RestITest { + + @Test + public void testManagementEndpoint() throws Exception { + HttpURLConnection connection = openConnection("/management/domain.xml"); + try { + assertEquals(200, connection.getResponseCode()); + } finally { + connection.disconnect(); + } + } + + @Test + public void testMonitoringEndpoint() throws Exception { + HttpURLConnection connection = openConnection("/monitoring/domain.xml"); + try { + assertEquals(200, connection.getResponseCode()); + } finally { + connection.disconnect(); + } + } + + @Test + public void testAdminCommandEndpoint() throws Exception { + HttpURLConnection connection = openConnection("/management/domain/version.xml"); + try { + assertEquals(200, connection.getResponseCode()); + } finally { + connection.disconnect(); + } + } + + @Test + public void testChildConfigBeanEndpoint() throws Exception { + HttpURLConnection connection = openConnection("/management/domain/applications.xml"); + try { + assertEquals(200, connection.getResponseCode()); + } finally { + connection.disconnect(); + } + } + + @Test + public void testPostGetDelete() throws Exception { + // FIXME: causes HTTP 500 without any log + assertThat(deleteNode(), greaterThanOrEqualTo(400)); + assertEquals(200, createNode()); + assertEquals(200, getNode()); + assertEquals(200, deleteNode()); + } + + private int createNode() throws IOException { + String parameters = "name=myConfigNode"; + HttpURLConnection connection = openConnection("/management/domain/nodes/create-node-config"); + try { + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + connection.setRequestProperty("Content-Length", Integer.toString(parameters.getBytes().length)); + connection.setUseCaches(false); + connection.setDoInput(true); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Language", "en-US"); + try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { + wr.writeBytes(parameters); + } + return connection.getResponseCode(); + } finally { + connection.disconnect(); + } + } + + private int getNode() throws IOException { + HttpURLConnection connection = openConnection("/management/domain/nodes/node/myConfigNode"); + try { + return connection.getResponseCode(); + } finally { + connection.disconnect(); + } + } + + private int deleteNode() throws IOException { + HttpURLConnection connection = openConnection("/management/domain/nodes/delete-node-config?id=myConfigNode"); + try { + connection.setRequestMethod("DELETE"); + connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + connection.setDoOutput(true); + return connection.getResponseCode(); + } finally { + connection.disconnect(); + } + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/DetachAttachITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/DetachAttachITest.java new file mode 100644 index 00000000000..0c7d3e5c464 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/DetachAttachITest.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.progress; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadFactory; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.glassfish.main.admin.test.tool.asadmin.Asadmin; +import org.glassfish.main.admin.test.tool.asadmin.AsadminResult; +import org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment; +import org.junit.jupiter.api.Test; + +import static org.glassfish.main.admin.test.tool.AsadminResultMatcher.asadminOK; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.stringContainsInOrder; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * @author martinmares + */ +public class DetachAttachITest { + private static final Logger LOG = Logger.getLogger(DetachAttachITest.class.getName()); + private static final Asadmin ASADMIN = GlassFishTestEnvironment.getAsadmin(); + + @Test + public void uptimePeriodically() throws Exception { + Set ids = new HashSet<>(); + for (int i = 0; i < 3; i++) { + LOG.log(Level.FINE, "detachAndAttachUptimePeriodically(): round " + i); + final String id; + { + AsadminResult result = ASADMIN.execDetached("--terse", "uptime"); + assertThat(result, asadminOK()); + id = parseJobIdFromEchoTerse(result.getStdOut()); + assertTrue(ids.add(id)); + } + Thread.sleep(1000L); + { + AsadminResult result = ASADMIN.exec("--terse", "attach", id); + assertThat(result, asadminOK()); + assertTrue(result.getStdOut().contains("uptime")); + } + } + } + + + @Test + public void commandWithProgressStatus() throws Exception { + AsadminResult result = ASADMIN.execDetached("--terse", "progress-custom", "6x1"); + assertThat(result, asadminOK()); + String id = parseJobIdFromEchoTerse(result.getStdOut()); + Thread.sleep(2000L); + // Now attach running + result = ASADMIN.exec("attach", id); + assertThat(result, asadminOK()); + assertThat(result.getStdOut(), stringContainsInOrder("progress-custom")); + List prgs = ProgressMessage.grepProgressMessages(result.getStdOut()); + assertFalse(prgs.isEmpty()); + assertThat(prgs.get(0).getValue(), greaterThan(0)); + assertEquals(100, prgs.get(prgs.size() - 1).getValue()); + // Now attach finished - must NOT exist - seen progress job is removed + assertThat(ASADMIN.exec("attach", id), not(asadminOK())); + } + + + @Test + public void detachOnesAttachMulti() throws Exception { + ExecutorService pool = Executors.newCachedThreadPool(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread result = new Thread(r); + result.setDaemon(true); + return result; + } + }); + AsadminResult result = ASADMIN.execDetached("--terse", "progress-custom", "8x1"); + assertThat(result, asadminOK()); + final String id = parseJobIdFromEchoTerse(result.getStdOut()); + assertNotNull(id, "id"); + Thread.sleep(1500L); + final int attachCount = 3; + Collection> attaches = new ArrayList<>(attachCount); + for (int i = 0; i < attachCount; i++) { + attaches.add(new Callable() { + @Override + public AsadminResult call() throws Exception { + return ASADMIN.exec("attach", id); + } + }); + } + List> results = pool.invokeAll(attaches); + for (Future fRes : results) { + AsadminResult res = fRes.get(); + assertThat(res, asadminOK()); + assertTrue(res.getStdOut().contains("progress-custom")); + List prgs = ProgressMessage.grepProgressMessages(res.getStdOut()); + assertFalse(prgs.isEmpty()); + assertThat(prgs.get(0).getValue(), greaterThan(0)); + assertEquals(100, prgs.get(prgs.size() - 1).getValue()); + } + } + + private String parseJobIdFromEchoTerse(String str) { + List stok = Collections.list(new StringTokenizer(str)); + assertThat(stok, hasSize(1)); + return (String) stok.get(0); + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/JobManagerITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/JobManagerITest.java new file mode 100644 index 00000000000..40ba44a1941 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/JobManagerITest.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.progress; + +import org.glassfish.main.admin.test.tool.asadmin.Asadmin; +import org.glassfish.main.admin.test.tool.asadmin.AsadminResult; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; + +import static org.glassfish.main.admin.test.tool.AsadminResultMatcher.asadminOK; +import static org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment.deleteJobsFile; +import static org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment.deleteOsgiDirectory; +import static org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment.getAsadmin; + +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.stringContainsInOrder; + +/** + * This tests the functionality of JobManager, list-jobs + * + * @author Bhakti Mehta + * @author David Matejcek + */ +@TestMethodOrder(OrderAnnotation.class) +public class JobManagerITest { + + private static final String COMMAND_PROGRESS_SIMPLE = "progress-simple"; + private static final Asadmin ASADMIN = getAsadmin(); + + @BeforeEach + public void setUp() throws Exception { + assertThat(ASADMIN.exec("stop-domain"), asadminOK()); + deleteJobsFile(); + deleteOsgiDirectory(); + assertThat(ASADMIN.exec("start-domain"), asadminOK()); + } + + @Test + @Order(1) + public void noJobsTest() { + AsadminResult result = ASADMIN.exec("list-jobs"); + assertThat(result, asadminOK()); + assertThat(result.getOutput(), stringContainsInOrder("Nothing to list")); + } + + + @Test + @Order(2) + public void jobSurvivesRestart() throws Exception { + assertThat(ASADMIN.exec("--terse", "progress-simple"), asadminOK()); + assertThat(ASADMIN.exec("list-jobs").getStdOut(), stringContainsInOrder(COMMAND_PROGRESS_SIMPLE, "COMPLETED")); + assertThat(ASADMIN.exec("list-jobs", "1").getStdOut(), stringContainsInOrder(COMMAND_PROGRESS_SIMPLE, "COMPLETED")); + + assertThat(ASADMIN.exec("stop-domain"), asadminOK()); + assertThat(ASADMIN.exec("start-domain"), asadminOK()); + AsadminResult result = ASADMIN.exec("list-jobs", "1"); + assertThat(result, asadminOK()); + assertThat(result.getStdOut(), stringContainsInOrder(COMMAND_PROGRESS_SIMPLE, "COMPLETED")); + } + + + @Test + @Order(3) + public void detachAndAttach() throws Exception { + assertThat(ASADMIN.execDetached(COMMAND_PROGRESS_SIMPLE).getStdOut(), stringContainsInOrder("Job ID: ")); + assertThat(ASADMIN.exec("list-jobs", "1").getStdOut(), stringContainsInOrder(COMMAND_PROGRESS_SIMPLE)); + assertThat(ASADMIN.exec("attach", "1"), asadminOK()); + + // list-jobs and it should be purged since the user + // starting is the same as the user who attached to it + assertThat(ASADMIN.exec("list-jobs").getOutput(), stringContainsInOrder("Nothing to list")); + } + + + @Test + @Order(4) + public void runConfigureManagedJobsTest() throws Exception { + assertThat(ASADMIN.exec("configure-managed-jobs", "--job-retention-period=60s", "--cleanup-initial-delay=1s", "--cleanup-poll-interval=1s"), asadminOK()); + assertThat(ASADMIN.exec(COMMAND_PROGRESS_SIMPLE), asadminOK()); + assertThat(ASADMIN.exec("list-jobs", "1").getStdOut(), stringContainsInOrder(COMMAND_PROGRESS_SIMPLE)); + + // FIXME: Random race condition on Linux caused by some bug in restart-domain; 4848 port is then blocked for start-domain in setUp(); + assertThat(ASADMIN.exec("stop-domain"), asadminOK()); + assertThat(ASADMIN.exec("start-domain"), asadminOK()); + assertThat(ASADMIN.exec("list-jobs", "1").getStdOut(), stringContainsInOrder(COMMAND_PROGRESS_SIMPLE)); + + assertThat(ASADMIN.exec("configure-managed-jobs", "--job-retention-period=1s", "--cleanup-initial-delay=1s", "--cleanup-poll-interval=1s"), asadminOK()); + Thread.sleep(2100L); + assertThat(ASADMIN.exec("list-jobs").getOutput(), stringContainsInOrder("Nothing to list")); + assertThat(ASADMIN.exec("configure-managed-jobs", "--job-retention-period=1h", "--cleanup-initial-delay=5m", "--cleanup-poll-interval=20m"), asadminOK()); + } +} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressMessage.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressMessage.java similarity index 58% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressMessage.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressMessage.java index 88f391d3a09..9198ae3ef61 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressMessage.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressMessage.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -14,29 +15,37 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package org.glassfish.nucleus.admin.progress; +package org.glassfish.main.admin.test.progress; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.StringTokenizer; +import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Collectors; -/** Parse progress status message. +import org.hamcrest.CustomTypeSafeMatcher; + +/** + * Parse progress status message. * * @author martinmares */ public class ProgressMessage { - private static final Pattern RGXP = Pattern.compile(" *(\\d+)(%)?:(.+:)?(.*)"); + private static final Pattern PATTERN = Pattern.compile("[ ]*(\\d+)(%)?:(.+:)?(.*)"); + private static final Predicate PREDICATE = PATTERN.asMatchPredicate(); private final int value; private final boolean percentage; private final String scope; private final String message; - public ProgressMessage(String txt) throws IllegalArgumentException { - Matcher matcher = RGXP.matcher(txt); + private ProgressMessage(String txt) throws IllegalArgumentException { + Matcher matcher = PATTERN.matcher(txt); if (!matcher.matches()) { throw new IllegalArgumentException("Arg txt is not progress message"); } @@ -69,24 +78,21 @@ public String getMessage() { return message; } + @Override + public String toString() { + return Arrays.toString(new Object[] {value, percentage, scope, message}); + } + public static List grepProgressMessages(String txt) { - StringTokenizer stok = new StringTokenizer(txt, "\n\r"); - List result = new ArrayList(); - while (stok.hasMoreTokens()) { - String line = stok.nextToken(); - try { - result.add(new ProgressMessage(line)); - } catch (Exception ex) { - //System.out.println(ex); - } - } - return result; + StringTokenizer stok = new StringTokenizer(txt, System.lineSeparator()); + return Collections.list(stok).stream().map(Object::toString).filter(PREDICATE).map(ProgressMessage::new) + .collect(Collectors.toList()); } /** Unique only that not equal with previous. */ public static String[] uniqueMessages(List pms) { - List messages = new ArrayList(); + List messages = new ArrayList<>(); for (ProgressMessage pm : pms) { if (pm.getMessage() != null && (messages.isEmpty() || !pm.getMessage().equals(messages.get(messages.size() - 1)))) { @@ -97,19 +103,24 @@ public static String[] uniqueMessages(List pms) { return messages.toArray(result); } - public static boolean isNonDecreasing(List pms) { - if (pms == null) { - return false; - } - int lastVal = Integer.MIN_VALUE; - for (ProgressMessage pm : pms) { - if (pm.getValue() < lastVal) { - return false; - } else { - lastVal = pm.getValue(); + public static CustomTypeSafeMatcher> isIncreasing() { + return new CustomTypeSafeMatcher<>("is increasing") { + + @Override + protected boolean matchesSafely(List pms) { + if (pms == null) { + return false; + } + int lastVal = Integer.MIN_VALUE; + for (ProgressMessage pm : pms) { + if (pm.getValue() < lastVal) { + return false; + } + lastVal = pm.getValue(); + } + return true; } - } - return true; + }; } } diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusBasicITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusBasicITest.java new file mode 100644 index 00000000000..6ba8b05c6f6 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusBasicITest.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.progress; + +import java.util.List; + +import org.glassfish.main.admin.test.tool.asadmin.Asadmin; +import org.glassfish.main.admin.test.tool.asadmin.AsadminResult; +import org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment; +import org.junit.jupiter.api.Test; + +import static org.glassfish.main.admin.test.progress.ProgressMessage.isIncreasing; +import static org.glassfish.main.admin.test.tool.AsadminResultMatcher.asadminOK; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * @author martinmares + */ +public class ProgressStatusBasicITest { + + private static final Asadmin ASADMIN = GlassFishTestEnvironment.getAsadmin(); + + @Test + public void simple() { + AsadminResult result = ASADMIN.exec("progress-simple"); + assertThat(result, asadminOK()); + List prgs = ProgressMessage.grepProgressMessages(result.getStdOut()); + assertThat(prgs, isIncreasing()); + assertEquals(12, prgs.size()); + for (int i = 0; i < 11; i++) { + assertEquals(10 * i, prgs.get(i + 1).getValue()); + assertTrue(prgs.get(i + 1).isPercentage()); + } + } + + @Test + public void simpleNoTotal() { + AsadminResult result = ASADMIN.exec("progress-simple", "--nototalsteps"); + assertThat(result, asadminOK()); + List prgs = ProgressMessage.grepProgressMessages(result.getStdOut()); + assertThat(prgs, isIncreasing()); + boolean nonPercentageExists = false; + for (ProgressMessage prg : prgs) { + if (prg.getValue() != 0 && prg.getValue() != 100) { + assertFalse(prg.isPercentage()); + nonPercentageExists = true; + } + } + assertTrue(nonPercentageExists); + } + + @Test + public void simpleSpecInAnnotation() { + AsadminResult result = ASADMIN.exec("progress-full-annotated"); + assertThat(result, asadminOK()); + List prgs = ProgressMessage.grepProgressMessages(result.getStdOut()); + assertThat(prgs, hasSize(12)); + assertThat(prgs, isIncreasing()); + for (int i = 0; i < 11; i++) { + assertEquals(10 * i, prgs.get(i + 1).getValue()); + assertTrue(prgs.get(i + 1).isPercentage()); + } + assertEquals("annotated:", prgs.get(5).getScope()); + } + + @Test + public void simpleTerse() { + AsadminResult result = ASADMIN.exec("--terse", "progress-simple"); + assertThat(result, asadminOK()); + List prgs = ProgressMessage.grepProgressMessages(result.getStdOut()); + assertThat(prgs, hasSize(0)); + } +} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusComplexTest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusComplexITest.java similarity index 54% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusComplexTest.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusComplexITest.java index e926ac1fb4c..3b7ae11eed2 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusComplexTest.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusComplexITest.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -14,73 +15,74 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package org.glassfish.nucleus.admin.progress; - -import static org.glassfish.nucleus.admin.progress.ProgressMessage.grepProgressMessages; -import static org.glassfish.nucleus.admin.progress.ProgressMessage.isNonDecreasing; -import static org.glassfish.nucleus.admin.progress.ProgressMessage.uniqueMessages; -import static org.glassfish.tests.utils.NucleusTestUtils.nadminWithOutput; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertTrue; -import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals; +package org.glassfish.main.admin.test.progress; import java.util.List; -import org.glassfish.tests.utils.NucleusTestUtils; -import org.glassfish.tests.utils.NucleusTestUtils.NadminReturn; -import org.testng.annotations.Test; +import org.glassfish.main.admin.test.tool.asadmin.Asadmin; +import org.glassfish.main.admin.test.tool.asadmin.AsadminResult; +import org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment; +import org.junit.jupiter.api.Test; + +import static org.glassfish.main.admin.test.progress.ProgressMessage.grepProgressMessages; +import static org.glassfish.main.admin.test.progress.ProgressMessage.isIncreasing; +import static org.glassfish.main.admin.test.progress.ProgressMessage.uniqueMessages; +import static org.glassfish.main.admin.test.tool.AsadminResultMatcher.asadminOK; +import static org.hamcrest.CoreMatchers.anyOf; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** - * * @author martinmares */ -@Test(testName = "ProgressStatusComplexTest") -public class ProgressStatusComplexTest { +public class ProgressStatusComplexITest { - public void executeCommandFromCommand() { - NadminReturn result = nadminWithOutput("progress-exec-other"); - - assertTrue(result.returnValue); + private static final Asadmin ASADMIN = GlassFishTestEnvironment.getAsadmin(); + @Test + public void executeCommandFromCommand() { + AsadminResult result = ASADMIN.exec(30_000, false, "progress-exec-other"); + assertThat(result, asadminOK()); assertArrayEquals(new String[] { "Starting", "Preparing", "Parsing", "Working on main part", "Cleaning", "Finished", "Finishing outer command", "Finished outer command" }, - - uniqueMessages(grepProgressMessages(result.out))); + uniqueMessages(grepProgressMessages(result.getStdOut()))); } - @Test(enabled = false) + @Test public void executeCommandWithSupplements() { - NadminReturn result = nadminWithOutput("progress-supplement"); - assertTrue(result.returnValue); - - List prgs = grepProgressMessages(result.out); + AsadminResult result = ASADMIN.exec("progress-supplement"); + assertThat(result, asadminOK()); + List prgs = grepProgressMessages(result.getStdOut()); assertArrayEquals(new String[] { "Starting", "2 seconds supplemental command", "Parsing", "Working on main part", "Finished", "3 seconds supplemental" }, - uniqueMessages(prgs)); - assertTrue(prgs.size() > 10); + assertThat(prgs, hasSize(21)); + assertThat(prgs, isIncreasing()); assertFalse(prgs.get(4).isPercentage()); assertTrue(prgs.get(10).isPercentage()); - assertTrue(isNonDecreasing(prgs)); } - // Test disabled till intermittent failures are fixed - @Test(enabled = false) + @Test public void executeVeryComplexCommand() { - NucleusTestUtils.NadminReturn result = nadminWithOutput("progress-complex"); + AsadminResult result = ASADMIN.exec("progress-complex"); + assertThat(result, asadminOK()); - assertTrue(result.returnValue); - - List prgs = ProgressMessage.grepProgressMessages(result.out); - assertTrue(prgs.size() > 40); - assertTrue(scopeCount(prgs, "complex:") >= 4); + List prgs = ProgressMessage.grepProgressMessages(result.getStdOut()); + assertThat(prgs, hasSize(greaterThanOrEqualTo(100))); + assertThat(prgs, isIncreasing()); + assertEquals(5, scopeCount(prgs, "complex:")); assertEquals(0, scopeCount(prgs, "complex.ch1:")); - assertEquals(5, scopeCount(prgs, "complex.ch2-paral:")); + assertThat(scopeCount(prgs, "complex.ch2-paral:"), anyOf(equalTo(5), equalTo(6))); assertEquals(4, scopeCount(prgs, "complex.ch3:")); assertEquals(5, scopeCount(prgs, "complex.ch1.ch11:")); assertEquals(6, scopeCount(prgs, "complex.ch1.ch12:")); @@ -90,7 +92,6 @@ public void executeVeryComplexCommand() { assertEquals(25, scopeCount(prgs, "complex.ch2-paral.ch24:")); assertEquals(5, scopeCount(prgs, "complex.ch3.ch31:")); assertEquals(5, scopeCount(prgs, "complex.ch3.ch32:")); - assertTrue(ProgressMessage.isNonDecreasing(prgs)); } private int scopeCount(List prgs, String scope) { @@ -102,5 +103,4 @@ private int scopeCount(List prgs, String scope) { } return result; } - } diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusFailTest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusFailITest.java similarity index 51% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusFailTest.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusFailITest.java index 7f04b899506..0ed4266d692 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusFailTest.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusFailITest.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -14,32 +15,42 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package org.glassfish.nucleus.admin.progress; +package org.glassfish.main.admin.test.progress; import java.util.List; -import org.testng.annotations.Test; -import static org.glassfish.tests.utils.NucleusTestUtils.*; -import static org.testng.AssertJUnit.*; + +import org.glassfish.main.admin.test.tool.asadmin.Asadmin; +import org.glassfish.main.admin.test.tool.asadmin.AsadminResult; +import org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment; +import org.junit.jupiter.api.Test; + +import static org.glassfish.main.admin.test.tool.AsadminResultMatcher.asadminOK; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** - * * @author martinmares */ -@Test(testName="ProgressStatusFailTest") -public class ProgressStatusFailTest { +public class ProgressStatusFailITest { + + private static final Asadmin ASADMIN = GlassFishTestEnvironment.getAsadmin(); + @Test public void failDuringExecution() { - NadminReturn result = nadminWithOutput("progress-fail-in-half"); - assertFalse(result.returnValue); - List prgs = ProgressMessage.grepProgressMessages(result.out); + AsadminResult result = ASADMIN.exec("progress-fail-in-half"); + assertThat(result, not(asadminOK())); + List prgs = ProgressMessage.grepProgressMessages(result.getStdOut()); assertFalse(prgs.isEmpty()); assertEquals(50, prgs.get(prgs.size() - 1).getValue()); } + @Test public void timeout() { - NadminReturn result = nadminWithOutput(6 * 1000, "progress-custom", "3x1", "1x8", "2x1"); - assertFalse(result.returnValue); - List prgs = ProgressMessage.grepProgressMessages(result.out); + AsadminResult result = ASADMIN.exec(6_000, false, "progress-custom", "3x1", "1x8", "2x1"); + assertThat(result, not(asadminOK())); + List prgs = ProgressMessage.grepProgressMessages(result.getStdOut()); assertFalse(prgs.isEmpty()); assertEquals(50, prgs.get(prgs.size() - 1).getValue()); } diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusSpecialITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusSpecialITest.java new file mode 100644 index 00000000000..e5a8bef66b0 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/progress/ProgressStatusSpecialITest.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.progress; + +import java.util.Iterator; +import java.util.List; + +import org.glassfish.main.admin.test.tool.asadmin.Asadmin; +import org.glassfish.main.admin.test.tool.asadmin.AsadminResult; +import org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment; +import org.junit.jupiter.api.Test; + +import static org.glassfish.main.admin.test.progress.ProgressMessage.isIncreasing; +import static org.glassfish.main.admin.test.tool.AsadminResultMatcher.asadminOK; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * @author martinmares + */ +public class ProgressStatusSpecialITest { + + private static final Asadmin ASADMIN = GlassFishTestEnvironment.getAsadmin(); + + @Test + public void stepBackCommand() { + AsadminResult result = ASADMIN.exec("progress-step-back"); + assertThat(result, asadminOK()); + List prgs = ProgressMessage.grepProgressMessages(result.getStdOut()); + assertThat(prgs, not(isIncreasing())); + Iterator itr = prgs.iterator(); + while (itr.hasNext()) { + ProgressMessage prg = itr.next(); + if (prg.getValue() >= 80) { + break; + } + } + assertTrue(itr.hasNext(), "Exist more records"); + while (itr.hasNext()) { + ProgressMessage prg = itr.next(); + assertThat(prg.getValue(), lessThanOrEqualTo(80)); + if (prg.getValue() < 80) { + break; + } + } + assertTrue(itr.hasNext(), "Exist more records"); + ProgressMessage prg = itr.next(); + assertThat(prg.getValue(), lessThan(80)); + } + + @Test + public void doubleTotalCommand() { + AsadminResult result = ASADMIN.exec("progress-double-totals"); + assertThat(result, asadminOK()); + List prgs = ProgressMessage.grepProgressMessages(result.getStdOut()); + assertThat(prgs, not(isIncreasing())); + } + +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ApplicationITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ApplicationITest.java new file mode 100644 index 00000000000..d2f39340b98 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ApplicationITest.java @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; + +import java.net.URISyntaxException; +import java.util.Map; + +import org.glassfish.main.admin.test.tool.DomainAdminRestClient; +import org.glassfish.main.admin.test.webapp.HelloServlet; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.stringContainsInOrder; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author jasonlee + */ +public class ApplicationITest extends RestTestBase { + + + private DomainAdminRestClient client; + private String appName; + + @BeforeEach + public void initInstanceClient() { + appName = "testApp" + generateRandomString(); + client = new DomainAdminRestClient(getBaseInstanceUrl() + "/" + appName); + } + + @AfterEach + public void closeInstanceClient() { + if (client != null) { + client.close(); + } + } + + @Test + public void testApplicationDeployment() throws URISyntaxException { + try { + Map deployedApp = deployApp(getWar("test"), appName, appName); + assertEquals(appName, deployedApp.get("name")); + assertEquals("/" + appName, deployedApp.get("contextRoot")); + } finally { + undeployApp(appName); + } + } + + + @Test + public void testApplicationDisableEnable() throws URISyntaxException { + Map deployedApp = deployApp(getWar("test"), appName, appName); + assertEquals(appName, deployedApp.get("name")); + assertEquals("/" + appName, deployedApp.get("contextRoot")); + try { + Response response = client.get(""); + assertEquals("Hello!", response.readEntity(String.class)); + + response = managementClient.post(URL_APPLICATION_DEPLOY + "/" + appName + "/disable"); + assertThat(response.getStatus(), equalTo(200)); + + response = client.get(""); + assertEquals(404, response.getStatus()); + + response = managementClient.post(URL_APPLICATION_DEPLOY + "/" + appName + "/enable"); + assertThat(response.getStatus(), equalTo(200)); + + response = client.get(""); + assertEquals("Hello!", response.readEntity(String.class).trim()); + } finally { + undeployApp(appName); + } + } + + @Test + public void listSubComponents() throws URISyntaxException { + try { + deployApp(getEar("simple"), appName, appName); + Response response = managementClient + .get(URL_APPLICATION_DEPLOY + "/" + appName + "/list-sub-components?id=" + appName); + assertThat(response.getStatus(), equalTo(200)); + String subComponents = response.readEntity(String.class); + assertThat(subComponents, stringContainsInOrder("simple")); + + response = managementClient + .get(URL_APPLICATION_DEPLOY + "/" + appName + "/list-sub-components?id=simple.war&appname=" + appName); + assertThat(response.getStatus(), equalTo(200)); + subComponents = response.readEntity(String.class); + assertThat(subComponents, stringContainsInOrder(HelloServlet.class.getName())); + } finally { + undeployApp(appName); + } + } + + @Test + public void testCreatingAndDeletingApplicationRefs() throws URISyntaxException { + final String instanceName = "instance_" + generateRandomString(); + final String appRefUrl = "/domain/servers/server/" + instanceName + "/application-ref"; + + Map newInstance = Map.of("id", instanceName, "node", "localhost-domain1"); + Map applicationRef = Map.of("id", appName, "target", instanceName); + try { + Response response = managementClient.post(URL_CREATE_INSTANCE, newInstance); + assertThat(response.getStatus(), equalTo(200)); + + deployApp(getWar("test"), appName, appName); + + response = managementClient.post(appRefUrl, applicationRef); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.get(appRefUrl + "/" + appName); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.delete(appRefUrl + "/" + appName, Map.of("target", instanceName)); + assertThat(response.getStatus(), equalTo(200)); + } finally { + Response response = managementClient.delete("/domain/servers/server/" + instanceName + "/delete-instance"); + assertThat(response.getStatus(), equalTo(200)); + response = managementClient.get("/domain/servers/server/" + instanceName); + assertEquals(404, response.getStatus()); + undeployApp(appName); + } + } + + @Test + public void testGetContextRoot() throws URISyntaxException { + try { + Map deployedApp = deployApp(getEar("simple"), appName, appName); + assertEquals(appName, deployedApp.get("name")); + Map contextRootPayload = Map.of("appname", appName, "modulename", "simple"); + Response response = managementClient + .get("/domain/applications/application/" + appName + "/get-context-root", contextRootPayload); + assertThat(response.getStatus(), equalTo(200)); + assertThat(response.readEntity(String.class), + stringContainsInOrder("command", "_get-context-root AdminCommand", "exit_code", "SUCCESS", "--appname", + appName, "--modulename", "simple", "method", "GET")); + } finally { + undeployApp(appName); + } + } + + + @Test + public void testUndeploySubActionWarnings() throws URISyntaxException { + final String serverName = "in" + generateRandomNumber(); + try { + Response response = managementClient.post("/domain/create-instance", + Map.of("id", serverName, "node", "localhost-domain1")); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.post("/domain/servers/server/" + serverName + "/start-instance"); + assertThat(response.getStatus(), equalTo(200)); + + deployApp(getWar("test"), appName, appName); + addAppRef(appName, serverName); + + response = managementClient.post("/domain/servers/server/" + serverName + "/stop-instance"); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.delete("/domain/applications/application/" + appName, + Map.of("target", "domain")); + assertThat(response.readEntity(String.class), + stringContainsInOrder("deleted successfully", "exit_code", "SUCCESS")); + } finally { + managementClient.delete("/domain/applications/application/" + appName, Map.of("target", "domain")); + } + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/AuthRealmITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/AuthRealmITest.java new file mode 100644 index 00000000000..c1d72256b68 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/AuthRealmITest.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; +import com.sun.enterprise.security.auth.realm.file.FileRealm; +import com.sun.enterprise.security.auth.realm.jdbc.JDBCRealm; +import com.sun.enterprise.security.auth.realm.ldap.LDAPRealm; +import com.sun.enterprise.security.auth.realm.pam.PamRealm; +import com.sun.enterprise.security.auth.realm.solaris.SolarisRealm; + +import jakarta.ws.rs.core.Response; + +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import org.glassfish.admin.rest.client.utils.MarshallingUtils; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class AuthRealmITest extends RestTestBase { + private static final String URL_LIST_GROUP_NAMES = "/domain/configs/config/server-config/security-service/auth-realm/admin-realm/list-group-names"; + private static final String URL_SUPPORTS_USER_MANAGEMENT = "/domain/configs/config/server-config/security-service/auth-realm/admin-realm/supports-user-management"; + private static final String URL_LIST_ADMIN_REALM_USERS = "/domain/configs/config/server-config/security-service/auth-realm/admin-realm/list-users"; + private static final String URL_LIST_FILE_USERS = "/domain/configs/config/server-config/security-service/auth-realm/file/list-users"; + private static final String URL_CREATE_USER = "/domain/configs/config/server-config/security-service/auth-realm/file/create-user"; + private static final String URL_DELETE_USER = "/domain/configs/config/server-config/security-service/auth-realm/file/delete-user"; + private static final String URL_AUTH_REALM_CLASS_NAMES = "/domain/list-predefined-authrealm-classnames"; + + @Test + public void testListGroupNames() { + Response response = managementClient.get(URL_LIST_GROUP_NAMES, Map.of("userName", "admin", "realmName", "admin-realm")); + assertEquals(200, response.getStatus()); + final String entity = response.readEntity(String.class); + Map responseMap = MarshallingUtils.buildMapFromDocument(entity); + Map extraProperties = (Map) responseMap.get("extraProperties"); + List groups = (List) extraProperties.get("groups"); + assertThat(groups, containsInAnyOrder("asadmin")); + } + + @Test + public void testListAdminUsers() { + Response response = managementClient.get(URL_LIST_ADMIN_REALM_USERS); + assertEquals(200, response.getStatus()); + final String entity = response.readEntity(String.class); + Map responseMap = MarshallingUtils.buildMapFromDocument(entity); + assertThat(responseMap.toString(), responseMap, aMapWithSize(5)); + Map extraProperties = (Map) responseMap.get("extraProperties"); + assertThat(extraProperties.toString(), extraProperties, aMapWithSize(3)); + List>> users = (List>>) extraProperties.get("users"); + assertThat(users, hasSize(1)); + Map userAdmin = users.get(0); + assertThat(userAdmin, aMapWithSize(2)); + assertThat((String) userAdmin.get("name"), equalTo("admin")); + assertThat((List) userAdmin.get("groups"), contains("asadmin")); + } + + @Test + public void testSupportsUserManagement() { + List groups = getCommandResults(managementClient.get(URL_SUPPORTS_USER_MANAGEMENT)); + assertEquals("true", groups.get(0)); + } + + + @Test + public void testUserManagement() { + final String userName = "user" + generateRandomString(); + { + Response response = managementClient.post(URL_CREATE_USER, Map.of("id", userName, "AS_ADMIN_USERPASSWORD", "password")); + assertEquals(200, response.getStatus()); + } + { + List values = getCommandResults(managementClient.get(URL_LIST_FILE_USERS)); + assertThat(values, hasItem(userName)); + } + { + Response response = managementClient.delete(URL_DELETE_USER, Map.of("id", userName)); + assertEquals(200, response.getStatus()); + } + { + List values = getCommandResults(managementClient.get(URL_LIST_FILE_USERS)); + assertThat(values, not(hasItem(userName))); + } + } + + + @Test + public void testListAuthRealmClassNames() { + List classNameList = getCommandResults(managementClient.get(URL_AUTH_REALM_CLASS_NAMES)); + assertThat(classNameList.toString(), classNameList, hasSize(6)); + String[] realms = Stream.of(JDBCRealm.class, PamRealm.class, CertificateRealm.class, FileRealm.class, + LDAPRealm.class, SolarisRealm.class).map(Class::getName).toArray(String[]::new); + assertThat(classNameList, containsInAnyOrder(realms)); + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ClusterITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ClusterITest.java new file mode 100644 index 00000000000..174bf79f193 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ClusterITest.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; + +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author jasonlee + */ +public class ClusterITest extends RestTestBase { + + @Test + public void testClusterCreationAndDeletion() { + final String clusterName = "cluster_" + generateRandomString(); + createCluster(clusterName); + + Map entity = getEntityValues(managementClient.get(URL_CLUSTER + "/" + clusterName)); + assertEquals(clusterName + "-config", entity.get("configRef")); + + deleteCluster(clusterName); + } + + @Test + public void testListLifecycleModules() { + final String clusterName = "cluster_" + generateRandomString(); + Response response = managementClient.post(URL_CLUSTER, Map.of("id", clusterName)); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.get(URL_CLUSTER + "/" + clusterName + "/list-lifecycle-modules"); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.delete(URL_CLUSTER + "/" + clusterName); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.get(URL_CLUSTER + "/" + clusterName); + assertEquals(404, response.getStatus()); + } +} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ConfigTest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ConfigITest.java similarity index 50% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ConfigTest.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ConfigITest.java index ccd5edbfe91..d156b822775 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ConfigTest.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ConfigITest.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -14,26 +15,25 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package org.glassfish.nucleus.admin.rest; +package org.glassfish.main.admin.test.rest; import jakarta.ws.rs.core.MultivaluedHashMap; -import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; /** - * * @author jasonlee */ -public class ConfigTest extends RestTestBase { - - public static final String BASE_CONFIGS_URL = "/domain/configs"; +public class ConfigITest extends RestTestBase { @Test public void testConfigCopy() { String configName = "config-" + generateRandomString(); - MultivaluedMap formData = new MultivaluedHashMap(); + MultivaluedHashMap formData = new MultivaluedHashMap<>(); formData.add("id", "default-config"); formData.add("id", configName); createAndVerifyConfig(configName, formData); @@ -41,28 +41,12 @@ public void testConfigCopy() { } @Test - public void duplicateCopyShouldFail() { - MultivaluedMap formData = new MultivaluedHashMap(); + public void duplicitCopyShouldFail() { + MultivaluedHashMap formData = new MultivaluedHashMap<>(); formData.add("id", "default-config"); formData.add("id", "server-config"); - - Response response = post(BASE_CONFIGS_URL + "/copy-config", formData); - assertFalse(isSuccess(response)); - } - - public void createAndVerifyConfig(String configName, MultivaluedMap configData) { - Response response = post(BASE_CONFIGS_URL + "/copy-config", configData); - checkStatusForSuccess(response); - - response = get(BASE_CONFIGS_URL + "/config/" + configName); - checkStatusForSuccess(response); - } - - public void deleteAndVerifyConfig(String configName) { - Response response = post(BASE_CONFIGS_URL + "/config/" + configName + "/delete-config"); - checkStatusForSuccess(response); - - response = get(BASE_CONFIGS_URL + "/config/" + configName); - assertFalse(isSuccess(response)); + Response response = managementClient.post(URL_CONFIGS + "/copy-config", formData); + // FIXME: causes HTTP 500 without any log, should be 422. + assertThat(response.getStatus(), equalTo(500)); } } diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/DomainTest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/DomainITest.java similarity index 55% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/DomainTest.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/DomainITest.java index 7e2ebbb703d..6368fe25c06 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/DomainTest.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/DomainITest.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -14,45 +15,45 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package org.glassfish.nucleus.admin.rest; +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; -import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; -import jakarta.ws.rs.core.Response; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; -public class DomainTest extends RestTestBase { +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class DomainITest extends RestTestBase { + + private static final String URL_DOMAIN = "/domain"; + @Test - public void testDomainGet() throws IOException { - Map payload = new HashMap(); - Map current = getEntityValues(get("/domain")); + public void testDomainGet() throws Exception { + Response response0 = managementClient.get(URL_DOMAIN); + assertThat(response0.getStatus(), equalTo(200)); + Map current = getEntityValues(response0); // Select a random locale so we're not setting the locale to its current value - List locales = new ArrayList() {{ - add("en_US"); - add("en"); - add("de_DE"); - add("_GB"); - add("en_US_WIN"); - add("de__POSIX"); - add("fr__MAC"); - }}; + List locales = new ArrayList<>(List.of("en_US", "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC")); locales.remove(current.get("locale")); final int random = new Random().nextInt(locales.size()); String newLocale = locales.get(random); + Map payload = new HashMap<>(); payload.put("locale", newLocale); - - Response response = post("/domain", payload); - assertTrue(isSuccess(response)); + Response response = managementClient.post(URL_DOMAIN, payload); + assertEquals(200, response.getStatus()); // Reload the domain and make sure our new locale was saved - Map map = getEntityValues(this.get("/domain")); + Map map = getEntityValues(managementClient.get(URL_DOMAIN)); assertEquals(newLocale, map.get("locale")); } } diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ElementStarITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ElementStarITest.java new file mode 100644 index 00000000000..4d4d565f6fa --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ElementStarITest.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; + +import java.net.URISyntaxException; +import java.util.Map; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.aMapWithSize; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * This class tests the changes to the handling of @Element("*") instances + * + * @author jasonlee + */ +public class ElementStarITest extends RestTestBase { + private static final String URL_CREATE_INSTANCE = "/domain/create-instance"; + + private String instanceName1; + private String instanceName2; + + @BeforeEach + public void before() { + instanceName1 = "instance_" + generateRandomString(); + instanceName2 = "instance_" + generateRandomString(); + + Response response = managementClient.post(URL_CREATE_INSTANCE, + Map.of("id", instanceName1, "node", "localhost-domain1")); + assertThat(response.getStatus(), equalTo(200)); + response = managementClient.post(URL_CREATE_INSTANCE, Map.of("id", instanceName2, "node", "localhost-domain1")); + assertEquals(200, response.getStatus()); + } + + + @AfterEach + public void after() { + Response response = managementClient.delete("/domain/servers/server/" + instanceName1 + "/delete-instance"); + assertEquals(200, response.getStatus()); + response = managementClient.delete("/domain/servers/server/" + instanceName2 + "/delete-instance"); + assertEquals(200, response.getStatus()); + } + + + @Test + public void testApplications() throws URISyntaxException { + final String app1 = "app" + generateRandomString(); + final String app2 = "app" + generateRandomString(); + + deployApp(getWar("test"), app1, app1); + deployApp(getWar("test"), app2, app2); + addAppRef(app1, instanceName1); + addAppRef(app2, instanceName1); + + Response response = managementClient.get("/domain/servers/server/" + instanceName1 + "/application-ref"); + Map children = this.getChildResources(response); + assertThat(children, aMapWithSize(2)); + } + + + @Test + public void testResources() { + // The DAS should already have two resource-refs (jdbc/__TimerPool and jdbc/__default) + Response response = managementClient.get("/domain/servers/server/server/resource-ref"); + Map children = this.getChildResources(response); + assertThat(children, aMapWithSize(7)); + } + + + @Test + public void testLoadBalancerConfigs() { + final String lbName = "lbconfig-" + generateRandomString(); + Response response = managementClient.post("/domain/lb-configs/lb-config/", + Map.of("id", lbName, "target", instanceName1)); + assertEquals(200, response.getStatus()); + + response = managementClient.post("/domain/lb-configs/lb-config/" + lbName + "/create-http-lb-ref", + Map.of("id", instanceName2)); + assertEquals(200, response.getStatus()); + + response = managementClient.get("/domain/lb-configs/lb-config/" + lbName + "/server-ref"); + Map children = getChildResources(response); + assertThat(children, aMapWithSize(1)); + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ExternalResourceITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ExternalResourceITest.java new file mode 100644 index 00000000000..12fc140c7cf --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ExternalResourceITest.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; + +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +/** + * @author jasonlee + */ +public class ExternalResourceITest extends RestTestBase { + + private static final String URL_EXTERNAL_RESOURCE = "/domain/resources/external-jndi-resource"; + + @Test + public void createAndDeleteExternalResource() { + final String resourceName = "resource_" + generateRandomString(); + final String jndiName = "jndi/" + resourceName; + Map newResource = Map.of( + "id", resourceName, + "jndilookupname", jndiName, + "factoryClass", "org.glassfish.resources.custom.factory.PrimitivesAndStringFactory", + "restype", Double.class.getName() + ); + Response response = managementClient.post(URL_EXTERNAL_RESOURCE, newResource); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.get(URL_EXTERNAL_RESOURCE + "/" + resourceName); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.delete(URL_EXTERNAL_RESOURCE + "/" + resourceName); + assertThat(response.getStatus(), equalTo(200)); + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JdbcITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JdbcITest.java new file mode 100644 index 00000000000..9643dbaa125 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JdbcITest.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.aMapWithSize; +import static org.hamcrest.Matchers.greaterThan; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * @author jasonlee + */ +public class JdbcITest extends RestTestBase { + + @Test + public void testReadingPoolEntity() { + Map entity = getEntityValues(managementClient.get(URL_JDBC_CONNECTION_POOL + "/__TimerPool")); + assertEquals("__TimerPool", entity.get("name")); + } + + + @Test + public void testCreateAndDeletePool() { + String poolName = "TestPool" + generateRandomString(); + Map params = new HashMap<>(); + params.put("name", poolName); + params.put("datasourceClassname", "org.apache.derby.jdbc.ClientDataSource"); + Response response = managementClient.post(URL_JDBC_CONNECTION_POOL, params); + assertEquals(200, response.getStatus()); + + Map entity = getEntityValues(managementClient.get(URL_JDBC_CONNECTION_POOL + "/" + poolName)); + assertThat(entity, aMapWithSize(greaterThan(40))); + + response = managementClient.delete(URL_JDBC_CONNECTION_POOL + "/" + poolName, Map.of()); + assertEquals(200, response.getStatus()); + + response = managementClient.get(URL_JDBC_CONNECTION_POOL + "/" + poolName); + assertEquals(404, response.getStatus()); + } + + + @Test + public void testBackslashValidation() { + String poolName = "TestPool\\" + generateRandomString(); + String encodedPoolName = URLEncoder.encode(poolName, StandardCharsets.UTF_8); + Map params = new HashMap<>(); + params.put("name", poolName); + params.put("poolName", "DerbyPool"); + + Response response = managementClient.post(URL_JDBC_RESOURCE, params); + assertEquals(500, response.getStatus()); + + Response responseGet = managementClient.get(URL_JDBC_CONNECTION_POOL + "/" + encodedPoolName); + assertEquals(500, response.getStatus()); + Map entity = getEntityValues(responseGet); + assertNull(entity); + + response = managementClient.delete("/" + encodedPoolName, Map.of()); + assertEquals(500, response.getStatus()); + + response = managementClient.get(URL_JDBC_CONNECTION_POOL + "/" + encodedPoolName); + assertEquals(500, response.getStatus()); + } + + + @Test + public void createDuplicateResource() { + final String resourceName = "jdbc/__default"; + Map params = Map.of("id", resourceName, "poolName", "DerbyPool"); + Response response = managementClient.post(URL_JDBC_RESOURCE, params); + assertEquals(500, response.getStatus()); + } + + + @Test + public void createDuplicateConnectionPool() { + final String poolName = "DerbyPool"; + Map params = Map.of("id", poolName, "datasourceClassname", + "org.apache.derby.jdbc.ClientDataSource"); + Response response = managementClient.post(URL_JDBC_CONNECTION_POOL, params); + assertEquals(500, response.getStatus()); + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JmsITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JmsITest.java new file mode 100644 index 00000000000..84dae21c699 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JmsITest.java @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.aMapWithSize; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.stringContainsInOrder; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author jasonlee + * @since May 26, 2010 + */ +public class JmsITest extends RestTestBase { + static final String URL_ADMIN_OBJECT_RESOURCE = "/domain/resources/admin-object-resource"; + static final String URL_CONNECTOR_CONNECTION_POOL = "/domain/resources/connector-connection-pool"; + static final String URL_CONNECTOR_RESOURCE = "/domain/resources/connector-resource"; + static final String URL_JMS_HOST = "/domain/configs/config/server-config/jms-service/jms-host"; + static final String URL_SEVER_JMS_DEST = "/domain/servers/server/server"; + static final String DEST_TYPE = "topic"; + + @Test + public void testJmsConnectionFactories() { + // Create connection pool + final String poolName = "JmsConnectionFactory" + generateRandomString(); + Map ccp_attrs = Map.of("name", poolName, "connectiondefinition", + "jakarta.jms.ConnectionFactory", "raname", "jmsra"); + Response response = managementClient.post(URL_CONNECTOR_CONNECTION_POOL, ccp_attrs); + assertThat(response.getStatus(), equalTo(200)); + + // Check connection pool creation + Map pool = getEntityValues(managementClient.get(URL_CONNECTOR_CONNECTION_POOL + "/" + poolName)); + assertThat(pool, aMapWithSize(greaterThanOrEqualTo(26))); + + // Create connector resource + String resourceName = poolName + "Resource"; + Map cr_attrs = Map.of("name", resourceName, "poolname", poolName); + response = managementClient.post(URL_CONNECTOR_RESOURCE, cr_attrs); + assertThat(response.getStatus(), equalTo(200)); + + // Check connector resource + Map resource = getEntityValues(managementClient.get(URL_CONNECTOR_RESOURCE + "/" + resourceName)); + assertThat(resource, aMapWithSize(6)); + + // Edit and check ccp + response = managementClient.post(URL_CONNECTOR_CONNECTION_POOL + "/" + poolName, Map.of("description", poolName)); + assertThat(response.getStatus(), equalTo(200)); + + pool = getEntityValues(managementClient.get(URL_CONNECTOR_CONNECTION_POOL + "/" + poolName)); + assertThat(pool.get("description"), equalTo(poolName)); + + // Edit and check cr + response = managementClient.post(URL_CONNECTOR_RESOURCE + "/" + resourceName, Map.of("description", poolName)); + assertThat(response.getStatus(), equalTo(200)); + + resource = getEntityValues(managementClient.get(URL_CONNECTOR_RESOURCE + "/" + resourceName)); + assertThat(pool.get("description"), equalTo(poolName)); + + // Delete objects + response = managementClient.delete(URL_CONNECTOR_CONNECTION_POOL + "/" + poolName, Map.of("cascade", "true")); + assertThat(response.getStatus(), equalTo(200)); + } + + @Test + public void testJmsDestinationResources() { + final String jndiName = "jndi/" + generateRandomString(); + String encodedJndiName = URLEncoder.encode(jndiName, StandardCharsets.UTF_8); + + Map attrs = Map.of("id", jndiName, "raname", "jmsra", "restype", "jakarta.jms.Topic"); + + Response response = managementClient.post(URL_ADMIN_OBJECT_RESOURCE, attrs); + assertThat(response.getStatus(), equalTo(200)); + + Map entity = getEntityValues( + managementClient.get(URL_ADMIN_OBJECT_RESOURCE + "/" + encodedJndiName)); + assertThat(entity, aMapWithSize(8)); + + response = managementClient.delete(URL_ADMIN_OBJECT_RESOURCE + "/" + encodedJndiName); + assertThat(response.getStatus(), equalTo(200)); + } + + @Test + public void testJmsPhysicalDestination() { + final String destName = "jmsDest" + generateRandomString(); + final int maxNumMsgs = generateRandomNumber(500); + final int consumerFlowLimit = generateRandomNumber(500); + + createJmsPhysicalDestination(destName, DEST_TYPE, URL_SEVER_JMS_DEST); + + final Map newDest = Map.of("id", destName, "desttype", DEST_TYPE); + Map destProps = new HashMap<>(newDest); + destProps.putAll(Map.of("property", "MaxNumMsgs=" + maxNumMsgs + ":ConsumerFlowLimit=" + consumerFlowLimit)); + + Response response = managementClient.get(URL_SEVER_JMS_DEST + "/__get-jmsdest", newDest); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.post(URL_SEVER_JMS_DEST + "/__update-jmsdest", destProps); + assertThat(response.getStatus(), equalTo(200)); + response = managementClient.get(URL_SEVER_JMS_DEST + "/__get-jmsdest", newDest); + assertThat(response.getStatus(), equalTo(200)); + Map entity = getEntityValues(response); + assertEquals(maxNumMsgs, entity.get("MaxNumMsgs")); + assertEquals(consumerFlowLimit, entity.get("ConsumerFlowLimit")); + + deleteJmsPhysicalDestination(destName, URL_SEVER_JMS_DEST); + } + + @Test + @Disabled("Enable and fix OpenMQ - require more detailed message and probably to fix the cause:" + + " MQJMSRA_RA4001: getJMXServiceURLList:Exception:Message=Caught exception when contacing portmapper.]]") + public void testJmsPhysicalDestionationsWithClusters() { + final String destName = "jmsDest" + generateRandomString(); + final String clusterName = createCluster(); + createClusterInstance(clusterName, "in1_" + clusterName); + startCluster(clusterName); + final String endpoint = "/domain/clusters/cluster/" + clusterName; + try { + createJmsPhysicalDestination(destName, "topic", endpoint); + final Map newDest = Map.of("id", destName, "desttype", DEST_TYPE); + Response response = managementClient.get(endpoint + "/__get-jmsdest", newDest); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.get(URL_SEVER_JMS_DEST + "/__get-jmsdest", newDest); + assertThat(response.getStatus(), equalTo(200)); + } finally { + deleteJmsPhysicalDestination(destName, endpoint); + stopCluster(clusterName); + deleteCluster(clusterName); + } + } + + @Test + public void testJmsPing() { + String results = managementClient.get(URL_SEVER_JMS_DEST + "/jms-ping").readEntity(String.class); + assertThat(results, stringContainsInOrder("JMS-ping command executed successfully")); + } + + @Test + public void testJmsFlush() { + Map payload = Map.of("id", "mq.sys.dmq", "destType", "queue"); + Response response = managementClient.post(URL_SEVER_JMS_DEST + "/flush-jmsdest", payload); + assertThat(response.getStatus(), equalTo(200)); + } + + @Test + public void testJmsHosts() { + final String jmsHostName = "jmshost" + generateRandomString(); + Map newHost = Map.of("id", jmsHostName, "adminPassword", "admin", "port", "7676", + "adminUserName", "admin", "host", "localhost"); + + // Test create + Response response = managementClient.post(URL_JMS_HOST, newHost); + assertThat(response.getStatus(), equalTo(200)); + + // Test edit + Map entity = getEntityValues(managementClient.get(URL_JMS_HOST + "/" + jmsHostName)); + assertThat(entity, aMapWithSize(greaterThanOrEqualTo(6))); + assertEquals(jmsHostName, entity.get("name")); + entity.put("port", "8686"); + response = managementClient.post(URL_JMS_HOST + "/" + jmsHostName, entity); + assertThat(response.getStatus(), equalTo(200)); + entity = getEntityValues(managementClient.get(URL_JMS_HOST + "/" + jmsHostName)); + assertEquals("8686", entity.get("port")); + + // Test delete + response = managementClient.delete(URL_JMS_HOST + "/" + jmsHostName); + assertThat(response.getStatus(), equalTo(200)); + } + + public void createJmsPhysicalDestination(final String destName, final String type, final String endpoint) { + final Map newDest = Map.of("id", destName, "desttype", type); + Response response = managementClient.post(endpoint + "/create-jmsdest", newDest); + assertThat(response.getStatus(), equalTo(200)); + } + + public void deleteJmsPhysicalDestination(final String destName, final String endpoint) { + final Map newDest = Map.of("id", destName, "desttype", DEST_TYPE); + Response response = managementClient.delete(endpoint + "/delete-jmsdest", newDest); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.get(endpoint + "__get-jmsdest", newDest); + assertThat(response.getStatus(), equalTo(404)); + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JobsResourceITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JobsResourceITest.java new file mode 100644 index 00000000000..b20bb43784c --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JobsResourceITest.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONObject; +import org.glassfish.main.admin.test.tool.DomainAdminRestClient; +import org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.glassfish.main.admin.test.tool.AsadminResultMatcher.asadminOK; +import static org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment.getAsadmin; +import static org.hamcrest.CoreMatchers.endsWith; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * @author jdlee + */ +public class JobsResourceITest extends RestTestBase { + + private static final String GF_JSON_TYPE = "application/vnd.oracle.glassfish+json"; + private static final String URL_JOBS = "/jobs"; + + private DomainAdminRestClient client; + private String jobId; + + @BeforeEach + public void initInstanceClient() { + client = new DomainAdminRestClient(getBaseAdminUrl() + "/management", GF_JSON_TYPE); + } + + + @AfterEach + public void closeInstanceClient() { + if (jobId != null) { + GlassFishTestEnvironment.getAsadmin().exec("attach", jobId); + } + if (client != null) { + client.close(); + } + } + + @Test + public void testJobsListing() { + assertEquals(200, client.get(URL_JOBS).getStatus()); + } + + @Test + public void testGetJob() throws Exception { + // make sure we have at least one detached job + assertThat(getAsadmin().exec("--detach", "uptime"), asadminOK()); + + // verify getting the collection + Response response = client.get(URL_JOBS); + assertEquals(200, response.getStatus()); + + // verify the overall structure + JSONObject json = response.readEntity(JSONObject.class); + JSONArray resources = json.getJSONArray("resources"); + assertNotNull(resources); + assertThat(resources.length(), equalTo(1)); + + JSONArray items = json.getJSONArray("items"); + assertNotNull(items); + assertThat(items.length(), equalTo(1)); + + // unlike most resources that also return a parent link, + // the jobs resource only returns child links. + // verify the first of them + JSONObject resource = resources.getJSONObject(0); + String uri = resource.getString("uri"); + assertNotNull(uri); + assertEquals("job", resource.getString("rel")); + + jobId = resource.getString("title"); + assertNotNull(jobId); + assertThat(uri, endsWith(URL_JOBS + "/id/" + jobId)); + + // verify the job it refers to by following the link. + // it should only have a parent link + try (GenericClient genericClient = new GenericClient()) { + response = genericClient.get(uri); + assertThat(response.getStatus(), equalTo(200)); + json = response.readEntity(JSONObject.class); + } + JSONObject item = json.getJSONObject("item"); + System.out.println(item.toString()); + assertNotNull(item); + assertEquals(jobId, item.getString("jobId")); + + resources = json.getJSONArray("resources"); + assertNotNull(resources); + assertThat(resources.length(), equalTo(1)); + + resource = resources.getJSONObject(0); + assertEquals("parent", resource.getString("rel")); + assertThat(resource.getString("uri"), endsWith(URL_JOBS)); + + // verify that the collection returned the item too + item = null; + for (int i = 0; item == null && i < items.length(); i++) { + JSONObject thisItem = items.getJSONObject(i); + if (jobId.equals(thisItem.getString("jobId"))) { + item = thisItem; + } + } + assertNotNull(item); + assertEquals(jobId, item.getString("jobId")); + } + + + private static class GenericClient extends DomainAdminRestClient { + public GenericClient() { + super(GlassFishTestEnvironment.createClient(), "", GF_JSON_TYPE); + } + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JvmOptionsITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JvmOptionsITest.java new file mode 100644 index 00000000000..18c847182da --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/JvmOptionsITest.java @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; + +import java.util.List; +import java.util.Map; + +import org.glassfish.admin.rest.client.utils.MarshallingUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author jasonlee + */ +public class JvmOptionsITest extends RestTestBase { + private static final String URL_SERVER_JVM_OPTIONS = "/domain/configs/config/server-config/java-config/jvm-options"; + private static final String URL_DEFAULT_JVM_OPTIONS = "/domain/configs/config/default-config/java-config/jvm-options"; + + private static final String URL_SERVER_CONFIG_CREATE_PROFILER = "/domain/configs/config/server-config/java-config/create-profiler"; + private static final String URL_SERVER_CONFIG_DELETE_PROFILER = "/domain/configs/config/server-config/java-config/profiler/delete-profiler"; + private static final String URL_SERVER_CONFIG_PROFILER_JVM_OPTIONS = "/domain/configs/config/server-config/java-config/profiler/jvm-options"; + + private static final String URL_DEFAULT_CONFIG_CREATE_PROFILER = "/domain/configs/config/default-config/java-config/create-profiler"; + private static final String URL_DEFAULT_CONFIG_DELETE_PROFILER = "/domain/configs/config/default-config/java-config/profiler/delete-profiler"; + private static final String URL_DEFAULT_CONFIG_PROFILER_JVM_OPTIONS = "/domain/configs/config/default-config/java-config/profiler/jvm-options"; + + private static RestTestBase configManagement; + private String testConfigName; + private String testConfigUrl; + private String testConfigJvmOptionsUrl; + + @BeforeAll + public static void initConfig() { + configManagement = new RestTestBase(); + } + + @BeforeEach + public void createConfig() { + testConfigName = "config-" + generateRandomString(); + MultivaluedMap formData = new MultivaluedHashMap<>() {{ + add("id", "default-config"); + add("id", testConfigName); + }}; + configManagement.createAndVerifyConfig(testConfigName, formData); + testConfigUrl = "/domain/configs/config/" + testConfigName; + testConfigJvmOptionsUrl = testConfigUrl + "/java-config/jvm-options"; + } + + @AfterEach + public void deleteConfig() { + configManagement.deleteAndVerifyConfig(testConfigName); + } + + + @Test + public void getJvmOptions() { + Response response = managementClient.get(URL_SERVER_JVM_OPTIONS); + assertEquals(200, response.getStatus()); + Map responseMap = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); + List jvmOptions = (List)((Map)responseMap.get("extraProperties")).get("leafList"); + assertThat(jvmOptions, hasSize(greaterThan(10))); + } + + @Test + public void createAndDeleteOptions() { + final String option1Name = "-Doption" + generateRandomString(); + Map newOptions = Map.of(option1Name, "someValue"); + + Response response = managementClient.post(testConfigJvmOptionsUrl, newOptions); + assertEquals(200, response.getStatus()); + response = managementClient.get(testConfigJvmOptionsUrl); + List jvmOptions = getJvmOptions(response); + assertThat(jvmOptions, hasItem(option1Name + "=someValue")); + + response = managementClient.delete(testConfigJvmOptionsUrl, newOptions); + assertEquals(200, response.getStatus()); + response = managementClient.get(testConfigJvmOptionsUrl); + jvmOptions = getJvmOptions(response); + assertThat(jvmOptions, not(hasItem(option1Name + "=someValue"))); + } + + @Test + public void createAndDeleteOptionsWithBackslashes() { + final String optionName = "-Dfile" + generateRandomString(); + final String optionValue = "C:\\ABC\\DEF\\"; + Map newOptions = Map.of(optionName, escape(optionValue)); + + Response response = managementClient.post(testConfigJvmOptionsUrl, newOptions); + assertEquals(200, response.getStatus()); + response = managementClient.get(testConfigJvmOptionsUrl); + List jvmOptions = getJvmOptions(response); + assertThat(jvmOptions, hasItem(optionName + "=" + optionValue)); + + response = managementClient.delete(testConfigJvmOptionsUrl, newOptions); + assertEquals(200, response.getStatus()); + response = managementClient.get(testConfigJvmOptionsUrl); + jvmOptions = getJvmOptions(response); + assertThat(jvmOptions, not(hasItem(optionName + "=" + optionValue))); + } + + @Test + public void createAndDeleteOptionsWithoutValues() { + final String option1Name = "-Doption" + generateRandomString(); + final String option2Name = "-Doption" + generateRandomString(); + Map newOptions = Map.of(option1Name, "", option2Name, ""); + Response response = managementClient.post(testConfigJvmOptionsUrl, newOptions); + assertEquals(200, response.getStatus()); + response = managementClient.get(testConfigJvmOptionsUrl); + List jvmOptions = getJvmOptions(response); + assertThat(jvmOptions, hasItems(option2Name, option2Name)); + assertThat(jvmOptions, not(hasItems(option1Name + '=', option2Name + '='))); + + response = managementClient.delete(testConfigJvmOptionsUrl, newOptions); + assertEquals(200, response.getStatus()); + response = managementClient.get(testConfigJvmOptionsUrl); + jvmOptions = getJvmOptions(response); + assertThat(jvmOptions, allOf(not(hasItem(option1Name)), not(hasItem(option2Name)))); + } + + @Test + public void testIsolatedOptionsCreationOnNewConfig() { + final String optionName = "-Doption" + generateRandomString(); + Map newOptions = Map.of(optionName, "", "target", testConfigName); + + // Test new config to make sure option is there + Response response = managementClient.post(testConfigJvmOptionsUrl, newOptions); + assertEquals(200, response.getStatus()); + response = managementClient.get(testConfigJvmOptionsUrl); + List jvmOptions = getJvmOptions(response); + assertThat(jvmOptions, hasItem(optionName)); + + // Test server-config to make sure the options are NOT there + response = managementClient.get(URL_SERVER_JVM_OPTIONS); + jvmOptions = getJvmOptions(response); + assertThat(jvmOptions, not(hasItem(optionName))); + } + + @Test + public void testProfilerJvmOptions() { + final String profilerName = "profiler" + generateRandomString(); + final String optionName = "-Doption" + generateRandomString(); + Map attrs = Map.of("name", profilerName, "target", testConfigName); + Map newOptions = Map.of(optionName, ""); + deleteProfiler(testConfigUrl + "/java-config/profiler/delete-profiler", testConfigName, false); + + Response response = managementClient.post(testConfigUrl + "/java-config/create-profiler", attrs); + assertEquals(200, response.getStatus()); + + response = managementClient.post(testConfigUrl + "/java-config/profiler/jvm-options", newOptions); + assertEquals(200, response.getStatus()); + + response = managementClient.get(testConfigUrl + "/java-config/profiler/jvm-options"); + List jvmOptions = getJvmOptions(response); + assertThat(jvmOptions, hasItem(optionName)); + + deleteProfiler(testConfigUrl + "/java-config/profiler/delete-profiler", testConfigName, true); + } + + @Test + public void testJvmOptionWithColon() { + final String optionName = "-XX:MaxPermSize"; + final String optionValue = "152m"; + Map newOptions = Map.of(escape(optionName), optionValue); + + Response response = managementClient.post(testConfigJvmOptionsUrl, newOptions); + assertEquals(200, response.getStatus()); + response = managementClient.get(testConfigJvmOptionsUrl); + assertEquals(200, response.getStatus()); + List jvmOptions = getJvmOptions(response); + assertThat(jvmOptions, hasItem(optionName + '=' + optionValue)); + + response = managementClient.delete(testConfigJvmOptionsUrl, newOptions); + assertEquals(200, response.getStatus()); + response = managementClient.get(testConfigJvmOptionsUrl); + jvmOptions = getJvmOptions(response); + assertThat(jvmOptions, not(hasItem(optionName + '=' + optionValue))); + } + + private void deleteProfiler(final String url, final String target, final boolean failOnError) { + Response response = managementClient.delete(url, Map.of("target", target)); + if (failOnError) { + assertEquals(200, response.getStatus()); + } + } + + private List getJvmOptions(Response response) { + Map responseMap = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); + List jvmOptions = (List)((Map)responseMap.get("extraProperties")).get("leafList"); + return jvmOptions; + } + + private String escape(String part) { + String changed = part + .replace("\\", "\\\\") + .replace(":", "\\:"); + return changed; + } +} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/MetadataTest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/MetadataITest.java similarity index 52% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/MetadataTest.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/MetadataITest.java index 2e11a93cb7b..7109299a750 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/MetadataTest.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/MetadataITest.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -14,51 +15,57 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package org.glassfish.nucleus.admin.rest; +package org.glassfish.main.admin.test.rest; -import java.util.Map; import jakarta.ws.rs.core.Response; + +import java.util.Map; + import org.glassfish.admin.rest.client.utils.MarshallingUtils; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.stringContainsInOrder; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** - * * @author jasonlee */ -public class MetadataTest extends RestTestBase { - protected static final String URL_CONFIG = "/domain/configs/config.json"; - protected static final String URL_UPTIMECOMMAND = "/domain/uptime.json"; +public class MetadataITest extends RestTestBase { + private static final String URL_CONFIG = "/domain/configs/config.json"; + private static final String URL_UPTIMECOMMAND = "/domain/uptime.json"; @Test public void configParameterTest() { - Response response = options(URL_CONFIG); - assertTrue(isSuccess(response)); + Response response = managementClient.options(URL_CONFIG); + assertEquals(200, response.getStatus()); // Really dumb test. Should be good enough for now Map extraProperties = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); assertNotNull(extraProperties); // Another dumb test to make sure that "name" shows up on the HTML page - response = getClient().target(getAddress(URL_CONFIG)).request().get(Response.class); - assertTrue(response.readEntity(String.class).contains("extraProperties")); + response = managementClient.get(URL_CONFIG); + String data = response.readEntity(String.class); + assertThat(data, stringContainsInOrder("extraProperties")); } @Test - public void UpTimeMetadaDataTest() { - Response response = options(URL_UPTIMECOMMAND); - assertTrue(isSuccess(response)); + public void upTimeMetadaDataTest() { + Response response = managementClient.options(URL_UPTIMECOMMAND); + assertEquals(200, response.getStatus()); - Map extraProperties = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); + Map extraProperties = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); assertNotNull(extraProperties); // Another dumb test to make sure that "extraProperties" shows up on the HTML page - response = getClient().target(getAddress(URL_UPTIMECOMMAND)).request().get(Response.class); + response = managementClient.get(URL_UPTIMECOMMAND); String resp = response.readEntity(String.class); - assertTrue(resp.contains("extraProperties")); + assertThat(resp, stringContainsInOrder("extraProperties")); // test to see if we get the milliseconds parameter description which is an //optional param metadata for the uptime command - assertTrue(resp.contains("milliseconds")); - assertTrue(resp.contains("GET")); + assertThat(resp, stringContainsInOrder("milliseconds")); + assertThat(resp, stringContainsInOrder("GET")); } } diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/MonitoringITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/MonitoringITest.java new file mode 100644 index 00000000000..8cd5b9a1425 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/MonitoringITest.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + + +import jakarta.ws.rs.core.Response; + +import java.util.HashMap; +import java.util.Map; + +import org.glassfish.main.admin.test.tool.DomainAdminRestClient; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.hamcrest.CoreMatchers.anyOf; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.aMapWithSize; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Note regards HTTP 200/202 - not sure why it is happening, but the server probably needs some time + * to propagate changes, while we request another. + * + * @author Mitesh Meswani + */ +@TestMethodOrder(OrderAnnotation.class) +public class MonitoringITest extends RestTestBase { + + private static final String MONITORING_RESOURCE_URL = "/domain/configs/config/server-config/monitoring-service/module-monitoring-levels"; + private static final String JDBC_CONNECTION_POOL_URL = "/domain/resources/jdbc-connection-pool"; + private static final String PING_CONNECTION_POOL_URL = "/domain/resources/ping-connection-pool"; + private static final String POOL_NAME_W_DOT = "poolNameWith.dot"; + + private static DomainAdminRestClient monitoringClient; + + @BeforeAll + public static void init() { + monitoringClient = new DomainAdminRestClient(getBaseAdminUrl() + "/monitoring"); + } + + + @AfterAll + public static void closeResources() { + Response responseDel = managementClient.delete(JDBC_CONNECTION_POOL_URL + '/' + POOL_NAME_W_DOT); + assertThat(responseDel.getStatus(), anyOf(equalTo(200), equalTo(202), equalTo(404))); + if (monitoringClient != null) { + monitoringClient.close(); + } + } + + + @Test + @Order(1) + public void enableMonitoring() { + Map payLoad = new HashMap<>() { + { + put("ThreadPool", "HIGH"); + put("Orb", "HIGH"); + put("EjbContainer", "HIGH"); + put("WebContainer", "HIGH"); + put("Deployment", "HIGH"); + put("TransactionService", "HIGH"); + put("HttpService", "HIGH"); + put("JdbcConnectionPool", "HIGH"); + put("ConnectorConnectionPool", "HIGH"); + put("ConnectorService", "HIGH"); + put("JmsService", "HIGH"); + put("Jvm", "HIGH"); + put("Security", "HIGH"); + put("WebServicesContainer", "HIGH"); + put("Jpa", "HIGH"); + put("Jersey", "HIGH"); + } + }; + Response response = managementClient.post(MONITORING_RESOURCE_URL, payLoad); + assertThat(response.getStatus(), anyOf(equalTo(200), equalTo(202))); + } + + /** + * Objective - Verify that basic monitoring is working + * Strategy - Call /monitoring/domain and assert that "server" is present as child element + */ + @Test + @Order(2) + public void testBaseURL() { + Response response = monitoringClient.get("/domain"); + assertThat(response.getStatus(), anyOf(equalTo(200), equalTo(202))); + // monitoring/domain + Map entity = getChildResources(response); + assertNotNull(entity.get("server"), entity.toString()); + } + + /** + * Objective - Verify that invalid resources returns 404 + * Strategy - Request an invalid resource under monitoring and ensure that 404 is returned + */ + @Test + @Order(10) + public void testInvalidResource() { + Response response = monitoringClient.get("/domain/server/foo"); + assertEquals(404, response.getStatus(), "Did not receive "); + } + + /** + * Objective - Verify that resources with dot work + * Strategy - create a resource with "." in name and then try to access it + */ + @Test + @Order(20) + public void testDot() { + Response responseDel = managementClient.delete(JDBC_CONNECTION_POOL_URL + '/' + POOL_NAME_W_DOT); + assertThat(responseDel.getStatus(), equalTo(404)); + + Map payLoad = new HashMap<>() { + { + put("name", POOL_NAME_W_DOT); + put("resType", "javax.sql.DataSource"); + put("datasourceClassname", "foo.bar"); + } + }; + Response response = managementClient.post(JDBC_CONNECTION_POOL_URL, payLoad); + assertThat(response.getStatus(), anyOf(equalTo(200), equalTo(202))); + + // Step 2- Ping the connection pool to generate some monitoring data + Response responsePing = managementClient.get(PING_CONNECTION_POOL_URL, Map.of("id", POOL_NAME_W_DOT)); + // foo.bar is invalid ds class + assertThat(responsePing.toString(), responsePing.getStatus(), equalTo(500)); + + // Step 3 - Access monitoring tree to assert it is accessible + Response responsePool = monitoringClient.get("/domain/server/resources/" + POOL_NAME_W_DOT); + assertEquals(200, responsePool.getStatus()); + Map responseEntity = getEntityValues(responsePool); + assertThat("Monitoring data: \n" + responseEntity, responseEntity, aMapWithSize(14)); + } + + + @Test + @Order(1000) + public void testCleanup() { + Map payLoad = new HashMap<>() { + { + put("ThreadPool", "OFF"); + put("Orb", "OFF"); + put("EjbContainer", "OFF"); + put("WebContainer", "OFF"); + put("Deployment", "OFF"); + put("TransactionService", "OFF"); + put("HttpService", "OFF"); + put("JdbcConnectionPool", "OFF"); + put("ConnectorConnectionPool", "OFF"); + put("ConnectorService", "OFF"); + put("JmsService", "OFF"); + put("Jvm", "OFF"); + put("Security", "OFF"); + put("WebServicesContainer", "OFF"); + put("Jpa", "OFF"); + put("Jersey", "OFF"); + } + }; + Response response = managementClient.post(MONITORING_RESOURCE_URL, payLoad); + assertThat(response.getStatus(), anyOf(equalTo(200), equalTo(202))); + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/NetworkListenerITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/NetworkListenerITest.java new file mode 100644 index 00000000000..3c315e4e474 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/NetworkListenerITest.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; + +import java.util.HashMap; +import java.util.Map; + +import org.codehaus.jettison.json.JSONObject; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.stringContainsInOrder; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author jasonlee + */ +public class NetworkListenerITest extends RestTestBase { + private static final String URL_PROTOCOL = "/domain/configs/config/server-config/network-config/protocols/protocol"; + private static final String URL_SSL = "/domain/configs/config/server-config/network-config/protocols/protocol/http-listener-2/ssl"; + + private static final String redirectProtocolName = "http-redirect"; + private static final String portUniProtocolName = "pu-protocol"; + + private static final String redirectFilterName = "redirect-filter"; + private static final String finderName1 = "http-finder"; + private static final String finderName2 = "http-redirect"; + + @AfterAll + public static void cleanup() { + Response response = managementClient.post( + "/domain/configs/config/server-config/network-config/network-listeners/network-listener/http-listener-1", + Map.of("protocol", "http-listener-1")); + assertEquals(200, response.getStatus()); + response = managementClient.delete(URL_PROTOCOL + "/" + portUniProtocolName + "/delete-protocol-finder", + Map.of("protocol", portUniProtocolName, "id", finderName1)); + assertEquals(200, response.getStatus()); + response = managementClient.delete(URL_PROTOCOL + "/" + portUniProtocolName + "/delete-protocol-finder", + Map.of("protocol", portUniProtocolName, "id", finderName2)); + assertEquals(200, response.getStatus()); + response = managementClient.delete( + URL_PROTOCOL + "/" + redirectProtocolName + + "/protocol-chain-instance-handler/protocol-chain/protocol-filter/" + redirectFilterName, + Map.of("protocol", redirectProtocolName)); + assertEquals(200, response.getStatus()); + response = managementClient.delete(URL_PROTOCOL + "/" + portUniProtocolName); + assertEquals(200, response.getStatus()); + response = managementClient.delete(URL_PROTOCOL + "/" + redirectProtocolName); + assertEquals(200, response.getStatus()); + } + + + @Test + public void createHttpListener() { + Response response = managementClient.post("/domain/set", Map.of( + "configs.config.server-config.network-config.network-listeners.network-listener.http-listener-1.protocol", + "http-listener-1")); + assertEquals(200, response.getStatus()); + managementClient.delete(URL_PROTOCOL + "/" + portUniProtocolName); + assertEquals(200, response.getStatus()); + managementClient.delete(URL_PROTOCOL + "/" + redirectProtocolName); + assertEquals(200, response.getStatus()); + // asadmin commands taken from: http://www.antwerkz.com/port-unification-in-glassfish-3-part-1/ + // asadmin create-protocol --securityenabled=false http-redirect + // asadmin create-protocol --securityenabled=false pu-protocol + response = managementClient.post(URL_PROTOCOL, Map.of("securityenabled", "false", "id", redirectProtocolName)); + assertEquals(200, response.getStatus()); + response = managementClient.post(URL_PROTOCOL, Map.of("securityenabled", "false", "id", portUniProtocolName)); + assertEquals(200, response.getStatus()); + + // asadmin create-protocol-filter --protocol http-redirect --classname org.glassfish.grizzly.config.portunif.HttpRedirectFilter redirect-filter + response = managementClient.post(URL_PROTOCOL + "/" + redirectProtocolName + "/create-protocol-filter", + Map.of("id", redirectFilterName, "protocol", redirectProtocolName, + "classname", "org.glassfish.grizzly.config.portunif.HttpRedirectFilter")); + assertEquals(200, response.getStatus()); + + // asadmin create-protocol-finder --protocol pu-protocol --targetprotocol http-listener-2 --classname org.glassfish.grizzly.config.portunif.HttpProtocolFinder http-finder + // asadmin create-protocol-finder --protocol pu-protocol --targetprotocol http-redirect --classname org.glassfish.grizzly.config.portunif.HttpProtocolFinder http-redirect + response = managementClient.post(URL_PROTOCOL + "/" + portUniProtocolName + "/create-protocol-finder", + new HashMap() {{ + put ("id", finderName1); + put ("protocol", portUniProtocolName); + put ("targetprotocol", "http-listener-2"); + put ("classname", "org.glassfish.grizzly.config.portunif.HttpProtocolFinder"); + }}); + assertEquals(200, response.getStatus()); + response = managementClient.post(URL_PROTOCOL + "/" + portUniProtocolName + "/create-protocol-finder", + new HashMap() {{ + put ("id", finderName2); + put ("protocol", portUniProtocolName); + put ("targetprotocol", redirectProtocolName); + put ("classname", "org.glassfish.grizzly.config.portunif.HttpProtocolFinder"); + }}); + assertEquals(200, response.getStatus()); + + + // asadmin set configs.config.server-config.network-config.network-listeners.network-listener.http-listener-1.protocol=pu-protocol + response = managementClient.post( + "/domain/configs/config/server-config/network-config/network-listeners/network-listener/http-listener-1", + Map.of("protocol", portUniProtocolName)); + assertEquals(200, response.getStatus()); + + response = managementClient.get("/domain/configs/config/server-config/network-config/network-listeners/network-listener/http-listener-1/find-http-protocol"); + assertThat(response.readEntity(String.class), stringContainsInOrder("http-listener-2")); + } + + @Test + public void testClearingProperties() { + Map params = new HashMap<>() {{ + put("keyStore", "foo"); + put("trustAlgorithm", "bar"); + put("trustMaxCertLength", "15"); + put("trustStore", "baz"); + }}; + + Response response = managementClient.post(URL_SSL, params); + assertEquals(200, response.getStatus()); + response = managementClient.get(URL_SSL, params); + Map entity = this.getEntityValues(response); + assertEquals(params.get("keyStore"), entity.get("keyStore")); + assertEquals(params.get("trustAlgorithm"), entity.get("trustAlgorithm")); + assertEquals(params.get("trustMaxCertLength"), entity.get("trustMaxCertLength")); + assertEquals(params.get("trustStore"), entity.get("trustStore")); + + params.put("keyStore", ""); + params.put("trustAlgorithm", ""); + params.put("trustStore", ""); + response = managementClient.post(URL_SSL, params); + assertEquals(200, response.getStatus()); + response = managementClient.get(URL_SSL, params); + entity = this.getEntityValues(response); + assertEquals(JSONObject.NULL, entity.get("keyStore")); + assertEquals(JSONObject.NULL, entity.get("trustAlgorithm")); + assertEquals(JSONObject.NULL, entity.get("trustStore")); + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/NoCLICommandResourceCreationITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/NoCLICommandResourceCreationITest.java new file mode 100644 index 00000000000..f8312880f47 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/NoCLICommandResourceCreationITest.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.core.Response; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import static jakarta.ws.rs.core.MediaType.APPLICATION_XML; +import static org.glassfish.admin.rest.client.utils.MarshallingUtils.getXmlForProperties; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author Mitesh Meswani + */ +public class NoCLICommandResourceCreationITest extends RestTestBase { + private static final String URL_SERVER_PROPERTY = "/domain/servers/server/server/property"; + + + @Test + public void testPropertyCreation() { + final String propertyKey = "propertyName" + generateRandomString(); + String propertyValue = generateRandomString(); + + //Create a property + Map param = new HashMap<>(); + param.put("name", propertyKey); + param.put("value", propertyValue); + Response response = managementClient.post(URL_SERVER_PROPERTY, + Entity.entity(getXmlForProperties(param), APPLICATION_XML)); + assertEquals(200, response.getStatus()); + + //Verify the property got created + String propertyURL = URL_SERVER_PROPERTY + "/" + propertyKey; + response = managementClient.get(propertyURL); + assertEquals(200, response.getStatus()); + Map entity = getEntityValues(response); + assertEquals(propertyKey, entity.get("name")); + assertEquals(propertyValue, entity.get("value")); + + // Verify property update + propertyValue = generateRandomString(); + param.put("value", propertyValue); + response = managementClient.put(URL_SERVER_PROPERTY, Entity.entity(getXmlForProperties(param), APPLICATION_XML)); + assertEquals(200, response.getStatus()); + response = managementClient.get(propertyURL); + assertEquals(200, response.getStatus()); + entity = getEntityValues(response); + assertEquals(propertyKey, entity.get("name")); + assertEquals(propertyValue, entity.get("value")); + + //Clean up to leave domain.xml good for next run + response = managementClient.delete(propertyURL, new HashMap()); + assertEquals(200, response.getStatus()); + } +} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/PartialUpdateTest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/PartialUpdateITest.java similarity index 70% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/PartialUpdateTest.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/PartialUpdateITest.java index f6f277f47e8..7fab0c0319e 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/PartialUpdateTest.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/PartialUpdateITest.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -14,29 +15,30 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package org.glassfish.nucleus.admin.rest; +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; -import java.util.HashMap; import java.util.Map; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** - * * @author jasonlee */ -public class PartialUpdateTest extends RestTestBase { - @Test(enabled=false) - // TODO: rework this to use something nucleus-friendly +public class PartialUpdateITest extends RestTestBase { + + @Test public void testPartialUpdate() { - final String endpoint = JdbcTest.BASE_JDBC_CONNECTION_POOL_URL + "/DerbyPool"; + final String endpoint = URL_JDBC_CONNECTION_POOL + "/DerbyPool"; final String newDesc = generateRandomString(); - Map origAttrs = getEntityValues(get(endpoint)); - Map newAttrs = new HashMap() {{ - put ("description", newDesc); - }}; - post(endpoint, newAttrs); - Map updatedAttrs = getEntityValues(get(endpoint)); + Map origAttrs = getEntityValues(managementClient.get(endpoint)); + Map newAttrs = Map.of("description", newDesc); + Response response = managementClient.post(endpoint, newAttrs); + assertEquals(200, response.getStatus()); + Map updatedAttrs = getEntityValues(managementClient.get(endpoint)); assertEquals(newDesc, updatedAttrs.get("description")); assertEquals(origAttrs.get("driverClassname"), updatedAttrs.get("driverClassname")); assertEquals(origAttrs.get("resType"), updatedAttrs.get("resType")); diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/PropertiesBagTest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/PropertiesBagITest.java similarity index 64% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/PropertiesBagTest.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/PropertiesBagITest.java index 1d6a0015e03..fe476a6e91a 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/PropertiesBagTest.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/PropertiesBagITest.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -14,37 +15,46 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package org.glassfish.nucleus.admin.rest; +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.core.Response; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import jakarta.ws.rs.client.Entity; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; + import org.codehaus.jettison.json.JSONArray; import org.glassfish.admin.rest.client.utils.MarshallingUtils; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; + +import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** - * * @author jasonlee */ -public class PropertiesBagTest extends RestTestBase { +public class PropertiesBagITest extends RestTestBase { - protected static final String PROP_DOMAIN_NAME = "administrative.domain.name"; - protected static final String URL_DOMAIN_PROPERTIES = "/domain/property"; - protected static final String URL_JAVA_CONFIG_PROPERTIES = "/domain/configs/config/default-config/java-config/property"; - protected static final String URL_SERVER_PROPERTIES = "/domain/servers/server/server/property"; - protected static final String URL_DERBYPOOL_PROPERTIES = "/domain/resources/jdbc-connection-pool/DerbyPool/property"; - private static final String REQUEST_FORMAT = MediaType.APPLICATION_JSON; + private static final String PROP_DOMAIN_NAME = "administrative.domain.name"; + private static final String URL_DOMAIN_PROPERTIES = "/domain/property"; + private static final String URL_JAVA_CONFIG_PROPERTIES = "/domain/configs/config/default-config/java-config/property"; + private static final String URL_SERVER_PROPERTIES = "/domain/servers/server/server/property"; + private static final String URL_DERBYPOOL_PROPERTIES = "/domain/resources/jdbc-connection-pool/DerbyPool/property"; @Test public void propertyRetrieval() { - Response response = get(URL_DOMAIN_PROPERTIES); - checkStatusForSuccess(response); + Response response = managementClient.get(URL_DOMAIN_PROPERTIES); + assertEquals(200, response.getStatus()); List> properties = getProperties(response); assertTrue(isPropertyFound(properties, PROP_DOMAIN_NAME)); } @@ -59,9 +69,9 @@ public void serverProperties() { createAndDeleteProperties(URL_SERVER_PROPERTIES); } - @Test(enabled=false) + @Test public void propsWithEmptyValues() { - List> properties = new ArrayList>(); + List> properties = new ArrayList<>(); final String empty = "empty" + generateRandomNumber(); final String foo = "foo" + generateRandomNumber(); final String bar = "bar" + generateRandomNumber(); @@ -71,7 +81,7 @@ public void propsWithEmptyValues() { properties.add(createProperty(foo,"foovalue")); properties.add(createProperty(bar,"barvalue")); createProperties(URL_DERBYPOOL_PROPERTIES, properties); - List> newProperties = getProperties(get(URL_DERBYPOOL_PROPERTIES)); + List> newProperties = getProperties(managementClient.get(URL_DERBYPOOL_PROPERTIES)); assertFalse(isPropertyFound(newProperties, empty)); assertTrue(isPropertyFound(newProperties, foo)); @@ -80,7 +90,7 @@ public void propsWithEmptyValues() { properties.clear(); properties.add(createProperty(abc,"abcvalue")); createProperties(URL_DERBYPOOL_PROPERTIES, properties); - newProperties = getProperties(get(URL_DERBYPOOL_PROPERTIES)); + newProperties = getProperties(managementClient.get(URL_DERBYPOOL_PROPERTIES)); assertTrue(isPropertyFound(newProperties, abc)); assertFalse(isPropertyFound(newProperties, empty)); @@ -88,10 +98,10 @@ public void propsWithEmptyValues() { assertFalse(isPropertyFound(newProperties, bar)); } - @Test(enabled=false) + @Test public void testOptimizedPropertyHandling() { // First, test changing one property and adding a new - List> properties = new ArrayList>(); + List> properties = new ArrayList<>(); properties.add(createProperty("PortNumber","1527")); properties.add(createProperty("Password","APP")); properties.add(createProperty("User","APP")); @@ -101,7 +111,7 @@ public void testOptimizedPropertyHandling() { properties.add(createProperty("foo","bar","test")); createProperties(URL_DERBYPOOL_PROPERTIES, properties); - List> newProperties = getProperties(get(URL_DERBYPOOL_PROPERTIES)); + List> newProperties = getProperties(managementClient.get(URL_DERBYPOOL_PROPERTIES)); for (Map property : newProperties) { if (property.get("name").equals("connectionAttributes")) { assertEquals(";create=false", property.get("value")); @@ -116,7 +126,7 @@ public void testOptimizedPropertyHandling() { properties.add(createProperty("foo","bar 2","test 2")); createProperties(URL_DERBYPOOL_PROPERTIES, properties); - newProperties = getProperties(get(URL_DERBYPOOL_PROPERTIES)); + newProperties = getProperties(managementClient.get(URL_DERBYPOOL_PROPERTIES)); assertNotSame(1, newProperties); for (Map property : newProperties) { if (property.get("name").equals("foo")) { @@ -136,7 +146,7 @@ public void testOptimizedPropertyHandling() { createProperties(URL_DERBYPOOL_PROPERTIES, properties); - newProperties = getProperties(get(URL_DERBYPOOL_PROPERTIES)); + newProperties = getProperties(managementClient.get(URL_DERBYPOOL_PROPERTIES)); for (Map property : newProperties) { if (property.get("name").equals("connectionAttributes")) { assertEquals(";create=true", property.get("value")); @@ -146,21 +156,20 @@ public void testOptimizedPropertyHandling() { } } - // the prop name can not contain . - // need to remove the . test when http://java.net/jira/browse/GLASSFISH-15418 is fixed -// @Test + @Test public void testPropertiesWithDots() { - List> properties = new ArrayList>(); - final String prop = "some.property.with.dots." + generateRandomNumber(); + List> properties = new ArrayList<>(); + final String key = "some.property.with.dots." + generateRandomNumber(); final String description = "This is the description"; final String value = generateRandomString(); - properties.add(createProperty(prop, value, description)); + properties.add(createProperty(key, value, description)); createProperties(URL_DERBYPOOL_PROPERTIES, properties); - List> newProperties = getProperties(get(URL_DERBYPOOL_PROPERTIES)); - Map newProp = getProperty(newProperties, prop); - assertTrue(newProp != null); - assertTrue(value.equals(newProp.get("value"))); - assertTrue(description.equals(newProp.get("description"))); + + List> newProperties = getProperties(managementClient.get(URL_DERBYPOOL_PROPERTIES)); + Map newProp = getProperty(newProperties, key); + assertNotNull(newProp); + assertEquals(value, newProp.get("value")); + assertNull(newProp.get("description"), "Descriptions are not returned at this moment: " + newProp); } // This operation is taking a REALLY long time from the console, probably due @@ -170,9 +179,9 @@ public void testPropertiesWithDots() { // saved. This test will create the jmsra config with a set of properties, // then update only one the object's properties, which should be a very quick, // inexpensive operation. - @Test(enabled=false) + @Test public void testJmsRaCreateAndUpdate() { - List> props = new ArrayList>(){{ + List> props = new ArrayList<>(){{ add(createProperty("AddressListBehavior", "random")); add(createProperty("AddressListIterations", "3")); add(createProperty("AdminPassword", "admin")); @@ -190,20 +199,20 @@ public void testJmsRaCreateAndUpdate() { add(createProperty("startRMIRegistry", "false")); }}; final String propertyList = buildPropertyList(props); - Map attrs = new HashMap() {{ + Map attrs = new HashMap<>() {{ put("objecttype","user"); put("id","jmsra"); put("threadPoolIds","thread-pool-1"); put("property", propertyList); }}; - final String URL = "/domain/resources/resource-adapter-config"; - delete(URL+"/jmsra"); - Response response = post(URL, attrs); - assertTrue(isSuccess(response)); + final String url = "/domain/resources/resource-adapter-config"; + managementClient.delete(url + "/jmsra"); + Response response = managementClient.post(url, attrs); + assertEquals(200, response.getStatus()); // Change one property value (AddressListIterations) and update the object - props = new ArrayList>(){{ + props = new ArrayList<>(){{ add(createProperty("AddressListBehavior", "random")); add(createProperty("AddressListIterations", "4")); add(createProperty("AdminPassword", "admin")); @@ -220,13 +229,12 @@ public void testJmsRaCreateAndUpdate() { add(createProperty("doBind", "false")); add(createProperty("startRMIRegistry", "false")); }}; - createProperties(URL+"/jmsra/property", props); + createProperties(url + "/jmsra/property", props); - delete(URL+"/jmsra"); + managementClient.delete(url + "/jmsra"); } - //Disable this test for now. The functionality this tests is not available in nucleus - //@Test + @Test public void test20810() { Map payload = new HashMap<>(); payload.put("persistenceScope","session"); @@ -238,21 +246,19 @@ public void test20810() { payload.put("ssoFailoverEnabled","false"); final String wcaUri = "/domain/configs/config/default-config/availability-service/web-container-availability"; - Response r = post(wcaUri, payload); - assertTrue(isSuccess(r)); + Response response = managementClient.post(wcaUri, payload); + assertThat(response.getStatus(), equalTo(200)); - assertTrue(isSuccess(get(wcaUri))); + assertThat(managementClient.get(wcaUri).getStatus(), equalTo(200)); - r = getClient() - .target(getAddress("/domain/configs/config/default-config/availability-service/web-container-availability/property")). - request(getResponseType()) - .post(Entity.json(new JSONArray()), Response.class); - assertTrue(isSuccess(r)); - - assertTrue(isSuccess(get(wcaUri))); + response = managementClient.post( + "/domain/configs/config/default-config/availability-service/web-container-availability/property", + Entity.json(new JSONArray())); + assertThat(response.getStatus(), equalTo(200)); + assertThat(managementClient.get(wcaUri).getStatus(), equalTo(200)); } - protected String buildPropertyList(List> props) { + private String buildPropertyList(List> props) { StringBuilder sb = new StringBuilder(); String sep = ""; for (Map prop : props) { @@ -263,81 +269,82 @@ protected String buildPropertyList(List> props) { return sb.toString(); } - protected void createAndDeleteProperties(String endpoint) { - Response response = get(endpoint); - checkStatusForSuccess(response); + private void createAndDeleteProperties(String endpoint) { + Response response = managementClient.get(endpoint); + assertEquals(200, response.getStatus()); assertNotNull(getProperties(response)); - List> properties = new ArrayList>(); + List> properties = new ArrayList<>(); for(int i = 0, max = generateRandomNumber(16); i < max; i++) { properties.add(createProperty("property_" + generateRandomString(), generateRandomString(), generateRandomString())); } createProperties(endpoint, properties); - response = delete(endpoint); - checkStatusForSuccess(response); + response = managementClient.delete(endpoint); + assertEquals(200, response.getStatus()); } - protected Map createProperty(final String name, final String value) { + private Map createProperty(final String name, final String value) { return createProperty(name, value, null); } - protected Map createProperty(final String name, final String value, final String description) { - return new HashMap() {{ - put ("name", name); - put ("value", value); + private Map createProperty(final String name, final String value, final String description) { + return new HashMap<>() { + { + put("name", name); + put("value", value); if (description != null) { - put ("description", description); + put("description", description); } - }}; + } + }; } - protected void createProperties(String endpoint, List> properties) { + private void createProperties(String endpoint, List> properties) { final String payload = buildPayload(properties); - Response response = getClient().target(getAddress(endpoint)) - .request(RESPONSE_TYPE) - .post(Entity.entity(payload, REQUEST_FORMAT), Response.class); - checkStatusForSuccess(response); - response = get(endpoint); - checkStatusForSuccess(response); + + Response response = managementClient.post(endpoint, Entity.entity(payload, APPLICATION_JSON)); + assertEquals(200, response.getStatus()); + response = managementClient.get(endpoint); + assertEquals(200, response.getStatus()); // Retrieve the properties and make sure they were created. -// List> newProperties = getProperties(response); -// -// for (Map property : properties) { -// assertTrue(isPropertyFound(newProperties, property.get("name"))); -// } + List> newProperties = getProperties(response); + for (Map property : properties) { + String name = property.get("name"); + String value = property.get("value"); + if (value == null || value.isBlank()) { + assertFalse(isPropertyFound(newProperties, name)); + } else { + assertTrue(isPropertyFound(newProperties, name)); + } + } } // Restore and verify the default domain properties - protected void restoreDomainProperties() { - final HashMap domainProps = new HashMap() {{ + private void restoreDomainProperties() { + final HashMap domainProps = new HashMap<>() {{ put("name", PROP_DOMAIN_NAME); put("value", "domain1"); }}; - Response response = getClient().target(getAddress(URL_DOMAIN_PROPERTIES)) - .request(RESPONSE_TYPE) - .put(Entity.entity(buildPayload(new ArrayList>() {{ add(domainProps); }}), REQUEST_FORMAT), Response.class); - checkStatusForSuccess(response); - response = get(URL_DOMAIN_PROPERTIES); - checkStatusForSuccess(response); + Response response = managementClient.put(URL_DOMAIN_PROPERTIES, + Entity.entity(buildPayload(List.of(domainProps)), APPLICATION_JSON)); + assertEquals(200, response.getStatus()); + response = managementClient.get(URL_DOMAIN_PROPERTIES); + assertEquals(200, response.getStatus()); assertTrue(isPropertyFound(getProperties(response), PROP_DOMAIN_NAME)); } - protected String buildPayload(List> properties) { - if (RESPONSE_TYPE.equals(MediaType.APPLICATION_XML)) { - return MarshallingUtils.getXmlForProperties(properties); - } else { - return MarshallingUtils.getJsonForProperties(properties); - } + private String buildPayload(List> properties) { + return MarshallingUtils.getJsonForProperties(properties); } - protected boolean isPropertyFound(List> properties, String name) { + private boolean isPropertyFound(List> properties, String name) { return getProperty(properties, name) != null; } - protected Map getProperty(List> properties, String name) { + private Map getProperty(List> properties, String name) { Map retval = null; for (Map property : properties) { if (name.equals(property.get("name"))) { diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ProvidersITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ProvidersITest.java new file mode 100644 index 00000000000..e911bcdd16b --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ProvidersITest.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; + +import org.glassfish.main.admin.test.tool.DomainAdminRestClient; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author jasonlee + */ +public class ProvidersITest extends RestTestBase { + private static final String URL_ACTION_REPORT_RESULT = "/domain/uptime"; + private static final String URL_COMMAND_RESOURCE_GET_RESULT = "/domain/stop"; + private static final String URL_GET_RESULT = "/domain"; + private static final String URL_GET_RESULT_LIST = "/domain/servers/server"; + private static final String URL_OPTIONS_RESULT = "/domain"; + private static final String URL_STRING_LIST_RESULT = "/domain/configs/config/server-config/java-config/jvm-options"; + + private static DomainAdminRestClient monitoringClient; + + @BeforeAll + public static void init() { + monitoringClient = new DomainAdminRestClient(getBaseAdminUrl() + "/monitoring/domain"); + } + + + @AfterAll + public static void closeResources() { + if (monitoringClient != null) { + monitoringClient.close(); + } + } + + @Test + public void testActionReportResultHtmlProvider() { + Response response = managementClient.get(URL_ACTION_REPORT_RESULT + ".html"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testActionReportResultXmlProvider() { + Response response = managementClient.get(URL_ACTION_REPORT_RESULT + ".xml"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testActionReportResultJsonProvider() { + Response response = managementClient.get(URL_ACTION_REPORT_RESULT + ".json"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testCommandResourceGetResultHtmlProvider() { + Response response = managementClient.get(URL_COMMAND_RESOURCE_GET_RESULT + ".html"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testCommandResourceGetResultXmlProvider() { + Response response = managementClient.get(URL_COMMAND_RESOURCE_GET_RESULT + ".xml"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testCommandResourceGetResultJsonProvider() { + Response response = managementClient.get(URL_COMMAND_RESOURCE_GET_RESULT + ".json"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testGetResultHtmlProvider() { + Response response = managementClient.get(URL_GET_RESULT + ".html"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testGetResultXmlProvider() { + Response response = managementClient.get(URL_GET_RESULT + ".xml"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testGetResultJsonProvider() { + Response response = managementClient.get(URL_GET_RESULT + ".json"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testGetResultListHtmlProvider() { + Response response = managementClient.get(URL_GET_RESULT_LIST + ".html"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testGetResultListXmlProvider() { + Response response = managementClient.get(URL_GET_RESULT_LIST + ".xml"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testGetResultListJsonProvider() { + Response response = managementClient.get(URL_GET_RESULT_LIST + ".json"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testOptionsResultXmlProvider() { + Response response = managementClient.options(URL_OPTIONS_RESULT + ".xml"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testOptionsResultJsonProvider() { + Response response = managementClient.options(URL_OPTIONS_RESULT + ".json"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testStringListResultHtmlProvider() { + Response response = managementClient.get(URL_STRING_LIST_RESULT + ".html"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testStringListResultXmlProvider() { + Response response = managementClient.get(URL_STRING_LIST_RESULT + ".xml"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testStringListResultJsonProvider() { + Response response = managementClient.get(URL_STRING_LIST_RESULT + ".json"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testTreeNodeHtmlProvider() { + Response response = monitoringClient.get(".html"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testTreeNodeXmlProvider() { + Response response = monitoringClient.get(".xml"); + assertEquals(200, response.getStatus()); + } + + @Test + public void testTreeNodeJsonProvider() { + Response response = monitoringClient.get(".json"); + assertEquals(200, response.getStatus()); + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ResourceRefITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ResourceRefITest.java new file mode 100644 index 00000000000..14c2d70ea1d --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ResourceRefITest.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; + +import java.util.HashMap; +import java.util.Map; + +import org.glassfish.main.admin.test.tool.asadmin.Asadmin; +import org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author jasonlee + */ +public class ResourceRefITest extends RestTestBase { + private static final String URL_CREATE_INSTANCE = "/domain/create-instance"; + private static final String URL_JDBC_RESOURCE = "/domain/resources/jdbc-resource"; + private static final String URL_RESOURCE_REF = "/domain/servers/server/server/resource-ref"; + + private final String instanceName = "instance_" + generateRandomString(); + private final String jdbcResourceName = "jdbc_" + generateRandomString(); + + @AfterEach + public void cleanup() { + Asadmin asadmin = GlassFishTestEnvironment.getAsadmin(); + asadmin.exec("delete-resource-ref", jdbcResourceName); + asadmin.exec("delete-jdbc-resource", jdbcResourceName); + asadmin.exec("delete-instance", instanceName); + } + + + @Test + public void testCreatingResourceRef() { + Map newInstance = new HashMap<>() {{ + put("id", instanceName); + put("node", "localhost-domain1"); + }}; + Map jdbcResource = new HashMap<>() {{ + put("id", jdbcResourceName); + put("connectionpoolid", "DerbyPool"); + put("target", instanceName); + }}; + Map resourceRef = new HashMap<>() {{ + put("id", jdbcResourceName); + put("target", "server"); + }}; + + Response response = managementClient.post(URL_CREATE_INSTANCE, newInstance); + assertEquals(200, response.getStatus()); + + response = managementClient.post(URL_JDBC_RESOURCE, jdbcResource); + assertEquals(200, response.getStatus()); + + response = managementClient.post(URL_RESOURCE_REF, resourceRef); + assertEquals(200, response.getStatus()); + response = managementClient.delete( + "/domain/servers/server/" + instanceName + "/resource-ref/" + jdbcResourceName, + Map.of("target", instanceName)); + assertEquals(200, response.getStatus()); + response = managementClient.get("/domain/servers/server/" + instanceName + "/resource-ref/" + jdbcResourceName); + assertEquals(404, response.getStatus()); + + response = managementClient.delete(URL_JDBC_RESOURCE + "/" + jdbcResourceName); + assertEquals(200, response.getStatus()); + response = managementClient.get(URL_JDBC_RESOURCE + "/" + jdbcResourceName); + assertEquals(404, response.getStatus()); + + response = managementClient.delete("/domain/servers/server/" + instanceName + "/delete-instance"); + assertEquals(200, response.getStatus()); + response = managementClient.get("/domain/servers/server/" + instanceName); + assertEquals(404, response.getStatus()); + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/RestTestBase.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/RestTestBase.java new file mode 100644 index 00000000000..fa5a84a4d08 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/RestTestBase.java @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.glassfish.admin.rest.client.utils.MarshallingUtils; +import org.glassfish.main.admin.test.tool.DomainAdminRestClient; +import org.glassfish.main.admin.test.webapp.HelloServlet; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.exporter.ZipExporter; +import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.TestInfo; + +import static jakarta.ws.rs.core.MediaType.TEXT_PLAIN; +import static org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment.getTargetDirectory; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class RestTestBase { + + private static final Logger LOG = Logger.getLogger(RestTestBase.class.getName()); + + protected static final String CONTEXT_ROOT_MANAGEMENT = "/management"; + + protected static final String URL_CLUSTER = "/domain/clusters/cluster"; + protected static final String URL_APPLICATION_DEPLOY = "/domain/applications/application"; + protected static final String URL_CREATE_INSTANCE = "/domain/create-instance"; + protected static final String URL_CONFIGS = "/domain/configs"; + protected static final String URL_JDBC_RESOURCE = "/domain/resources/jdbc-resource"; + protected static final String URL_JDBC_CONNECTION_POOL = "/domain/resources/jdbc-connection-pool"; + + private static String baseAdminUrl; + private static String baseInstanceUrl; + protected static DomainAdminRestClient managementClient; + + private Client client; + + @BeforeAll + public static void initialize() { + baseAdminUrl = "http://localhost:4848"; + baseInstanceUrl = "http://localhost:8080"; + managementClient = new DomainAdminRestClient(baseAdminUrl + CONTEXT_ROOT_MANAGEMENT); + Response response = managementClient.get("/domain/rotate-log"); + assertThat(response.getStatus(), equalTo(200)); + } + + @AfterAll + public static void captureLogAndCloseClient(final TestInfo testInfo) throws Exception { + if (managementClient != null) { + managementClient.close(); + } + try (DomainAdminRestClient client = new DomainAdminRestClient(baseAdminUrl + CONTEXT_ROOT_MANAGEMENT, TEXT_PLAIN)) { + Response response = client.get("/domain/view-log"); + assertThat(response.getStatus(), equalTo(200)); + File directory = new File(getTargetDirectory(), "surefire-reports"); + directory.mkdirs(); + File output = new File(directory, testInfo.getTestClass().get().getName() + "-server.log"); + try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(output)))) { + out.write(response.readEntity(String.class)); + } + } + } + + @AfterEach + protected void closeClient() throws Exception { + if (client == null) { + return; + } + client.close(); + client = null; + } + + public void createAndVerifyConfig(String configName, MultivaluedMap configData) { + Response response = managementClient.post(URL_CONFIGS + "/copy-config", configData); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.get(URL_CONFIGS + "/config/" + configName); + assertThat(response.getStatus(), equalTo(200)); + } + + public void deleteAndVerifyConfig(String configName) { + Response response = managementClient.post(URL_CONFIGS + "/config/" + configName + "/delete-config"); + assertThat(response.getStatus(), equalTo(200)); + + response = managementClient.get(URL_CONFIGS + "/config/" + configName); + assertThat(response.getStatus(), equalTo(404)); + } + + public String createCluster() { + final String clusterName = "cluster_" + generateRandomString(); + createCluster(clusterName); + return clusterName; + } + + public void createCluster(final String clusterName) { + Map newCluster = Map.of("id", clusterName); + Response response = managementClient.post(URL_CLUSTER, newCluster); + assertThat(response.getStatus(), equalTo(200)); + } + + public void startCluster(String clusterName) { + Response response = managementClient.post(URL_CLUSTER + "/" + clusterName + "/start-cluster"); + assertThat(response.getStatus(), equalTo(200)); + } + + public void stopCluster(String clusterName) { + Response response = managementClient.post(URL_CLUSTER + "/" + clusterName + "/stop-cluster"); + assertThat(response.getStatus(), equalTo(200)); + } + + public void createClusterInstance(final String clusterName, final String instanceName) { + Response response = managementClient.post("/domain/create-instance", + Map.of("cluster", clusterName, "id", instanceName, "node", "localhost-domain1")); + assertThat(response.getStatus(), equalTo(200)); + } + + public void deleteCluster(String clusterName) { + Response response = managementClient.get(URL_CLUSTER + "/" + clusterName + "/list-instances"); + Map body = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); + Map extraProperties = (Map) body.get("extraProperties"); + if (extraProperties != null) { + List> instanceList = (List>) extraProperties.get("instanceList"); + LOG.log(Level.INFO, "Found instances: {0}", instanceList); + if (instanceList != null && !instanceList.isEmpty()) { + for (Map instance : instanceList) { + String instanceName = instance.get("name"); + response = managementClient.post("/domain/servers/server/" + instanceName + "/stop-instance"); + assertThat(instanceName, response.getStatus(), equalTo(200)); + response = managementClient.delete("/domain/servers/server/" + instanceName + "/delete-instance"); + assertThat(instanceName, response.getStatus(), equalTo(200)); + } + } + } + response = managementClient.delete(URL_CLUSTER + "/" + clusterName); + assertEquals(200, response.getStatus()); + response = managementClient.get(URL_CLUSTER + "/" + clusterName); + assertEquals(404, response.getStatus()); + } + + public Map deployApp(final File archive, final String contextRoot, final String name) { + Map app = Map.of( + "id", archive, + "contextroot", contextRoot, + "name", name + ); + Response response = managementClient.postWithUpload(URL_APPLICATION_DEPLOY, app); + assertThat(response.getStatus(), equalTo(200)); + return getEntityValues(managementClient.get(URL_APPLICATION_DEPLOY + "/" + app.get("name"))); + } + + public void addAppRef(final String applicationName, final String targetName){ + Response response = managementClient.post("/domain/servers/server/" + targetName + "/application-ref", + Map.of("id", applicationName, "target", targetName)); + assertThat(response.getStatus(), equalTo(200)); + } + + public Response undeployApp(String appName) { + Response response = managementClient.delete(URL_APPLICATION_DEPLOY + "/" + appName); + assertThat(response.getStatus(), equalTo(200)); + return response; + } + + protected static String generateRandomString() { + SecureRandom random = new SecureRandom(); + return new BigInteger(130, random).toString(16); + } + + protected static int generateRandomNumber() { + Random r = new Random(); + return Math.abs(r.nextInt()) + 1; + } + + protected int generateRandomNumber(int max) { + Random r = new Random(); + return Math.abs(r.nextInt(max - 1)) + 1; + } + + protected static String getBaseAdminUrl() { + return baseAdminUrl; + } + + protected static String getBaseInstanceUrl() { + return baseInstanceUrl; + } + + + /** + * This method will parse the provided XML document and return a map of the attributes and values on the root + * element + * + * @param response + * @return + */ + protected Map getEntityValues(Response response) { + String xml = response.readEntity(String.class); + Map responseMap = MarshallingUtils.buildMapFromDocument(xml); + if (responseMap == null) { + return null; + } + Map obj = (Map) responseMap.get("extraProperties"); + if (obj == null) { + return null; + } + return (Map) obj.get("entity"); + } + + protected List getCommandResults(Response response) { + String document = response.readEntity(String.class); + List results = new ArrayList<>(); + Map map = MarshallingUtils.buildMapFromDocument(document); + String message = (String) map.get("message"); + if (message != null && !"".equals(message)) { + results.add(message); + } + Object children = map.get("children"); + if (children instanceof List) { + for (Object child : (List) children) { + Map childMap = (Map) child; + message = (String) childMap.get("message"); + if (message != null) { + results.add(message); + } + } + } + return results; + } + + protected Map getChildResources(Response response) { + Map responseMap = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); + LOG.log(Level.INFO, "responseMap: \n{0}", responseMap); + Map extraProperties = (Map) responseMap.get("extraProperties"); + if (extraProperties != null) { + return extraProperties.get("childResources"); + } + + return new HashMap<>(); + } + + + protected List> getProperties(Response response) { + Map responseMap = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); + Map extraProperties = (Map) responseMap.get("extraProperties"); + if (extraProperties != null) { + return (List>) extraProperties.get("properties"); + } + return new ArrayList<>(); + } + + + protected static File getEar(final String appName) { + final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class).addAsModule(getWar(appName), "simple.war"); + LOG.info(ear.toString(true)); + try { + File tempFile = File.createTempFile(appName, ".ear"); + ear.as(ZipExporter.class).exportTo(tempFile, true); + return tempFile; + } catch (IOException e) { + throw new IllegalStateException("Deployment failed - cannot load the input archive!", e); + } + } + + protected static File getWar(final String appName) { + final WebArchive war = ShrinkWrap.create(WebArchive.class).addPackage(HelloServlet.class.getPackage()); + LOG.info(war.toString(true)); + try { + File tempFile = File.createTempFile(appName, ".war"); + war.as(ZipExporter.class).exportTo(tempFile, true); + return tempFile; + } catch (IOException e) { + throw new IllegalStateException("Deployment failed - cannot load the input archive!", e); + } + } +} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/SystemPropertiesTest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/SystemPropertiesITest.java similarity index 55% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/SystemPropertiesTest.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/SystemPropertiesITest.java index 66d83802cbb..2211a03ed62 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/SystemPropertiesTest.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/SystemPropertiesITest.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -14,21 +15,24 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package org.glassfish.nucleus.admin.rest; +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Response; import java.util.HashMap; import java.util.List; import java.util.Map; -import jakarta.ws.rs.core.Response; -import org.glassfish.admin.rest.client.utils.MarshallingUtils; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; + +import org.junit.jupiter.api.Test; + +import static org.glassfish.admin.rest.client.utils.MarshallingUtils.buildMapFromDocument; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** - * * @author jasonlee */ -public class SystemPropertiesTest extends RestTestBase { +public class SystemPropertiesITest extends RestTestBase { public static final String URL_CONFIG_SYSTEM_PROPERTIES = "/domain/configs/config/%config%/system-properties"; public static final String URL_CLUSTER_SYSTEM_PROPERTIES = "/domain/clusters/cluster/%clusterName%/system-properties"; public static final String URL_INSTANCE_SYSTEM_PROPERTIES = "/domain/servers/server/%instanceName%/system-properties"; @@ -38,29 +42,35 @@ public class SystemPropertiesTest extends RestTestBase { @Test public void getSystemProperties() { - Response response = get(URL_DAS_SYSTEM_PROPERTIES); - checkStatusForSuccess(response); - List> systemProperties = getSystemProperties(MarshallingUtils.buildMapFromDocument(response.readEntity(String.class))); - assertNotNull(systemProperties); // This may or may not be empty, depending on whether or not other tests failed + Response response = managementClient.get(URL_DAS_SYSTEM_PROPERTIES); + assertEquals(200, response.getStatus()); + List> systemProperties = getSystemProperties( + buildMapFromDocument(response.readEntity(String.class))); + assertNotNull(systemProperties); } + @Test public void createSystemProperties() { final String prop1 = "property" + generateRandomString(); final String prop2 = "property" + generateRandomString(); - Map payload = new HashMap() {{ - put(prop1, "value1"); - put(prop2, "value2"); - }}; - Response response = post(URL_DAS_SYSTEM_PROPERTIES, payload); - checkStatusForSuccess(response); - response = get(URL_DAS_SYSTEM_PROPERTIES); - List> systemProperties = getSystemProperties(MarshallingUtils.buildMapFromDocument(response.readEntity(String.class))); - assertNotNull(systemProperties); // This may or may not be empty, depending on whether or not other tests failed + Map payload = new HashMap<>() { + + { + put(prop1, "value1"); + put(prop2, "value2"); + } + }; + Response response = managementClient.post(URL_DAS_SYSTEM_PROPERTIES, payload); + assertEquals(200, response.getStatus()); + response = managementClient.get(URL_DAS_SYSTEM_PROPERTIES); + List> systemProperties = getSystemProperties( + buildMapFromDocument(response.readEntity(String.class))); + assertNotNull(systemProperties); int testPropsFound = 0; for (Map systemProperty : systemProperties) { - String name = (String)systemProperty.get("name"); + String name = systemProperty.get("name"); if (prop1.equals(name) || prop2.equals(name)) { testPropsFound++; } @@ -68,27 +78,28 @@ public void createSystemProperties() { assertEquals(2, testPropsFound); - response = delete(URL_DAS_SYSTEM_PROPERTIES+"/"+prop1); - checkStatusForSuccess(response); - response = delete(URL_DAS_SYSTEM_PROPERTIES+"/"+prop2); - checkStatusForSuccess(response); + response = managementClient.delete(URL_DAS_SYSTEM_PROPERTIES+"/"+prop1); + assertEquals(200, response.getStatus()); + response = managementClient.delete(URL_DAS_SYSTEM_PROPERTIES+"/"+prop2); + assertEquals(200, response.getStatus()); } @Test public void createPropertiesWithColons() { final String prop1 = "property" + generateRandomString(); - Map payload = new HashMap() {{ + Map payload = new HashMap<>() {{ put(prop1, "http://localhost:4848"); }}; - Response response = post(URL_DAS_SYSTEM_PROPERTIES, payload); - checkStatusForSuccess(response); - response = get(URL_DAS_SYSTEM_PROPERTIES); - List> systemProperties = getSystemProperties(MarshallingUtils.buildMapFromDocument(response.readEntity(String.class))); - assertNotNull(systemProperties); // This may or may not be empty, depending on whether or not other tests failed + Response response = managementClient.post(URL_DAS_SYSTEM_PROPERTIES, payload); + assertEquals(200, response.getStatus()); + response = managementClient.get(URL_DAS_SYSTEM_PROPERTIES); + List> systemProperties = getSystemProperties( + buildMapFromDocument(response.readEntity(String.class))); + assertNotNull(systemProperties); int testPropsFound = 0; for (Map systemProperty : systemProperties) { - String name = (String)systemProperty.get("name"); + String name = systemProperty.get("name"); if (prop1.equals(name)) { testPropsFound++; } @@ -96,118 +107,107 @@ public void createPropertiesWithColons() { assertEquals(1, testPropsFound); - response = delete(URL_DAS_SYSTEM_PROPERTIES+"/"+prop1); - checkStatusForSuccess(response); + response = managementClient.delete(URL_DAS_SYSTEM_PROPERTIES + "/" + prop1); + assertEquals(200, response.getStatus()); } @Test public void testNotResolvingDasSystemProperties() { final String prop1 = "property" + generateRandomString(); - Map payload = new HashMap() {{ - put(prop1, PROP_VALUE); - }}; createAndTestConfigProperty(prop1, PROP_VALUE, "server-config"); createAndTestInstanceOverride(prop1, PROP_VALUE, PROP_VALUE+"-instace", "server"); } - @Test() + @Test public void testNotResolvingDasInstanceProperties() { final String instanceName = "in" + generateRandomNumber(); final String propertyName = "property" + generateRandomString(); - Response cr = post(URL_CREATE_INSTANCE, new HashMap() {{ - put("id", instanceName); - put("node", "localhost-domain1"); - }}); - checkStatusForSuccess(cr); + Response response = managementClient.post(URL_CREATE_INSTANCE, Map.of("id", instanceName, "node", "localhost-domain1")); + assertEquals(200, response.getStatus()); createAndTestConfigProperty(propertyName, PROP_VALUE, instanceName + "-config"); - createAndTestInstanceOverride(propertyName, PROP_VALUE, PROP_VALUE + "-instance", instanceName); } - @Test() + @Test public void testNotResolvingClusterProperties() { final String propertyName = "property" + generateRandomString(); - final String clusterName = "c" + generateRandomNumber(); - final String instanceName = clusterName + "in" + generateRandomNumber(); - ClusterTest ct = new ClusterTest(); - ct.setup(); - ct.createCluster(clusterName); - ct.createClusterInstance(clusterName, instanceName); + final String clusterName = "cluster_" + generateRandomNumber(); + final String instanceName = clusterName + "_instance_" + generateRandomNumber(); + createCluster(clusterName); + createClusterInstance(clusterName, instanceName); createAndTestConfigProperty(propertyName, PROP_VALUE, clusterName + "-config"); createAndTestClusterOverride(propertyName, PROP_VALUE, PROP_VALUE + "-cluster", clusterName); createAndTestInstanceOverride(propertyName, PROP_VALUE+"-cluster", PROP_VALUE + "-instance", instanceName); - ct.deleteCluster(clusterName); + deleteCluster(clusterName); } - protected void createAndTestConfigProperty(final String propertyName, final String propertyValue, String configName) { + private void createAndTestConfigProperty(final String propertyName, final String propertyValue, String configName) { final String url = URL_CONFIG_SYSTEM_PROPERTIES.replaceAll("%config%", configName); - Response response = get(url); - Map payload = getSystemPropertiesMap(getSystemProperties(MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)))); + Response response = managementClient.get(url); + Map payload = getSystemPropertiesMap(getSystemProperties(buildMapFromDocument(response.readEntity(String.class)))); payload.put(propertyName, propertyValue); - response = post(url, payload); - checkStatusForSuccess(response); + response = managementClient.post(url, payload); + assertEquals(200, response.getStatus()); - // Check config props - response = get(url); - List> systemProperties = getSystemProperties(MarshallingUtils.buildMapFromDocument(response.readEntity(String.class))); + response = managementClient.get(url); + List> systemProperties = getSystemProperties(buildMapFromDocument(response.readEntity(String.class))); Map sysProp = getSystemProperty(propertyName, systemProperties); assertNotNull(sysProp); - assertEquals(sysProp.get("value"), propertyValue); + assertEquals(propertyValue, sysProp.get("value")); } - protected void createAndTestClusterOverride(final String propertyName, final String defaultValue, final String propertyValue, final String clusterName) { + private void createAndTestClusterOverride(final String propertyName, final String defaultValue, final String propertyValue, final String clusterName) { final String clusterSysPropsUrl = URL_CLUSTER_SYSTEM_PROPERTIES.replaceAll("%clusterName%", clusterName); - Response response = get(clusterSysPropsUrl); - List> systemProperties = getSystemProperties(MarshallingUtils.buildMapFromDocument(response.readEntity(String.class))); + Response response = managementClient.get(clusterSysPropsUrl); + List> systemProperties = getSystemProperties(buildMapFromDocument(response.readEntity(String.class))); Map sysProp = getSystemProperty(propertyName, systemProperties); assertNotNull(sysProp); assertEquals(sysProp.get("defaultValue"), defaultValue); - response = post(clusterSysPropsUrl, new HashMap() {{ - put(propertyName, propertyValue); - }}); - checkStatusForSuccess(response); + response = managementClient.post(clusterSysPropsUrl, Map.of(propertyName, propertyValue)); + assertEquals(200, response.getStatus()); // Check updated/overriden system property - response = get(clusterSysPropsUrl); - systemProperties = getSystemProperties(MarshallingUtils.buildMapFromDocument(response.readEntity(String.class))); + response = managementClient.get(clusterSysPropsUrl); + systemProperties = getSystemProperties(buildMapFromDocument(response.readEntity(String.class))); sysProp = getSystemProperty(propertyName, systemProperties); assertNotNull(sysProp); assertEquals(sysProp.get("value"), propertyValue); assertEquals(sysProp.get("defaultValue"), defaultValue); } - protected void createAndTestInstanceOverride(final String propertyName, final String defaultValue, final String propertyValue, final String instanceName) { + private void createAndTestInstanceOverride(final String propertyName, final String defaultValue, final String propertyValue, final String instanceName) { final String instanceSysPropsUrl = URL_INSTANCE_SYSTEM_PROPERTIES.replaceAll("%instanceName%", instanceName); - Response response = get(instanceSysPropsUrl); - List> systemProperties = getSystemProperties(MarshallingUtils.buildMapFromDocument(response.readEntity(String.class))); + Response response = managementClient.get(instanceSysPropsUrl); + List> systemProperties = getSystemProperties(buildMapFromDocument(response.readEntity(String.class))); Map sysProp = getSystemProperty(propertyName, systemProperties); assertNotNull(sysProp); assertEquals(sysProp.get("defaultValue"), defaultValue); - response = post(instanceSysPropsUrl, new HashMap() {{ - put(propertyName, propertyValue); - }}); - checkStatusForSuccess(response); + response = managementClient.post(instanceSysPropsUrl, Map.of(propertyName, propertyValue)); + assertEquals(200, response.getStatus()); // Check updated/overriden system property - response = get(instanceSysPropsUrl); - systemProperties = getSystemProperties(MarshallingUtils.buildMapFromDocument(response.readEntity(String.class))); + response = managementClient.get(instanceSysPropsUrl); + systemProperties = getSystemProperties(buildMapFromDocument(response.readEntity(String.class))); sysProp = getSystemProperty(propertyName, systemProperties); assertNotNull(sysProp); - assertEquals(sysProp.get("value"), propertyValue); - assertEquals(sysProp.get("defaultValue"), defaultValue); + assertEquals(propertyValue, sysProp.get("value")); + assertEquals(defaultValue, sysProp.get("defaultValue")); } - private List> getSystemProperties(Map responseMap) { - Map extraProperties = (Map)responseMap.get("extraProperties"); - return (List>)extraProperties.get("systemProperties"); + private List> getSystemProperties(Map map) { + Map extraProperties = (Map) map.get("extraProperties"); + if (extraProperties == null) { + return null; + } + return (List>) extraProperties.get("systemProperties"); } private Map getSystemProperty(String propName, List> systemProperties) { @@ -221,7 +221,10 @@ private Map getSystemProperty(String propName, List getSystemPropertiesMap (List> propsList) { - Map allPropsMap = new HashMap(); + if (propsList == null) { + return new HashMap<>(); + } + Map allPropsMap = new HashMap<>(); for (Map sysProp : propsList) { allPropsMap.put(sysProp.get("name"), sysProp.get("value")); } diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/TokenAuthenticationITest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/TokenAuthenticationITest.java new file mode 100644 index 00000000000..13bd63f6888 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/TokenAuthenticationITest.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.rest; + +import jakarta.ws.rs.core.Cookie; +import jakarta.ws.rs.core.Response; + +import java.util.Map; + +import org.glassfish.admin.rest.client.ClientWrapper; +import org.glassfish.admin.rest.client.utils.MarshallingUtils; +import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; +import org.glassfish.main.admin.test.tool.DomainAdminRestClient; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; + +import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * @author Mitesh Meswani + */ +public class TokenAuthenticationITest extends RestTestBase { + private static final String URL_DOMAIN_SESSIONS = "/sessions"; + private static final String URL_CREATE_USER = "/domain/configs/config/server-config/security-service/auth-realm/admin-realm/create-user"; + private static final String URL_DELETE_USER = "/domain/configs/config/server-config/security-service/auth-realm/admin-realm/delete-user"; + private static final String GF_REST_TOKEN_COOKIE_NAME = "gfresttoken"; + + private static final String AUTH_USER_NAME = "dummyuser"; + private static final String AUTH_PASSWORD = "dummypass"; + private static final HttpAuthenticationFeature AUTH_DUMMY = HttpAuthenticationFeature.basic(AUTH_USER_NAME, AUTH_PASSWORD); + + @AfterAll + public static void cleanup() { + managementClient.delete(URL_DELETE_USER, Map.of("id", AUTH_USER_NAME)); + } + + + @Test + public void testTokenCreateAndDelete() { + String token = getSessionToken(managementClient); + assertNotNull(token, "token"); + + // Verify we can use the session token. + Response response = managementClient.getRequestBuilder("/domain") + .cookie(new Cookie(GF_REST_TOKEN_COOKIE_NAME, token)).get(Response.class); + assertEquals(200, response.getStatus()); + + // Delete the token + response = managementClient.getRequestBuilder(URL_DOMAIN_SESSIONS + "/" + token) + .cookie(new Cookie(GF_REST_TOKEN_COOKIE_NAME, token)).delete(Response.class); + managementClient.delete(URL_DOMAIN_SESSIONS); + assertEquals(200, response.getStatus()); + } + + + @Test + public void testAuthRequired() { + Response delResponse = managementClient.delete(URL_DELETE_USER, Map.of("id", AUTH_USER_NAME)); + // as of gf6 any error means 500. The user doesn't exist. + assertEquals(500, delResponse.getStatus()); + + try (DummyClient client = new DummyClient()) { + Response response = client.get("/domain"); + assertEquals(401, response.getStatus()); + } + { + // Create the new user + Map newUser = Map.of( + "id", AUTH_USER_NAME, + "groups", "asadmin", + "authrealmname", "admin-realm", + "AS_ADMIN_USERPASSWORD", AUTH_PASSWORD + ); + Response createUserResponse = managementClient.post(URL_CREATE_USER, newUser); + assertEquals(200, createUserResponse.getStatus()); + } + try (AnonymousClient client = new AnonymousClient()) { + Response response = client.getRequestBuilder("/domain").get(Response.class); + assertEquals(401, response.getStatus()); + } + final String token; + try (DummyClient dummyClient = new DummyClient()) { + token = getSessionToken(dummyClient); + } + + try (CookieClient cookieClient = new CookieClient(token)) { + Response response = cookieClient.get("/domain"); + assertEquals(200, response.getStatus()); + } + try (AnonymousClient client = new AnonymousClient()) { + Response response = client.getRequestBuilder("/domain").get(Response.class); + assertEquals(401, response.getStatus()); + } + try (CookieClient cookieClient = new CookieClient(token)) { + Response response = cookieClient.delete(URL_DELETE_USER, Map.of("id", AUTH_USER_NAME)); + assertEquals(200, response.getStatus()); + } + } + + + private String getSessionToken(DomainAdminRestClient client) { + Response response = client.post(URL_DOMAIN_SESSIONS); + assertEquals(200, response.getStatus()); + Map responseMap = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); + Map extraProperties = (Map) responseMap.get("extraProperties"); + return (String) extraProperties.get("token"); + } + + + private static final class AnonymousClient extends DomainAdminRestClient { + + public AnonymousClient() { + super(new ClientWrapper(), managementClient.getBaseUrl(), APPLICATION_JSON); + } + } + + + private static final class DummyClient extends DomainAdminRestClient { + + public DummyClient() { + super(createClient(), managementClient.getBaseUrl(), APPLICATION_JSON); + } + + private static ClientWrapper createClient() { + ClientWrapper client = new ClientWrapper(); + client.register(AUTH_DUMMY); + return client; + } + } + + + private static final class CookieClient extends DomainAdminRestClient { + + private final String securityCookie; + + public CookieClient(final String securityCookie) { + super(new ClientWrapper(), managementClient.getBaseUrl(), APPLICATION_JSON); + this.securityCookie = securityCookie; + } + + @Override + public Response delete(final String relativePath, final Map queryParams) { + return getTarget(relativePath, queryParams).request() + .cookie(new Cookie(GF_REST_TOKEN_COOKIE_NAME, securityCookie)).delete(Response.class); + } + + + @Override + public Response get(final String relativePath, final Map queryParams) { + return getTarget(relativePath, queryParams).request() + .cookie(new Cookie(GF_REST_TOKEN_COOKIE_NAME, securityCookie)).get(Response.class); + } + + } +} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ZeroConfigTest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ZeroConfigITest.java similarity index 74% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ZeroConfigTest.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ZeroConfigITest.java index 6380a083e66..103ebda25c0 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ZeroConfigTest.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/rest/ZeroConfigITest.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -14,12 +15,16 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package org.glassfish.nucleus.admin.rest; +package org.glassfish.main.admin.test.rest; -import java.util.Map; import jakarta.ws.rs.core.Response; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; + +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * This class will test that the zero-config effort is handled correctly by the @@ -31,17 +36,18 @@ * data. * @author jdlee */ -public class ZeroConfigTest extends RestTestBase { +public class ZeroConfigITest extends RestTestBase { public static final String BASE_SERVER_CONFIG_URL = "/domain/configs/config/server-config"; + /** * Currently (6/29/2012), the transaction-service element is missing from - * server-config out of the box. This should continue to be the case once + * server-config stdOut of the box. This should continue to be the case once * zero-config is fully implemented and integrated. */ - @Test(enabled=false) + @Test public void testTransactionService() { - final Response response = get(BASE_SERVER_CONFIG_URL + "/transaction-service"); - assertTrue(isSuccess(response)); + final Response response = managementClient.get(BASE_SERVER_CONFIG_URL + "/transaction-service"); + assertEquals(200, response.getStatus()); Map entity = getEntityValues(response); assertNotNull(entity); } diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/AsadminResultMatcher.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/AsadminResultMatcher.java new file mode 100644 index 00000000000..5e7ef0d3efe --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/AsadminResultMatcher.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Eclipse Foundation and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.tool; + +import org.glassfish.main.admin.test.tool.asadmin.Asadmin; +import org.glassfish.main.admin.test.tool.asadmin.AsadminResult; +import org.hamcrest.CustomTypeSafeMatcher; + + +/** + * Matcher checking that {@link Asadmin} command succeeded. Prints it's output otherwise. + * + * @author David Matejcek + */ +public class AsadminResultMatcher extends CustomTypeSafeMatcher { + + private AsadminResultMatcher() { + super("asadmin succeeded"); + } + + + @Override + protected boolean matchesSafely(AsadminResult item) { + return !item.isError(); + } + + + /** + * @return matcher checking that {@link Asadmin} command succeeded. Prints it's output otherwise. + */ + public static AsadminResultMatcher asadminOK() { + return new AsadminResultMatcher(); + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/DomainAdminRestClient.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/DomainAdminRestClient.java new file mode 100644 index 00000000000..280b0008dc2 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/DomainAdminRestClient.java @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2022 Eclipse Foundation and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.tool; + +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation.Builder; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; + +import java.io.Closeable; +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.glassfish.admin.rest.client.ClientWrapper; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.glassfish.main.admin.test.tool.asadmin.GlassFishTestEnvironment; + +import static jakarta.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED; + +/** + * @author David Matejcek + */ +public class DomainAdminRestClient implements Closeable { + + private final ClientWrapper client; + private final String baseUrl; + private final String responseType; + + public DomainAdminRestClient(final String baseUrl) { + this(baseUrl, MediaType.APPLICATION_JSON); + } + + + public DomainAdminRestClient(final String baseUrl, final String responseType) { + this(GlassFishTestEnvironment.createClient(), baseUrl, responseType); + } + + + public DomainAdminRestClient(final ClientWrapper client, final String baseUrl, final String responseType) { + this.client = client; + this.baseUrl = baseUrl; + this.responseType = responseType; + } + + + /** + * @return http://localhost:4848/management or something else, see constructor. + */ + public final String getBaseUrl() { + return baseUrl; + } + + + public Response options(final String relativePath) { + return getRequestBuilder(relativePath).options(Response.class); + } + + + public Response get(final String relativePath) { + return get(relativePath, new HashMap()); + } + + + public Response get(final String relativePath, final Map queryParams) { + final WebTarget target = getTarget(relativePath, queryParams); + return target.request(responseType).get(Response.class); + } + + public Response put(final String relativePath, final Entity entityPayload) { + return getRequestBuilder(relativePath).put(entityPayload, Response.class); + } + + + public Response post(final String relativePath) { + return getRequestBuilder(relativePath).post(Entity.entity(null, APPLICATION_FORM_URLENCODED), Response.class); + } + + + public Response post(final String relativePath, final Map payload) { + return post(relativePath, buildMultivaluedMap(payload)); + } + + + public Response post(final String relativePath, final MultivaluedMap payload) { + return getRequestBuilder(relativePath).post(Entity.entity(payload, APPLICATION_FORM_URLENCODED), Response.class); + } + + + public Response post(final String relativePath, final Entity entityPayload) { + return getRequestBuilder(relativePath).post(entityPayload, Response.class); + } + + public Response postWithUpload(final String relativePath, final Map payload) { + final FormDataMultiPart form = new FormDataMultiPart(); + for (final Map.Entry entry : payload.entrySet()) { + if (entry.getValue() instanceof File) { + form.getBodyParts().add((new FileDataBodyPart(entry.getKey(), (File) entry.getValue()))); + } else { + form.field(entry.getKey(), entry.getValue(), MediaType.TEXT_PLAIN_TYPE); + } + } + return getRequestBuilder(relativePath).post(Entity.entity(form, MediaType.MULTIPART_FORM_DATA), Response.class); + } + + + public Response delete(final String relativePath) { + return delete(relativePath, new HashMap()); + } + + public Response delete(final String relativePath, final Map queryParams) { + final WebTarget target = getTarget(relativePath, queryParams); + return target.request(responseType).delete(Response.class); + } + + + public Builder getRequestBuilder(final String relativePath) { + return getTarget(relativePath, null).request(responseType); + } + + + public WebTarget getTarget(final String relativePath, final Map queryParams) { + WebTarget target = client.target(baseUrl + relativePath); + if (queryParams == null) { + return target; + } + for (final Map.Entry entry : queryParams.entrySet()) { + target = target.queryParam(entry.getKey(), entry.getValue()); + } + return target; + } + + + @Override + public void close() { + client.close(); + } + + + private MultivaluedMap buildMultivaluedMap(final Map payload) { + final MultivaluedMap formData = new MultivaluedHashMap<>(); + if (payload != null) { + for (final Entry entry : payload.entrySet()) { + formData.add(entry.getKey(), entry.getValue()); + } + } + return formData; + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/asadmin/Asadmin.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/asadmin/Asadmin.java new file mode 100644 index 00000000000..e40e999e2cf --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/asadmin/Asadmin.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2022 Eclipse Foundation and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.tool.asadmin; + +import com.sun.enterprise.universal.process.ProcessManager; +import com.sun.enterprise.universal.process.ProcessManagerException; +import com.sun.enterprise.universal.process.ProcessManagerTimeoutException; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static java.util.Arrays.asList; + +/** + * Tool for executing asadmin/asadmin.bat commands. + * The tool is stateless. + * + * @author David Matejcek + */ +public class Asadmin { + private static final Logger LOG = Logger.getLogger(Asadmin.class.getName()); + + private static final int DEFAULT_TIMEOUT_MSEC = 10 * 1000; + + private final File asadmin; + private final String adminUser; + private final File adminPasswordFile; + + + /** + * Creates a stateless instance of the tool. + * + * @param asadmin - executable file + * @param adminUser - username authorized to use the domain + * @param adminPasswordFile - a file containing admin's password set as AS_ADMIN_PASSWORD=... + */ + public Asadmin(final File asadmin, final String adminUser, final File adminPasswordFile) { + this.asadmin = asadmin; + this.adminUser = adminUser; + this.adminPasswordFile = adminPasswordFile; + } + + + /** + * @return asadmin command file name + */ + public String getCommandName() { + return asadmin.getName(); + } + + + /** + * Executes the command with arguments asynchronously with {@value #DEFAULT_TIMEOUT_MSEC} ms timeout. + * The command can be attached by the attach command. + * You should find the job id in the {@link AsadminResult#getStdOut()} as Job ID: [0-9]+ + * + * @param args + * @return {@link AsadminResult} never null. + */ + public AsadminResult execDetached(final String... args) { + return exec(DEFAULT_TIMEOUT_MSEC, true, args); + } + + /** + * Executes the command with arguments synchronously with {@value #DEFAULT_TIMEOUT_MSEC} ms timeout. + * + * @param args + * @return {@link AsadminResult} never null. + */ + public AsadminResult exec(final String... args) { + return exec(DEFAULT_TIMEOUT_MSEC, false, args); + } + + + /** + * Executes the command with arguments. + * + * @param timeout timeout in millis + * @param detached - detached command is executed asynchronously, can be attached later by the attach command. + * @param args - command and arguments. + * @return {@link AsadminResult} never null. + */ + public AsadminResult exec(final int timeout, final boolean detached, final String... args) { + final List parameters = asList(args); + LOG.log(Level.INFO, "exec(timeout={0}, detached={1}, args={2})", new Object[] {timeout, detached, parameters}); + final List command = new ArrayList<>(); + command.add(asadmin.getAbsolutePath()); + command.add("--user"); + command.add(adminUser); + command.add("--passwordfile"); + command.add(adminPasswordFile.getAbsolutePath()); + if (detached) { + command.add("--detach"); + } + command.addAll(parameters); + + final ProcessManager pm = new ProcessManager(command); + pm.setTimeoutMsec(timeout); + pm.setEcho(false); + + int exitCode; + String asadminErrorMessage = ""; + try { + exitCode = pm.execute(); + } catch (final ProcessManagerTimeoutException e) { + asadminErrorMessage = "ProcessManagerTimeoutException: command timed stdOut after " + timeout + " ms.\n"; + exitCode = 1; + } catch (final ProcessManagerException e) { + LOG.log(Level.SEVERE, "The execution failed.", e); + asadminErrorMessage = e.getMessage(); + exitCode = 1; + } + + final String stdErr = pm.getStderr() + '\n' + asadminErrorMessage; + final AsadminResult ret = new AsadminResult(args[0], exitCode, pm.getStdout(), stdErr); + writeToStdOut(ret.getOutput()); + return ret; + } + + + private static void writeToStdOut(final String text) { + if (!text.isEmpty()) { + System.out.print(text); + } + } +} diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/asadmin/AsadminResult.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/asadmin/AsadminResult.java new file mode 100644 index 00000000000..e11433baf1b --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/asadmin/AsadminResult.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2022 Eclipse Foundation and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.tool.asadmin; + +/** + * Result of the {@link Asadmin} execution. + * + * @author David Matejcek + */ +public class AsadminResult { + + private final boolean error; + private final String stdOut; + private final String stdErr; + private final String output; + + /** + * Creates a value object instance. + * + * @param cmd - command name + * @param exitCode + * @param stdOut + * @param stdErr + */ + public AsadminResult(final String cmd, final int exitCode, final String stdOut, final String stdErr) { + this.error = exitCode != 0 || containsError(stdOut, String.format("Command %s failed.", cmd)); + this.stdOut = stdOut; + this.stdErr = stdErr; + this.output = this.stdOut + this.stdErr; + } + + + /** + * @return true if the error code was not zero OR stdOut contained text Command x failed. + */ + public boolean isError() { + return error; + } + + + /** + * @return standard output made by the command. + */ + public String getStdOut() { + return stdOut; + } + + /** + * @return error output made by the command. + */ + public String getStdErr() { + return stdErr; + } + + + /** + * @return {@link #getStdOut()} + {@link #getStdErr()} + */ + public String getOutput() { + return output; + } + + + /** + * Returns {@link #getOutput()}. Important for hamcrest matchers! + */ + @Override + public String toString() { + return getOutput(); + } + + + private static boolean containsError(final String text, final String... invalidResults) { + for (final String result : invalidResults) { + if (text.contains(result)) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/asadmin/GlassFishTestEnvironment.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/asadmin/GlassFishTestEnvironment.java new file mode 100644 index 00000000000..b41b7b3844f --- /dev/null +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/tool/asadmin/GlassFishTestEnvironment.java @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2022 Eclipse Foundation and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package org.glassfish.main.admin.test.tool.asadmin; + +import jakarta.ws.rs.client.Client; + +import java.io.File; +import java.io.IOException; +import java.net.Authenticator; +import java.net.HttpURLConnection; +import java.net.PasswordAuthentication; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Locale; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.glassfish.admin.rest.client.ClientWrapper; +import org.glassfish.main.admin.test.tool.AsadminResultMatcher; + +import static org.hamcrest.MatcherAssert.assertThat; + +/** + * This class represents GlassFish installation outside test environment. + *

+ * Ensures that the domain in executed before first test started, and that the domain stops + * after tests are finished. + * + * @author David Matejcek + */ +public class GlassFishTestEnvironment { + private static final Logger LOG = Logger.getLogger(GlassFishTestEnvironment.class.getName()); + + private static final File BASEDIR = detectBasedir(); + private static final File GF_ROOT = resolveGlassFishRoot(); + + private static final String ADMIN_USER = "admin"; + private static final String ADMIN_PASSWORD = "admintest"; + + private static final File ASADMIN = findAsadmin(); + private static final File PASSWORD_FILE_FOR_UPDATE = findPasswordFile("password_update.txt"); + private static final File PASSWORD_FILE = findPasswordFile("password.txt"); + + + static { + LOG.log(Level.INFO, "Using basedir: {0}", BASEDIR); + LOG.log(Level.INFO, "Expected GlassFish directory: {0}", GF_ROOT); + changePassword(); + Thread hook = new Thread(() -> { + getAsadmin().exec(10_000, false, "stop-domain", "--kill", "--force"); + }); + Runtime.getRuntime().addShutdownHook(hook); + assertThat(getAsadmin().exec(30_000, false, "start-domain"), AsadminResultMatcher.asadminOK()); + } + + /** + * @return {@link Asadmin} command api for tests. + */ + public static Asadmin getAsadmin() { + return new Asadmin(ASADMIN, ADMIN_USER, PASSWORD_FILE); + } + + + /** + * @return project's target directory. + */ + public static File getTargetDirectory() { + return new File(BASEDIR, "target"); + } + + + /** + * Creates a {@link Client} instance for the domain administrator. + * Caller is responsible for closing. + * + * @return new {@link Client} instance + */ + public static ClientWrapper createClient() { + return new ClientWrapper(new HashMap(), ADMIN_USER, ADMIN_PASSWORD); + } + + + /** + * Creates a {@link HttpURLConnection} for the admin administrator. + * + * @param context - part of the url behind the http://localhost:4848 + * @return a new disconnected {@link HttpURLConnection}. + * @throws IOException + */ + public static HttpURLConnection openConnection(final String context) throws IOException { + final HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:4848" + context) + .openConnection(); + connection.setRequestProperty("X-Requested-By", "JUnit5Test"); + connection.setAuthenticator(new DasAuthenticator()); + return connection; + } + + + /** + * This will delete the jobs.xml file + */ + public static void deleteJobsFile() { + Path path = GF_ROOT.toPath().resolve(Paths.get("domains", "domain1", "config", "jobs.xml")); + LOG.log(Level.CONFIG, "Deleting: " + path); + try { + Files.deleteIfExists(path); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + + /** + * osgi-cache workaround + */ + public static void deleteOsgiDirectory() { + Path osgiCacheDir = GF_ROOT.toPath().resolve(Paths.get("domains", "domain1", "osgi-cache")); + try { + Files.list(osgiCacheDir).forEach(GlassFishTestEnvironment::deleteSubpaths); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + + public static void deleteSubpaths(final Path path) { + try { + Files.walk(path).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + } catch (Exception e) { + throw new IllegalStateException("Cannot delete path recursively: " + path, e); + } + } + + + /** + * Useful for a heuristic inside Eclipse and other environments. + * + * @return Absolute path to the glassfish directory. + */ + private static File detectBasedir() { + final String basedir = System.getProperty("basedir"); + if (basedir != null) { + return new File(basedir); + } + final File target = new File("target"); + if (target.exists()) { + return target.getAbsoluteFile().getParentFile(); + } + return new File(".").getAbsoluteFile().getParentFile(); + } + + + private static File resolveGlassFishRoot() { + final File gfDir = BASEDIR.toPath().resolve(Path.of("target", "glassfish6", "glassfish")).toFile(); + if (gfDir == null || !gfDir.exists()) { + throw new IllegalStateException("The expected GlassFish home directory doesn't exist: " + gfDir); + } + return gfDir; + } + + + private static File findAsadmin() { + return new File(GF_ROOT, isWindows() ? "bin/asadmin.bat" : "bin/asadmin"); + } + + + private static boolean isWindows() { + return System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("win"); + } + + + private static File findPasswordFile(final String filename) { + try { + final URL url = Asadmin.class.getResource("/" + filename); + if (url == null) { + throw new IllegalStateException(filename + " not found"); + } + return Path.of(url.toURI()).toFile().getAbsoluteFile(); + } catch (final URISyntaxException e) { + throw new IllegalStateException(e); + } + } + + + private static void changePassword() { + final Asadmin asadmin = new Asadmin(ASADMIN, ADMIN_USER, PASSWORD_FILE_FOR_UPDATE); + final AsadminResult result = asadmin.exec(5_000, false, "change-admin-password"); + if (result.isError()) { + // probably changed by previous execution without maven clean + System.out.println("Admin password NOT changed."); + } else { + System.out.println("Admin password changed."); + } + } + + private static class DasAuthenticator extends Authenticator { + + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(ADMIN_USER, ADMIN_PASSWORD.toCharArray()); + } + } +} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ExceptionFilterTest.java b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/webapp/HelloServlet.java similarity index 50% rename from nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ExceptionFilterTest.java rename to appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/webapp/HelloServlet.java index ef4a7e02e34..151567427e6 100644 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ExceptionFilterTest.java +++ b/appserver/tests/admin/tests/src/test/java/org/glassfish/main/admin/test/webapp/HelloServlet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022 Eclipse Foundation and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at @@ -14,21 +14,25 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.glassfish.nucleus.admin.rest; +package org.glassfish.main.admin.test.webapp; -import org.testng.annotations.Test; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import java.io.IOException; /** - * - * @author jdlee + * @author David Matejcek */ -@Test(enabled = false) -public class ExceptionFilterTest { - public void testExceptionFiler() { - // TODO +@WebServlet(urlPatterns = "/") +public class HelloServlet extends HttpServlet { + + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + response.getOutputStream().print("Hello!"); } + } diff --git a/appserver/tests/admin/tests/src/test/resources/password.txt b/appserver/tests/admin/tests/src/test/resources/password.txt new file mode 100644 index 00000000000..09e24de7428 --- /dev/null +++ b/appserver/tests/admin/tests/src/test/resources/password.txt @@ -0,0 +1 @@ +AS_ADMIN_PASSWORD=admintest diff --git a/appserver/tests/admin/tests/src/test/resources/password_update.txt b/appserver/tests/admin/tests/src/test/resources/password_update.txt new file mode 100644 index 00000000000..73f0e0424ae --- /dev/null +++ b/appserver/tests/admin/tests/src/test/resources/password_update.txt @@ -0,0 +1,2 @@ +AS_ADMIN_PASSWORD= +AS_ADMIN_NEWPASSWORD=admintest diff --git a/appserver/tests/pom.xml b/appserver/tests/pom.xml index 5f723b07087..0798f4026a5 100755 --- a/appserver/tests/pom.xml +++ b/appserver/tests/pom.xml @@ -119,6 +119,7 @@ tck + admin appserv-tests @@ -129,7 +130,7 @@ fastest - + appserv-tests diff --git a/appserver/webservices/connector/src/main/java/org/glassfish/webservices/config/RegistryLocation.java b/appserver/webservices/connector/src/main/java/org/glassfish/webservices/config/RegistryLocation.java index 9ee64c829f3..b2e645acf8c 100644 --- a/appserver/webservices/connector/src/main/java/org/glassfish/webservices/config/RegistryLocation.java +++ b/appserver/webservices/connector/src/main/java/org/glassfish/webservices/config/RegistryLocation.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,15 +17,16 @@ package org.glassfish.webservices.config; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.ConfigBeanProxy; -import static org.glassfish.config.support.Constants.NAME_REGEX; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; + +import static org.glassfish.config.support.Constants.NAME_REGEX; /** * Specifies the registry where web service end point artifacts are published. @@ -41,17 +43,17 @@ public interface RegistryLocation extends ConfigBeanProxy { * @return possible object is * {@link String } */ - @Attribute(key=true) + @Attribute(key = true) @NotNull - @Pattern(regexp=NAME_REGEX) - public String getConnectorResourceJndiName(); + @Pattern(regexp = NAME_REGEX, message = "Pattern: " + NAME_REGEX) + String getConnectorResourceJndiName(); /** * Sets the value of the connectorResourceJndiName property. * * @param value allowed object is - * {@link String } + * {@link String } */ - public void setConnectorResourceJndiName(String value) throws PropertyVetoException; + void setConnectorResourceJndiName(String value) throws PropertyVetoException; } diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AdminService.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AdminService.java index 70ee5295024..dc59d6392fd 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AdminService.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AdminService.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,17 +17,21 @@ package com.sun.enterprise.config.serverbeans; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; + import java.beans.PropertyVetoException; import java.util.List; import org.glassfish.api.admin.config.PropertiesDesc; +import org.glassfish.quality.ToDo; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.DuckTyped; +import org.jvnet.hk2.config.Element; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import org.glassfish.quality.ToDo; -import org.jvnet.hk2.config.*; - -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; /* @XmlType(name = "", propOrder = { "jmxConnector", @@ -40,6 +45,8 @@ @Configured public interface AdminService extends ConfigBeanProxy, PropertyBag { + String PATTERN_TYPE = "(das|das-and-server|server)"; + /** * Gets the value of the type property. An instance can either be of type das Domain Administration Server in SE/EE or * the PE instance das-and-server same as das server Any non-DAS instance in SE/EE. Not valid for PE. @@ -47,7 +54,7 @@ public interface AdminService extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "server") - @Pattern(regexp = "(das|das-and-server|server)") + @Pattern(regexp = PATTERN_TYPE, message = "Pattern: " + PATTERN_TYPE) String getType(); /** @@ -98,6 +105,7 @@ public interface AdminService extends ConfigBeanProxy, PropertyBag { /** * Properties as per {@link org.jvnet.hk2.config.types.PropertyBag} */ + @Override @ToDo(priority = ToDo.Priority.IMPORTANT, details = "Provide PropertyDesc for legal props") @PropertiesDesc(props = {}) @Element @@ -150,8 +158,9 @@ public static AuthRealm getAssociatedAuthRealm(AdminService as) { SecurityService ss = cfg.getSecurityService(); List realms = ss.getAuthRealm(); for (AuthRealm realm : realms) { - if (rn.equals(realm.getName())) + if (rn.equals(realm.getName())) { return realm; + } } return null; } @@ -167,8 +176,9 @@ public static boolean usesFileRealm(AdminService as) { boolean usesFR = false; AuthRealm ar = as.getAssociatedAuthRealm(); //Note: This is type unsafe. - if (ar != null && "com.sun.enterprise.security.auth.realm.file.FileRealm".equals(ar.getClassname())) + if (ar != null && "com.sun.enterprise.security.auth.realm.file.FileRealm".equals(ar.getClassname())) { usesFR = true; + } return usesFR; } } diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuditModule.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuditModule.java index dd22685b7cd..82a5fb90e0e 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuditModule.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuditModule.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,26 +17,26 @@ package com.sun.enterprise.config.serverbeans; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.ConfigBeanProxy; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.Element; +import com.sun.enterprise.config.serverbeans.customvalidators.JavaClassName; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; import java.util.List; +import org.glassfish.api.admin.RestRedirect; +import org.glassfish.api.admin.RestRedirects; import org.glassfish.api.admin.config.PropertiesDesc; +import org.glassfish.quality.ToDo; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.Element; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import org.glassfish.api.admin.RestRedirects; -import org.glassfish.api.admin.RestRedirect; -import org.glassfish.quality.ToDo; -import static org.glassfish.config.support.Constants.NAME_REGEX; - -import jakarta.validation.constraints.Pattern; -import jakarta.validation.constraints.NotNull; -import com.sun.enterprise.config.serverbeans.customvalidators.JavaClassName; +import static org.glassfish.config.support.Constants.NAME_REGEX; /** * An audit-module specifies an optional plug-in module which implements audit capabilities. @@ -57,7 +58,7 @@ public interface AuditModule extends ConfigBeanProxy, PropertyBag { */ @Attribute(key = true) @NotNull - @Pattern(regexp = NAME_REGEX) + @Pattern(regexp = NAME_REGEX, message = "Pattern: " + NAME_REGEX) String getName(); /** @@ -87,6 +88,7 @@ public interface AuditModule extends ConfigBeanProxy, PropertyBag { /** * Properties as per {@link PropertyBag} */ + @Override @ToDo(priority = ToDo.Priority.IMPORTANT, details = "Provide PropertyDesc for legal props") @PropertiesDesc(props = {}) @Element diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuthRealm.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuthRealm.java index ffe4941e972..cc8127df9a4 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuthRealm.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuthRealm.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,28 +17,42 @@ package com.sun.enterprise.config.serverbeans; -import com.sun.enterprise.config.serverbeans.customvalidators.*; +import com.sun.enterprise.config.serverbeans.customvalidators.FileRealmPropertyCheck; +import com.sun.enterprise.config.serverbeans.customvalidators.JDBCRealmPropertyCheck; +import com.sun.enterprise.config.serverbeans.customvalidators.JavaClassName; +import com.sun.enterprise.config.serverbeans.customvalidators.LDAPRealmPropertyCheck; +import com.sun.enterprise.config.serverbeans.customvalidators.SolarisRealmPropertyCheck; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; + +import java.beans.PropertyVetoException; +import java.util.List; + import org.glassfish.api.admin.RestRedirect; import org.glassfish.api.admin.RestRedirects; import org.glassfish.api.admin.config.PropertiesDesc; import org.glassfish.api.admin.config.PropertyDesc; -import org.jvnet.hk2.config.*; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.DuckTyped; +import org.jvnet.hk2.config.Element; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import static org.glassfish.config.support.Constants.NAME_REGEX; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; -import java.beans.PropertyVetoException; -import java.util.List; +import static org.glassfish.config.support.Constants.NAME_REGEX; @Configured @FileRealmPropertyCheck @LDAPRealmPropertyCheck @JDBCRealmPropertyCheck @SolarisRealmPropertyCheck -@RestRedirects({ @RestRedirect(opType = RestRedirect.OpType.POST, commandName = "create-auth-realm"), - @RestRedirect(opType = RestRedirect.OpType.DELETE, commandName = "delete-auth-realm") }) +@RestRedirects({ + @RestRedirect(opType = RestRedirect.OpType.POST, commandName = "create-auth-realm"), + @RestRedirect(opType = RestRedirect.OpType.DELETE, commandName = "delete-auth-realm") +}) + /** * The auth-realm element defines and configures one authentication realm. There must be at least one realm available * for a server instance; any number can be configured, as desired. Authentication realms need provider-specific @@ -54,7 +69,7 @@ public interface AuthRealm extends ConfigBeanProxy, PropertyBag { */ @Attribute(key = true) @NotNull - @Pattern(regexp = NAME_REGEX) + @Pattern(regexp = NAME_REGEX, message = "Pattern: " + NAME_REGEX) String getName(); /** @@ -87,8 +102,9 @@ public interface AuthRealm extends ConfigBeanProxy, PropertyBag { class Duck { public static String getGroupMapping(AuthRealm me) { Property prop = me.getProperty("group-mapping"); //have to hard-code this, unfortunately :( - if (prop != null) + if (prop != null) { return prop.getValue(); + } return null; } } @@ -96,6 +112,7 @@ public static String getGroupMapping(AuthRealm me) { /** * Properties. */ + @Override @PropertiesDesc(props = { @PropertyDesc(name = "jaas-context", description = "jaas-contextfile,jdbcSpecifies the JAAS (Java Authentication and Authorization Service) context"), @PropertyDesc(name = "file", defaultValue = "${com.sun.aas.instanceRoot}/config/keyfile", description = "file realm. Specifies the file that stores user names, passwords, and group names."), diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/BindableResource.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/BindableResource.java index 1ca80f86061..677596db516 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/BindableResource.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/BindableResource.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -17,17 +18,21 @@ package com.sun.enterprise.config.serverbeans; import com.sun.enterprise.config.serverbeans.customvalidators.ResourceNameConstraint; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.DuckTyped; -import java.beans.PropertyVetoException; import jakarta.validation.Payload; - import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Pattern; +import java.beans.PropertyVetoException; + +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.DuckTyped; + @ResourceNameConstraint(message = "{resourcename.invalid.character}", payload = BindableResource.class) public interface BindableResource extends Resource, Payload { + + String PATTERN_JNDI = "[^',][^',\\\\]*"; + /** * Gets the value of the jndiName property. * @@ -35,15 +40,15 @@ public interface BindableResource extends Resource, Payload { */ @Attribute(key = true) @NotNull - @Pattern(regexp = "[^',][^',\\\\]*") - public String getJndiName(); + @Pattern(regexp = PATTERN_JNDI, message = "Pattern: " + PATTERN_JNDI) + String getJndiName(); /** * Sets the value of the jndiName property. * * @param value allowed object is {@link String } */ - public void setJndiName(String value) throws PropertyVetoException; + void setJndiName(String value) throws PropertyVetoException; /** * Gets the value of the enabled property. @@ -60,6 +65,7 @@ public interface BindableResource extends Resource, Payload { */ void setEnabled(String value) throws PropertyVetoException; + @Override @DuckTyped String getIdentity(); diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Cluster.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Cluster.java index 4bfffa8dd02..7e2df7964c7 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Cluster.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Cluster.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,58 +17,67 @@ package com.sun.enterprise.config.serverbeans; -import com.sun.enterprise.config.serverbeans.customvalidators.NotTargetKeyword; -import com.sun.enterprise.config.serverbeans.customvalidators.NotDuplicateTargetName; import com.sun.enterprise.config.serverbeans.customvalidators.ConfigRefConstraint; import com.sun.enterprise.config.serverbeans.customvalidators.ConfigRefValidator; +import com.sun.enterprise.config.serverbeans.customvalidators.NotDuplicateTargetName; +import com.sun.enterprise.config.serverbeans.customvalidators.NotTargetKeyword; import com.sun.enterprise.config.serverbeans.customvalidators.ReferenceConstraint; import com.sun.enterprise.config.util.ConfigApiLoggerInfo; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.io.FileUtils; -import com.sun.logging.LogDomains; -import java.io.*; -import org.glassfish.api.ActionReport; -import org.glassfish.api.I18n; -import org.glassfish.api.Param; -import org.glassfish.api.admin.*; -import org.glassfish.config.support.*; -import static org.glassfish.config.support.Constants.NAME_SERVER_REGEX; -import org.jvnet.hk2.annotations.Service; -import org.glassfish.hk2.api.PerLookup; -import org.glassfish.hk2.api.ServiceLocator; -import org.jvnet.hk2.config.*; -import org.glassfish.api.admin.config.Named; -import org.glassfish.api.admin.config.PropertyDesc; -import org.glassfish.api.admin.config.ReferenceContainer; -// import org.glassfish.virtualization.util.RuntimeContext; +import jakarta.inject.Inject; +import jakarta.validation.Payload; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; -import java.util.List; -import java.util.ArrayList; +import java.io.File; import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; +import org.glassfish.api.ActionReport; +import org.glassfish.api.I18n; +import org.glassfish.api.Param; +import org.glassfish.api.admin.AdminCommand; +import org.glassfish.api.admin.AdminCommandContext; +import org.glassfish.api.admin.CommandRunner; +import org.glassfish.api.admin.ServerEnvironment; +import org.glassfish.api.admin.config.Named; import org.glassfish.api.admin.config.PropertiesDesc; +import org.glassfish.api.admin.config.PropertyDesc; +import org.glassfish.api.admin.config.ReferenceContainer; +import org.glassfish.config.support.CreationDecorator; +import org.glassfish.config.support.DeletionDecorator; +import org.glassfish.hk2.api.PerLookup; +import org.glassfish.hk2.api.ServiceLocator; +import org.glassfish.quality.ToDo; +import org.jvnet.hk2.annotations.Service; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.ConfigSupport; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.Dom; +import org.jvnet.hk2.config.DuckTyped; +import org.jvnet.hk2.config.Element; +import org.jvnet.hk2.config.SingleConfigCode; +import org.jvnet.hk2.config.Transaction; +import org.jvnet.hk2.config.TransactionFailure; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import org.glassfish.quality.ToDo; - -import jakarta.inject.Inject; -import jakarta.validation.Payload; -import jakarta.validation.constraints.Max; -import jakarta.validation.constraints.Min; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; +import static org.glassfish.config.support.Constants.NAME_SERVER_REGEX; /** * A cluster defines a homogeneous set of server instances that share the same applications, resources, and * configuration. */ @Configured -@SuppressWarnings("unused") @ConfigRefConstraint(message = "{configref.invalid}", payload = ConfigRefValidator.class) @NotDuplicateTargetName(message = "{cluster.duplicate.name}", payload = Cluster.class) @ReferenceConstraint(skipDuringCreation = true, payload = Cluster.class) @@ -80,13 +90,11 @@ public interface Cluster extends ConfigBeanProxy, PropertyBag, Named, SystemProp * @throws PropertyVetoException if a listener vetoes the change */ @Param(name = "name", primary = true) - @Override - public void setName(String value) throws PropertyVetoException; + @Override void setName(String value) throws PropertyVetoException; @NotTargetKeyword(message = "{cluster.reserved.name}", payload = Cluster.class) @Pattern(regexp = NAME_SERVER_REGEX, message = "{cluster.invalid.name}", payload = Cluster.class) - @Override - public String getName(); + @Override String getName(); /** * points to a named config. All server instances in the cluster will share this config. @@ -95,7 +103,7 @@ public interface Cluster extends ConfigBeanProxy, PropertyBag, Named, SystemProp */ @Attribute @NotNull - @Pattern(regexp = NAME_SERVER_REGEX) + @Pattern(regexp = NAME_SERVER_REGEX, message = "{config.invalid.name}") @ReferenceConstraint.RemoteKey(message = "{resourceref.invalid.configref}", type = Config.class) String getConfigRef(); @@ -334,8 +342,7 @@ public interface Cluster extends ConfigBeanProxy, PropertyBag, Named, SystemProp @DuckTyped List getInstances(); - @DuckTyped - public ServerRef getServerRefByRef(String ref); + @DuckTyped ServerRef getServerRefByRef(String ref); // four trivial methods that ReferenceContainer's need to implement @DuckTyped @@ -408,7 +415,7 @@ public static List getInstances(Cluster cluster) { Dom clusterDom = Dom.unwrap(cluster); Domain domain = clusterDom.getHabitat().getService(Domain.class); - ArrayList instances = new ArrayList(); + ArrayList instances = new ArrayList<>(); for (ServerRef sRef : cluster.getServerRef()) { Server svr = domain.getServerNamed(sRef.getRef()); // the instance's domain.xml only has its own server @@ -456,6 +463,7 @@ public static void deleteResourceRef(Cluster cluster, String refName) throws Tra if (ref != null) { ConfigSupport.apply(new SingleConfigCode() { + @Override public Object run(Cluster param) { return param.getResourceRef().remove(ref); } @@ -467,6 +475,7 @@ public static void createResourceRef(Cluster cluster, final String enabled, fina ConfigSupport.apply(new SingleConfigCode() { + @Override public Object run(Cluster param) throws PropertyVetoException, TransactionFailure { ResourceRef newResourceRef = param.createChild(ResourceRef.class); @@ -479,7 +488,7 @@ public Object run(Cluster param) throws PropertyVetoException, TransactionFailur } public static List getExtensionsByType(Cluster cluster, Class type) { - List extensions = new ArrayList(); + List extensions = new ArrayList<>(); for (ClusterExtension ce : cluster.getExtensions()) { try { type.cast(ce); @@ -829,8 +838,9 @@ public void decorate(AdminCommandContext context, Clusters parent, Cluster child // check if the config is null or still in use by some other // ReferenceContainer or is not -config -- if so just return... - if (config == null || domain.getReferenceContainersOf(config).size() > 1 || !instanceConfig.equals(child.getName() + "-config")) + if (config == null || domain.getReferenceContainersOf(config).size() > 1 || !instanceConfig.equals(child.getName() + "-config")) { return; + } try { File configConfigDir = new File(env.getConfigDirPath(), config.getName()); diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ClusterRef.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ClusterRef.java index 588aa7a4a5e..de372c6d4cd 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ClusterRef.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ClusterRef.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -17,18 +18,22 @@ package com.sun.enterprise.config.serverbeans; import com.sun.enterprise.config.serverbeans.customvalidators.ReferenceConstraint; + import jakarta.validation.Payload; -import org.jvnet.hk2.config.*; -import static org.glassfish.config.support.Constants.NAME_SERVER_REGEX; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.Element; + +import static org.glassfish.config.support.Constants.NAME_SERVER_REGEX; /** * Element relating a reference to a cluster to be load balanced to an (optional) health-checker - * */ /* @XmlType(name = "", propOrder = { @@ -47,17 +52,16 @@ public interface ClusterRef extends ConfigBeanProxy, Ref, Payload { @Override @Attribute(key = true) @NotNull - @Pattern(regexp = NAME_SERVER_REGEX) + @Pattern(regexp = NAME_SERVER_REGEX, message = "{config.invalid.name}") @ReferenceConstraint.RemoteKey(message = "{resourceref.invalid.cluster-ref}", type = Cluster.class) - public String getRef(); + String getRef(); /** * Sets the value of the ref property. * * @param value allowed object is {@link String } */ - @Override - public void setRef(String value) throws PropertyVetoException; + @Override void setRef(String value) throws PropertyVetoException; /** * Gets the value of the lbPolicy property. @@ -70,14 +74,14 @@ public interface ClusterRef extends ConfigBeanProxy, Ref, Payload { * @return possible object is {@link String } */ @Attribute(defaultValue = "round-robin") - public String getLbPolicy(); + String getLbPolicy(); /** * Sets the value of the lbPolicy property. * * @param value allowed object is {@link String } */ - public void setLbPolicy(String value) throws PropertyVetoException; + void setLbPolicy(String value) throws PropertyVetoException; /** * Gets the value of the lbPolicyModule property. @@ -89,14 +93,14 @@ public interface ClusterRef extends ConfigBeanProxy, Ref, Payload { * @return possible object is {@link String } */ @Attribute - public String getLbPolicyModule(); + String getLbPolicyModule(); /** * Sets the value of the lbPolicyModule property. * * @param value allowed object is {@link String } */ - public void setLbPolicyModule(String value) throws PropertyVetoException; + void setLbPolicyModule(String value) throws PropertyVetoException; /** * Gets the value of the healthChecker property. @@ -106,12 +110,12 @@ public interface ClusterRef extends ConfigBeanProxy, Ref, Payload { * @return possible object is {@link HealthChecker } */ @Element - public HealthChecker getHealthChecker(); + HealthChecker getHealthChecker(); /** * Sets the value of the healthChecker property. * * @param value allowed object is {@link HealthChecker } */ - public void setHealthChecker(HealthChecker value) throws PropertyVetoException; + void setHealthChecker(HealthChecker value) throws PropertyVetoException; } diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Config.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Config.java index a48383aa368..a01b3b5c53d 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Config.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Config.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -17,10 +18,21 @@ package com.sun.enterprise.config.serverbeans; import com.sun.common.util.logging.LoggingConfigImpl; -import com.sun.enterprise.config.modularity.parser.ModuleConfigurationLoader; import com.sun.enterprise.config.serverbeans.customvalidators.NotDuplicateTargetName; import com.sun.enterprise.config.serverbeans.customvalidators.NotTargetKeyword; import com.sun.enterprise.config.util.ServerHelper; + +import jakarta.validation.Payload; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; + +import java.beans.PropertyVetoException; +import java.io.IOException; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.glassfish.api.admin.config.ConfigExtension; import org.glassfish.api.admin.config.Container; import org.glassfish.api.admin.config.Named; @@ -29,26 +41,25 @@ import org.glassfish.config.support.datatypes.Port; import org.glassfish.grizzly.config.dom.NetworkConfig; import org.glassfish.grizzly.config.dom.NetworkListener; -import org.glassfish.hk2.api.ActiveDescriptor; import org.glassfish.hk2.api.ServiceLocator; import org.glassfish.hk2.utilities.BuilderHelper; import org.glassfish.hk2.utilities.ServiceLocatorUtilities; import org.glassfish.quality.ToDo; import org.glassfish.server.ServerEnvironmentImpl; -import org.jvnet.hk2.config.*; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBean; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.ConfigExtensionMethod; +import org.jvnet.hk2.config.ConfigSupport; +import org.jvnet.hk2.config.ConfigView; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.DuckTyped; +import org.jvnet.hk2.config.Element; +import org.jvnet.hk2.config.SingleConfigCode; +import org.jvnet.hk2.config.TransactionFailure; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import jakarta.validation.Payload; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; -import java.beans.PropertyVetoException; -import java.io.IOException; -import java.lang.reflect.Proxy; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import static org.glassfish.config.support.Constants.NAME_SERVER_REGEX; /** @@ -373,8 +384,9 @@ public static boolean isDas(Config c) { try { String type = c.getAdminService().getType(); - if (type != null && (type.equals("das") || type.equals("das-and-server"))) + if (type != null && (type.equals("das") || type.equals("das-and-server"))) { return true; + } } catch (Exception e) { // fall through } @@ -401,7 +413,7 @@ public static Map getLoggingProperties(Config c) { LoggingConfigImpl loggingConfig = new LoggingConfigImpl(); loggingConfig.setupConfigDir(env.getConfigDirPath(), env.getLibPath()); - Map map = new HashMap(); + Map map = new HashMap<>(); try { map = loggingConfig.getLoggingProperties(); } catch (IOException ex) { @@ -415,7 +427,7 @@ public static Map updateLoggingProperties(Config c, Map map = new HashMap(); + Map map = new HashMap<>(); try { map = loggingConfig.updateLoggingProperties(properties); } catch (IOException ex) { @@ -463,6 +475,7 @@ public static

boolean checkIfExtensionExists(Config public static void createResourceRef(Config config, final String enabled, final String refName) throws TransactionFailure { ConfigSupport.apply(new SingleConfigCode() { + @Override public Object run(Config param) throws PropertyVetoException, TransactionFailure { ResourceRef newResourceRef = param.createChild(ResourceRef.class); @@ -492,6 +505,7 @@ public static void deleteResourceRef(Config config, String refName) throws Trans if (ref != null) { ConfigSupport.apply(new SingleConfigCode() { + @Override public Object run(Config param) { return param.getResourceRef().remove(ref); } diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Domain.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Domain.java index f5eedd574e9..7a50092805f 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Domain.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Domain.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,9 +17,20 @@ package com.sun.enterprise.config.serverbeans; -import com.sun.enterprise.config.modularity.parser.ModuleConfigurationLoader; import com.sun.enterprise.config.util.ConfigApiLoggerInfo; import com.sun.enterprise.util.StringUtils; + +import jakarta.validation.constraints.NotNull; + +import java.beans.PropertyVetoException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + import org.glassfish.api.admin.config.ApplicationName; import org.glassfish.api.admin.config.PropertiesDesc; import org.glassfish.api.admin.config.PropertyDesc; @@ -30,20 +42,9 @@ import org.jvnet.hk2.config.Configured; import org.jvnet.hk2.config.DuckTyped; import org.jvnet.hk2.config.Element; -import org.jvnet.hk2.config.TransactionFailure; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import jakarta.validation.constraints.NotNull; -import java.beans.PropertyVetoException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - @Configured /** * Top level Domain Element that includes applications, resources, configs, servers, clusters and node-agents, load @@ -52,7 +53,7 @@ */ public interface Domain extends ConfigBeanProxy, PropertyBag, SystemPropertyBag, ConfigLoader { - public static final String DOMAIN_NAME_PROPERTY = "administrative.domain.name"; + String DOMAIN_NAME_PROPERTY = "administrative.domain.name"; /** * Gets the value of the applicationRoot property. @@ -269,6 +270,7 @@ public interface Domain extends ConfigBeanProxy, PropertyBag, SystemPropertyBag, *

* Objects of the following type(s) are allowed in the list {@link SystemProperty } */ + @Override @ToDo(priority = ToDo.Priority.IMPORTANT, details = "Any more legal system properties?") @PropertiesDesc(systemProperties = true, props = { @PropertyDesc(name = "com.sun.aas.installRoot", description = "Operating system dependent. Path to the directory where the server is installed"), @@ -294,6 +296,7 @@ public interface Domain extends ConfigBeanProxy, PropertyBag, SystemPropertyBag, /** * Properties as per {@link PropertyBag} */ + @Override @ToDo(priority = ToDo.Priority.IMPORTANT, details = "Provide PropertyDesc for legal props") @PropertiesDesc(props = {}) @Element @@ -376,8 +379,7 @@ public interface Domain extends ConfigBeanProxy, PropertyBag, SystemPropertyBag, @DuckTyped List getAllTargets(); - @DuckTyped - public List getTargets(final String tgt); + @DuckTyped List getTargets(final String tgt); @DuckTyped List getApplicationsInTarget(String target); @@ -428,16 +430,18 @@ public static String getName(Domain domain) { * or if no matches */ public static List getInstancesOnNode(Domain domain, String nodeName) { - List ret = new LinkedList(); + List ret = new LinkedList<>(); try { - if (!StringUtils.ok(nodeName)) + if (!StringUtils.ok(nodeName)) { return ret; + } List servers = domain.getServers().getServer(); for (Server server : servers) { - if (nodeName.equals(server.getNodeRef())) + if (nodeName.equals(server.getNodeRef())) { ret.add(server); + } } } catch (Exception e) { logger.log(Level.WARNING, ConfigApiLoggerInfo.errorGettingServers, e.getLocalizedMessage()); @@ -450,7 +454,7 @@ public static List getInstancesOnNode(Domain domain, String nodeName) { */ public static List getClustersOnNode(Domain domain, String nodeName) { - HashMap clMap = new HashMap(); + HashMap clMap = new HashMap<>(); List serverList = getInstancesOnNode(domain, nodeName); try { @@ -468,12 +472,13 @@ public static List getClustersOnNode(Domain domain, String nodeName) { } public static List getAllDefinedSystemApplications(Domain me) { - List allSysApps = new ArrayList(); + List allSysApps = new ArrayList<>(); SystemApplications sa = me.getSystemApplications(); if (sa != null) { for (ApplicationName m : sa.getModules()) { - if (m instanceof Application) + if (m instanceof Application) { allSysApps.add((Application) m); + } } } return Collections.unmodifiableList(allSysApps); @@ -512,14 +517,17 @@ public static List getApplicationRefsInServer(Domain me, String } public static List getSystemApplicationsReferencedFrom(Domain d, String sn) { - if (d == null || sn == null) + if (d == null || sn == null) { throw new IllegalArgumentException("Null argument"); + } List allApps = d.getAllDefinedSystemApplications(); if (allApps.isEmpty()) + { return allApps; //if there are no sys-apps, none can reference one :) + } //allApps now contains ALL the system applications Server s = getServerNamed(d, sn); - List referencedApps = new ArrayList(); + List referencedApps = new ArrayList<>(); List appsReferenced = s.getApplicationRef(); for (ApplicationRef ref : appsReferenced) { for (Application app : allApps) { @@ -545,15 +553,17 @@ public static Application getSystemApplicationReferencedFrom(Domain d, String sn public static boolean isNamedSystemApplicationReferencedFrom(Domain d, String appName, String serverName) { List referencedApps = getSystemApplicationsReferencedFrom(d, serverName); for (Application app : referencedApps) { - if (app.getName().equals(appName)) + if (app.getName().equals(appName)) { return true; + } } return false; } public static Server getServerNamed(Domain d, String name) { - if (d.getServers() == null || name == null) + if (d.getServers() == null || name == null) { throw new IllegalArgumentException("no element"); + } List servers = d.getServers().getServer(); for (Server s : servers) { if (name.equals(s.getName().trim())) { @@ -564,8 +574,9 @@ public static Server getServerNamed(Domain d, String name) { } public static Config getConfigNamed(Domain d, String name) { - if (d.getConfigs() == null || name == null) + if (d.getConfigs() == null || name == null) { throw new IllegalArgumentException("no element"); + } List configs = d.getConfigs().getConfig(); for (Config c : configs) { if (name.equals(c.getName().trim())) { @@ -608,7 +619,7 @@ public static boolean isCurrentInstanceMatchingTarget(Domain d, String target, S return false; } - List targets = new ArrayList(); + List targets = new ArrayList<>(); if (!target.equals("domain")) { targets.add(target); } else { @@ -639,7 +650,7 @@ public static boolean isCurrentInstanceMatchingTarget(Domain d, String target, S } public static List getServersInTarget(Domain me, String target) { - List servers = new ArrayList(); + List servers = new ArrayList<>(); Server server = me.getServerNamed(target); if (server != null) { servers.add(server); @@ -657,7 +668,7 @@ public static List getApplicationRefsInTarget(Domain me, String } public static List getTargets(final Domain me, final String tgt) { - List targets = new ArrayList(); + List targets = new ArrayList<>(); if (!tgt.equals("domain")) { targets.add(tgt); } else { @@ -668,7 +679,7 @@ public static List getTargets(final Domain me, final String tgt) { public static List getApplicationRefsInTarget(Domain me, String tgt, boolean includeInstances) { List targets = getTargets(me, tgt); - List allAppRefs = new ArrayList(); + List allAppRefs = new ArrayList<>(); for (String target : targets) { Server server = me.getServerNamed(target); @@ -731,7 +742,7 @@ public static boolean isAppRefEnabledInTarget(Domain me, String appName, String public static boolean isAppEnabledInTarget(Domain me, String appName, String target) { Application application = me.getApplications().getApplication(appName); if (application != null && Boolean.valueOf(application.getEnabled())) { - List targets = new ArrayList(); + List targets = new ArrayList<>(); if (!target.equals("domain")) { targets.add(target); } else { @@ -748,7 +759,7 @@ public static boolean isAppEnabledInTarget(Domain me, String appName, String tar } public static List getAllTargets(Domain d) { - List targets = new ArrayList(); + List targets = new ArrayList<>(); // only add non-clustered servers as the cluster // targets will be separately added for (Server server : d.getServers().getServer()) { @@ -765,7 +776,7 @@ public static List getAllTargets(Domain d) { } public static List getAllReferencedTargetsForApplication(Domain me, String appName) { - List referencedTargets = new ArrayList(); + List referencedTargets = new ArrayList<>(); for (String target : me.getAllTargets()) { if (me.getApplicationRefInTarget(appName, target) != null) { referencedTargets.add(target); @@ -793,7 +804,7 @@ public static List getApplicationsInTarget(Domain me, String target return me.getApplications().getApplications(); } - List apps = new ArrayList(); + List apps = new ArrayList<>(); List applicationRefs = me.getApplicationRefsInTarget(target); for (ApplicationRef ref : applicationRefs) { @@ -827,36 +838,40 @@ public static ReferenceContainer getReferenceContainerNamed(Domain d, String nam // Clusters and Servers are ReferenceContainers Cluster c = getClusterNamed(d, name); - if (c != null) + if (c != null) { return c; + } return getServerNamed(d, name); } public static List getReferenceContainersOf(Domain d, Config config) { // Clusters and Servers are ReferenceContainers - List sub = new LinkedList(); + List sub = new LinkedList<>(); // both the config and its name need to be sanity-checked String name = null; - if (config != null) + if (config != null) { name = config.getName(); + } - if (!StringUtils.ok(name)) // we choose to make this not an error + if (!StringUtils.ok(name)) { // we choose to make this not an error return sub; + } List all = getAllReferenceContainers(d); for (ReferenceContainer rc : all) { - if (name.equals(rc.getReference())) + if (name.equals(rc.getReference())) { sub.add(rc); + } } return sub; } public static List getAllReferenceContainers(Domain d) { - List ReferenceContainers = new LinkedList(); + List ReferenceContainers = new LinkedList<>(); ReferenceContainers.addAll(d.getServers().getServer()); if (d.getClusters() != null) { ReferenceContainers.addAll(d.getClusters().getCluster()); diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/HttpService.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/HttpService.java index d4a6eb8553b..af5eb5f28a3 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/HttpService.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/HttpService.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,22 +17,32 @@ package com.sun.enterprise.config.serverbeans; +import com.sun.enterprise.config.util.ConfigApiLoggerInfo; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; + import java.beans.PropertyVetoException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; -import com.sun.enterprise.config.util.ConfigApiLoggerInfo; import org.glassfish.api.admin.config.ConfigExtension; -import org.jvnet.hk2.config.*; -import org.jvnet.hk2.config.types.Property; -import org.jvnet.hk2.config.types.PropertyBag; import org.glassfish.api.admin.config.PropertiesDesc; import org.glassfish.api.admin.config.PropertyDesc; import org.glassfish.config.support.datatypes.NonNegativeInteger; - -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.ConfigSupport; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.DuckTyped; +import org.jvnet.hk2.config.Element; +import org.jvnet.hk2.config.SingleConfigCode; +import org.jvnet.hk2.config.TransactionFailure; +import org.jvnet.hk2.config.types.Property; +import org.jvnet.hk2.config.types.PropertyBag; @Configured public interface HttpService extends ConfigBeanProxy, PropertyBag, ConfigExtension { @@ -81,7 +92,7 @@ public interface HttpService extends ConfigBeanProxy, PropertyBag, ConfigExtensi List getNonAdminVirtualServerList(); @Attribute(defaultValue = "false") - @Pattern(regexp = "(false|true|on|off)") + @Pattern(regexp = "(false|true|on|off)", message = "Valid values: true|false") String getAccessLoggingEnabled(); void setAccessLoggingEnabled(String enabled); @@ -96,7 +107,7 @@ public interface HttpService extends ConfigBeanProxy, PropertyBag, ConfigExtensi * @return possible object is {@link String } */ @Attribute(defaultValue = "false") - @Pattern(regexp = "(true|false|on|off)") + @Pattern(regexp = "(true|false|on|off)", message = "Valid values: true|false") String getSsoEnabled(); /** @@ -119,7 +130,7 @@ public static VirtualServer getVirtualServerByName(HttpService target, String na } public static List getNonAdminVirtualServerList(HttpService target) { - List nonAdminVSList = new ArrayList(); + List nonAdminVSList = new ArrayList<>(); for (VirtualServer v : target.getVirtualServer()) { if (!v.getId().equals("__asadmin")) { nonAdminVSList.add(v.getId()); @@ -162,6 +173,7 @@ public Object run(Config param) throws PropertyVetoException, TransactionFailure } } + @Override @PropertiesDesc(props = { @PropertyDesc(name = "monitoring-cache-enabled", defaultValue = "true", dataType = Boolean.class, description = "Enables the monitoring cache"), diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/MessageSecurityConfig.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/MessageSecurityConfig.java index 908b8aa2df6..7525eb9846f 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/MessageSecurityConfig.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/MessageSecurityConfig.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,20 +17,19 @@ package com.sun.enterprise.config.serverbeans; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.Element; -import org.jvnet.hk2.config.ConfigBeanProxy; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; -import java.io.Serializable; import java.util.List; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; - -import org.glassfish.api.admin.RestRedirects; import org.glassfish.api.admin.RestRedirect; +import org.glassfish.api.admin.RestRedirects; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.Element; + import static org.glassfish.config.support.Constants.NAME_REGEX; /** @@ -43,8 +43,10 @@ }) */ @Configured -@RestRedirects({ @RestRedirect(opType = RestRedirect.OpType.POST, commandName = "create-message-security-provider"), - @RestRedirect(opType = RestRedirect.OpType.DELETE, commandName = "delete-message-security-provider") }) +@RestRedirects({ + @RestRedirect(opType = RestRedirect.OpType.POST, commandName = "create-message-security-provider"), + @RestRedirect(opType = RestRedirect.OpType.DELETE, commandName = "delete-message-security-provider") +}) public interface MessageSecurityConfig extends ConfigBeanProxy { /** @@ -57,14 +59,14 @@ public interface MessageSecurityConfig extends ConfigBeanProxy { */ @Attribute(key = true) @NotNull - public String getAuthLayer(); + String getAuthLayer(); /** * Sets the value of the authLayer property. * * @param value allowed object is {@link String } */ - public void setAuthLayer(String value) throws PropertyVetoException; + void setAuthLayer(String value) throws PropertyVetoException; /** * Gets the value of the defaultProvider property. @@ -78,15 +80,15 @@ public interface MessageSecurityConfig extends ConfigBeanProxy { * @return possible object is {@link String } */ @Attribute - @Pattern(regexp = NAME_REGEX) - public String getDefaultProvider(); + @Pattern(regexp = NAME_REGEX, message = "Pattern: " + NAME_REGEX) + String getDefaultProvider(); /** * Sets the value of the defaultProvider property. * * @param value allowed object is {@link String } */ - public void setDefaultProvider(String value) throws PropertyVetoException; + void setDefaultProvider(String value) throws PropertyVetoException; /** * Gets the value of the defaultClientProvider property. @@ -97,15 +99,15 @@ public interface MessageSecurityConfig extends ConfigBeanProxy { * @return possible object is {@link String } */ @Attribute - @Pattern(regexp = NAME_REGEX) - public String getDefaultClientProvider(); + @Pattern(regexp = NAME_REGEX, message = "Pattern: " + NAME_REGEX) + String getDefaultClientProvider(); /** * Sets the value of the defaultClientProvider property. * * @param value allowed object is {@link String } */ - public void setDefaultClientProvider(String value) throws PropertyVetoException; + void setDefaultClientProvider(String value) throws PropertyVetoException; /** * Gets the value of the providerConfig property. @@ -127,5 +129,5 @@ public interface MessageSecurityConfig extends ConfigBeanProxy { * Objects of the following type(s) are allowed in the list {@link ProviderConfig } */ @Element(required = true) - public List getProviderConfig(); + List getProviderConfig(); } diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ModuleMonitoringLevels.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ModuleMonitoringLevels.java index 12506c94da8..e3a96fca540 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ModuleMonitoringLevels.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ModuleMonitoringLevels.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,22 +17,20 @@ package com.sun.enterprise.config.serverbeans; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.ConfigBeanProxy; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.Element; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; import java.util.List; import org.glassfish.api.admin.config.PropertiesDesc; +import org.glassfish.quality.ToDo; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.Element; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import org.glassfish.quality.ToDo; - -import jakarta.validation.constraints.Pattern; - /** * */ @@ -43,59 +42,59 @@ @Configured public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { + String MONITORING_LEVELS = "(OFF|LOW|HIGH)"; + String MONITORING_LEVELS_MSG = "Valid values: " + MONITORING_LEVELS; + /** * Gets the value of the threadPool property. - * * All the thread-pools used by the run time * * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getThreadPool(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getThreadPool(); /** * Sets the value of the threadPool property. * * @param value allowed object is {@link String } */ - public void setThreadPool(String value) throws PropertyVetoException; + void setThreadPool(String value) throws PropertyVetoException; /** * Gets the value of the orb property. - * * Specifies the level for connection managers of the orb, which apply to connections to the orb * * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getOrb(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getOrb(); /** * Sets the value of the orb property. * * @param value allowed object is {@link String } */ - public void setOrb(String value) throws PropertyVetoException; + void setOrb(String value) throws PropertyVetoException; /** * Gets the value of the ejbContainer property. - * * Various ejbs deployed to the server, ejb-pools, ejb-caches & ejb-methods * * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getEjbContainer(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getEjbContainer(); /** * Sets the value of the ejbContainer property. * * @param value allowed object is {@link String } */ - public void setEjbContainer(String value) throws PropertyVetoException; + void setEjbContainer(String value) throws PropertyVetoException; /** * Gets the value of the webContainer property. @@ -103,15 +102,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getWebContainer(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getWebContainer(); /** * Sets the value of the webContainer property. * * @param value allowed object is {@link String } */ - public void setWebContainer(String value) throws PropertyVetoException; + void setWebContainer(String value) throws PropertyVetoException; /** * Gets the value of the deployment property. @@ -119,87 +118,83 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getDeployment(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getDeployment(); /** * Sets the value of the webContainer property. * * @param value allowed object is {@link String } */ - public void setDeployment(String value) throws PropertyVetoException; + void setDeployment(String value) throws PropertyVetoException; /** * Gets the value of the transactionService property. - * * Transaction subsystem * * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getTransactionService(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getTransactionService(); /** * Sets the value of the transactionService property. * * @param value allowed object is {@link String } */ - public void setTransactionService(String value) throws PropertyVetoException; + void setTransactionService(String value) throws PropertyVetoException; /** * Gets the value of the httpService property. - * * http engine and the http listeners therein. * * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getHttpService(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getHttpService(); /** * Sets the value of the httpService property. * * @param value allowed object is {@link String } */ - public void setHttpService(String value) throws PropertyVetoException; + void setHttpService(String value) throws PropertyVetoException; /** * Gets the value of the jdbcConnectionPool property. - * * Monitoring level for all the jdbc-connection-pools used by the runtime. * * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getJdbcConnectionPool(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getJdbcConnectionPool(); /** * Sets the value of the jdbcConnectionPool property. * * @param value allowed object is {@link String } */ - public void setJdbcConnectionPool(String value) throws PropertyVetoException; + void setJdbcConnectionPool(String value) throws PropertyVetoException; /** * Gets the value of the connectorConnectionPool property. - * * Monitoring level for all the connector-connection-pools used by runtime. * * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getConnectorConnectionPool(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getConnectorConnectionPool(); /** * Sets the value of the connectorConnectionPool property. * * @param value allowed object is {@link String } */ - public void setConnectorConnectionPool(String value) throws PropertyVetoException; + void setConnectorConnectionPool(String value) throws PropertyVetoException; /** * Gets the value of the connectorService property. @@ -207,15 +202,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getConnectorService(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getConnectorService(); /** * Sets the value of the connectorService property. * * @param value allowed object is {@link String } */ - public void setConnectorService(String value) throws PropertyVetoException; + void setConnectorService(String value) throws PropertyVetoException; /** * Gets the value of the jmsService property. @@ -223,15 +218,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getJmsService(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getJmsService(); /** * Sets the value of the jmsService property. * * @param value allowed object is {@link String } */ - public void setJmsService(String value) throws PropertyVetoException; + void setJmsService(String value) throws PropertyVetoException; /** * Gets the value of the jvm property. @@ -239,15 +234,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getJvm(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getJvm(); /** * Sets the value of the jvm property. * * @param value allowed object is {@link String } */ - public void setJvm(String value) throws PropertyVetoException; + void setJvm(String value) throws PropertyVetoException; /** * Gets the value of the security property. @@ -255,15 +250,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getSecurity(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getSecurity(); /** * Sets the value of the security property. * * @param value allowed object is {@link String } */ - public void setSecurity(String value) throws PropertyVetoException; + void setSecurity(String value) throws PropertyVetoException; /** * Gets the value of the web-service-container property. @@ -271,15 +266,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getWebServicesContainer(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getWebServicesContainer(); /** * Sets the value of the web-service-container property. * * @param value allowed object is {@link String } */ - public void setWebServicesContainer(String value) throws PropertyVetoException; + void setWebServicesContainer(String value) throws PropertyVetoException; /** * Gets the value of the jpa property. @@ -287,15 +282,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getJpa(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getJpa(); /** * Sets the value of the jpa property. * * @param value allowed object is {@link String } */ - public void setJpa(String value) throws PropertyVetoException; + void setJpa(String value) throws PropertyVetoException; /** * Gets the value of the jax-ra property. @@ -303,15 +298,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getJersey(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getJersey(); /** * Sets the value of the jax-ra property. * * @param value allowed object is {@link String } */ - public void setJersey(String value) throws PropertyVetoException; + void setJersey(String value) throws PropertyVetoException; /** * Gets the value of the cloudTenantManager property. @@ -319,15 +314,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getCloudTenantManager(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getCloudTenantManager(); /** * Sets the value of the cloudTenantManager property. * * @param value allowed object is {@link String } */ - public void setCloudTenantManager(String value) throws PropertyVetoException; + void setCloudTenantManager(String value) throws PropertyVetoException; /** * Gets the value of the cloud property. @@ -335,15 +330,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getCloud(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getCloud(); /** * Sets the value of the cloud property. * * @param value allowed object is {@link String } */ - public void setCloud(String value) throws PropertyVetoException; + void setCloud(String value) throws PropertyVetoException; /** * Gets the value of the cloud Orchestrator property. @@ -351,15 +346,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getCloudOrchestrator(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getCloudOrchestrator(); /** * Sets the value of the cloud Orchestrator property. * * @param value allowed object is {@link String } */ - public void setCloudOrchestrator(String value) throws PropertyVetoException; + void setCloudOrchestrator(String value) throws PropertyVetoException; /** * Gets the value of the cloud Elasticity property. @@ -367,19 +362,15 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getCloudElasticity(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getCloudElasticity(); /** * Sets the value of the cloud elasticity property. * * @param value allowed object is {@link String } */ - public void setCloudElasticity(String value) throws PropertyVetoException; - - /** - * Properties as per {@link PropertyBag} - */ + void setCloudElasticity(String value) throws PropertyVetoException; /** * Gets the value of the cloud IMS property. @@ -387,20 +378,20 @@ public interface ModuleMonitoringLevels extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "OFF") - @Pattern(regexp = "(OFF|LOW|HIGH)") - public String getCloudVirtAssemblyService(); + @Pattern(regexp = MONITORING_LEVELS, message = MONITORING_LEVELS_MSG) + String getCloudVirtAssemblyService(); /** * Sets the value of the cloud IMS property. * * @param value allowed object is {@link String } */ - public void setCloudVirtAssemblyService(String value) throws PropertyVetoException; + void setCloudVirtAssemblyService(String value) throws PropertyVetoException; /** * Properties as per {@link PropertyBag} */ - + @Override @ToDo(priority = ToDo.Priority.IMPORTANT, details = "Provide PropertyDesc for legal props") @PropertiesDesc(props = {}) @Element diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Profiler.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Profiler.java index b6a33ba6483..83bec43f4ef 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Profiler.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Profiler.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,23 +17,22 @@ package com.sun.enterprise.config.serverbeans; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.Element; -import org.jvnet.hk2.config.ConfigBeanProxy; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; import java.util.List; import org.glassfish.api.admin.config.PropertiesDesc; -import static org.glassfish.config.support.Constants.NAME_REGEX; +import org.glassfish.quality.ToDo; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.Element; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import org.glassfish.quality.ToDo; - -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; +import static org.glassfish.config.support.Constants.NAME_REGEX; /** * @@ -59,15 +59,15 @@ public interface Profiler extends ConfigBeanProxy, PropertyBag, JvmOptionBag { */ @Attribute(key = false) // bizarre case of having a name, but it's not a key; it's a singleton @NotNull - @Pattern(regexp = NAME_REGEX) - public String getName(); + @Pattern(regexp = NAME_REGEX, message = "Pattern: " + NAME_REGEX) + String getName(); /** * Sets the value of the name property. * * @param value allowed object is {@link String } */ - public void setName(String value) throws PropertyVetoException; + void setName(String value) throws PropertyVetoException; /** * Gets the value of the classpath property. @@ -75,14 +75,14 @@ public interface Profiler extends ConfigBeanProxy, PropertyBag, JvmOptionBag { * @return possible object is {@link String } */ @Attribute - public String getClasspath(); + String getClasspath(); /** * Sets the value of the classpath property. * * @param value allowed object is {@link String } */ - public void setClasspath(String value) throws PropertyVetoException; + void setClasspath(String value) throws PropertyVetoException; /** * Gets the value of the nativeLibraryPath property. @@ -90,14 +90,14 @@ public interface Profiler extends ConfigBeanProxy, PropertyBag, JvmOptionBag { * @return possible object is {@link String } */ @Attribute - public String getNativeLibraryPath(); + String getNativeLibraryPath(); /** * Sets the value of the nativeLibraryPath property. * * @param value allowed object is {@link String } */ - public void setNativeLibraryPath(String value) throws PropertyVetoException; + void setNativeLibraryPath(String value) throws PropertyVetoException; /** * Gets the value of the enabled property. @@ -105,18 +105,19 @@ public interface Profiler extends ConfigBeanProxy, PropertyBag, JvmOptionBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "true", dataType = Boolean.class) - public String getEnabled(); + String getEnabled(); /** * Sets the value of the enabled property. * * @param value allowed object is {@link String } */ - public void setEnabled(String value) throws PropertyVetoException; + void setEnabled(String value) throws PropertyVetoException; /** * Properties as per {@link org.jvnet.hk2.config.types.PropertyBag} */ + @Override @ToDo(priority = ToDo.Priority.IMPORTANT, details = "Provide PropertyDesc for legal props") @PropertiesDesc(props = {}) @Element diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ProviderConfig.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ProviderConfig.java index 2d4e93d0002..d3ace247333 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ProviderConfig.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ProviderConfig.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,24 +17,24 @@ package com.sun.enterprise.config.serverbeans; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.Element; -import org.jvnet.hk2.config.ConfigBeanProxy; +import com.sun.enterprise.config.serverbeans.customvalidators.JavaClassName; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; import java.util.List; -import org.glassfish.api.admin.config.PropertyDesc; import org.glassfish.api.admin.config.PropertiesDesc; -import static org.glassfish.config.support.Constants.NAME_REGEX; +import org.glassfish.api.admin.config.PropertyDesc; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.Element; import org.jvnet.hk2.config.types.Property; import org.jvnet.hk2.config.types.PropertyBag; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; - -import com.sun.enterprise.config.serverbeans.customvalidators.JavaClassName; +import static org.glassfish.config.support.Constants.NAME_REGEX; /** * The provider-config element defines the configuration of an authentication provider @@ -52,120 +53,141 @@ @Configured public interface ProviderConfig extends ConfigBeanProxy, PropertyBag { + String PROVIDER_TYPES = "(client|server|client-server)"; + /** * Gets the value of the providerId property. - * * Identifier used to uniquely identify this provider-config element * * @return possible object is {@link String } */ @Attribute(key = true) - @Pattern(regexp = NAME_REGEX) + @Pattern(regexp = NAME_REGEX, message = "Pattern: " + NAME_REGEX) @NotNull - public String getProviderId(); + String getProviderId(); /** * Sets the value of the providerId property. * * @param value allowed object is {@link String } */ - public void setProviderId(String value) throws PropertyVetoException; + void setProviderId(String value) throws PropertyVetoException; /** * Gets the value of the providerType property. - * - * Defines whether the provider is a client authentication provider or a server authentication provider. + * Defines whether the provider is a client authentication provider or a server authentication + * provider. * * @return possible object is {@link String } */ @Attribute @NotNull - @Pattern(regexp = "(client|server|client-server)") - public String getProviderType(); + @Pattern(regexp = PROVIDER_TYPES, message = "Valid values: " + PROVIDER_TYPES) + String getProviderType(); /** * Sets the value of the providerType property. * * @param value allowed object is {@link String } */ - public void setProviderType(String value) throws PropertyVetoException; + void setProviderType(String value) throws PropertyVetoException; /** * Gets the value of the className property. - * * Defines the java implementation class of the provider. - * - * Client authentication providers must implement the com.sun.enterprise.security.jauth.ClientAuthModule interface. - * - * Server-side providers must implement the com.sun.enterprise.security.jauth.ServerAuthModule interface. - * - * A provider may implement both interfaces, but it must implement the interface corresponding to its provider type. + * Client authentication providers must implement the + * com.sun.enterprise.security.jauth.ClientAuthModule interface. + * Server-side providers must implement the com.sun.enterprise.security.jauth.ServerAuthModule + * interface. + * A provider may implement both interfaces, but it must implement the interface corresponding + * to its provider type. * * @return possible object is {@link String } */ @Attribute @NotNull @JavaClassName - public String getClassName(); + String getClassName(); /** * Sets the value of the className property. * * @param value allowed object is {@link String } */ - public void setClassName(String value) throws PropertyVetoException; + void setClassName(String value) throws PropertyVetoException; /** * Gets the value of the requestPolicy property. - * - * Defines the authentication policy requirements associated with request processing performed by the authentication + * Defines the authentication policy requirements associated with request processing performed + * by the authentication * provider * * @return possible object is {@link RequestPolicy } */ @Element - public RequestPolicy getRequestPolicy(); + RequestPolicy getRequestPolicy(); /** * Sets the value of the requestPolicy property. * * @param value allowed object is {@link RequestPolicy } */ - public void setRequestPolicy(RequestPolicy value) throws PropertyVetoException; + void setRequestPolicy(RequestPolicy value) throws PropertyVetoException; /** * Gets the value of the responsePolicy property. - * - * Defines the authentication policy requirements associated with the response processing performed by the + * Defines the authentication policy requirements associated with the response processing + * performed by the * authentication provider. * * @return possible object is {@link ResponsePolicy } */ @Element - public ResponsePolicy getResponsePolicy(); + ResponsePolicy getResponsePolicy(); /** * Sets the value of the responsePolicy property. * * @param value allowed object is {@link ResponsePolicy } */ - public void setResponsePolicy(ResponsePolicy value) throws PropertyVetoException; + void setResponsePolicy(ResponsePolicy value) throws PropertyVetoException; /** * Properties. */ - @PropertiesDesc(props = { - @PropertyDesc(name = "security.config", defaultValue = "${com.sun.aas.instanceRoot}/config/wss-server-config-1.0.xml", description = "Specifies the location of the message security configuration file"), - - @PropertyDesc(name = "debug", defaultValue = "false", dataType = Boolean.class, description = "Enables dumping of server provider debug messages to the server log"), - - @PropertyDesc(name = "dynamic.username.password", defaultValue = "false", dataType = Boolean.class, description = "Signals the provider runtime to collect the user name and password from the " + @Override + @PropertiesDesc( + props = { + @PropertyDesc( + name = "security.config", + defaultValue = "${com.sun.aas.instanceRoot}/config/wss-server-config-1.0.xml", + description = "Specifies the location of the message security configuration file"), + + @PropertyDesc( + name = "debug", + defaultValue = "false", + dataType = Boolean.class, + description = "Enables dumping of server provider debug messages to the server log"), + + @PropertyDesc( + name = "dynamic.username.password", + defaultValue = "false", + dataType = Boolean.class, + description = "Signals the provider runtime to collect the user name and password from the " + "CallbackHandler for each request. If false, the user name and password for wsse:UsernameToken(s) is " + "collected once, during module initialization. Applicable only for a ClientAuthModule"), - @PropertyDesc(name = "encryption.key.alias", defaultValue = "s1as", description = "Specifies the encryption key used by the provider. The key is identified by its keystore alias"), - - @PropertyDesc(name = "signature.key.alias", defaultValue = "s1as", description = "Specifies the signature key used by the provider. The key is identified by its keystore alias") }) + @PropertyDesc( + name = "encryption.key.alias", + defaultValue = "s1as", + description = "Specifies the encryption key used by the provider. The key is identified by its keystore alias"), + + @PropertyDesc( + name = "signature.key.alias", + defaultValue = "s1as", + description = "Specifies the signature key used by the provider. The key is identified by its keystore alias") + } + ) @Element List getProperty(); } diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/RequestPolicy.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/RequestPolicy.java index 874fc34bbeb..38b32077e27 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/RequestPolicy.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/RequestPolicy.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,18 +17,19 @@ package com.sun.enterprise.config.serverbeans; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.ConfigBeanProxy; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; -import java.io.Serializable; -import jakarta.validation.constraints.Pattern; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; /** - * Used to define the authentication policy requirements associated with the request processing performed by an - * authentication provider (i.e. when a client provider's ClientAuthModule.initiateRequest() method is called or when a + * Used to define the authentication policy requirements associated with the request processing + * performed by an + * authentication provider (i.e. when a client provider's ClientAuthModule.initiateRequest() method + * is called or when a * server provider's ServerAuthModule.validateRequest() method is called) */ @@ -36,46 +38,49 @@ @Configured public interface RequestPolicy extends ConfigBeanProxy { + String AUTH_RECIPIENT_TIMINGS = "(before-content|after-content)"; + String AUTH_SOURCES = "(sender|content|username-password)"; + /** * Gets the value of the authSource property. - * - * Defines a requirement for message layer sender authentication (e.g. username password) or content authentication + * Defines a requirement for message layer sender authentication (e.g. username password) or + * content authentication * (e.g. digital signature) * * @return possible object is {@link String } */ @Attribute - @Pattern(regexp = "(sender|content|username-password)") - public String getAuthSource(); + @Pattern(regexp = AUTH_SOURCES, message = "Valid values: " + AUTH_SOURCES) + String getAuthSource(); /** * Sets the value of the authSource property. * * @param value allowed object is {@link String } */ - public void setAuthSource(String value) throws PropertyVetoException; + void setAuthSource(String value) throws PropertyVetoException; /** - * Specifies whether recipient authentication occurs before or after content authentication. Allowed values are - * 'before-content' and 'after-content'. - * - * Defines a requirement for message layer authentication of the reciever of a message to its sender (e.g. by XML - * encryption). before-content indicates that recipient authentication (e.g. encryption) is to occur before any content - * authentication (e.g. encrypt then sign) with respect to the target of the containing auth-policy. after-content - * indicates that recipient authentication (e.g. encryption) is to occur after any content authentication (e.g. sign + * Specifies whether recipient authentication occurs before or after content authentication. + * Allowed values are 'before-content' and 'after-content'. + * Defines a requirement for message layer authentication of the reciever of a message to its + * sender (e.g. by XML encryption). before-content indicates that recipient authentication + * (e.g. encryption) is to occur before any content authentication (e.g. encrypt then sign) with + * respect to the target of the containing auth-policy. after-content indicates that recipient + * authentication (e.g. encryption) is to occur after any content authentication (e.g. sign * then encrypt) with respect to the target of the containing auth-policy * * @return possible object is {@link String } */ @Attribute - @Pattern(regexp = "(before-content|after-content)") - public String getAuthRecipient(); + @Pattern(regexp = AUTH_RECIPIENT_TIMINGS, message = "Valid values: " + AUTH_RECIPIENT_TIMINGS) + String getAuthRecipient(); /** * Sets the value of the authRecipient property. * * @param value allowed object is {@link String } */ - public void setAuthRecipient(String value) throws PropertyVetoException; + void setAuthRecipient(String value) throws PropertyVetoException; } diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Resource.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Resource.java index e71f755cec1..683e899f881 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Resource.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Resource.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,14 +17,15 @@ package com.sun.enterprise.config.serverbeans; +import jakarta.validation.constraints.Pattern; + +import java.beans.PropertyVetoException; + import org.jvnet.hk2.config.Attribute; import org.jvnet.hk2.config.ConfigBeanProxy; import org.jvnet.hk2.config.Configured; import org.jvnet.hk2.config.DuckTyped; -import jakarta.validation.constraints.Pattern; -import java.beans.PropertyVetoException; - /** * Tag interface for all types of resource. * @@ -32,6 +34,8 @@ @Configured public interface Resource extends ConfigBeanProxy { + String OBJECT_TYPES = "(system-all|system-all-req|system-admin|system-instance|user)"; + /** * Gets the value of the objectType property. where object-type defines the type of the resource. It can be: system-all * - These are system resources for all instances and DAS system-all-req - These are system-all resources that are @@ -42,7 +46,7 @@ public interface Resource extends ConfigBeanProxy { * @return possible object is {@link String } */ @Attribute(defaultValue = "user") - @Pattern(regexp = "(system-all|system-all-req|system-admin|system-instance|user)") + @Pattern(regexp = OBJECT_TYPES, message = "Valid values: " + OBJECT_TYPES) String getObjectType(); /** diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ResourceRef.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ResourceRef.java index c333b8c8ef3..b21745be6cd 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ResourceRef.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ResourceRef.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,21 +17,16 @@ package com.sun.enterprise.config.serverbeans; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.ConfigBeanProxy; -import org.jvnet.hk2.config.Configured; - -import java.beans.PropertyVetoException; - import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Pattern; -import org.glassfish.api.admin.RestRedirects; -import org.glassfish.api.admin.RestRedirect; +import java.beans.PropertyVetoException; -/** - * - */ +import org.glassfish.api.admin.RestRedirect; +import org.glassfish.api.admin.RestRedirects; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; /* @XmlType(name = "") */ @@ -39,6 +35,8 @@ @RestRedirect(opType = RestRedirect.OpType.DELETE, commandName = "delete-resource-ref") }) public interface ResourceRef extends ConfigBeanProxy { + String PATTERN_REF = "[^':,][^':,]*"; + /** * Determines whether the resource is active or ignored. * @@ -55,14 +53,15 @@ public interface ResourceRef extends ConfigBeanProxy { void setEnabled(String value) throws PropertyVetoException; /** - * References the name attribute of a resources, such as an {@link org.glassfish.connectors.config.JdbcResource} or + * References the name attribute of a resources, such as an + * {@link org.glassfish.connectors.config.JdbcResource} or * {@link org.glassfish.connectors.config.JdbcConnectionPool}. * * @return possible object is {@link String } */ @Attribute(key = true) @NotNull - @Pattern(regexp = "[^':,][^':,]*") + @Pattern(regexp = PATTERN_REF, message = "Pattern: " + PATTERN_REF) String getRef(); /** diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ResponsePolicy.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ResponsePolicy.java index f28877cf5bc..7b5a2162287 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ResponsePolicy.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ResponsePolicy.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,14 +17,13 @@ package com.sun.enterprise.config.serverbeans; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.ConfigBeanProxy; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; -import java.io.Serializable; -import jakarta.validation.constraints.Pattern; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; /** * Used to define the authentication policy requirements associated with the response processing performed by an @@ -36,25 +36,27 @@ @Configured public interface ResponsePolicy extends ConfigBeanProxy { + String AUTH_RECIPIENT_TIMINGS = "(before-content|after-content)"; + String AUTH_SOURCES = "(sender|content|username-password)"; + /** - * Specifies the type of required authentication, either "sender" (user name and password) or "content" (digital - * signature). - * - * Defines a requirement for message layer sender authentication (e.g. username password) or content authentication - * (e.g. digital signature) + * Specifies the type of required authentication, either "sender" (user name and password) or + * "content" (digital signature). + * Defines a requirement for message layer sender authentication (e.g. username password) or + * content authentication (e.g. digital signature) * * @return possible object is {@link String } */ @Attribute - @Pattern(regexp = "(sender|content|username-password)") - public String getAuthSource(); + @Pattern(regexp = AUTH_SOURCES, message = "Valid values: " + AUTH_SOURCES) + String getAuthSource(); /** * Sets the value of the authSource property. * * @param value allowed object is {@link String } */ - public void setAuthSource(String value) throws PropertyVetoException; + void setAuthSource(String value) throws PropertyVetoException; /** * Specifies whether recipient authentication occurs before or after content authentication. Allowed values are @@ -70,14 +72,14 @@ public interface ResponsePolicy extends ConfigBeanProxy { * @return possible object is {@link String } */ @Attribute - @Pattern(regexp = "(before-content|after-content)") - public String getAuthRecipient(); + @Pattern(regexp = AUTH_RECIPIENT_TIMINGS, message = "Valid values: " + AUTH_RECIPIENT_TIMINGS) + String getAuthRecipient(); /** * Sets the value of the authRecipient property. * * @param value allowed object is {@link String } */ - public void setAuthRecipient(String value) throws PropertyVetoException; + void setAuthRecipient(String value) throws PropertyVetoException; } diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Server.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Server.java index da76d3c1744..dc1385a929a 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Server.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/Server.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,60 +17,74 @@ package com.sun.enterprise.config.serverbeans; -import com.sun.enterprise.config.util.ConfigApiLoggerInfo; -import com.sun.enterprise.config.util.InstanceRegisterInstanceCommandParameters; -import static com.sun.enterprise.config.util.RegisterInstanceCommandParameters.ParameterNames.*; import com.sun.enterprise.config.serverbeans.customvalidators.ConfigRefConstraint; import com.sun.enterprise.config.serverbeans.customvalidators.ConfigRefValidator; -import com.sun.enterprise.config.serverbeans.customvalidators.NotTargetKeyword; import com.sun.enterprise.config.serverbeans.customvalidators.NotDuplicateTargetName; -import com.sun.enterprise.config.util.ServerHelper; +import com.sun.enterprise.config.serverbeans.customvalidators.NotTargetKeyword; +import com.sun.enterprise.config.serverbeans.customvalidators.ReferenceConstraint; +import com.sun.enterprise.config.util.ConfigApiLoggerInfo; +import com.sun.enterprise.config.util.InstanceRegisterInstanceCommandParameters; import com.sun.enterprise.config.util.PortBaseHelper; import com.sun.enterprise.config.util.PortManager; +import com.sun.enterprise.config.util.ServerHelper; import com.sun.enterprise.util.LocalStringManagerImpl; import com.sun.enterprise.util.io.FileUtils; import com.sun.enterprise.util.net.NetUtils; -import java.io.*; -import org.glassfish.api.Param; -import org.glassfish.api.admin.AdminCommandContext; -import org.glassfish.config.support.*; -import com.sun.enterprise.config.serverbeans.customvalidators.ReferenceConstraint; -import org.jvnet.hk2.annotations.Service; -import org.glassfish.hk2.api.PerLookup; -import org.jvnet.hk2.config.*; -import org.jvnet.hk2.config.types.Property; -import org.jvnet.hk2.config.types.PropertyBag; -import org.glassfish.api.ActionReport; -import org.glassfish.api.admin.config.Named; -import org.glassfish.api.admin.config.PropertiesDesc; -import org.glassfish.api.admin.config.ReferenceContainer; -import org.glassfish.quality.ToDo; -import static org.glassfish.config.support.Constants.*; +import jakarta.inject.Inject; +import jakarta.validation.Payload; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.beans.PropertyVetoException; -import java.util.List; +import java.io.File; import java.util.Iterator; +import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; -import jakarta.inject.Inject; -import jakarta.validation.Payload; -import jakarta.validation.constraints.Min; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; -import org.glassfish.api.admin.ServerEnvironment; +import org.glassfish.api.ActionReport; +import org.glassfish.api.Param; +import org.glassfish.api.admin.AdminCommandContext; import org.glassfish.api.admin.CommandRunner; +import org.glassfish.api.admin.ServerEnvironment; +import org.glassfish.api.admin.config.Named; +import org.glassfish.api.admin.config.PropertiesDesc; +import org.glassfish.api.admin.config.ReferenceContainer; import org.glassfish.api.logging.LogHelper; +import org.glassfish.config.support.CreationDecorator; +import org.glassfish.config.support.DeletionDecorator; +import org.glassfish.hk2.api.PerLookup; +import org.glassfish.quality.ToDo; +import org.jvnet.hk2.annotations.Service; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.ConfigSupport; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.Dom; +import org.jvnet.hk2.config.DuckTyped; +import org.jvnet.hk2.config.Element; +import org.jvnet.hk2.config.SingleConfigCode; +import org.jvnet.hk2.config.Transaction; +import org.jvnet.hk2.config.TransactionFailure; +import org.jvnet.hk2.config.types.Property; +import org.jvnet.hk2.config.types.PropertyBag; + +import static com.sun.enterprise.config.util.RegisterInstanceCommandParameters.ParameterNames.OPERAND_NAME; +import static com.sun.enterprise.config.util.RegisterInstanceCommandParameters.ParameterNames.PARAM_CHECKPORTS; +import static com.sun.enterprise.config.util.RegisterInstanceCommandParameters.ParameterNames.PARAM_CLUSTER; +import static com.sun.enterprise.config.util.RegisterInstanceCommandParameters.ParameterNames.PARAM_CONFIG; +import static com.sun.enterprise.config.util.RegisterInstanceCommandParameters.ParameterNames.PARAM_LBENABLED; +import static com.sun.enterprise.config.util.RegisterInstanceCommandParameters.ParameterNames.PARAM_NODE; +import static com.sun.enterprise.config.util.RegisterInstanceCommandParameters.ParameterNames.PARAM_PORTBASE; +import static org.glassfish.config.support.Constants.NAME_SERVER_REGEX; /** - * - * Java EE Application Server Configuration - * - * Each Application Server instance is a Java EE compliant container. One server instance is specially designated as the - * Administration Server in SE/EE - * + * Jakarta EE Application Server Configuration + * Each Application Server instance is a Jakarta EE compliant container. + * One server instance is specially designated as the Administration Server in SE/EE * User applications cannot be deployed to an Administration Server instance */ @Configured @@ -77,31 +92,31 @@ @SuppressWarnings("unused") @NotDuplicateTargetName(message = "{server.duplicate.name}", payload = Server.class) @ReferenceConstraint(skipDuringCreation = true, payload = Server.class) -public interface Server extends ConfigBeanProxy, PropertyBag, Named, SystemPropertyBag, ReferenceContainer, RefContainer, Payload { +public interface Server + extends ConfigBeanProxy, PropertyBag, Named, SystemPropertyBag, ReferenceContainer, RefContainer, Payload { String lbEnabledSystemProperty = "org.glassfish.lb-enabled-default"; @Param(name = OPERAND_NAME, primary = true) @Override - public void setName(String value) throws PropertyVetoException; + void setName(String value) throws PropertyVetoException; @NotTargetKeyword(message = "{server.reserved.name}", payload = Server.class) @Pattern(regexp = NAME_SERVER_REGEX, message = "{server.invalid.name}", payload = Server.class) @Override - public String getName(); + String getName(); /** * Gets the value of the configRef property. - * - * Points to a named config. Needed for stand-alone servers. If server instance is part of a cluster, then it points to - * the cluster config + * Points to a named config. Needed for stand-alone servers. + * If server instance is part of a cluster, then it points to the cluster config * * @return possible object is {@link String } */ @Attribute @NotNull @NotTargetKeyword(message = "{server.reserved.name}", payload = Server.class) - @Pattern(regexp = NAME_SERVER_REGEX) + @Pattern(regexp = NAME_SERVER_REGEX, message = "Pattern: " + NAME_SERVER_REGEX) @ReferenceConstraint.RemoteKey(message = "{resourceref.invalid.configref}", type = Config.class) String getConfigRef(); @@ -359,8 +374,9 @@ public Object run(Server param) throws PropertyVetoException, TransactionFailure public static Config getConfig(Server server) { try { - if (server == null) + if (server == null) { return null; + } Dom serverDom = Dom.unwrap(server); Configs configs = serverDom.getHabitat().getService(Configs.class); @@ -763,8 +779,9 @@ public void decorate(AdminCommandContext context, Servers parent, final Server c // bnevins September 30, 2010 // don't delete the config if it wasn't auto-generated. final String autoGeneratedName = child.getName() + "-config"; - if (!autoGeneratedName.equals(instanceConfig)) + if (!autoGeneratedName.equals(instanceConfig)) { return; + } try { if (config != null) { diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ServerRef.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ServerRef.java index cd0b236e099..52cf09072c4 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ServerRef.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/ServerRef.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -17,32 +18,35 @@ package com.sun.enterprise.config.serverbeans; import com.sun.enterprise.config.serverbeans.customvalidators.ReferenceConstraint; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.Element; -import org.jvnet.hk2.config.ConfigBeanProxy; -import static org.glassfish.config.support.Constants.NAME_SERVER_REGEX; -import java.beans.PropertyVetoException; import jakarta.validation.Payload; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Pattern; -/** - * - */ +import java.beans.PropertyVetoException; -/* @XmlType(name = "", propOrder = { - "healthChecker" -}) */ +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; +import org.jvnet.hk2.config.Element; + +import static org.glassfish.config.support.Constants.NAME_SERVER_REGEX; + +/* + * @XmlType(name = "", propOrder = { + * "healthChecker" + * }) + */ @Configured @ReferenceConstraint(skipDuringCreation = true, payload = ServerRef.class) public interface ServerRef extends ConfigBeanProxy, Ref, Payload { + // defines the default value for lb-enabled attribute + String LBENABLED_DEFAULT_VALUE = "true"; + /** * Gets the value of the ref property. - * * A reference to the name of a server defined elsewhere * * @return possible object is {@link String } @@ -52,7 +56,7 @@ public interface ServerRef extends ConfigBeanProxy, Ref, Payload { @NotNull @Pattern(regexp = NAME_SERVER_REGEX, message = "{server.invalid.name}", payload = ServerRef.class) @ReferenceConstraint.RemoteKey(message = "{resourceref.invalid.server-ref}", type = Server.class) - public String getRef(); + String getRef(); /** * Sets the value of the ref property. @@ -60,59 +64,58 @@ public interface ServerRef extends ConfigBeanProxy, Ref, Payload { * @param value allowed object is {@link String } */ @Override - public void setRef(String value) throws PropertyVetoException; + void setRef(String value) throws PropertyVetoException; /** * Gets the value of the disableTimeoutInMinutes property. - * - * The time, in minutes, that it takes this server to reach a quiescent state after having been disabled + * The time, in minutes, that it takes this server to reach a quiescent state after having been + * disabled * * @return possible object is {@link String } */ @Attribute(defaultValue = "30") - public String getDisableTimeoutInMinutes(); + String getDisableTimeoutInMinutes(); /** * Sets the value of the disableTimeoutInMinutes property. * * @param value allowed object is {@link String } */ - public void setDisableTimeoutInMinutes(String value) throws PropertyVetoException; + void setDisableTimeoutInMinutes(String value) throws PropertyVetoException; /** * Gets the value of the lbEnabled property. - * - * Causes any and all load-balancers using this server to consider this server available to them. Defaults to - * available(true) + * Causes any and all load-balancers using this server to consider this server available to + * them. Defaults to available(true) * * @return possible object is {@link String } */ @Attribute(defaultValue = LBENABLED_DEFAULT_VALUE, dataType = Boolean.class) - public String getLbEnabled(); + String getLbEnabled(); /** * Sets the value of the lbEnabled property. * * @param value allowed object is {@link String } */ - public void setLbEnabled(String value) throws PropertyVetoException; + void setLbEnabled(String value) throws PropertyVetoException; /** * Gets the value of the enabled property. - * - * A boolean flag that causes the server to be enabled to serve end-users, or not. Default is to be enabled (true) + * A boolean flag that causes the server to be enabled to serve end-users, or not. + * Default is to be enabled (true) * * @return possible object is {@link String } */ @Attribute(defaultValue = "true", dataType = Boolean.class) - public String getEnabled(); + String getEnabled(); /** * Sets the value of the enabled property. * * @param value allowed object is {@link String } */ - public void setEnabled(String value) throws PropertyVetoException; + void setEnabled(String value) throws PropertyVetoException; /** * Gets the value of the healthChecker property. @@ -120,16 +123,12 @@ public interface ServerRef extends ConfigBeanProxy, Ref, Payload { * @return possible object is {@link HealthChecker } */ @Element("health-checker") - public HealthChecker getHealthChecker(); + HealthChecker getHealthChecker(); /** * Sets the value of the healthChecker property. * * @param value allowed object is {@link HealthChecker } */ - public void setHealthChecker(HealthChecker value) throws PropertyVetoException; - - //defines the default value for lb-enabled attribute - public String LBENABLED_DEFAULT_VALUE = "true"; - + void setHealthChecker(HealthChecker value) throws PropertyVetoException; } diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/SystemProperty.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/SystemProperty.java index 226ae49ed0f..651954b8d15 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/SystemProperty.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/SystemProperty.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,17 +17,17 @@ package com.sun.enterprise.config.serverbeans; -import org.jvnet.hk2.config.Attribute; -import org.jvnet.hk2.config.Configured; -import org.jvnet.hk2.config.ConfigBeanProxy; - -import java.beans.PropertyVetoException; - import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Pattern; -import org.glassfish.api.admin.RestRedirects; +import java.beans.PropertyVetoException; + import org.glassfish.api.admin.RestRedirect; +import org.glassfish.api.admin.RestRedirects; +import org.jvnet.hk2.config.Attribute; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.Configured; + import static org.glassfish.config.support.Constants.NAME_REGEX; /** @@ -38,8 +39,10 @@ }) */ @Configured -@RestRedirects({ @RestRedirect(opType = RestRedirect.OpType.POST, commandName = "create-system-properties"), - @RestRedirect(opType = RestRedirect.OpType.DELETE, commandName = "delete-system-property") }) +@RestRedirects({ + @RestRedirect(opType = RestRedirect.OpType.POST, commandName = "create-system-properties"), + @RestRedirect(opType = RestRedirect.OpType.DELETE, commandName = "delete-system-property") +}) public interface SystemProperty extends ConfigBeanProxy { /** @@ -49,15 +52,15 @@ public interface SystemProperty extends ConfigBeanProxy { */ @Attribute(key = true) @NotNull - @Pattern(regexp = NAME_REGEX) - public String getName(); + @Pattern(regexp = NAME_REGEX, message = "Pattern: " + NAME_REGEX) + String getName(); /** * Sets the value of the name property. * * @param value allowed object is {@link String } */ - public void setName(String value) throws PropertyVetoException; + void setName(String value) throws PropertyVetoException; /** * Gets the value of the value property. @@ -66,14 +69,14 @@ public interface SystemProperty extends ConfigBeanProxy { */ @Attribute @NotNull - public String getValue(); + String getValue(); /** * Sets the value of the value property. * * @param value allowed object is {@link String } */ - public void setValue(String value) throws PropertyVetoException; + void setValue(String value) throws PropertyVetoException; /** * Gets the value of the description property. @@ -81,13 +84,13 @@ public interface SystemProperty extends ConfigBeanProxy { * @return possible object is {@link String } */ @Attribute - public String getDescription(); + String getDescription(); /** * Sets the value of the description property. * * @param value allowed object is {@link String } */ - public void setDescription(String value) throws PropertyVetoException; + void setDescription(String value) throws PropertyVetoException; } diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/VirtualServer.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/VirtualServer.java index 52356bacb99..2fd876d539d 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/VirtualServer.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/VirtualServer.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,21 +17,22 @@ package com.sun.enterprise.config.serverbeans; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; + import java.beans.PropertyVetoException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; -import org.glassfish.grizzly.config.dom.NetworkConfig; -import org.glassfish.grizzly.config.dom.NetworkListener; import org.glassfish.api.admin.RestRedirect; import org.glassfish.api.admin.RestRedirects; import org.glassfish.api.admin.config.PropertiesDesc; import org.glassfish.api.admin.config.PropertyDesc; import org.glassfish.config.support.datatypes.PositiveInteger; +import org.glassfish.grizzly.config.dom.NetworkConfig; +import org.glassfish.grizzly.config.dom.NetworkListener; import org.jvnet.hk2.config.Attribute; import org.jvnet.hk2.config.ConfigBeanProxy; import org.jvnet.hk2.config.Configured; @@ -44,15 +46,23 @@ * * Virtualization in Application Server allows multiple URL domains to be served by the same HTTP server process, which * is listening on multiple host addresses If an application is available at two virtual servers, they still share same - * physical resource pools, such as JDBC connection pools. Sun ONE Application Server allows a list of virtual servers, - * to be specified along with web-module and j2ee-application elements. This establishes an association between URL + * physical resource pools, such as JDBC connection pools. GlassFish allows a list of virtual servers, + * to be specified along with web-module and Jakarta EE application elements. This establishes an association between URL * domains, represented by the virtual server and the web modules (standalone web modules or web modules inside the ear * file) */ @Configured -@RestRedirects({ @RestRedirect(opType = RestRedirect.OpType.POST, commandName = "create-virtual-server"), - @RestRedirect(opType = RestRedirect.OpType.DELETE, commandName = "delete-virtual-server") }) +@RestRedirects({ + @RestRedirect(opType = RestRedirect.OpType.POST, commandName = "create-virtual-server"), + @RestRedirect(opType = RestRedirect.OpType.DELETE, commandName = "delete-virtual-server" +)}) public interface VirtualServer extends ConfigBeanProxy, PropertyBag { + + String VALUES_ACCESS_LOG_ENABLED = "(true|on|false|off|inherit)"; + String VALUES_SSO_ENABLED = "(true|on|false|off|inherit)"; + String VALUES_SSO_COOKIE_ENABLED = "(true|false|dynamic)"; + String VALUES_STATE = "(on|off|disabled)"; + /** * Gets the value of the id property. * @@ -154,7 +164,7 @@ public interface VirtualServer extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "on") - @Pattern(regexp = "(on|off|disabled)") + @Pattern(regexp = VALUES_STATE, message = "Valid values: " + VALUES_STATE) String getState(); /** @@ -202,7 +212,7 @@ public interface VirtualServer extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "inherit") - @Pattern(regexp = "(true|on|false|off|inherit)") + @Pattern(regexp = VALUES_SSO_ENABLED, message = "Valid values: " + VALUES_SSO_ENABLED) String getSsoEnabled(); /** @@ -218,7 +228,7 @@ public interface VirtualServer extends ConfigBeanProxy, PropertyBag { * @return possible object is {@link String } */ @Attribute(defaultValue = "inherit") - @Pattern(regexp = "(true|on|false|off|inherit)") + @Pattern(regexp = VALUES_ACCESS_LOG_ENABLED, message = "Valid values: " + VALUES_ACCESS_LOG_ENABLED) String getAccessLoggingEnabled(); /** @@ -268,7 +278,7 @@ public interface VirtualServer extends ConfigBeanProxy, PropertyBag { * "dynamic" */ @Attribute(defaultValue = "dynamic") - @Pattern(regexp = "(true|false|dynamic)") + @Pattern(regexp = VALUES_SSO_COOKIE_ENABLED, message = "Valid values: " + VALUES_SSO_COOKIE_ENABLED) String getSsoCookieSecure(); void setSsoCookieSecure(String value); @@ -294,7 +304,7 @@ class Duck { public static void addNetworkListener(VirtualServer server, String name) throws PropertyVetoException { final String listeners = server.getNetworkListeners(); final String[] strings = listeners == null ? new String[0] : listeners.split(","); - final Set set = new TreeSet(); + final Set set = new TreeSet<>(); for (String string : strings) { set.add(string.trim()); } @@ -305,7 +315,7 @@ public static void addNetworkListener(VirtualServer server, String name) throws public static void removeNetworkListener(VirtualServer server, String name) throws PropertyVetoException { final String listeners = server.getNetworkListeners(); final String[] strings = listeners == null ? new String[0] : listeners.split(","); - final Set set = new TreeSet(); + final Set set = new TreeSet<>(); for (String string : strings) { set.add(string.trim()); } @@ -327,7 +337,7 @@ public static List findNetworkListeners(VirtualServer server) { final String listeners = server.getNetworkListeners(); final String[] strings = listeners == null ? new String[0] : listeners.split(","); final NetworkConfig config = server.getParent().getParent(Config.class).getNetworkConfig(); - List list = new ArrayList(); + List list = new ArrayList<>(); for (String s : strings) { final String name = s.trim(); final NetworkListener networkListener = config.getNetworkListener(name); @@ -342,46 +352,90 @@ public static List findNetworkListeners(VirtualServer server) { /** * Properties. */ - @PropertiesDesc(props = { - @PropertyDesc(name = "sso-max-inactive-seconds", defaultValue = "300", dataType = PositiveInteger.class, description = "The time after which a user's single sign-on record becomes eligible for purging if " - + "no client activity is received. Since single sign-on applies across several applications on the same virtual server, " - + "access to any of the applications keeps the single sign-on record active. Higher values provide longer " - + "single sign-on persistence for the users at the expense of more memory use on the server"), - @PropertyDesc(name = "sso-reap-interval-seconds", defaultValue = "60", dataType = PositiveInteger.class, description = "Interval between purges of expired single sign-on records"), - @PropertyDesc(name = "setCacheControl", description = "Comma-separated list of Cache-Control response directives. For a list of valid directives, " + @Override + @PropertiesDesc( + props = {@PropertyDesc( + name = "sso-max-inactive-seconds", + defaultValue = "300", + dataType = PositiveInteger.class, + description = "The time after which a user's single sign-on record becomes eligible for purging if " + + "no client activity is received. Since single sign-on applies across several applications on the same virtual server, " + + "access to any of the applications keeps the single sign-on record active. Higher values provide longer " + + "single sign-on persistence for the users at the expense of more memory use on the server"), + @PropertyDesc( + name = "sso-reap-interval-seconds", + defaultValue = "60", + dataType = PositiveInteger.class, + description = "Interval between purges of expired single sign-on records"), + @PropertyDesc( + name = "setCacheControl", + description = "Comma-separated list of Cache-Control response directives. For a list of valid directives, " + "see section 14.9 of the document at http://www.ietf.org/rfc/rfc2616.txt"), - @PropertyDesc(name = "accessLoggingEnabled", defaultValue = "false", dataType = Boolean.class, description = "Enables access logging for this virtual server only"), - @PropertyDesc(name = "accessLogBufferSize", defaultValue = "32768", dataType = PositiveInteger.class, description = "Size in bytes of the buffer where access log calls are stored. If the value is " + @PropertyDesc( + name = "accessLoggingEnabled", + defaultValue = "false", + dataType = Boolean.class, + description = "Enables access logging for this virtual server only"), + @PropertyDesc( + name = "accessLogBufferSize", + defaultValue = "32768", + dataType = PositiveInteger.class, + description = "Size in bytes of the buffer where access log calls are stored. If the value is " + "less than 5120, a warning message is issued, and the value is set to 5120. To set this " + "property for all virtual servers, set it as a property of the parent http-service"), - @PropertyDesc(name = "accessLogWriteInterval", defaultValue = "300", dataType = PositiveInteger.class, description = "Number of seconds before the log is written to the disk. The access log is written when " + @PropertyDesc( + name = "accessLogWriteInterval", + defaultValue = "300", + dataType = PositiveInteger.class, + description = "Number of seconds before the log is written to the disk. The access log is written when " + "the buffer is full or when the interval expires. If the value is 0, the buffer is always written even if " + "it is not full. This means that each time the server is accessed, the log message is stored directly to the file. " + "To set this property for all virtual servers, set it as a property of the parent http-service"), - @PropertyDesc(name = "allowRemoteAddress", description = "Comma-separated list of regular expression patterns that the remote client's IP address is " + @PropertyDesc( + name = "allowRemoteAddress", + description = "Comma-separated list of regular expression patterns that the remote client's IP address is " + "compared to. If this property is specified, the remote address must match for this request to be accepted. " + "If this property is not specified, all requests are accepted unless the remote address matches a 'denyRemoteAddress' pattern"), - @PropertyDesc(name = "denyRemoteAddress", description = "Comma-separated list of regular expression patterns that the remote client's " + @PropertyDesc( + name = "denyRemoteAddress", + description = "Comma-separated list of regular expression patterns that the remote client's " + "IP address is compared to. If this property is specified, the remote address must not " + "match for this request to be accepted. If this property is not specified, request " + "acceptance is governed solely by the 'allowRemoteAddress' property"), - @PropertyDesc(name = "allowRemoteHost", description = "Comma-separated list of regular expression patterns that the remote client's " + @PropertyDesc( + name = "allowRemoteHost", + description = "Comma-separated list of regular expression patterns that the remote client's " + "hostname (as returned by java.net.Socket.getInetAddress().getHostName()) is compared to. " + "If this property is specified, the remote hostname must match for the request to be accepted. " + "If this property is not specified, all requests are accepted unless the remote hostname matches a 'denyRemoteHost' pattern"), - @PropertyDesc(name = "denyRemoteHost", description = "Specifies a comma-separated list of regular expression patterns that the remote client's " + @PropertyDesc( + name = "denyRemoteHost", + description = "Specifies a comma-separated list of regular expression patterns that the remote client's " + "hostname (as returned by java.net.Socket.getInetAddress().getHostName()) is compared to. " + "If this property is specified, the remote hostname must not match for this request to be accepted. " + "If this property is not specified, request acceptance is governed solely by the 'allowRemoteHost' property"), - @PropertyDesc(name = "authRealm", description = "Specifies the name attribute of an “auth-realm�? on page 23 element, which overrides " + @PropertyDesc( + name = "authRealm", + description = "Specifies the name attribute of an “auth-realm“ on page 23 element, which overrides " + "the server instance's default realm for stand-alone web applications deployed to this virtual server. " + "A realm defined in a stand-alone web application's web.xml file overrides the virtual server's realm"), - @PropertyDesc(name = "securePagesWithPragma", defaultValue = "true", dataType = Boolean.class, description = "Set this property to false to ensure that for all web applications on this virtual server " + @PropertyDesc( + name = "securePagesWithPragma", + defaultValue = "true", + dataType = Boolean.class, + description = "Set this property to false to ensure that for all web applications on this virtual server " + "file downloads using SSL work properly in Internet Explorer. You can set this property for a specific web application."), - @PropertyDesc(name = "contextXmlDefault", description = "The location, relative to domain-dir, of the context.xml file for this virtual server, if one is used"), - @PropertyDesc(name = "allowLinking", defaultValue = "false", dataType = Boolean.class, description = "If true, resources that are symbolic links in web applications on this virtual server are served. " + @PropertyDesc( + name = "contextXmlDefault", + description = "The location, relative to domain-dir, of the context.xml file for this virtual server, if one is used"), + @PropertyDesc( + name = "allowLinking", + defaultValue = "false", + dataType = Boolean.class, + description = "If true, resources that are symbolic links in web applications on this virtual server are served. " + "The value of this property in the sun-web.xml file takes precedence if defined. " + "Caution: setting this property to true on Windows systems exposes JSP source code."), + /** * Specifies an alternate document root (docroot), where n is a positive integer that allows specification of more than * one. Alternate docroots allow web applications to serve requests for certain resources from outside their own diff --git a/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/ClientWrapper.java b/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/ClientWrapper.java index d8ca29e0361..5f5689c09b7 100644 --- a/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/ClientWrapper.java +++ b/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/ClientWrapper.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,12 +17,8 @@ package org.glassfish.admin.rest.client; -import java.io.IOException; -import java.net.URI; -import java.util.HashMap; -import java.util.Map; - import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; import jakarta.ws.rs.client.ClientRequestContext; import jakarta.ws.rs.client.ClientRequestFilter; import jakarta.ws.rs.client.Invocation.Builder; @@ -30,10 +27,15 @@ import jakarta.ws.rs.core.Link; import jakarta.ws.rs.core.UriBuilder; +import java.io.Closeable; +import java.io.IOException; +import java.net.URI; +import java.util.HashMap; +import java.util.Map; + import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; -import org.glassfish.jersey.client.JerseyClientBuilder; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; import org.glassfish.jersey.client.filter.CsrfProtectionFilter; import org.glassfish.jersey.jettison.JettisonFeature; @@ -45,7 +47,7 @@ * * @author jdlee */ -public class ClientWrapper implements Client { +public class ClientWrapper implements Client, Closeable { protected Client realClient; public ClientWrapper() { @@ -63,11 +65,11 @@ public ClientWrapper(final Map headers) { } public ClientWrapper(final Map headers, String userName, String password) { - realClient = JerseyClientBuilder.newClient(); + realClient = ClientBuilder.newClient(); realClient.register(new MultiPartFeature()); realClient.register(new JettisonFeature()); realClient.register(new CsrfProtectionFilter()); - if ((userName != null) && (password != null)) { + if (userName != null && password != null) { realClient.register(HttpAuthenticationFeature.basic(userName, password)); } realClient.register(new ClientRequestFilter() { diff --git a/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/MarshallingUtils.java b/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/MarshallingUtils.java index 09af0d961a7..1cc151575db 100644 --- a/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/MarshallingUtils.java +++ b/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/MarshallingUtils.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -39,7 +40,6 @@ import org.glassfish.api.logging.LogHelper; /** - * * @author jasonlee */ public class MarshallingUtils { @@ -47,7 +47,7 @@ public static List> getPropertiesFromJson(String json) { List> properties = null; json = json.trim(); if (json.startsWith("{")) { - properties = new ArrayList>(); + properties = new ArrayList<>(); properties.add(processJsonMap(json)); } else if (json.startsWith("[")) { try { @@ -63,7 +63,7 @@ public static List> getPropertiesFromJson(String json) { } public static List> getPropertiesFromXml(String xml) { - List> list = new ArrayList>(); + List> list = new ArrayList<>(); InputStream input = null; try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); @@ -157,13 +157,13 @@ public static String getJsonForProperties(List> properties) } public static Map buildMapFromDocument(String text) { - Map map = null; - if ((text == null) || text.isEmpty()) { + if (text == null || text.isEmpty()) { return new HashMap(); } text = text.trim(); + Map map = null; if (text.startsWith("{")) { map = processJsonMap(text); } else if (text.startsWith("<")) { @@ -176,15 +176,15 @@ public static Map buildMapFromDocument(String text) { while (parser.hasNext()) { int event = parser.next(); switch (event) { - case XMLStreamConstants.START_ELEMENT: { - if ("map".equals(parser.getLocalName())) { - map = processXmlMap(parser); + case XMLStreamConstants.START_ELEMENT: { + if ("map".equals(parser.getLocalName())) { + map = processXmlMap(parser); + } + break; + } + default: { + // No-op } - break; - } - default: { - // No-op - } } } } catch (UnsupportedEncodingException ex) { @@ -204,7 +204,7 @@ public static Map buildMapFromDocument(String text) { } } else { System.out.println(text); - throw new RuntimeException("An unknown document type was provided: " + text); //.substring(0, 10)); + throw new RuntimeException("An unknown document type was provided: " + text); } return map; @@ -212,21 +212,20 @@ public static Map buildMapFromDocument(String text) { /**************************************************************************/ private static Map processJsonMap(String json) { - Map map; try { - map = processJsonObject(new JSONObject(json)); + return processJsonObject(new JSONObject(json)); } catch (JSONException e) { - map = new HashMap(); + // FIXME: Really swallow exception? + return new HashMap<>(); } - return map; } - private static Map processJsonObject(JSONObject jo) { - Map map = new HashMap(); + private static Map processJsonObject(JSONObject jo) { + Map map = new HashMap<>(); try { - Iterator i = jo.keys(); + Iterator i = jo.keys(); while (i.hasNext()) { - String key = (String) i.next(); + String key = i.next(); Object value = jo.get(key); if (value instanceof JSONArray) { map.put(key, processJsonArray((JSONArray) value)); @@ -270,7 +269,7 @@ private static List processJsonArray(JSONArray ja) { private static Map processXmlMap(XMLStreamReader parser) throws XMLStreamException { boolean endOfMap = false; - Map entry = new HashMap(); + Map entry = new HashMap<>(); String key = null; String element = null; while (!endOfMap) { diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/Constants.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/Constants.java index 677786ba544..956252f930f 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/Constants.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/Constants.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -24,41 +25,41 @@ * @author Rajeshwar Paitl */ public interface Constants { - public static final String INDENT = " "; - public static final String JAVA_STRING_TYPE = "java.lang.String"; - public static final String JAVA_BOOLEAN_TYPE = "java.lang.Boolean"; - public static final String JAVA_INT_TYPE = "java.lang.Integer"; - public static final String JAVA_PROPERTIES_TYPE = "java.util.Properties"; - public static final String XSD_STRING_TYPE = "string"; - public static final String XSD_BOOLEAN_TYPE = "boolean"; - public static final String XSD_INT_TYPE = "int"; - public static final String XSD_PROPERTIES_TYPE = "string"; //? - public static final String TYPE = "type"; - public static final String KEY = "key"; - public static final String OPTIONAL = "optional"; - public static final String DEFAULT_VALUE = "defaultValue"; - public static final String ACCEPTABLE_VALUES = "acceptableValues"; - public static final String DEPRECATED = "deprecated"; + String INDENT = " "; + String JAVA_STRING_TYPE = "java.lang.String"; + String JAVA_BOOLEAN_TYPE = "java.lang.Boolean"; + String JAVA_INT_TYPE = "java.lang.Integer"; + String JAVA_PROPERTIES_TYPE = "java.util.Properties"; + String XSD_STRING_TYPE = "string"; + String XSD_BOOLEAN_TYPE = "boolean"; + String XSD_INT_TYPE = "int"; + String XSD_PROPERTIES_TYPE = "string"; //? + String TYPE = "type"; + String KEY = "key"; + String OPTIONAL = "optional"; + String DEFAULT_VALUE = "defaultValue"; + String ACCEPTABLE_VALUES = "acceptableValues"; + String DEPRECATED = "deprecated"; - public static final String VAR_PARENT = "$parent"; - public static final String VAR_GRANDPARENT = "$grandparent"; + String VAR_PARENT = "$parent"; + String VAR_GRANDPARENT = "$grandparent"; - public static final String ENCODING = "UTF-8"; + String ENCODING = "UTF-8"; - public static final String CLIENT_JAVA_PACKAGE = "org.glassfish.admin.rest.client"; - public static final String CLIENT_JAVA_PACKAGE_DIR = CLIENT_JAVA_PACKAGE.replace(".", System.getProperty("file.separator")); + String CLIENT_JAVA_PACKAGE = "org.glassfish.admin.rest.client"; + String CLIENT_JAVA_PACKAGE_DIR = CLIENT_JAVA_PACKAGE.replace(".", System.getProperty("file.separator")); - public static final String CLIENT_PYTHON_PACKAGE = "glassfih.rest"; - public static final String CLIENT_PYTHON_PACKAGE_DIR = CLIENT_PYTHON_PACKAGE.replace(".", System.getProperty("file.separator")); + String CLIENT_PYTHON_PACKAGE = "glassfih.rest"; + String CLIENT_PYTHON_PACKAGE_DIR = CLIENT_PYTHON_PACKAGE.replace(".", System.getProperty("file.separator")); - public static final String REQ_ATTR_SUBJECT = "SUBJECT"; + String REQ_ATTR_SUBJECT = "SUBJECT"; - public static final String HEADER_LEGACY_FORMAT = "X-GlassFish-3"; + String HEADER_LEGACY_FORMAT = "X-GlassFish-3"; - public static final String MEDIA_TYPE = "application"; - public static final String MEDIA_SUB_TYPE = "vnd.oracle.glassfish"; - public static final String MEDIA_TYPE_BASE = MEDIA_TYPE + "/" + MEDIA_SUB_TYPE; - public static final String MEDIA_TYPE_JSON = MEDIA_TYPE_BASE + "+json"; - public static final MediaType MEDIA_TYPE_JSON_TYPE = new MediaType(MEDIA_TYPE, MEDIA_SUB_TYPE + "+json"); - public static final String MEDIA_TYPE_SSE = MEDIA_TYPE_BASE + "+sse"; + String MEDIA_TYPE = "application"; + String MEDIA_SUB_TYPE = "vnd.oracle.glassfish"; + String MEDIA_TYPE_BASE = MEDIA_TYPE + "/" + MEDIA_SUB_TYPE; + String MEDIA_TYPE_JSON = MEDIA_TYPE_BASE + "+json"; + MediaType MEDIA_TYPE_JSON_TYPE = new MediaType(MEDIA_TYPE, MEDIA_SUB_TYPE + "+json"); + String MEDIA_TYPE_SSE = MEDIA_TYPE_BASE + "+sse"; } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/clientutils/.gitkeep_empty_dir b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/clientutils/.gitkeep_empty_dir deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/JsonPropertyListReader.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/JsonPropertyListReader.java index 76c0da9e704..95d3225ceb5 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/JsonPropertyListReader.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/JsonPropertyListReader.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,22 +17,23 @@ package org.glassfish.admin.rest.readers; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.WebApplicationException; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.ext.MessageBodyReader; +import jakarta.ws.rs.ext.Provider; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.annotation.Annotation; -import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import java.util.Map; -import jakarta.ws.rs.Consumes; -import jakarta.ws.rs.WebApplicationException; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.MultivaluedMap; -import jakarta.ws.rs.core.Response; -import jakarta.ws.rs.ext.MessageBodyReader; -import jakarta.ws.rs.ext.Provider; + import org.glassfish.admin.rest.client.utils.MarshallingUtils; import org.glassfish.admin.rest.utils.Util; @@ -51,17 +53,14 @@ public boolean isReadable(Class type, Type genericType, Annotation[] annotati @Override public List> readFrom(Class>> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap headers, InputStream in) throws IOException { - try { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { StringBuilder sb = new StringBuilder(); - BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = reader.readLine(); while (line != null) { sb.append(line); line = reader.readLine(); } - return MarshallingUtils.getPropertiesFromJson(sb.toString()); - } catch (Exception exception) { throw new WebApplicationException(exception, Response.Status.INTERNAL_SERVER_ERROR); } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/XmlPropertyListReader.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/XmlPropertyListReader.java index 3f75fc2e4f3..d921aa3c9bd 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/XmlPropertyListReader.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/XmlPropertyListReader.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -50,17 +51,14 @@ public boolean isReadable(Class type, Type genericType, Annotation[] annotati @Override public List> readFrom(Class>> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap headers, InputStream in) throws IOException { - try { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { StringBuilder sb = new StringBuilder(); - BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = reader.readLine(); while (line != null) { sb.append(line); line = reader.readLine(); } - return MarshallingUtils.getPropertiesFromXml(sb.toString()); - } catch (Exception exception) { throw new WebApplicationException(exception, Response.Status.INTERNAL_SERVER_ERROR); } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/MonitoringResource.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/MonitoringResource.java index a81134b3c72..bd7b6bc585a 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/MonitoringResource.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/MonitoringResource.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,42 +17,44 @@ package org.glassfish.admin.rest.resources; -import org.glassfish.admin.rest.utils.Util; -import org.glassfish.admin.rest.utils.ProxyImpl; +import com.sun.enterprise.config.serverbeans.Domain; +import com.sun.enterprise.config.serverbeans.Server; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.PathSegment; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriBuilder; import jakarta.ws.rs.core.UriInfo; -import jakarta.ws.rs.core.Context; -import static jakarta.ws.rs.core.Response.Status.*; + import java.net.URL; -import java.util.Properties; -import java.util.TreeMap; -import jakarta.ws.rs.Consumes; import java.util.ArrayList; import java.util.List; import java.util.Map; - -import jakarta.ws.rs.GET; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.Produces; -import jakarta.ws.rs.PathParam; - -import com.sun.enterprise.config.serverbeans.Domain; -import com.sun.enterprise.config.serverbeans.Server; +import java.util.Properties; +import java.util.TreeMap; import org.glassfish.admin.rest.adapter.LocatorBridge; import org.glassfish.admin.rest.results.ActionReportResult; +import org.glassfish.admin.rest.utils.ProxyImpl; +import org.glassfish.admin.rest.utils.Util; import org.glassfish.admin.rest.utils.xml.RestActionReporter; import org.glassfish.external.statistics.Statistic; import org.glassfish.external.statistics.Stats; - -import org.glassfish.flashlight.datatree.TreeNode; import org.glassfish.flashlight.MonitoringRuntimeDataRegistry; +import org.glassfish.flashlight.datatree.TreeNode; -import static org.glassfish.admin.rest.provider.ProviderUtil.*; +import static jakarta.ws.rs.core.Response.Status.FORBIDDEN; +import static jakarta.ws.rs.core.Response.Status.NOT_FOUND; +import static jakarta.ws.rs.core.Response.Status.OK; +import static org.glassfish.admin.rest.provider.ProviderUtil.getElementLink; +import static org.glassfish.admin.rest.provider.ProviderUtil.getStatistic; +import static org.glassfish.admin.rest.provider.ProviderUtil.jsonValue; /** * @author rajeshwar patil @@ -88,28 +91,57 @@ public Response getChildNodes(@PathParam("path") List pathSegments) pathSegments = pathSegments.subList(1, pathSegments.size()); if (!pathSegments.isEmpty()) { PathSegment lastSegment = pathSegments.get(pathSegments.size() - 1); - if (lastSegment.getPath().isEmpty()) { // if there is a trailing '/' (like monitoring/domain/), a spurious pathSegment is added. Discard it. + if (lastSegment.getPath().isEmpty()) { + // if there is a trailing '/' (like monitoring/domain/), a spurious pathSegment is added. Discard it. pathSegments = pathSegments.subList(0, pathSegments.size() - 1); } } - if (!pathSegments.isEmpty()) { + if (pathSegments.isEmpty()) { + // Called for /monitoring/domain/ + List list = new ArrayList<>(); + if (rootNode != null) { + //Add currentInstance to response + list.add(rootNode); + } + constructEntity(list, ar); + + if (isRunningOnDAS) { + // Add links to instances from the cluster + Domain domain = habitat.getRemoteLocator().getService(Domain.class); + Map links = (Map) ar.getExtraProperties().get("childResources"); + for (Server s : domain.getServers().getServer()) { + if (!"server".equals(s.getName())) { + // add all non 'server' instances + links.put(s.getName(), getElementLink(uriInfo, s.getName())); + } + } + } + responseBuilder.entity(new ActionReportResult(ar)); + } else { String firstPathElement = pathSegments.get(0).getPath(); - if (firstPathElement.equals(currentInstanceName)) { // Query for current instance. Execute it + if (firstPathElement.equals(currentInstanceName)) { + // Query for current instance. Execute it //iterate over pathsegments and build a dotted name to look up in monitoring registry StringBuilder pathInMonitoringRegistry = new StringBuilder(); for (PathSegment pathSegment : pathSegments.subList(1, pathSegments.size())) { if (pathInMonitoringRegistry.length() > 0) { pathInMonitoringRegistry.append('.'); } - pathInMonitoringRegistry.append(pathSegment.getPath().replaceAll("\\.", "\\\\.")); // Need to escape '.' before passing it to monitoring code + // Need to escape '.' before passing it to monitoring code + pathInMonitoringRegistry.append(pathSegment.getPath().replaceAll("\\.", "\\\\.")); } TreeNode resultNode = pathInMonitoringRegistry.length() > 0 && rootNode != null ? rootNode.getNode(pathInMonitoringRegistry.toString()) : rootNode; - if (resultNode != null) { - List list = new ArrayList(); + if (resultNode == null) { + //No monitoring data, so nothing to list + responseBuilder.status(NOT_FOUND); + ar.setFailure(); + responseBuilder.entity(new ActionReportResult(ar)); + } else { + List list = new ArrayList<>(); if (resultNode.hasChildNodes()) { list.addAll(resultNode.getEnabledChildNodes()); } else { @@ -117,16 +149,13 @@ public Response getChildNodes(@PathParam("path") List pathSegments) } constructEntity(list, ar); responseBuilder.entity(new ActionReportResult(ar)); - } else { - //No monitoring data, so nothing to list - responseBuilder.status(NOT_FOUND); - ar.setFailure(); - responseBuilder.entity(new ActionReportResult(ar)); } } else { //firstPathElement != currentInstanceName => A proxy request if (isRunningOnDAS) { //Attempt to forward to instance if running on Das //TODO validate that firstPathElement corresponds to a valid server name + // FIXME: As of 03.04.2022 Utils.getJerseyClient here throws exception: + // java.lang.ClassNotFoundException: Provider for jakarta.ws.rs.client.ClientBuilder cannot be found Properties proxiedResponse = new MonitoringProxyImpl().proxyRequest(uriInfo, Util.getJerseyClient(), habitat.getRemoteLocator()); ar.setExtraProperties(proxiedResponse); @@ -135,31 +164,14 @@ public Response getChildNodes(@PathParam("path") List pathSegments) return Response.status(FORBIDDEN).build(); } } - } else { // Called for /monitoring/domain/ - List list = new ArrayList(); - if (rootNode != null) { - list.add(rootNode); //Add currentInstance to response - } - constructEntity(list, ar); - - if (isRunningOnDAS) { // Add links to instances from the cluster - Domain domain = habitat.getRemoteLocator().getService(Domain.class); - Map links = (Map) ar.getExtraProperties().get("childResources"); - for (Server s : domain.getServers().getServer()) { - if (!s.getName().equals("server")) {// add all non 'server' instances - links.put(s.getName(), getElementLink(uriInfo, s.getName())); - } - } - } - responseBuilder.entity(new ActionReportResult(ar)); } return responseBuilder.build(); } private void constructEntity(List nodeList, RestActionReporter ar) { - Map entity = new TreeMap(); - Map links = new TreeMap(); + Map entity = new TreeMap<>(); + Map links = new TreeMap<>(); for (TreeNode node : nodeList) { //process only the leaf nodes, if any @@ -174,7 +186,7 @@ private void constructEntity(List nodeList, RestActionReporter ar) { Statistic statisticObject = (Statistic) value; entity.put(node.getName(), getStatistic(statisticObject)); } else if (value instanceof Stats) { - Map subMap = new TreeMap(); + Map subMap = new TreeMap<>(); for (Statistic statistic : ((Stats) value).getStatistics()) { subMap.put(statistic.getName(), getStatistic(statistic)); } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateCommandPostResource.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateCommandPostResource.java index 62950c12ea6..dbfe1ff3f89 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateCommandPostResource.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateCommandPostResource.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -43,13 +44,9 @@ import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.glassfish.jersey.media.sse.SseFeature; -import static org.glassfish.admin.rest.resources.TemplateExecCommand.localStrings; - /** - * * @author ludovic champenois ludo@dev.java.net Code moved from generated classes to here. Gen code inherits from this * template class that contains the logic for mapped commands RS Resources - * */ @Produces({ "text/html", MediaType.APPLICATION_JSON + ";qs=0.5", MediaType.APPLICATION_XML + ";qs=0.5" }) public class TemplateCommandPostResource extends TemplateExecCommand { @@ -175,20 +172,18 @@ private static ParameterMap createDataBasedOnForm(FormDataMultiPart formData) { formData = new FormDataMultiPart(); } try { - /* data passed to the generic command running - * - * */ - + // data passed to the generic command running Map> m1 = formData.getFields(); Set ss = m1.keySet(); for (String fieldName : ss) { for (FormDataBodyPart bodyPart : formData.getFields(fieldName)) { - if (bodyPart.getContentDisposition().getFileName() != null) {//we have a file + if (bodyPart.getContentDisposition().getFileName() == null) { + data.add(fieldName, bodyPart.getValue()); + } else { //save it and mark it as delete on exit. InputStream fileStream = bodyPart.getValueAs(InputStream.class); - String mimeType = bodyPart.getMediaType().toString(); //Use just the filename without complete path. File creation //in case of remote deployment failing because fo this. @@ -201,12 +196,9 @@ private static ParameterMap createDataBasedOnForm(FormDataMultiPart formData) { } } - File f = Util.saveFile(fileName, mimeType, fileStream); - f.deleteOnExit(); + File f = Util.saveTemporaryFile(fileName, fileStream); //put only the local path of the file in the same field. data.add(fieldName, f.getAbsolutePath()); - } else { - data.add(fieldName, bodyPart.getValue()); } } } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateListOfResource.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateListOfResource.java index 778c9cce7ca..b2441251e70 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateListOfResource.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateListOfResource.java @@ -16,27 +16,9 @@ package org.glassfish.admin.rest.resources; -import java.lang.reflect.Method; -import org.glassfish.config.support.Create; -import java.net.HttpURLConnection; import com.sun.enterprise.util.LocalStringManagerImpl; -import org.glassfish.admin.rest.utils.ResourceUtil; -import org.glassfish.admin.rest.utils.Util; -import org.glassfish.admin.rest.provider.MethodMetaData; -import org.glassfish.admin.rest.results.ActionReportResult; -import org.glassfish.admin.rest.results.OptionsResult; -import org.glassfish.admin.rest.utils.xml.RestActionReporter; -import org.glassfish.api.ActionReport; -import org.glassfish.api.admin.RestRedirect; -import org.jvnet.hk2.config.ConfigBeanProxy; -import org.jvnet.hk2.config.ConfigModel; -import org.jvnet.hk2.config.Dom; -import org.jvnet.hk2.config.DomDocument; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +import jakarta.validation.ConstraintViolationException; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.GET; @@ -49,10 +31,33 @@ import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.glassfish.admin.rest.provider.MethodMetaData; +import org.glassfish.admin.rest.results.ActionReportResult; +import org.glassfish.admin.rest.results.OptionsResult; +import org.glassfish.admin.rest.utils.ResourceUtil; +import org.glassfish.admin.rest.utils.Util; +import org.glassfish.admin.rest.utils.xml.RestActionReporter; +import org.glassfish.api.ActionReport; +import org.glassfish.api.admin.RestRedirect; +import org.glassfish.config.support.Create; import org.glassfish.hk2.api.MultiException; import org.glassfish.hk2.api.ServiceLocator; import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.jvnet.hk2.config.ConfigBeanProxy; +import org.jvnet.hk2.config.ConfigModel; +import org.jvnet.hk2.config.Dom; +import org.jvnet.hk2.config.DomDocument; +import org.jvnet.hk2.config.TransactionFailure; +import static org.glassfish.admin.rest.utils.ResourceUtil.getActionReportResult; import static org.glassfish.admin.rest.utils.Util.decode; import static org.glassfish.admin.rest.utils.Util.getName; @@ -61,13 +66,15 @@ * @author Rajeshwar Patil */ public abstract class TemplateListOfResource extends AbstractResource { + private static final Logger LOG = Logger.getLogger(TemplateListOfResource.class.getName()); + private static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(TemplateListOfResource.class); + @Context protected ServiceLocator injector; protected List entity; protected Dom parent; protected String tagName; - public final static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(TemplateListOfResource.class); @GET @Produces({ "text/html", MediaType.APPLICATION_JSON + ";qs=0.5", MediaType.APPLICATION_XML + ";qs=0.5" }) @@ -81,13 +88,13 @@ public Response get(@QueryParam("expandLevel") @DefaultValue("1") int expandLeve @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_FORM_URLENCODED }) public Response createResource(HashMap data) { if (data == null) { - data = new HashMap(); + data = new HashMap<>(); } try { if (data.containsKey("error")) { String errorMessage = localStrings.getLocalString("rest.request.parsing.error", "Unable to parse the input entity. Please check the syntax."); - ActionReportResult arr = ResourceUtil.getActionReportResult(ActionReport.ExitCode.FAILURE, errorMessage, requestHeaders, + ActionReportResult arr = getActionReportResult(ActionReport.ExitCode.FAILURE, errorMessage, requestHeaders, uriInfo); return Response.status(400).entity(arr).build(); } @@ -98,42 +105,39 @@ public Response createResource(HashMap data) { String commandName = getPostCommand(); String resourceToCreate = uriInfo.getAbsolutePath() + "/"; - if (null != commandName) { - ResourceUtil.adjustParameters(data); //adjusting for DEFAULT is required only while executing a CLI command - if (data.containsKey("name")) { - resourceToCreate += data.get("name"); - } else { - resourceToCreate += data.get("DEFAULT"); - } - RestActionReporter actionReport = ResourceUtil.runCommand(commandName, data, getSubject()); - - ActionReport.ExitCode exitCode = actionReport.getActionExitCode(); - if (exitCode != ActionReport.ExitCode.FAILURE) { - String successMessage = localStrings.getLocalString("rest.resource.create.message", "\"{0}\" created successfully.", - resourceToCreate); - ActionReportResult arr = ResourceUtil.getActionReportResult(actionReport, successMessage, requestHeaders, uriInfo); - return Response.ok(arr).build(); - } - - String errorMessage = getErrorMessage(data, actionReport); - ActionReportResult arr = ResourceUtil.getActionReportResult(actionReport, errorMessage, requestHeaders, uriInfo); + if (commandName == null) { + ActionReportResult arr = getActionReportResult(ActionReport.ExitCode.FAILURE, + "No CRUD Create possible.", requestHeaders, uriInfo); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(arr).build(); + } + ResourceUtil.adjustParameters(data); + if (data.containsKey("name")) { + resourceToCreate += data.get("name"); } else { - ActionReportResult arr = ResourceUtil.getActionReportResult(ActionReport.ExitCode.FAILURE, "No CRUD Create possible.", - requestHeaders, uriInfo); - return Response.status(HttpURLConnection.HTTP_INTERNAL_ERROR).entity(arr).build(); + resourceToCreate += data.get("DEFAULT"); } + RestActionReporter actionReport = ResourceUtil.runCommand(commandName, data, getSubject()); + + ActionReport.ExitCode exitCode = actionReport.getActionExitCode(); + if (exitCode == ActionReport.ExitCode.FAILURE) { + String errorMessage = actionReport.getMessage(); + LOG.log(Level.SEVERE, errorMessage, actionReport.getFailureCause()); + ActionReportResult result = getActionReportResult(actionReport, errorMessage, requestHeaders, uriInfo); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + String successMessage = localStrings.getLocalString("rest.resource.create.message", + "\"{0}\" created successfully.", resourceToCreate); + ActionReportResult arr = getActionReportResult(actionReport, successMessage, requestHeaders, uriInfo); + return Response.ok(arr).build(); } catch (Exception e) { - throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); + throw handleException(e); } } @POST @Consumes(MediaType.MULTIPART_FORM_DATA) public Response post(FormDataMultiPart formData) { - /* data passed to the generic command running - * - * */ + // data passed to the generic command running HashMap data = TemplateRestResource.createDataBasedOnForm(formData); return createResource(data, data.get("name")); //execute the deploy command with a copy of the file locally @@ -196,7 +200,7 @@ public String getPostCommand() { try { cbp = (Class) parent.model.classLoaderHolder.loadClass(parent.model.targetTypeName); } catch (MultiException e) { - return null;// + return null; } Create create = null; for (Method m : cbp.getMethods()) { @@ -243,7 +247,7 @@ public static Class getElementTypeByName(Dom parentDo protected ActionReportResult buildActionReportResult() { if (entity == null) {//wrong resource String errorMessage = localStrings.getLocalString("rest.resource.erromessage.noentity", "Resource not found."); - return ResourceUtil.getActionReportResult(ActionReport.ExitCode.FAILURE, errorMessage, requestHeaders, uriInfo); + return getActionReportResult(ActionReport.ExitCode.FAILURE, errorMessage, requestHeaders, uriInfo); } RestActionReporter ar = new RestActionReporter(); final String typeKey = (decode(getName(uriInfo.getPath(), '/'))); @@ -271,7 +275,7 @@ private Response createResource(HashMap data, String resourceToC String errorMessage = localStrings.getLocalString("rest.request.parsing.error", "Unable to parse the input entity. Please check the syntax."); return Response.status(400) - .entity(ResourceUtil.getActionReportResult(ActionReport.ExitCode.FAILURE, errorMessage, requestHeaders, uriInfo)) + .entity(getActionReportResult(ActionReport.ExitCode.FAILURE, errorMessage, requestHeaders, uriInfo)) .build(); } @@ -304,26 +308,26 @@ private Response createResource(HashMap data, String resourceToC if (exitCode != ActionReport.ExitCode.FAILURE) { String successMessage = localStrings.getLocalString("rest.resource.create.message", "\"{0}\" created successfully.", new Object[] { resourceToCreate }); - return Response.ok().entity(ResourceUtil.getActionReportResult(actionReport, successMessage, requestHeaders, uriInfo)) + return Response.ok().entity(getActionReportResult(actionReport, successMessage, requestHeaders, uriInfo)) .build(); } - String errorMessage = getErrorMessage(data, actionReport); - return Response.status(400).entity(ResourceUtil.getActionReportResult(actionReport, errorMessage, requestHeaders, uriInfo)) - .build(); + String errorMessage = actionReport.getMessage(); + return Response.status(400) + .entity(getActionReportResult(actionReport, errorMessage, requestHeaders, uriInfo)).build(); } - String message = localStrings.getLocalString("rest.resource.post.forbidden", "POST on \"{0}\" is forbidden.", - new Object[] { resourceToCreate }); + String message = localStrings.getLocalString("rest.resource.post.forbidden", + "POST on \"{0}\" is forbidden.", new Object[] {resourceToCreate}); return Response.status(403) - .entity(ResourceUtil.getActionReportResult(ActionReport.ExitCode.FAILURE, message, requestHeaders, uriInfo)).build(); + .entity(getActionReportResult(ActionReport.ExitCode.FAILURE, message, requestHeaders, uriInfo)).build(); } catch (Exception e) { - throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); + throw new WebApplicationException(e); } } private Map getMethodMetaData() { - Map map = new TreeMap(); + Map map = new TreeMap<>(); //GET meta data map.put("GET", new MethodMetaData()); @@ -340,7 +344,15 @@ private Map getMethodMetaData() { return map; } - private String getErrorMessage(HashMap data, ActionReport ar) { - return ar.getMessage(); + private WebApplicationException handleException(Exception e) { + // note: WeApplicationExceptions are not logged otherwise. + LOG.log(Level.SEVERE, "Create resource call failed", e); + if (e instanceof TransactionFailure) { + TransactionFailure failure = (TransactionFailure) e; + if (failure.getCause() instanceof ConstraintViolationException) { + return new WebApplicationException(failure, Response.Status.BAD_REQUEST); + } + } + return new WebApplicationException(e); } } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateRestResource.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateRestResource.java index 9dba63eb09b..34e526eb48d 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateRestResource.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/resources/TemplateRestResource.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -86,7 +87,7 @@ public class TemplateRestResource extends AbstractResource implements OptionsCap protected ConfigModel childModel; //good model even if the child entity is null protected String childID; // id of the current child if part of a list, might be null public final static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(TemplateRestResource.class); - final private static List attributesToSkip = new ArrayList() { + final private static List attributesToSkip = new ArrayList<>() { { add("parent"); @@ -118,7 +119,7 @@ public Map getEntity(@QueryParam("expandLevel") @DefaultValue("1 throw new WebApplicationException(Response.Status.NOT_FOUND); } - return getAttributes((ConfigBean) getEntity()); + return getAttributes(getEntity()); } @POST @@ -183,7 +184,7 @@ public RestResourceMetadata options() { */ protected RestActionReporter doCreateOrUpdate(HashMap data) { if (data == null) { - data = new HashMap(); + data = new HashMap<>(); } try { //data.remove("submit"); @@ -226,7 +227,7 @@ protected RestActionReporter doCreateOrUpdate(HashMap data) { protected ExitCode doDelete(HashMap data) { if (data == null) { - data = new HashMap(); + data = new HashMap<>(); } if (entity == null) {//wrong resource // return Response.status(404).entity(ResourceUtil.getActionReportResult(ActionReport.ExitCode.FAILURE, errorMessage, requestHeaders, uriInfo)).build(); @@ -372,7 +373,7 @@ private String buildPath(Dom node) { * local location on the server side (ie. just the path) */ public static HashMap createDataBasedOnForm(FormDataMultiPart formData) { - HashMap data = new HashMap(); + HashMap data = new HashMap<>(); try { //data passed to the generic command running Map> m1 = formData.getFields(); @@ -380,10 +381,11 @@ public static HashMap createDataBasedOnForm(FormDataMultiPart fo Set ss = m1.keySet(); for (String fieldName : ss) { for (FormDataBodyPart bodyPart : formData.getFields(fieldName)) { - if (bodyPart.getContentDisposition().getFileName() != null) {//we have a file + if (bodyPart.getContentDisposition().getFileName() == null) { + data.put(fieldName, bodyPart.getValue()); + } else { //save it and mark it as delete on exit. InputStream fileStream = bodyPart.getValueAs(InputStream.class); - String mimeType = bodyPart.getMediaType().toString(); //Use just the filename without complete path. File creation //in case of remote deployment failing because fo this. @@ -396,13 +398,9 @@ public static HashMap createDataBasedOnForm(FormDataMultiPart fo } } - File f = Util.saveFile(fileName, mimeType, fileStream); - f.deleteOnExit(); + File f = Util.saveTemporaryFile(fileName, fileStream); //put only the local path of the file in the same field. data.put(fieldName, f.getAbsolutePath()); - - } else { - data.put(fieldName, bodyPart.getValue()); } } } @@ -448,7 +446,7 @@ public void setBeanByKey(List parentList, String id, String tag) { String keyvalue = c.attribute(keyAttributeName.toLowerCase(Locale.US)); if (keyvalue.equals(childID)) { - setEntity((ConfigBean) c); + setEntity(c); } } } @@ -565,7 +563,7 @@ private String getResourceName(String absoluteName, String delimiter) { //****************************************************************************************************************** private Map getAttributes(Dom entity) { - Map result = new TreeMap(); + Map result = new TreeMap<>(); Set attributeNames = entity.model.getAttributeNames(); for (String attributeName : attributeNames) { result.put(eleminateHypen(attributeName), entity.attribute(attributeName)); @@ -575,7 +573,7 @@ private Map getAttributes(Dom entity) { } private Map getMethodMetaData() { - Map map = new TreeMap(); + Map map = new TreeMap<>(); //GET meta data map.put("GET", new MethodMetaData()); diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/utils/Util.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/utils/Util.java index 8d8fd6532a6..f876697bdfc 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/utils/Util.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/utils/Util.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -44,8 +45,6 @@ import jakarta.ws.rs.core.HttpHeaders; import org.glassfish.admin.rest.Constants; import org.glassfish.admin.rest.RestLogging; -import org.glassfish.admin.rest.model.ResponseBody; - import org.glassfish.admin.rest.utils.xml.RestActionReporter; import org.glassfish.admin.restconnector.RestConfig; import org.glassfish.api.ActionReport.MessagePart; @@ -330,7 +329,7 @@ public static Map getCurrentValues(String basePath, Subject subj } public static Map getCurrentValues(String basePath, ServiceLocator habitat, Subject subject) { - Map values = new HashMap(); + Map values = new HashMap<>(); final String path = (basePath.endsWith(".")) ? basePath.substring(0, basePath.length() - 1) : basePath; RestActionReporter gr = ResourceUtil.runCommand("get", new ParameterMap() { { @@ -442,7 +441,6 @@ public static String getMethodParameterList(CommandModel cm, boolean withType, b String sep = ""; for (CommandModel.ParamModel model : params) { Param param = model.getParam(); - boolean include = true; if (param.optional() && !includeOptional) { continue; } @@ -467,38 +465,38 @@ public static String getMethodParameterList(CommandModel cm, boolean withType, b return sb.toString(); } - public static File saveFile(String fileName, String mimeType, InputStream fileStream) { - BufferedOutputStream out = null; - File f = null; + public static File saveTemporaryFile(String fileName, InputStream fileStream) { + File file; try { - if (fileName.contains(".")) { - //String prefix = fileName.substring(0, fileName.indexOf(".")); - // String suffix = fileName.substring(fileName.indexOf("."), fileName.length()); - //if (prefix.length() < 3) { - // prefix = "glassfish" + prefix; - //} - f = new File(new File(System.getProperty("java.io.tmpdir")), fileName); - } - - out = new BufferedOutputStream(new FileOutputStream(f)); + String[] parts = getNameAndSuffix(fileName); + file = File.createTempFile(parts[0], parts[1]); + } catch (IOException e) { + throw new IllegalStateException("Could not create a temp file for " + fileName, e); + } + try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { byte[] buffer = new byte[32 * 1024]; int bytesRead = 0; while ((bytesRead = fileStream.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } - return f; - } catch (IOException ex) { - RestLogging.restLogger.log(Level.SEVERE, RestLogging.IO_EXCEPTION, ex.getMessage()); - } finally { - try { - if (out != null) { - out.close(); - } - } catch (IOException ex) { - RestLogging.restLogger.log(Level.SEVERE, RestLogging.IO_EXCEPTION, ex.getMessage()); - } + return file; + } catch (IOException e) { + throw new IllegalStateException("Could not write to a temp file " + file, e); } - return null; + } + + + private static String[] getNameAndSuffix(String fileName) { + if (fileName == null) { + return new String[2]; + } + int dotPosition = fileName.lastIndexOf('.'); + if (dotPosition < 1) { + // on Linux: files with dots as the first char mean hidden files. + // or the dot wasn't found at all + return new String[] {fileName, null}; + } + return new String[] {fileName.substring(0, dotPosition), fileName.substring(dotPosition)}; } public static boolean isGenericType(Type type) { diff --git a/nucleus/cluster/admin/src/main/java/com/sun/enterprise/v3/admin/cluster/DeleteNodeConfigCommand.java b/nucleus/cluster/admin/src/main/java/com/sun/enterprise/v3/admin/cluster/DeleteNodeConfigCommand.java index 425ce46d1a1..8358051ca0f 100644 --- a/nucleus/cluster/admin/src/main/java/com/sun/enterprise/v3/admin/cluster/DeleteNodeConfigCommand.java +++ b/nucleus/cluster/admin/src/main/java/com/sun/enterprise/v3/admin/cluster/DeleteNodeConfigCommand.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,28 +17,34 @@ package com.sun.enterprise.v3.admin.cluster; -import com.sun.enterprise.config.serverbeans.*; -import com.sun.enterprise.util.SystemPropertyConstants; -import com.sun.enterprise.util.StringUtils; +import com.sun.enterprise.config.serverbeans.Node; +import com.sun.enterprise.config.serverbeans.Nodes; + +import jakarta.inject.Inject; + +import java.util.logging.Logger; + import org.glassfish.api.ActionReport; import org.glassfish.api.I18n; import org.glassfish.api.Param; -import org.glassfish.api.admin.*; +import org.glassfish.api.admin.AdminCommand; +import org.glassfish.api.admin.AdminCommandContext; +import org.glassfish.api.admin.CommandRunner; import org.glassfish.api.admin.CommandRunner.CommandInvocation; -import jakarta.inject.Inject; - +import org.glassfish.api.admin.ExecuteOn; +import org.glassfish.api.admin.ParameterMap; +import org.glassfish.api.admin.RestEndpoint; +import org.glassfish.api.admin.RestEndpoints; +import org.glassfish.api.admin.RuntimeType; import org.glassfish.hk2.api.IterableProvider; import org.glassfish.hk2.api.PerLookup; import org.glassfish.hk2.api.ServiceLocator; - import org.jvnet.hk2.annotations.Service; -import org.jvnet.hk2.component.*; -import java.util.logging.Logger; /** * Remote AdminCommand to create a config node. This command is run only on DAS. - * Register the config node on DAS + * Register the config node on DAS * * @author Carla Mott */ diff --git a/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/admin/GetHabitatInfo.java b/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/admin/GetHabitatInfo.java index 3e4415d9626..6f699595c3b 100644 --- a/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/admin/GetHabitatInfo.java +++ b/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/admin/GetHabitatInfo.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2008, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,8 +17,17 @@ package com.sun.enterprise.v3.admin; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; +import com.sun.enterprise.config.serverbeans.Domain; +import com.sun.enterprise.config.serverbeans.customvalidators.JavaClassName; +import com.sun.enterprise.module.ModulesRegistry; +import com.sun.enterprise.universal.collections.ManifestUtils; +import com.sun.enterprise.v3.common.PropsFileActionReporter; + +import jakarta.inject.Inject; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; +import jakarta.validation.Payload; +import jakarta.validation.constraints.Pattern; import java.io.ByteArrayOutputStream; import java.io.PrintStream; @@ -27,18 +37,11 @@ import java.util.Iterator; import java.util.List; import java.util.Locale; -import java.util.SortedSet; -import java.util.TreeSet; - -import jakarta.inject.Inject; -import jakarta.validation.ConstraintValidator; -import jakarta.validation.ConstraintValidatorContext; -import jakarta.validation.Payload; -import jakarta.validation.constraints.Pattern; - +import java.util.concurrent.atomic.AtomicInteger; import org.glassfish.api.ActionReport; import org.glassfish.api.ActionReport.ExitCode; import org.glassfish.api.Param; +import org.glassfish.api.admin.AccessRequired; import org.glassfish.api.admin.AdminCommand; import org.glassfish.api.admin.AdminCommandContext; import org.glassfish.api.admin.RestEndpoint; @@ -50,12 +53,8 @@ import org.glassfish.hk2.utilities.BuilderHelper; import org.jvnet.hk2.annotations.Service; -import com.sun.enterprise.config.serverbeans.Domain; -import com.sun.enterprise.config.serverbeans.customvalidators.JavaClassName; -import com.sun.enterprise.module.ModulesRegistry; -import com.sun.enterprise.universal.collections.ManifestUtils; -import com.sun.enterprise.v3.common.PropsFileActionReporter; -import org.glassfish.api.admin.AccessRequired; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Dumps a sorted list of all registered Contract's in the Habitat @@ -86,7 +85,7 @@ public class GetHabitatInfo implements AdminCommand { @Param(primary = true, optional = true) String contract; - @Pattern(regexp="true|false") + @Pattern(regexp="true|false", message = "Valid values: true|false") @Param(optional = true) String started = "false"; @@ -97,8 +96,7 @@ public void execute(AdminCommandContext context) { dumpContracts(sb); dumpModules(sb); dumpTypes(sb); - } - else { + } else { dumpInhabitantsImplementingContractPattern(contract, sb); } @@ -114,29 +112,17 @@ public void execute(AdminCommandContext context) { } private void dumpContracts(StringBuilder sb) { - // Probably not very efficient but it is not a factor for this rarely-used - // user-called command... - sb.append("\n*********** Sorted List of all Registered Contracts in the Habitat **************\n"); List> allDescriptors = serviceLocator.getDescriptors(BuilderHelper.allFilter()); - - SortedSet allContracts = new TreeSet(); - for (ActiveDescriptor aDescriptor : allDescriptors) { - allContracts.addAll(aDescriptor.getAdvertisedContracts()); - } - - // now the contracts are sorted... - - Iterator it = allContracts.iterator(); - for (int i = 1; it.hasNext(); i++) { - sb.append("Contract-" + i + ": " + it.next() + "\n"); - } + AtomicInteger counter = new AtomicInteger(0); + allDescriptors.stream().flatMap(desc -> desc.getAdvertisedContracts().stream()).sorted().forEach(contract -> sb + .append("Contract-").append(counter.incrementAndGet()).append(": ").append(contract).append('\n')); } private void dumpInhabitantsImplementingContractPattern(String pattern, StringBuilder sb) { sb.append("\n*********** List of all services for contract named like " + contract + " **************\n"); List> allDescriptors = serviceLocator.getDescriptors(BuilderHelper.allFilter()); - HashSet allContracts = new HashSet(); + HashSet allContracts = new HashSet<>(); for (ActiveDescriptor aDescriptor : allDescriptors) { allContracts.addAll(aDescriptor.getAdvertisedContracts()); } @@ -144,17 +130,17 @@ private void dumpInhabitantsImplementingContractPattern(String pattern, StringBu Iterator it = allContracts.iterator(); while (it.hasNext()) { String cn = it.next(); - if (cn.toLowerCase(Locale.ENGLISH).indexOf(pattern.toLowerCase(Locale.ENGLISH)) < 0) + if (cn.toLowerCase(Locale.ENGLISH).indexOf(pattern.toLowerCase(Locale.ENGLISH)) < 0) { continue; - sb.append("\n-----------------------------\n"); + } + sb.append("-----------------------------\n"); for ( ActiveDescriptor descriptor : serviceLocator.getDescriptors(BuilderHelper.createContractFilter(cn))) { sb.append("Inhabitant-Metadata: " + descriptor.getMetadata()); sb.append("\n"); boolean isStarted = Boolean.parseBoolean(started); if (isStarted) { - ServiceHandle handle = serviceLocator.getServiceHandle(descriptor); - - sb.append((handle.isActive() ? " started" : " not started")); + ServiceHandle handle = serviceLocator.getServiceHandle(descriptor); + sb.append(handle.isActive() ? " started" : " not started"); } } } @@ -163,40 +149,20 @@ private void dumpInhabitantsImplementingContractPattern(String pattern, StringBu private void dumpTypes(StringBuilder sb) { sb.append("\n\n*********** Sorted List of all Types in the Habitat **************\n\n"); List> allDescriptors = serviceLocator.getDescriptors(BuilderHelper.allFilter()); - HashSet allTypes = new HashSet(); - for (ActiveDescriptor aDescriptor : allDescriptors) { - allTypes.add(aDescriptor.getImplementation()); - } - - Iterator it = allTypes.iterator(); - - if (it == null) //PP (paranoid programmer) - return; - - SortedSet types = new TreeSet(); - - while (it.hasNext()) { - types.add(it.next()); - } - - // now the types are sorted... - - it = types.iterator(); - - for (int i = 1; it.hasNext(); i++) { - sb.append("Type-" + i + ": " + it.next() + "\n"); - } + AtomicInteger counter = new AtomicInteger(0); + allDescriptors.stream().map(ActiveDescriptor::getImplementation).sorted().forEach( + impl -> sb.append("Type-").append(counter.incrementAndGet()).append(": ").append(impl).append('\n')); } private void dumpModules(StringBuilder sb) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); modulesRegistry.dumpState(new PrintStream(baos)); sb.append("\n\n*********** List of all Registered Modules **************\n\n"); - sb.append(baos.toString()); + sb.append(baos); } - /* - * NOTE: this valdation is here just to test the AdminCommand validation - * implementation. + + /** + * NOTE: this valdation is here just to test the AdminCommand validation implementation. */ @Retention(RUNTIME) @Target({TYPE}) @@ -216,8 +182,9 @@ public void initialize(final GetHabitatInfo.Constraint constraint) { } @Override public boolean isValid(final GetHabitatInfo bean, final ConstraintValidatorContext constraintValidatorContext) { - if (bean.contract.equals("test") && bean.started.equals("true")) + if ("test".equals(bean.contract) && "true".equals(bean.started)) { return false; + } return true; } } diff --git a/nucleus/deployment/common/src/main/resources/com/sun/logging/enterprise/system/tools/deployment/LogStrings.properties b/nucleus/deployment/common/src/main/resources/com/sun/logging/enterprise/system/tools/deployment/LogStrings.properties index b0f6b4561b1..4fd76aa6059 100644 --- a/nucleus/deployment/common/src/main/resources/com/sun/logging/enterprise/system/tools/deployment/LogStrings.properties +++ b/nucleus/deployment/common/src/main/resources/com/sun/logging/enterprise/system/tools/deployment/LogStrings.properties @@ -114,17 +114,6 @@ DPL8011.diag.cause.2=Mostly because of application specific failure DPL8011.diag.check.1=Ensure that the application can be deployed using CLI DPL8011.diag.check.2=Ensure that there autodeploy config info is set properly and the server is up and running - - - -enterprise.deployment.backend.invalidDescriptorFailure=DPL8015: Invalid Deployment Descriptors in {0} \nLine {1} Column {2} -- {3} -DPL8015.diag.cause.1=Failed to find the resource specified in the deployment descriptor -DPL8015.diag.cause.2=May be because of wrong specification in the descriptor -DPL8015.diag.check.1=Ensure that the resource specified is present -DPL8015.diag.check.2=Ensure that there is no typo in the resource specified in the descriptor - - - enterprise.deployment.backend.ejbRefTypeMismatch=DPL8017: Ejb-ref type mismatch for ejb reference {0}. Reference declares type {1} but target ejb {2} has {3} interface of type {4}. DPL8017.diag.cause.1=Possible type mismatch in ejb-ref/ejb-local-ref/@EJB DPL8017.diag.cause.2=May be because of wrong specification in the descriptor diff --git a/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Http.java b/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Http.java index 6278b838557..6b68d3f5b0c 100644 --- a/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Http.java +++ b/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Http.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -113,7 +114,7 @@ public interface Http extends ConfigBeanProxy, PropertyBag { void setCompressableMimeType(String type); @Attribute(defaultValue = COMPRESSION, dataType = String.class) - @Pattern(regexp = COMPRESSION_PATTERN) + @Pattern(regexp = COMPRESSION_PATTERN, message = "Pattern: " + COMPRESSION_PATTERN) String getCompression(); void setCompression(String compression); @@ -470,6 +471,7 @@ public interface Http extends ConfigBeanProxy, PropertyBag { void setHttp2Enabled(boolean http2Enabled); + @Override @DuckTyped Protocol getParent(); diff --git a/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/NetworkListener.java b/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/NetworkListener.java index 58470478592..c661fd1872a 100644 --- a/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/NetworkListener.java +++ b/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/NetworkListener.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,13 +17,13 @@ package org.glassfish.grizzly.config.dom; +import jakarta.validation.constraints.Pattern; + import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -import jakarta.validation.constraints.Pattern; - import org.jvnet.hk2.config.Attribute; import org.jvnet.hk2.config.ConfigBeanProxy; import org.jvnet.hk2.config.Configured; @@ -39,7 +40,7 @@ public interface NetworkListener extends ConfigBeanProxy, PropertyBag { boolean JK_ENABLED = false; String DEFAULT_ADDRESS = "0.0.0.0"; String DEFAULT_CONFIGURATION_FILE = "${com.sun.aas.instanceRoot}/config/glassfish-jk.properties"; - String TYPE_PATTERN = "(standard|proxy)"; + String LISTENER_TYPES = "(standard|proxy)"; String DEFAULT_TYPE = "standard"; @@ -85,7 +86,7 @@ public interface NetworkListener extends ConfigBeanProxy, PropertyBag { * Network-listener name, which could be used as reference */ @Attribute(required = true, dataType = String.class, defaultValue = DEFAULT_TYPE) - @Pattern(regexp = TYPE_PATTERN) + @Pattern(regexp = LISTENER_TYPES, message = "Valid values: " + LISTENER_TYPES) String getType(); void setType(String type); @@ -138,6 +139,7 @@ public interface NetworkListener extends ConfigBeanProxy, PropertyBag { @DuckTyped Transport findTransport(); + @Override @DuckTyped NetworkListeners getParent(); @@ -204,7 +206,7 @@ public static ThreadPool findThreadPool(NetworkListener listener) { final ConfigBeanProxy parent = listener.getParent().getParent().getParent(); final Dom proxy = Dom.unwrap(parent).element("thread-pools"); final List domList = proxy.nodeElements("thread-pool"); - list = new ArrayList(domList.size()); + list = new ArrayList<>(domList.size()); for (Dom dom : domList) { list.add(dom.createProxy()); } diff --git a/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/ProtocolChain.java b/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/ProtocolChain.java index 1672f06de5f..9f4c8cd538c 100644 --- a/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/ProtocolChain.java +++ b/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/ProtocolChain.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -46,7 +47,7 @@ public interface ProtocolChain extends ConfigBeanProxy, PropertyBag { * Protocol chain type. Could be STATEFUL or STATELESS */ @Attribute(defaultValue = TYPE) - @Pattern(regexp = TYPE_PATTERN) + @Pattern(regexp = TYPE_PATTERN, message = "Valid values: " + TYPE_PATTERN) String getType(); void setType(String value); @@ -59,6 +60,7 @@ public interface ProtocolChain extends ConfigBeanProxy, PropertyBag { void setProtocolFilter(List list); + @Override @DuckTyped Protocol getParent(); diff --git a/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Ssl.java b/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Ssl.java index e74b3f65bc6..a1054cc6baa 100644 --- a/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Ssl.java +++ b/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Ssl.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -57,8 +58,8 @@ public interface Ssl extends ConfigBeanProxy, PropertyBag { void setCertNickname(String value); /** - * Determines whether SSL3 client authentication is performed on every request, independent of ACL-based access - * control. + * Determines whether SSL3 client authentication is performed on every request, + * independent of ACL-based access control. */ @Attribute(defaultValue = "" + CLIENT_AUTH_ENABLED, dataType = Boolean.class) String getClientAuthEnabled(); @@ -66,11 +67,11 @@ public interface Ssl extends ConfigBeanProxy, PropertyBag { void setClientAuthEnabled(String value); /** - * Determines if if the engine will request (want) or require (need) client authentication. Valid values: want, - * need, or left blank + * Determines if if the engine will request (want) or require (need) client authentication. + * Valid values: want, need, or left blank */ @Attribute(dataType = String.class, defaultValue = "") - @Pattern(regexp = CLIENT_AUTH_PATTERN) + @Pattern(regexp = CLIENT_AUTH_PATTERN, message = "Valid values: " + CLIENT_AUTH_PATTERN) String getClientAuth(); void setClientAuth(String value); @@ -89,7 +90,7 @@ public interface Ssl extends ConfigBeanProxy, PropertyBag { * type of the keystore file */ @Attribute(dataType = String.class) - @Pattern(regexp = STORE_TYPE_PATTERN) + @Pattern(regexp = STORE_TYPE_PATTERN, message = "Valid values: " + STORE_TYPE_PATTERN) String getKeyStoreType(); void setKeyStoreType(String type); @@ -126,7 +127,7 @@ public interface Ssl extends ConfigBeanProxy, PropertyBag { * ciphers are assumed to be enabled. NOT Used in PE */ @Attribute - @Pattern(regexp = SSL2_CIPHERS_PATTERN) + @Pattern(regexp = SSL2_CIPHERS_PATTERN, message = "Valid values: " + SSL2_CIPHERS_PATTERN) String getSsl2Ciphers(); void setSsl2Ciphers(String value); @@ -221,7 +222,7 @@ public interface Ssl extends ConfigBeanProxy, PropertyBag { * type of the truststore file */ @Attribute(dataType = String.class) - @Pattern(regexp = STORE_TYPE_PATTERN) + @Pattern(regexp = STORE_TYPE_PATTERN, message = "Valid values: " + STORE_TYPE_PATTERN) String getTrustStoreType(); void setTrustStoreType(String type); diff --git a/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Transport.java b/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Transport.java index a13648b5261..4df3eddf0e3 100644 --- a/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Transport.java +++ b/nucleus/grizzly/config/src/main/java/org/glassfish/grizzly/config/dom/Transport.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -33,6 +34,7 @@ @Configured public interface Transport extends ConfigBeanProxy, PropertyBag { + String BYTE_BUFFER_TYPES = "heap|direct"; boolean DISPLAY_CONFIGURATION = false; boolean ENABLE_SNOOP = false; boolean TCP_NO_DELAY = true; @@ -89,7 +91,11 @@ public interface Transport extends ConfigBeanProxy, PropertyBag { * Type of ByteBuffer, which will be used with transport. Possible values are: HEAP and DIRECT */ @Attribute(defaultValue = BYTE_BUFFER_TYPE, dataType = String.class) - @Pattern(regexp = "heap|direct", flags = Pattern.Flag.CASE_INSENSITIVE) + @Pattern( + regexp = BYTE_BUFFER_TYPES, + message = "Valid values: " + BYTE_BUFFER_TYPES, + flags = Pattern.Flag.CASE_INSENSITIVE + ) String getByteBufferType(); void setByteBufferType(String value); @@ -208,6 +214,7 @@ public interface Transport extends ConfigBeanProxy, PropertyBag { @DuckTyped List findNetworkListeners(); + @Override @DuckTyped Transports getParent(); @@ -215,7 +222,7 @@ class Duck { static public List findNetworkListeners(Transport transport) { NetworkListeners networkListeners = transport.getParent().getParent().getNetworkListeners(); - List refs = new ArrayList(); + List refs = new ArrayList<>(); for (NetworkListener listener : networkListeners.getNetworkListener()) { if (listener.getTransport().equals(transport.getName())) { refs.add(listener); diff --git a/nucleus/hk2/hk2-config/src/main/java/org/jvnet/hk2/config/WriteableView.java b/nucleus/hk2/hk2-config/src/main/java/org/jvnet/hk2/config/WriteableView.java index 4b09ea1bf56..cb10c388d55 100644 --- a/nucleus/hk2/hk2-config/src/main/java/org/jvnet/hk2/config/WriteableView.java +++ b/nucleus/hk2/hk2-config/src/main/java/org/jvnet/hk2/config/WriteableView.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2022 Contributors to the Eclipse Foundation * Copyright (c) 2007, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,23 +17,43 @@ package org.jvnet.hk2.config; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Proxy; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Type; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.ConstraintViolationException; +import jakarta.validation.ElementKind; +import jakarta.validation.Path; +import jakarta.validation.TraversableResolver; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.ValidatorContext; +import jakarta.validation.ValidatorFactory; +import jakarta.validation.metadata.ConstraintDescriptor; + import java.beans.PropertyChangeEvent; import java.beans.PropertyVetoException; import java.lang.annotation.ElementType; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Proxy; +import java.lang.reflect.Type; import java.security.AccessController; import java.security.PrivilegedAction; import java.text.MessageFormat; -import java.util.*; -import java.util.concurrent.locks.Lock; - -import jakarta.validation.*; -import jakarta.validation.metadata.ConstraintDescriptor; - +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.Set; +import java.util.StringTokenizer; + +import org.hibernate.validator.HibernateValidator; +import org.jvnet.hk2.config.ConfigModel.AttributeLeaf; import org.jvnet.hk2.config.ConfigModel.Property; /** @@ -42,17 +63,19 @@ * @author Jerome Dochez */ public class WriteableView implements InvocationHandler, Transactor, ConfigView { + private static final TraversableResolver TRAVERSABLE_RESOLVER = new TraversableResolver() { - public boolean isReachable(Object traversableObject, - Path.Node traversableProperty, Class rootBeanType, - Path pathToTraversableObject, ElementType elementType) { - return true; + + @Override + public boolean isReachable(Object traversableObject, Path.Node traversableProperty, Class rootBeanType, + Path pathToTraversableObject, ElementType elementType) { + return true; } - public boolean isCascadable(Object traversableObject, - Path.Node traversableProperty, Class rootBeanType, - Path pathToTraversableObject, ElementType elementType) { - return true; + @Override + public boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class rootBeanType, + Path pathToTraversableObject, ElementType elementType) { + return true; } }; @@ -60,22 +83,22 @@ public boolean isCascadable(Object traversableObject, private final static Validator beanValidator; static { - ClassLoader cl = System.getSecurityManager()==null?Thread.currentThread().getContextClassLoader(): - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public ClassLoader run() { - return Thread.currentThread().getContextClassLoader(); - } + ClassLoader cl = System.getSecurityManager() == null + ? Thread.currentThread().getContextClassLoader() + : AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public ClassLoader run() { + return Thread.currentThread().getContextClassLoader(); + } }); try { - Thread.currentThread().setContextClassLoader(org.hibernate.validator.HibernateValidator.class.getClassLoader()); - + Thread.currentThread().setContextClassLoader(HibernateValidator.class.getClassLoader()); ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); ValidatorContext validatorContext = validatorFactory.usingContext(); validatorContext.messageInterpolator(new MessageInterpolatorImpl()); - beanValidator = validatorContext.traversableResolver( - TRAVERSABLE_RESOLVER).getValidator(); + beanValidator = validatorContext.traversableResolver(TRAVERSABLE_RESOLVER).getValidator(); } finally { Thread.currentThread().setContextClassLoader(cl); } @@ -97,85 +120,80 @@ public ClassLoader run() { public WriteableView(ConfigBeanProxy readView) { this.bean = (ConfigBean) ((ConfigView) Proxy.getInvocationHandler(readView)).getMasterView(); this.defaultView = bean.createProxy(); - changedAttributes = new HashMap(); - changedCollections = new HashMap(); + changedAttributes = new HashMap<>(); + changedCollections = new HashMap<>(); } + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - - if (method.getName().equals("hashCode")) + if (method.getName().equals("hashCode")) { return super.hashCode(); + } - if (method.getName().equals("equals")) + if (method.getName().equals("equals")) { return super.equals(args[0]); + } - if(method.getAnnotation(DuckTyped.class)!=null) { + if (method.getAnnotation(DuckTyped.class) != null) { return bean.invokeDuckMethod(method,proxy,args); } ConfigModel.Property property = bean.model.toProperty(method); + if (property == null) { + throw new IllegalArgumentException("No corresponding property found for method: " + method); + } - if(property==null) - throw new IllegalArgumentException( - "No corresponding property found for method: "+method); - - if(args==null || args.length==0) { + if (args == null || args.length == 0) { // getter, maybe one of our changed properties if (changedAttributes.containsKey(property.xmlName())) { // serve masked changes. Object changedValue = changedAttributes.get(property.xmlName()).getNewValue(); if (changedValue instanceof Dom) { return ((Dom) changedValue).createProxy(); - } else { - return changedValue; } - } else { - // pass through. - return getter(property, method.getGenericReturnType()); + return changedValue; } - } else { - setter(property, args[0], method.getGenericParameterTypes()[0]); - return null; + // pass through. + return getter(property, method.getGenericReturnType()); } + setter(property, args[0], method.getGenericParameterTypes()[0]); + return null; } public String getPropertyValue(String propertyName) { - ConfigModel.Property prop = this.getProperty(propertyName); - if (prop!=null) { - if (changedAttributes.containsKey(prop.xmlName())) { - // serve masked changes. - return (String) changedAttributes.get(prop.xmlName()).getNewValue(); - } else { - return (String) getter(prop, String.class); - } + if (prop == null) { + return null; } - return null; + if (changedAttributes.containsKey(prop.xmlName())) { + // serve masked changes. + return (String) changedAttributes.get(prop.xmlName()).getNewValue(); + } + return (String) getter(prop, String.class); } - public synchronized Object getter(ConfigModel.Property property, java.lang.reflect.Type t) { + public synchronized Object getter(ConfigModel.Property property, Type t) { Object value = bean._getter(property, t); if (value instanceof List) { if (!changedCollections.containsKey(property.xmlName())) { // wrap collections so we can record events on that collection mutation. changedCollections.put(property.xmlName(), - new ProtectedList(List.class.cast(value), defaultView, property.xmlName())); + new ProtectedList(List.class.cast(value), defaultView, property.xmlName())); } return changedCollections.get(property.xmlName()); } return value; } - public synchronized void setter(ConfigModel.Property property, - Object newValue, java.lang.reflect.Type t) { - + public synchronized void setter(ConfigModel.Property property, Object newValue, Type t) { // are we still in a transaction - if (currentTx==null) { + if (currentTx == null) { throw new IllegalStateException("Not part of a transaction"); } try { - if (newValue != null) + if (newValue != null) { handleValidation(property, newValue); + } } catch(Exception v) { bean.getLock().unlock(); throw new RuntimeException(v); @@ -211,14 +229,14 @@ public synchronized void setter(ConfigModel.Property property, // Resources List siblings = parent != null ? parent.domNodeByTypeElements(thisview.getProxyType()) - : new ArrayList(); + : new ArrayList<>(); // Iterate through each sibling element and see if anyone has // same key. If true throw an exception after unlocking this // element for (Dom sibling : siblings) { String siblingKey = sibling.getKey(); - if (newValue.equals(siblingKey)) { + if (siblingKey.equals(newValue)) { bean.getLock().unlock(); throw new IllegalArgumentException( "Keys cannot be duplicate. Old value of this key " + @@ -231,14 +249,13 @@ public synchronized void setter(ConfigModel.Property property, // setter Object oldValue = bean.getter(property, t); if (newValue instanceof ConfigBeanProxy) { - ConfigView bean = (ConfigView) - Proxy.getInvocationHandler((ConfigBeanProxy) newValue); - newValue = bean.getMasterView(); + ConfigView view = (ConfigView) Proxy.getInvocationHandler(newValue); + newValue = view.getMasterView(); } PropertyChangeEvent evt = new PropertyChangeEvent( defaultView,property.xmlName(), oldValue, newValue); try { - for (ConfigBeanInterceptor interceptor : bean.getOptionalFeatures()) { + for (ConfigBeanInterceptor interceptor : bean.getOptionalFeatures()) { interceptor.beforeChange(evt); } } catch(PropertyVetoException e) { @@ -246,7 +263,7 @@ public synchronized void setter(ConfigModel.Property property, } changedAttributes.put(property.xmlName(), evt); - for (ConfigBeanInterceptor interceptor : bean.getOptionalFeatures()) { + for (ConfigBeanInterceptor interceptor : bean.getOptionalFeatures()) { interceptor.afterChange(evt, System.currentTimeMillis()); } } @@ -266,8 +283,9 @@ public ConfigModel.Property getProperty(String xmlName) { * @return true if the enlisting with the passed transaction was accepted, * false otherwise */ + @Override public synchronized boolean join(Transaction t) { - if (currentTx==null) { + if (currentTx == null) { currentTx = t; t.addParticipant(this); return true; @@ -282,50 +300,49 @@ public synchronized boolean join(Transaction t) { * one passed during the join(Transaction t) call. * @return true if the trsaction commiting would be successful */ + @Override public synchronized boolean canCommit(Transaction t) throws TransactionFailure { - if (!isDeleted) { // HK2-127: validate only if not marked for deletion - - Set constraintViolations = - beanValidator.validate(this.getProxy(this.getProxyType())); - + // HK2-127: validate only if not marked for deletion + if (!isDeleted) { + Set> constraintViolations = beanValidator + .validate(this.getProxy(this.getProxyType())); try { handleValidationException(constraintViolations); - } catch (ConstraintViolationException constraintViolationException) { - throw new TransactionFailure(constraintViolationException.getMessage(), constraintViolationException); + } catch (ConstraintViolationException e) { + throw new TransactionFailure(e.getMessage(), e); } } - - return currentTx==t; + return currentTx == t; } - private void handleValidationException(Set constraintViolations) throws ConstraintViolationException { - if (constraintViolations != null && !constraintViolations.isEmpty()) { - Iterator> it = constraintViolations.iterator(); - - StringBuilder sb = new StringBuilder(); - sb.append(MessageFormat.format(i18n.getString("bean.validation.failure"), this.getProxyType().getSimpleName())); - String violationMsg = i18n.getString("bean.validation.constraintViolation"); - while (it.hasNext()) { - ConstraintViolation cv = it.next(); - sb.append(" "); - sb.append(MessageFormat.format(violationMsg, cv.getMessage(), cv.getPropertyPath())); - if (it.hasNext()) { - sb.append(i18n.getString("bean.validation.separator")); - } + private void handleValidationException(Set> violations) + throws ConstraintViolationException { + if (violations == null || violations.isEmpty()) { + return; + } + Iterator> it = violations.iterator(); + StringBuilder sb = new StringBuilder(); + sb.append(MessageFormat.format(i18n.getString("bean.validation.failure"), getProxyType().getSimpleName())); + String violationMsg = i18n.getString("bean.validation.constraintViolation"); + while (it.hasNext()) { + ConstraintViolation violation = it.next(); + sb.append(" "); + sb.append(MessageFormat.format(violationMsg, violation.getMessage(), violation.getPropertyPath())); + if (it.hasNext()) { + sb.append(i18n.getString("bean.validation.separator")); } - bean.getLock().unlock(); - throw new ConstraintViolationException(sb.toString(), constraintViolations); } + bean.getLock().unlock(); + throw new ConstraintViolationException(sb.toString(), violations); } /** remove @ or <> eg "@foo" => "foo" or "" => "foo" */ - public static String stripMarkers(final String s ) { - if ( s.startsWith("@") ) { + public static String stripMarkers(final String s) { + if (s.startsWith("@")) { return s.substring(1); - } - else if ( s.startsWith("<") ) { - return s.substring(1, s.length()-1); + } else if (s.startsWith("<")) { + return s.substring(1, s.length() - 1); } return s; } @@ -334,34 +351,33 @@ else if ( s.startsWith("<") ) { * Commit this Transaction. * * @param t the transaction commiting. - * @throws TransactionFailure - * if the transaction commit failed + * @throws TransactionFailure if the transaction commit failed */ + @Override public synchronized List commit(Transaction t) throws TransactionFailure { - if (currentTx==t) { - currentTx=null; + if (currentTx == t) { + currentTx = null; } // a key attribute must be non-null and have length >= 1 final ConfigBean master = getMasterView(); final String keyStr = master.model.key; - if ( keyStr != null) { + if (keyStr != null) { final String key = stripMarkers(keyStr); final String value = getPropertyValue(key); - if ( value == null ) { - throw new TransactionFailure( "Key value cannot be null: " + key ); + if (value == null) { + throw new TransactionFailure("Key value cannot be null: " + key); } - if ( value.length() == 0 ) { - throw new TransactionFailure( "Key value cannot be empty string: " + key ); + if (value.length() == 0) { + throw new TransactionFailure("Key value cannot be empty string: " + key); } } - try { - List appliedChanges = new ArrayList(); + List appliedChanges = new ArrayList<>(); for (PropertyChangeEvent event : changedAttributes.values()) { ConfigModel.Property property = bean.model.findIgnoreCase(event.getPropertyName()); - ConfigBeanInterceptor interceptor = bean.getOptionalFeature(ConfigBeanInterceptor.class); + ConfigBeanInterceptor interceptor = bean.getOptionalFeature(ConfigBeanInterceptor.class); try { if (interceptor!=null) { interceptor.beforeChange(event); @@ -370,24 +386,24 @@ public synchronized List commit(Transaction t) throws Trans throw new TransactionFailure(e.getMessage(), e); } property.set(bean, event.getNewValue()); - if (interceptor!=null) { + if (interceptor != null) { interceptor.afterChange(event, System.currentTimeMillis()); } appliedChanges.add(event); } - for (ProtectedList entry : changedCollections.values()) { + for (ProtectedList entry : changedCollections.values()) { List originalList = entry.readOnly; for (PropertyChangeEvent event : entry.changeEvents) { - if (event.getOldValue()==null) { + if (event.getOldValue() == null) { originalList.add(event.getNewValue()); } else { final Object toBeRemovedObj = event.getOldValue(); - if ( toBeRemovedObj instanceof ConfigBeanProxy ) { - final Dom toBeRemoved = Dom.unwrap((ConfigBeanProxy)toBeRemovedObj); - for (int index=0;index commit(Transaction t) throws Trans } } } - } - else if ( toBeRemovedObj instanceof String ) { - final String toBeRemoved = (String)toBeRemovedObj; - for (int index=0;index T allocateProxy(Class type) throws TransactionFailure { - if (currentTx==null) { + if (currentTx == null) { throw new TransactionFailure("Not part of a transaction", null); } ConfigBean newBean = bean.allocate(type); - WriteableView writeableView = bean.getHabitat().getService(ConfigSupport.class).getWriteableView(newBean.getProxy(type), newBean); + bean.getHabitat(). getService(ConfigSupport.class); + WriteableView writeableView = ConfigSupport.getWriteableView(newBean.getProxy(type), newBean); writeableView.join(currentTx); - return writeableView.getProxy(type); } + @Override public ConfigBean getMasterView() { return bean; } + @Override public void setMasterView(ConfigView view) { } + @Override public Class getProxyType() { return bean.getProxyType(); } + @Override @SuppressWarnings("unchecked") public T getProxy(final Class type) { final ConfigBean sourceBean = getMasterView(); @@ -478,55 +497,56 @@ public T getProxy(final Class type) { throw new IllegalArgumentException("This config bean interface is " + sourceBean.model.targetTypeName + " not " + type.getName()); } - Class[] interfacesClasses = { type }; ClassLoader cl; - if (System.getSecurityManager()!=null) { + if (System.getSecurityManager() == null) { + cl = type.getClassLoader(); + } else { cl = AccessController.doPrivileged(new PrivilegedAction() { + @Override public ClassLoader run() { return type.getClassLoader(); } }); - } else { - cl = type.getClassLoader(); } + Class[] interfacesClasses = {type}; return (T) Proxy.newProxyInstance(cl, interfacesClasses, this); } boolean removeNestedElements(Object object) { - InvocationHandler h = Proxy.getInvocationHandler(object); - if (!(h instanceof WriteableView)) { // h instanceof ConfigView - ConfigBean bean = (ConfigBean) ((ConfigView) h).getMasterView(); - h = bean.getWriteableView(); - if (h == null) { + InvocationHandler handler = Proxy.getInvocationHandler(object); + if (!(handler instanceof WriteableView)) { + ConfigBean masterView = (ConfigBean) ((ConfigView) handler).getMasterView(); + handler = masterView.getWriteableView(); + if (handler == null) { ConfigBeanProxy writable; try { writable = currentTx.enroll((ConfigBeanProxy) object); } catch (TransactionFailure e) { - throw new RuntimeException(e); // something is seriously wrong + // something is seriously wrong + throw new IllegalStateException(e); } - h = Proxy.getInvocationHandler(writable); + handler = Proxy.getInvocationHandler(writable); } else { // it's possible to set leaf multiple times, // so oldValue was already processed return false; } } - WriteableView writableView = (WriteableView) h; + WriteableView writableView = (WriteableView) handler; synchronized (writableView) { writableView.isDeleted = true; } boolean removed = false; for (Property property : writableView.bean.model.elements.values()) { if (property.isCollection()) { - Object nested = writableView.getter(property, - parameterizedType); + Object nested = writableView.getter(property, parameterizedType); ProtectedList list = (ProtectedList) nested; if (list.size() > 0) { list.clear(); removed = true; } - } else if (!property.isLeaf()) { // Element + } else if (!property.isLeaf()) { Object oldValue = writableView.getter(property, ConfigBeanProxy.class); if (oldValue != null) { writableView.setter(property, null, Dom.class); @@ -538,381 +558,384 @@ boolean removeNestedElements(Object object) { return removed; } -/** - * A Protected List is a @Link java.util.List implementation which mutable - * operations are constrained by the owner of the list. - * - * @author Jerome Dochez - */ -private class ProtectedList extends AbstractList { - - final ConfigBeanProxy readView; - final List readOnly; - final String id; - final List changeEvents = new ArrayList(); - final List proxied; - - ProtectedList(List readOnly, ConfigBeanProxy parent, String id) { - proxied = Collections.synchronizedList(new ArrayList(readOnly)); - this.readView = parent; - this.readOnly = readOnly; - this.id = id; - } + private final class WriteableViewConstraintViolation implements ConstraintViolation { - /** - * Returns the number of elements in this collection. If the collection - * contains more than Integer.MAX_VALUE elements, returns - * Integer.MAX_VALUE. - * - * @return the number of elements in this collection. - */ - public int size() { - return proxied.size(); - } + private final AttributeLeaf leaf; + private final String value; - /** - * Returns the element at the specified position in this list. - * - * @param index index of element to return. - * @return the element at the specified position in this list. - * @throws IndexOutOfBoundsException if the given index is out of range - * (index < 0 || index >= size()). - */ - public Object get(int index) { - return proxied.get(index); - } + private WriteableViewConstraintViolation(AttributeLeaf leaf, String value) { + this.leaf = leaf; + this.value = value; + } - @Override - public synchronized boolean add(Object object) { - Object param = object; - Object handler = null; - try { - handler = Proxy.getInvocationHandler(object); - } catch(IllegalArgumentException e) { - // ignore, this is a leaf + @Override + public String getMessage() { + return i18n.getString(getMessageTemplate()) + leaf.dataType; } - if (handler!=null && handler instanceof WriteableView) { - ConfigBean master = ((WriteableView) handler).getMasterView(); - String key = master.model.key; - if (key!=null) { - // remove leading @ - key = key.substring(1); - // check that we are not adding a duplicate key element - String keyValue = ((WriteableView) handler).getPropertyValue(key); - for (Object o : proxied) { - // the proxied object can be a read-only or a writeable view, we need - // to be careful - // ToDo : we need to encasulate this test. - String value = null; - if (Proxy.getInvocationHandler(o) instanceof WriteableView) { - ConfigBean masterView = ((WriteableView) handler).getMasterView(); - String masterViewKey = masterView.model.key; - if(masterViewKey != null && key.equals(masterViewKey.substring(1))){ - value = ((WriteableView) Proxy.getInvocationHandler(o)).getPropertyValue(key); - } - } else { - Dom cbo = Dom.unwrap((ConfigBeanProxy) o); - String cboKey = cbo.model.key; - if(cboKey != null && key.equals(cboKey.substring(1))){ - value = cbo.attribute(key); - } - } - if (keyValue!=null && value != null && keyValue.equals(value)) { - Dom parent = Dom.unwrap(readView); - throw new IllegalArgumentException("A " + master.getProxyType().getSimpleName() + - " with the same key \"" + keyValue + "\" already exists in " + - parent.getProxyType().getSimpleName() + " " + parent.getKey()) ; - } - } - } - param = ((WriteableView) handler).getMasterView().createProxy( - (Class) master.getImplementationClass()); + @Override + public String getMessageTemplate() { + return "bean.validation.dataType.failure"; + } + @Override + public ConfigBeanProxy getRootBean() { + return (ConfigBeanProxy) WriteableView.this; } - PropertyChangeEvent evt = new PropertyChangeEvent(defaultView, id, null, param); - changeEvents.add(evt); - boolean added = proxied.add(object); + @Override + public Class getRootBeanClass() { + return WriteableView.this.getProxyType(); + } - try { - for (ConfigBeanInterceptor interceptor : bean.getOptionalFeatures()) { - interceptor.beforeChange(evt); - } - } catch(PropertyVetoException e) { - throw new RuntimeException(e); + @Override + public Object getLeafBean() { + return null; } - return added; - } + @Override + public Object[] getExecutableParameters() { + return null; + } - @Override - public synchronized void clear() { - // make a temporary list, iterating while removing doesn't work - final List allItems = new ArrayList( proxied ); - for( final Object item : allItems ) { - remove( item ); + @Override + public Object getExecutableReturnValue() { + return null; } - } - @Override - public synchronized boolean retainAll( final Collection keepers ) { - final List toRemoveList = new ArrayList(); - for( final Object iffy : proxied ) { - if ( ! keepers.contains(iffy) ) { - toRemoveList.add(iffy); - } + @Override + public Path getPropertyPath() { + final Set nodes = new HashSet<>(); + nodes.add(new Path.Node() { + @Override + public String getName() { + return leaf.xmlName; + } + + @Override + public boolean isInIterable() { + return false; + } + + @Override + public Integer getIndex() { + return null; + } + + @Override + public Object getKey() { + return null; + } + + @Override + public ElementKind getKind() { + return null; + } + + @Override + public T as(Class tClass) { + return null; + } + }); + return new Path() { + @Override + public Iterator iterator() { + return nodes.iterator(); + } + + @Override + public String toString() { + return nodes.iterator().next().getName(); + } + }; } - final boolean changed = removeAll(toRemoveList); - return changed; - } + @Override + public Object getInvalidValue() { + return value; + } - @Override - public synchronized boolean removeAll( final Collection goners ) { - boolean listChanged = false; - for( final Object goner : goners ) { - if ( remove(goner) ) { - listChanged = true; - } + @Override + public ConstraintDescriptor getConstraintDescriptor() { + return null; } - return listChanged; + @Override + public Object unwrap(Class type) { + return null; + } } - @Override - public synchronized boolean remove(Object object) { - PropertyChangeEvent evt = new PropertyChangeEvent(defaultView, id, object, null); - boolean removed = false; + /** + * A Protected List is a @Link java.util.List implementation which mutable + * operations are constrained by the owner of the list. + * + * @author Jerome Dochez + */ + private class ProtectedList extends AbstractList { + + final ConfigBeanProxy readView; + final List readOnly; + final String id; + final List changeEvents = new ArrayList<>(); + final List proxied; + + ProtectedList(List readOnly, ConfigBeanProxy parent, String id) { + proxied = Collections.synchronizedList(new ArrayList<>(readOnly)); + this.readView = parent; + this.readOnly = readOnly; + this.id = id; + } + + /** + * Returns the number of elements in this collection. If the collection + * contains more than Integer.MAX_VALUE elements, returns + * Integer.MAX_VALUE. + * + * @return the number of elements in this collection. + */ + @Override + public int size() { + return proxied.size(); + } + + /** + * Returns the element at the specified position in this list. + * + * @param index index of element to return. + * @return the element at the specified position in this list. + * @throws IndexOutOfBoundsException if the given index is out of range + * (index < 0 || index >= size()). + */ + @Override + public Object get(int index) { + return proxied.get(index); + } - try { - ConfigView handler = ((ConfigView) Proxy.getInvocationHandler(object)).getMasterView(); - for (int index = 0 ; index) master.getImplementationClass()); + } - } catch(IllegalArgumentException e) { - // ignore, this is a leaf - removed = proxied.remove(object); + PropertyChangeEvent evt = new PropertyChangeEvent(defaultView, id, null, param); + changeEvents.add(evt); + boolean added = proxied.add(object); + + try { + for (ConfigBeanInterceptor interceptor : bean.getOptionalFeatures()) { + interceptor.beforeChange(evt); + } + } catch (PropertyVetoException e) { + throw new RuntimeException(e); + } + + return added; } - try { - for (ConfigBeanInterceptor interceptor : bean.getOptionalFeatures()) { - interceptor.beforeChange(evt); + @Override + public synchronized void clear() { + // make a temporary list, iterating while removing doesn't work + final List allItems = new ArrayList<>(proxied); + for (Object item : allItems) { + remove(item); } - } catch(PropertyVetoException e) { - throw new RuntimeException(e); } - changeEvents.add(evt); + @Override + public synchronized boolean retainAll(final Collection keepers) { + final List toRemoveList = new ArrayList<>(); + for (Object iffy : proxied) { + if (!keepers.contains(iffy)) { + toRemoveList.add(iffy); + } + } + return removeAll(toRemoveList); + } - return removed; - } + @Override + public synchronized boolean removeAll(final Collection goners) { + boolean listChanged = false; + for (Object goner : goners) { + if (remove(goner)) { + listChanged = true; + } + } + return listChanged; + } + + @Override + public synchronized boolean remove(Object object) { + PropertyChangeEvent evt = new PropertyChangeEvent(defaultView, id, object, null); + boolean removed = false; + try { + ConfigView handler = ((ConfigView) Proxy.getInvocationHandler(object)).getMasterView(); + for (int index = 0; index < proxied.size() && !removed; index++) { + Object target = proxied.get(index); + try { + ConfigView targetHandler = ((ConfigView) Proxy.getInvocationHandler(target)).getMasterView(); + if (targetHandler == handler) { + removed = (proxied.remove(index) != null); + } + } catch (IllegalArgumentException ex) { + // ignore + } + } + } catch (IllegalArgumentException e) { + // ignore, this is a leaf + removed = proxied.remove(object); - public Object set(int index, Object object) { - Object replaced = proxied.set(index, object); - PropertyChangeEvent evt = new PropertyChangeEvent(defaultView, id, replaced, object); - try { - for (ConfigBeanInterceptor interceptor : bean.getOptionalFeatures()) { - interceptor.beforeChange(evt); } - } catch(PropertyVetoException e) { - throw new RuntimeException(e); + + try { + for (ConfigBeanInterceptor interceptor : bean.getOptionalFeatures()) { + interceptor.beforeChange(evt); + } + } catch (PropertyVetoException e) { + throw new RuntimeException(e); + } + + changeEvents.add(evt); + + return removed; } - changeEvents.add(evt); - return replaced; - }} + + @Override + public Object set(int index, Object object) { + Object replaced = proxied.set(index, object); + PropertyChangeEvent evt = new PropertyChangeEvent(defaultView, id, replaced, object); + try { + for (ConfigBeanInterceptor interceptor : bean.getOptionalFeatures()) { + interceptor.beforeChange(evt); + } + } catch (PropertyVetoException e) { + throw new RuntimeException(e); + } + changeEvents.add(evt); + return replaced; + }} private String toCamelCase(String xmlName) { - StringTokenizer st = new StringTokenizer(xmlName, "-"); - StringBuffer camelCaseName = null; - if (st.hasMoreTokens()) { - camelCaseName = new StringBuffer(st.nextToken()); + if (xmlName == null) { + return null; } - StringBuffer sb = null; + StringTokenizer st = new StringTokenizer(xmlName, "-"); + StringBuilder camelCaseName = new StringBuilder(); + camelCaseName.append(st.nextToken()); while (st.hasMoreTokens()) { - sb = new StringBuffer(st.nextToken()); + StringBuilder sb = new StringBuilder(st.nextToken()); char startChar = sb.charAt(0); - sb.setCharAt(0,Character.toUpperCase(startChar)); + sb.setCharAt(0, Character.toUpperCase(startChar)); camelCaseName.append(sb); } - return (camelCaseName == null) ? null : camelCaseName.toString(); + return camelCaseName.toString(); } private void handleValidation(ConfigModel.Property property, Object value) - throws ConstraintViolationException { + throws ConstraintViolationException { // First check for dataType constraints -- as was done for v3 Prelude // These validations could be transformed into BV custom annotations // such as AssertBoolean, AssertInteger etc. But since GUI and other // config clients such as AMX need dataType key in @Attribute it's been // decided to validate using existing annotation information - Set> constraintViolations = new HashSet>(); + Set> constraintViolations = new HashSet<>(); if (property instanceof ConfigModel.AttributeLeaf) { ConfigModel.AttributeLeaf al = (ConfigModel.AttributeLeaf)property; if (!al.isReference()) { - ConstraintViolation cv = validateDataType(al, value.toString()); - if (cv!=null) { + ConstraintViolation cv = validateDataType(al, value.toString()); + if (cv != null) { constraintViolations.add(cv); } } } - constraintViolations.addAll( - beanValidator.validateValue( - bean.getProxyType(), toCamelCase(property.xmlName()), value)); + constraintViolations + .addAll(beanValidator.validateValue(bean.getProxyType(), toCamelCase(property.xmlName()), value)); handleValidationException(constraintViolations); } - private ConstraintViolation validateDataType(final ConfigModel.AttributeLeaf al, final String value) - { - if (value.startsWith("${") && value.endsWith("}")) - return null; - boolean isValid = String.class.getName().equals(al.dataType); - if ("int".equals(al.dataType) || - "java.lang.Integer".equals(al.dataType)) + private ConstraintViolation validateDataType(final AttributeLeaf leaf, final String value) { + if (value.startsWith("${") && value.endsWith("}")) { + return null; + } + boolean isValid = String.class.getName().equals(leaf.dataType); + if ("int".equals(leaf.dataType) || "java.lang.Integer".equals(leaf.dataType)) { isValid = representsInteger(value); - else if ("long".equals(al.dataType) || - "java.lang.Long".equals(al.dataType)) + } else if ("long".equals(leaf.dataType) || "java.lang.Long".equals(leaf.dataType)) { isValid = representsLong(value); - else if ("boolean".equals(al.dataType) || - "java.lang.Boolean".endsWith(al.dataType)) + } else if ("boolean".equals(leaf.dataType) || "java.lang.Boolean".endsWith(leaf.dataType)) { isValid = representsBoolean(value); - else if ("char".equals(al.dataType) || - "java.lang.Character".equals(al.dataType)) + } else if ("char".equals(leaf.dataType) || "java.lang.Character".equals(leaf.dataType)) { isValid = representsChar(value); + } if (!isValid) { - return new ConstraintViolation() { - @Override - public String getMessage() { - return i18n.getString("bean.validation.dataType.failure") + al.dataType; - } - - @Override - public String getMessageTemplate() { - return null; - } - - @Override - public Object getRootBean() { - return WriteableView.this; - } - - @Override - public Class getRootBeanClass() { - return WriteableView.this.getProxyType(); - } - - @Override - public Object getLeafBean() { - return null; - } - - @Override - public Object[] getExecutableParameters() { - return null; - } - - @Override - public Object getExecutableReturnValue() { - return null; - } - - @Override - public Path getPropertyPath() { - final Set nodes = new HashSet(); - nodes.add(new Path.Node() { - @Override - public String getName() { - return al.xmlName; - } - - @Override - public boolean isInIterable() { - return false; - } - - @Override - public Integer getIndex() { - return null; - } - - @Override - public Object getKey() { - return null; - } - - @Override - public ElementKind getKind() { - return null; - } - - @Override - public T as(Class tClass) { - return null; - } - }); - return new jakarta.validation.Path() { - @Override - public Iterator iterator() { - return nodes.iterator(); - } - - @Override - public String toString() { - return nodes.iterator().next().getName(); - } - }; - } - - @Override - public Object getInvalidValue() { - return value; - } - - @Override - public ConstraintDescriptor getConstraintDescriptor() { - return null; - } - - @Override - public Object unwrap(Class type) { - return null; - } - - - }; - }; + return new WriteableViewConstraintViolation(leaf, value); + } return null; } private boolean representsBoolean(String value) { - boolean isBoolean = - "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value); - return (isBoolean); + return "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value); } private boolean representsChar(String value) { - if (value.length() == 1) - return true; - return false; + if (value.length() == 1) { + return true; + } + return false; } private boolean representsInteger(String value) { try { Integer.parseInt(value); return true; - } catch(NumberFormatException ne) { + } catch (NumberFormatException ne) { return false; } } @@ -922,12 +945,12 @@ private boolean representsLong(String value) { try { Long.parseLong(value); return true; - } catch(NumberFormatException ne) { + } catch (NumberFormatException ne) { return false; } } - private final static ParameterizedType parameterizedType = new ParameterizedType() { + private static final ParameterizedType parameterizedType = new ParameterizedType() { @Override public Type[] getActualTypeArguments() { diff --git a/nucleus/parent/pom.xml b/nucleus/parent/pom.xml index 2deca2f6061..cfb23e8b74f 100644 --- a/nucleus/parent/pom.xml +++ b/nucleus/parent/pom.xml @@ -490,6 +490,12 @@ ${jmh.version} test + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-impl-maven-archive + 3.1.4 + test + commons-io diff --git a/nucleus/pom.xml b/nucleus/pom.xml index cbd2417bc34..58f50d79cff 100644 --- a/nucleus/pom.xml +++ b/nucleus/pom.xml @@ -1,7 +1,7 @@ - - - - 4.0.0 - - - org.glassfish.main.tests - nucleus-tests - 6.2.6-SNAPSHOT - - - org.glassfish.tests - nucleus-admin - - Nucleus Tests - Admin - This pom describes how to run admin developer tests on the Nucleus Bundle - - - - org.glassfish.hk2 - hk2-api - test - - - org.glassfish.jersey.core - jersey-server - test - - - org.glassfish.jersey.inject - jersey-hk2 - test - - - - org.glassfish.main.admin - rest-client - ${project.version} - test - - - org.glassfish.main.admin - rest-service - ${project.version} - jar - test - - - org.glassfish.main.common - common-util - ${project.version} - test - - - jakarta.xml.bind - jakarta.xml.bind-api - - - com.sun.xml.bind - jaxb-osgi - - - - - - - maven-invoker-plugin - - - modules/*/pom.xml - asadmin/*/pom.xml - - - clean - package - - ${basedir}/src/addon/ - ${project.build.directory}/addon - - - - build-addons - process-test-resources - - run - - - - - - - maven-surefire-plugin - - - alphabetical - - - - - - diff --git a/nucleus/tests/admin/src/main/java/.gitkeep_empty_dir b/nucleus/tests/admin/src/main/java/.gitkeep_empty_dir deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/nucleus/tests/admin/src/main/resources/.gitkeep_empty_dir b/nucleus/tests/admin/src/main/resources/.gitkeep_empty_dir deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/ClusterTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/ClusterTest.java deleted file mode 100644 index 566259d0558..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/ClusterTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2012, 2020 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin; - -import static org.glassfish.tests.utils.NucleusTestUtils.getURL; -import static org.glassfish.tests.utils.NucleusTestUtils.matchString; -import static org.glassfish.tests.utils.NucleusTestUtils.nadmin; -import static org.testng.AssertJUnit.assertTrue; - -import org.testng.annotations.Test; - -/** - * - * @author Tom Mueller - */ -@Test(testName = "ClusterTest", enabled = true) -public class ClusterTest { - - final String tn = "QLCluster"; - final String port1 = "55123"; - final String port2 = "55124"; - final String cname = "eec1"; - final String i1name = "eein1-with-a-very-very-very-long-name"; - final String i2name = "eein2"; - String i1url = "http://localhost:" + port1; - String i2url = "http://localhost:" + port2; - - @Test - public void createClusterTest() { - // create a cluster and two instances - assertTrue("create cluster", nadmin("create-cluster", cname)); - } - - @Test(dependsOnMethods = { "createClusterTest" }) - public void createInstancesTest() { - assertTrue("create instance1", - nadmin("create-local-instance", "--cluster", cname, "--systemproperties", - "HTTP_LISTENER_PORT=" + port1 + ":" + - "HTTP_SSL_LISTENER_PORT=18181:" + - "IIOP_SSL_LISTENER_PORT=13800:" + - "IIOP_LISTENER_PORT=13700:" + - "JMX_SYSTEM_CONNECTOR_PORT=17676:" + - "IIOP_SSL_MUTUALAUTH_PORT=13801:" + - "JMS_PROVIDER_PORT=18686:" + - "ASADMIN_LISTENER_PORT=14848", - i1name)); - - assertTrue("create instance2", - nadmin("create-local-instance", "--cluster", cname, "--systemproperties", - "HTTP_LISTENER_PORT=" + port2 + - ":HTTP_SSL_LISTENER_PORT=28181:IIOP_SSL_LISTENER_PORT=23800:" + - "IIOP_LISTENER_PORT=23700:JMX_SYSTEM_CONNECTOR_PORT=27676:IIOP_SSL_MUTUALAUTH_PORT=23801:" + - "JMS_PROVIDER_PORT=28686:ASADMIN_LISTENER_PORT=24848", - i2name)); - } - - @Test(dependsOnMethods = { "createInstancesTest" }) - public void startInstancesTest() { - // start the instances - assertTrue("start instance1", nadmin("start-local-instance", i1name)); - assertTrue("start instance2", nadmin("start-local-instance", i2name)); - } - - @Test(dependsOnMethods = { "startInstancesTest" }) - public void checkClusterTest() { - // check that the instances are there - assertTrue("list-instances", nadmin("list-instances")); - assertTrue("getindex1", matchString("GlassFish Server", getURL(i1url))); - assertTrue("getindex2", matchString("GlassFish Server", getURL(i2url))); - } - - @Test(dependsOnMethods = { "checkClusterTest" }) - public void stopInstancesTest() { - // stop and delete the instances and cluster - assertTrue("stop instance1", nadmin("stop-local-instance", "--kill", i1name)); - assertTrue("stop instance2", nadmin("stop-local-instance", "--kill", i2name)); - } - - @Test(dependsOnMethods = { "stopInstancesTest" }) - public void deleteInstancesTest() { - assertTrue("delete instance1", nadmin("delete-local-instance", i1name)); - assertTrue("delete instance2", nadmin("delete-local-instance", i2name)); - } - - @Test(dependsOnMethods = { "deleteInstancesTest" }) - public void deleteClusterTest() { - assertTrue("delete cluster", nadmin("delete-cluster", cname)); - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/MiscCommandsTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/MiscCommandsTest.java deleted file mode 100644 index 6067b94ea19..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/MiscCommandsTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin; - -import static org.glassfish.tests.utils.NucleusTestUtils.*; -import static org.testng.AssertJUnit.assertTrue; -import org.testng.annotations.Test; - -/** - * - * @author Tom Mueller - */ -@Test(testName="MiscCommandsTest") -public class MiscCommandsTest { - - public void uptime() { - assertTrue(nadmin("uptime")); - } - - public void version1() { - assertTrue(nadmin("version")); - } - - public void version2() { - assertTrue(nadmin("stop-domain")); - assertTrue(nadmin("version", "--local")); - assertTrue(nadmin("start-domain")); - } - -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/NucleusStartStopTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/NucleusStartStopTest.java deleted file mode 100644 index edabfbf98c6..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/NucleusStartStopTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2012, 2020 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin; - -import static org.glassfish.tests.utils.NucleusTestUtils.getNucleusRoot; -import static org.glassfish.tests.utils.NucleusTestUtils.nadmin; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.channels.FileChannel; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.testng.ITestContext; -import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeSuite; - -public class NucleusStartStopTest { - - private static final String TEST_LIBS_KEY = "TEST_LIBS"; - private static final Map COPY_LIB; - static { - Map map = new HashMap<>(); - map.put("modules", "modules"); - COPY_LIB = Collections.unmodifiableMap(map); - } - - @BeforeSuite - public void setUp(ITestContext context) throws IOException { - // Copy testing libraries into Nucleus distribution - Collection testLibs = new ArrayList(); - context.setAttribute(TEST_LIBS_KEY, testLibs); - String basedir = System.getProperty("basedir"); - assertNotNull(basedir); - - File addondir = new File(basedir, "target/addon"); - for (Map.Entry copyLibEntry : COPY_LIB.entrySet()) { - copyLibraries( - new File(addondir, copyLibEntry.getKey()), - new File(getNucleusRoot(), copyLibEntry.getValue()), - testLibs); - } - - // Start - assertTrue(nadmin("start-domain")); - } - - @AfterSuite(alwaysRun = true) - public void tearDown(ITestContext context) { - try { - assertTrue(nadmin("stop-domain")); - } finally { - @SuppressWarnings("unchecked") - Collection libs = (Collection) context.getAttribute(TEST_LIBS_KEY); - if (libs != null) { - for (File lib : libs) { - if (lib.exists()) { - try { - lib.delete(); - } catch (Exception ex) { - System.out.println("Can not delete " + lib.getAbsolutePath()); - } - } - } - } - } - } - - private void copyLibraries(File src, File dest, Collection copiedLibs) throws IOException { - if (src.exists() && src.isDirectory()) { - File[] dirs = src.listFiles(f -> f.isDirectory()); - - for (File dir : dirs) { - File target = new File(dir, "target"); - if (target.exists() && target.isDirectory()) { - File[] jars = target.listFiles(f-> f.isFile() && f.getName().toLowerCase().endsWith(".jar")); - - for (File jar : jars) { - File destinationFile = new File(dest, jar.getName()); - copiedLibs.add(destinationFile); - copy(jar, destinationFile); - - System.out.println("TESTING LIBRARY: " + destinationFile.getAbsolutePath()); - } - } - } - } - } - - private static void copy(File src, File dest) throws IOException { - if (!dest.exists()) { - dest.createNewFile(); - } - - try (FileChannel sch = new FileInputStream(src).getChannel(); FileChannel dch = new FileOutputStream(dest).getChannel()) { - dch.transferFrom(sch, 0, sch.size()); - } - } - -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/RestTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/RestTest.java deleted file mode 100644 index f73e62cac42..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/RestTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin; - -import java.io.DataOutputStream; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -@Test -public class RestTest { - - public void testManagementEndpoint() { - try { - HttpURLConnection connection = getConnection("http://localhost:4848/management/domain.xml"); - assertEquals(200, connection.getResponseCode()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - public void testMonitoringEndpoint() { - try { - HttpURLConnection connection = getConnection("http://localhost:4848/monitoring/domain.xml"); - assertEquals(200, connection.getResponseCode()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - public void testAdminCommandEndpoint() { - try { - HttpURLConnection connection = getConnection("http://localhost:4848/management/domain/version.xml"); - assertEquals(200, connection.getResponseCode()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - public void testChildConfigBeanEndpoint() { - try { - HttpURLConnection connection = getConnection("http://localhost:4848/management/domain/applications.xml"); - assertEquals(200, connection.getResponseCode()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - public void testPostGetDelete() { - deleteNode(); // This should almost always fail, so we don't check the status. Just need to clean up from any prior runs - assertEquals(200, createNode()); - assertEquals(200, getNode()); - assertEquals(200, deleteNode()); - } - - protected HttpURLConnection getConnection(String url) throws IOException { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setRequestProperty("X-GlassFish-3", "true"); - connection.setRequestProperty("X-Requested-By", "dummy"); - return connection; - } - - private int createNode() { - HttpURLConnection connection = null; - try { - String parameters = "name=myConfigNode"; - connection = getConnection("http://localhost:4848/management/domain/nodes/create-node-config"); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - connection.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length)); - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setDoOutput(true); - connection.setRequestProperty("Content-Language", "en-US"); - DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); - wr.writeBytes(parameters); - wr.flush(); - wr.close(); - return connection.getResponseCode(); - } catch (Exception ex) { - fail(ex.getMessage()); - } finally { - if (connection != null) { - connection.disconnect(); - } - } - - return -1; - } - - private int getNode() { - HttpURLConnection connection = null; - try { - connection = getConnection("http://localhost:4848/management/domain/nodes/node/myConfigNode"); - return connection.getResponseCode(); - } catch (Exception ex) { - fail(ex.getMessage()); - } finally { - if (connection != null) { - connection.disconnect(); - } - } - - return -1; - } - - private int deleteNode() { - HttpURLConnection connection = null; - try { - connection = getConnection("http://localhost:4848/management/domain/nodes/delete-node-config?name=myConfigNode"); - connection.setRequestMethod("DELETE"); - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - connection.setDoOutput(true); - return connection.getResponseCode(); - } catch (Exception ex) { - fail(ex.getMessage()); - } finally { - if (connection != null) { - connection.disconnect(); - } - } - - return -1; - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/DetachAttachTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/DetachAttachTest.java deleted file mode 100644 index 92e064e11b3..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/DetachAttachTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.progress; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.io.File; -import java.util.StringTokenizer; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ThreadFactory; -import static org.glassfish.tests.utils.NucleusTestUtils.*; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.AfterTest; -import org.testng.annotations.Test; - -/** - * - * @author martinmares - */ -@Test(testName="DetachAttachTest") -public class DetachAttachTest { - private static File nucleusRoot = getNucleusRoot(); - - @AfterTest - public void cleanUp() throws Exception { - nadmin("stop-domain"); - JobManagerTest.deleteJobsFile(); - //osgi-cache workaround - File osgiCacheDir = new File(nucleusRoot, "domains"+File.separator+"domain1"+File.separator+"osgi-cache"); - deleteDirectoryContents(osgiCacheDir); - nadmin("start-domain"); - } - - // Test disabled till intermittent failures are fixed - @Test(enabled = false) - public void uptimePeriodically() throws InterruptedException { - Set ids = new HashSet(); - for (int i = 0; i < 3; i++) { - System.out.println("detachAndAttachUptimePeriodically(): round " + i); - NadminReturn result = nadminWithOutput("--detach", "--terse", "uptime"); - assertTrue(result.returnValue); - String id = parseJobIdFromEchoTerse(result.out); - assertTrue(ids.add(id)); //Must be unique - Thread.sleep(1000L); - //Now attach - result = nadminWithOutput("--terse", "attach", id); - assertTrue(result.returnValue); - assertTrue(result.out.contains("uptime")); - } - } - - public void commandWithProgressStatus() throws InterruptedException { - NadminReturn result = nadminWithOutput("--detach", "--terse", "progress-custom", "6x1"); - assertTrue(result.returnValue); - String id = parseJobIdFromEchoTerse(result.out); - Thread.sleep(2000L); - //Now attach running - result = nadminWithOutput("attach", id); - assertTrue(result.returnValue); - assertTrue(result.out.contains("progress-custom")); - List prgs = ProgressMessage.grepProgressMessages(result.out); - assertFalse(prgs.isEmpty()); - assertTrue(prgs.get(0).getValue() > 0); - assertEquals(100, prgs.get(prgs.size() - 1).getValue()); - //Now attach finished - must NOT exists - seen progress job is removed - result = nadminWithOutput("attach", id); - assertFalse(result.returnValue); - } - - public void detachOnesAttachMulti() throws InterruptedException, ExecutionException { - ExecutorService pool = Executors.newCachedThreadPool(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread result = new Thread(r); - result.setDaemon(true); - return result; - } - }); - //Execute command with progress status suport - NadminReturn result = nadminWithOutput("--detach", "--terse", "progress-custom", "8x1"); - assertTrue(result.returnValue); - final String id = parseJobIdFromEchoTerse(result.out); - Thread.sleep(1500L); - //Now attach - final int _attach_count = 3; - Collection> attaches = new ArrayList>(_attach_count); - for (int i = 0; i < _attach_count; i++) { - attaches.add(new Callable() { - @Override - public NadminReturn call() throws Exception { - return nadminWithOutput("attach", id); - } - }); - } - List> results = pool.invokeAll(attaches); - //Test results - for (Future fRes : results) { - NadminReturn res = fRes.get(); - assertTrue(res.returnValue); - assertTrue(res.out.contains("progress-custom")); - List prgs = ProgressMessage.grepProgressMessages(res.out); - assertFalse(prgs.isEmpty()); - assertTrue(prgs.get(0).getValue() > 0); - assertEquals(100, prgs.get(prgs.size() - 1).getValue()); - } - } - - private String parseJobIdFromEchoTerse(String str) { - StringTokenizer stok = new StringTokenizer(str, "\n\r"); - assertTrue(stok.hasMoreTokens()); - stok.nextToken(); - //Id is second non empty line - assertTrue(stok.hasMoreTokens()); - String result = stok.nextToken().trim(); - assertFalse(result.isEmpty()); - assertFalse(result.contains(" ")); //With space does not look like ID but like some error message - return result; - } - - static class NadminCallable implements Callable { - - private final String[] args; - - public NadminCallable(String... args) { - this.args = args; - } - - @Override - public NadminReturn call() throws Exception { - throw new UnsupportedOperationException("Not supported yet."); - } - - - - } - -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/JobManagerTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/JobManagerTest.java deleted file mode 100644 index b6d16b678df..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/JobManagerTest.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.progress; - -import java.io.File; -import java.lang.InterruptedException; -import java.lang.Thread; - -import static org.glassfish.tests.utils.NucleusTestUtils.*; -import org.glassfish.tests.utils.NucleusTestUtils; -import static org.testng.AssertJUnit.assertTrue; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -/** - * This tests the functionality of JobManager, list-jobs - * @author Bhakti Mehta - */ -@Test(testName="JobManagerTest", enabled=true) -public class JobManagerTest { - private static File nucleusRoot = NucleusTestUtils.getNucleusRoot(); - - private final String COMMAND1 = "progress-simple"; - - @BeforeTest - public void setUp() throws Exception { - nadmin("stop-domain"); - //delete jobs.xml incase there were other jobs run - deleteJobsFile(); - //osgi-cache workaround - File osgiCacheDir = new File(nucleusRoot, "domains"+File.separator+"domain1"+File.separator+"osgi-cache"); - deleteDirectoryContents(osgiCacheDir); - nadmin("start-domain"); - - - } - - @AfterTest - public void cleanUp() throws Exception { - nadmin("stop-domain"); - nadmin("start-domain"); - - } - - @Test(enabled=true) - public void noJobsTest() { - nadmin("stop-domain"); - //delete jobs.xml incase there were other jobs run - deleteJobsFile(); - nadmin("start-domain"); - String result = null; - result = nadminWithOutput("list-jobs").outAndErr; - assertTrue(matchString("Nothing to list", result)); - - - } - - @Test(dependsOnMethods = { "noJobsTest" },enabled=true) - public void runJobTest() { - String result = null; - - NadminReturn result1 = nadminWithOutput("--terse", "progress-simple"); - assertTrue(result1.returnValue); - //check list-jobs - result = nadminWithOutput("list-jobs").out; - assertTrue( result.contains(COMMAND1) && result.contains("COMPLETED")); - //check list-jobs with id 1 - result = nadminWithOutput("list-jobs","1").out; - assertTrue( result.contains(COMMAND1) && result.contains("COMPLETED")); - //shutdown server - assertTrue( nadmin("stop-domain")); - //restart - assertTrue( nadmin("start-domain")); - //check jobs - result = nadminWithOutput("list-jobs","1").out; - assertTrue( result.contains(COMMAND1) && result.contains("COMPLETED")); - nadmin("start-domain"); - - } - - @Test(dependsOnMethods = { "runJobTest" }, enabled=true) - public void runDetachTest() { - String result = null; - //shutdown server - assertTrue( nadmin("stop-domain")); - - //delete the jobs file - deleteJobsFile(); - - //restart - assertTrue( nadmin("start-domain")); - result = nadminDetachWithOutput( COMMAND1).out; - //Detached job id is returned - assertTrue( result.contains("Job ID: ")); - - //list-jobs - result = nadminWithOutput("list-jobs","1").out; - assertTrue( result.contains(COMMAND1) ); - //attach to the job - assertTrue(nadmin("attach", "1")); - - //list-jobs and it should be purged since the user - //starting is the same as the user who attached to it - result = nadminWithOutput("list-jobs").outAndErr; - assertTrue(matchString("Nothing to list", result)); - - //delete the jobs file - deleteJobsFile(); - - - - } - - @Test(dependsOnMethods = { "runDetachTest" }, enabled=false) - public void runConfigureManagedJobsTest() throws InterruptedException { - try { - String result = null; - //shutdown server - assertTrue( nadmin("stop-domain")); - - //delete the jobs file - deleteJobsFile(); - - //restart - assertTrue( nadmin("start-domain")); - //configure-managed-jobs - assertTrue( nadmin("configure-managed-jobs","--job-retention-period=6s","--cleanup-initial-delay=2s", - "--cleanup-poll-interval=2s")); - assertTrue(COMMAND1, nadmin(COMMAND1)); - - - //list-jobs - result = nadminWithOutput("list-jobs","1").out; - assertTrue( result.contains(COMMAND1) ); - //shutdown server - assertTrue( nadmin("stop-domain")); - - //start server - assertTrue( nadmin("start-domain")); - Thread.sleep(5000L); - - //list-jobs there should be none since the configure-managed-jobs command will purge it - result = nadminWithOutput("list-jobs").outAndErr; - assertTrue(matchString("Nothing to list", result)); - - } finally { - //reset configure-managed-jobs - assertTrue( nadmin("configure-managed-jobs","--job-retention-period=24h","--cleanup-initial-delay=20m", - "--cleanup-poll-interval=20m")); - } - //delete the jobs file - deleteJobsFile(); - - - - } - - /** - * This will delete the jobs.xml file - */ - public static void deleteJobsFile() { - File configDir = new File(nucleusRoot,"domains/domain1/config"); - File jobsFile = new File (configDir,"jobs.xml"); - System.out.println("Deleting.. " + jobsFile); - if (jobsFile!= null && jobsFile.exists()) { - jobsFile.delete(); - } - } - - -} - diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusBasicTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusBasicTest.java deleted file mode 100644 index 93ab234d07d..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusBasicTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.progress; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import static org.glassfish.tests.utils.NucleusTestUtils.*; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -/** - * - * @author martinmares - */ -@Test(testName="ProgressStatusBasicTest") -public class ProgressStatusBasicTest { - - public void simple() { - NadminReturn result = nadminWithOutput("progress-simple"); - assertTrue(result.returnValue); - List prgs = ProgressMessage.grepProgressMessages(result.out); - assertEquals(12, prgs.size()); - for (int i = 0; i < 11; i++) { - assertEquals(10 * i, prgs.get(i + 1).getValue()); - assertTrue(prgs.get(i + 1).isPercentage()); - } - assertTrue(ProgressMessage.isNonDecreasing(prgs)); - } - - public void simpleNoTotal() { - NadminReturn result = nadminWithOutput("progress-simple", "--nototalsteps"); - assertTrue(result.returnValue); - List prgs = ProgressMessage.grepProgressMessages(result.out); - boolean nonPercentageExists = false; - for (ProgressMessage prg : prgs) { - if (prg.getValue() != 0 && prg.getValue() != 100) { - assertFalse(prg.isPercentage()); - nonPercentageExists = true; - } - } - assertTrue(nonPercentageExists); - assertTrue(ProgressMessage.isNonDecreasing(prgs)); - } - - public void simpleSpecInAnnotation() { - NadminReturn result = nadminWithOutput("progress-full-annotated"); - assertTrue(result.returnValue); - List prgs = ProgressMessage.grepProgressMessages(result.out); - assertEquals(12, prgs.size()); - for (int i = 0; i < 11; i++) { - assertEquals(10 * i, prgs.get(i + 1).getValue()); - assertTrue(prgs.get(i + 1).isPercentage()); - } - assertTrue(ProgressMessage.isNonDecreasing(prgs)); - assertEquals("annotated:", prgs.get(5).getScope()); - } - - public void simpleTerse() { - NadminReturn result = nadminWithOutput("--terse", "progress-simple"); - assertTrue(result.returnValue); - List prgs = ProgressMessage.grepProgressMessages(result.out); - assertTrue(prgs.isEmpty()); - } - -// public void commandWithPayloud() throws IOException { -// File tmp = File.createTempFile(String.valueOf(System.currentTimeMillis()) + "ms_", "test"); -// FileWriter writer = null; -// try { -// writer = new FileWriter(tmp); -// writer.write("This is testing file for nucleus admin tests.\n"); -// writer.write("Created - " + System.currentTimeMillis() + "\n"); -// writer.close(); -// NadminReturn result = nadminWithOutput("progress-payload", tmp.getCanonicalPath()); -// assertTrue(result.returnValue); -// List prgs = ProgressMessage.grepProgressMessages(result.out); -// assertTrue(prgs.size() > 0); -// } finally { -// try {tmp.delete();} catch (Exception ex) {} -// } -// } - -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusSpecialTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusSpecialTest.java deleted file mode 100644 index 5d4063d7e74..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/progress/ProgressStatusSpecialTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.progress; - -import java.util.Iterator; -import java.util.List; -import static org.glassfish.tests.utils.NucleusTestUtils.*; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -/** - * - * @author martinmares - */ -@Test(testName="ProgressStatusSpecialTest") -public class ProgressStatusSpecialTest { - - public void stepBackCommand() { - NadminReturn result = nadminWithOutput("progress-step-back"); - assertTrue(result.returnValue); - List prgs = ProgressMessage.grepProgressMessages(result.out); - assertFalse(ProgressMessage.isNonDecreasing(prgs)); - Iterator itr = prgs.iterator(); - while (itr.hasNext()) { - ProgressMessage prg = itr.next(); - if (prg.getValue() >= 80) { - break; - } - } - assertTrue(itr.hasNext()); //Exist more record - while (itr.hasNext()) { - ProgressMessage prg = itr.next(); - assertTrue(prg.getValue() <= 80); - if (prg.getValue() < 80) { - break; - } - } - assertTrue(itr.hasNext()); //Exist more record - ProgressMessage prg = itr.next(); - assertTrue(prg.getValue() < 80); - } - - public void doubleTotalCommand() { - NadminReturn result = nadminWithOutput("progress-double-totals"); - assertTrue(result.returnValue); - List prgs = ProgressMessage.grepProgressMessages(result.out); - assertFalse(ProgressMessage.isNonDecreasing(prgs)); - } - -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ApplicationTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ApplicationTest.java deleted file mode 100644 index 508d1229625..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ApplicationTest.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import jakarta.ws.rs.core.Response; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; -/** - * - * @author jasonlee - */ -public class ApplicationTest extends RestTestBase { - public static final String BASE_JDBC_RESOURCE_URL = "/domain/resources/jdbc-resource"; - public static final String URL_APPLICATION_DEPLOY = "/domain/applications/application"; - public static final String URL_CODI_SAMPLE = "http://java.net/jira/secure/attachment/44850/GlassfishIssues.war"; - public static final String URL_CREATE_INSTANCE = "/domain/create-instance"; - - @Test(enabled=false) - public void testApplicationDeployment() throws URISyntaxException { - final String appName = "testApp" + generateRandomString(); - - try { - Map deployedApp = deployApp(getFile("test.war"), appName, appName); - assertEquals(appName, deployedApp.get("name")); - - assertEquals("/" + appName, deployedApp.get("contextRoot")); - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - undeployApp(appName); - } - } - -// @Test(enabled=false) - public void deployCodiApp() throws URISyntaxException, MalformedURLException, IOException { - try { - final String appName = "testApp" + generateRandomString(); - - Map params = new HashMap(); - params.put("name", "CloudBeesDS"); - params.put("poolName", "DerbyPool"); - - Response response = post (BASE_JDBC_RESOURCE_URL, params); - assertTrue(isSuccess(response)); - - Map deployedApp = deployApp(downloadFile(new URL(URL_CODI_SAMPLE)), appName, appName); - assertEquals(appName, deployedApp.get("name")); - - assertEquals("/" + appName, deployedApp.get("contextRoot")); - - undeployApp(appName); - } finally { - delete(BASE_JDBC_RESOURCE_URL + "/CloudBeesDS"); - } - } - - @Test(enabled=false) - public void testApplicationDisableEnable() throws URISyntaxException { - final String appName = "testApp" + generateRandomString(); - - Map deployedApp = deployApp(getFile("test.war"), appName, appName); - assertEquals(appName, deployedApp.get("name")); - - assertEquals("/" + appName, deployedApp.get("contextRoot")); - - try { - String appUrl = "http://localhost:" + instancePort + "/" + appName; - Response response = get(appUrl); - assertEquals ("Test", response.readEntity(String.class).trim()); - - response = post(URL_APPLICATION_DEPLOY + "/" + appName + "/disable"); - checkStatusForSuccess(response); - - response = get(appUrl); - assertFalse("Response was " + response.getStatus(), isSuccess(response)); - - response = post(URL_APPLICATION_DEPLOY + "/" + appName + "/enable"); - checkStatusForSuccess(response); - - response = get(appUrl); - assertEquals ("Test", response.readEntity(String.class).trim()); - } finally { - undeployApp(appName); - } - } - - @Test(enabled=false) - public void listSubComponents() throws URISyntaxException { - final String appName = "testApp" + generateRandomString(); - - try { - deployApp(getFile("stateless-simple.ear"), appName, appName); - Response response = get(URL_APPLICATION_DEPLOY +"/" + appName + "/list-sub-components?id=" + appName); - checkStatusForSuccess(response); - String subComponents = response.readEntity(String.class); - assertTrue(subComponents.contains("stateless-simple.war")); - - response = get(URL_APPLICATION_DEPLOY +"/" + appName + "/list-sub-components?id=stateless-simple.war&appname=" + appName); - checkStatusForSuccess(response); - subComponents = response.readEntity(String.class); - assertTrue(subComponents.contains("GreeterServlet")); - } finally { - undeployApp(appName); - } - } - - @Test(enabled=false) - public void testCreatingAndDeletingApplicationRefs() throws URISyntaxException { - final String instanceName = "instance_" + generateRandomString(); - final String appName = "testApp" + generateRandomString(); - final String appRefUrl = "/domain/servers/server/" + instanceName + "/application-ref"; - - Map newInstance = new HashMap() {{ - put("id", instanceName); - put("node", "localhost-domain1"); - }}; - Map applicationRef = new HashMap() {{ - put("id", appName); - put("target", instanceName); - }}; - - try { - Response response = post(URL_CREATE_INSTANCE, newInstance); - checkStatusForSuccess(response); - - deployApp(getFile("test.war"), appName, appName); - - response = post (appRefUrl, applicationRef); - checkStatusForSuccess(response); - - response = get(appRefUrl + "/" + appName); - checkStatusForSuccess(response); - - response = delete(appRefUrl + "/" + appName, new HashMap() {{ put("target", instanceName); }}); - checkStatusForSuccess(response); - } finally { - Response response = delete("/domain/servers/server/" + instanceName + "/delete-instance"); - checkStatusForSuccess(response); - response = get("/domain/servers/server/" + instanceName); - assertFalse(isSuccess(response)); - undeployApp(appName); - } - } - - @Test(enabled=false) - public void testGetContextRoot() throws URISyntaxException { - final String appName = "testApp" + generateRandomString(); - - try { - Map deployedApp = deployApp(getFile("stateless-simple.ear"), appName, appName); - assertEquals(appName, deployedApp.get("name")); - Map contextRootPayload = new HashMap() {{ - put("appname", appName); - put("modulename", "stateless-simple.war"); - }}; - - Response response = get("/domain/applications/application/" +appName + "/get-context-root", contextRootPayload); - checkStatusForSuccess(response); - assertTrue(response.readEntity(String.class).contains("helloworld")); - } finally { - undeployApp(appName); - } - } - -// @Test(enabled=false) - public void testUndeploySubActionWarnings() throws URISyntaxException { - final String appName = "testApp" + generateRandomString(); - final String serverName = "in" + generateRandomNumber(); - try { - Response response = post ("/domain/create-instance", new HashMap() {{ - put("id", serverName); - put("node", "localhost-domain1"); - }}); - checkStatusForSuccess(response); - - response = post("/domain/servers/server/" + serverName + "/start-instance"); - checkStatusForSuccess(response); - - deployApp(getFile("test.war"), appName, appName); - addAppRef(appName, serverName); - - response = post("/domain/servers/server/" + serverName + "/stop-instance"); - checkStatusForSuccess(response); - - response = delete ("/domain/applications/application/"+appName, new HashMap() {{ - put("target", "domain"); - }}); - assertTrue(response.readEntity(String.class).contains("WARNING: Instance " + serverName + " seems to be offline")); - } finally { - delete ("/domain/applications/application/" + appName, new HashMap() {{ - put("target", "domain"); - }}); - } - } - - protected File getFile(String fileName) throws URISyntaxException { - final URL resource = getClass().getResource("/" + fileName); - return new File(resource.toURI()); - } - - protected File downloadFile(URL url) throws IOException { - String urlText = url.getFile(); - String fileName = urlText.substring(urlText.lastIndexOf("/")+1); - File file = new File(fileName); - file.deleteOnExit(); - BufferedInputStream in = new BufferedInputStream(url.openStream()); - FileOutputStream fos = new FileOutputStream(file); - BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); - byte data[] = new byte[8192]; - int read = in.read(data, 0, 8192); - while (read >= 0) { - bout.write(data, 0, read); - data = new byte[8192]; - read = in.read(data, 0, 8192); - } - bout.close(); - in.close(); - - return file; - } - - public Map deployApp (final String fileName, final String contextRoot, final String name) throws URISyntaxException { - return deployApp(getFile(fileName), contextRoot, name); - } - - public Map deployApp (final File archive, final String contextRoot, final String name) { - Map app = new HashMap() {{ - put("id", archive); - put("contextroot", contextRoot); - put("name", name); - }}; - - Response response = postWithUpload(URL_APPLICATION_DEPLOY, app); - checkStatusForSuccess(response); - - return getEntityValues(get(URL_APPLICATION_DEPLOY + "/" + app.get("name"))); - } - - public void addAppRef(final String applicationName, final String targetName){ - Response cr = post("/domain/servers/server/" + targetName + "/application-ref", new HashMap() {{ - put("id", applicationName); - put("target", targetName); - }}); - checkStatusForSuccess(cr); - } - - public Response undeployApp(String appName) { - Response response = delete(URL_APPLICATION_DEPLOY + "/" + appName); - checkStatusForSuccess(response); - - return response; - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/AuthRealmTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/AuthRealmTest.java deleted file mode 100644 index 47d11bf945c..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/AuthRealmTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import jakarta.ws.rs.core.Response; -import org.glassfish.admin.rest.client.utils.MarshallingUtils; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -public class AuthRealmTest extends RestTestBase { - public static final String URL_LIST_GROUP_NAMES = "/domain/configs/config/server-config/security-service/auth-realm/admin-realm/list-group-names"; - public static final String URL_SUPPORTS_USER_MANAGEMENT = "/domain/configs/config/server-config/security-service/auth-realm/admin-realm/supports-user-management"; - public static final String URL_LIST_ADMIN_REALM_USERS = "/domain/configs/config/server-config/security-service/auth-realm/admin-realm/list-users"; - public static final String URL_LIST_FILE_USERS = "/domain/configs/config/server-config/security-service/auth-realm/file/list-users"; - public static final String URL_CREATE_USER = "/domain/configs/config/server-config/security-service/auth-realm/file/create-user"; - public static final String URL_DELETE_USER = "/domain/configs/config/server-config/security-service/auth-realm/file/delete-user"; - public static final String URL_AUTH_REALM_CLASS_NAMES = "/domain/list-predefined-authrealm-classnames"; - - // Disable this test for now... -// @Test - public void testListGroupNames() { - Response response = get(URL_LIST_GROUP_NAMES, new HashMap() {{ - put("userName", "admin"); - put("realmName", "admin-realm"); - }}); - checkStatusForSuccess(response); - final String entity = response.readEntity(String.class); - Map responseMap = MarshallingUtils.buildMapFromDocument(entity); - Map extraProperties = (Map)responseMap.get("extraProperties"); - List groups = (List)extraProperties.get("groups"); - - assertTrue(groups.size() > 0); - } - - @Test - public void testSupportsUserManagement() { - List groups = getCommandResults(get(URL_SUPPORTS_USER_MANAGEMENT)); - assertEquals("true", groups.get(0)); - } - -// @Test - public void testUserManagement() { - final String userName = "user" + generateRandomString(); - Map newUser = new HashMap() {{ - put ("id", userName); - put ("AS_ADMIN_USERPASSWORD", "password"); - }}; - - Response response = post(URL_CREATE_USER, newUser); - assertTrue(isSuccess(response)); - - List values = getCommandResults(get(URL_LIST_FILE_USERS)); - assertTrue(values.contains(userName)); - - response = delete(URL_DELETE_USER, newUser); - assertTrue(isSuccess(response)); - - values = getCommandResults(get(URL_LIST_FILE_USERS)); - assertFalse(values.contains(userName)); - } - - @Test - public void testListAuthRealmClassNames() { - List classNameList = getCommandResults(get(URL_AUTH_REALM_CLASS_NAMES)); - assertTrue(!classNameList.isEmpty()); - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ClusterTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ClusterTest.java deleted file mode 100644 index 7fef09156e2..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ClusterTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import jakarta.ws.rs.core.Response; -import org.glassfish.admin.rest.client.utils.MarshallingUtils; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -/** - * - * @author jasonlee - */ -public class ClusterTest extends RestTestBase { - public static final String URL_CLUSTER = "/domain/clusters/cluster"; - - @Test - public void testClusterCreationAndDeletion() { - final String clusterName = "cluster_" + generateRandomString(); - createCluster(clusterName); - - Map entity = getEntityValues(get(URL_CLUSTER + "/" + clusterName)); - assertEquals(clusterName + "-config", entity.get("configRef")); - - deleteCluster(clusterName); - } - - @Test - public void testListLifecycleModules() { - final String clusterName = "cluster_" + generateRandomString(); - Map newCluster = new HashMap() { - { - put("id", clusterName); - } - }; - - Response response = post(URL_CLUSTER, newCluster); - checkStatusForSuccess(response); - - response = get(URL_CLUSTER + "/" + clusterName + "/list-lifecycle-modules"); - checkStatusForSuccess(response); - - response = delete(URL_CLUSTER + "/" + clusterName); // + "/delete-cluster"); - checkStatusForSuccess(response); - - response = get(URL_CLUSTER + "/" + clusterName); - checkStatusForFailure(response); - - } - - public String createCluster() { - final String clusterName = "cluster_" + generateRandomString(); - createCluster(clusterName); - - return clusterName; - } - - public void createCluster(final String clusterName) { - Map newCluster = new HashMap() { - { - put("id", clusterName); - } - }; - - Response response = post(URL_CLUSTER, newCluster); - checkStatusForSuccess(response); - } - - public void startCluster(String clusterName) { - Response response = post(URL_CLUSTER + "/" + clusterName + "/start-cluster"); - checkStatusForSuccess(response); - } - - public void stopCluster(String clusterName) { - Response response = post(URL_CLUSTER + "/" + clusterName + "/stop-cluster"); - checkStatusForSuccess(response); - } - - public void createClusterInstance(final String clusterName, final String instanceName) { - Response response = post("/domain/create-instance", new HashMap() { - { - put("cluster", clusterName); - put("id", instanceName); - put("node", "localhost-domain1"); - } - }); - checkStatusForSuccess(response); - } - - public void deleteCluster(String clusterName) { - Response response = get(URL_CLUSTER + "/" + clusterName + "/list-instances"); - Map body = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); - Map extraProperties = (Map) body.get("extraProperties"); - if (extraProperties != null) { - List> instanceList = (List>) extraProperties.get("instanceList"); - if ((instanceList != null) && (!instanceList.isEmpty())) { - for (Map instance : instanceList) { - String status = instance.get("status"); - String instanceName = instance.get("name"); - if (!"NOT_RUNNING".equalsIgnoreCase(status)) { - response = post("/domain/servers/server/" + instanceName + "/stop-instance"); - checkStatusForSuccess(response); - } - response = delete("/domain/servers/server/" + instanceName + "/delete-instance"); - checkStatusForSuccess(response); - } - } - } - - - response = delete(URL_CLUSTER + "/" + clusterName);// + "/delete-cluster"); - checkStatusForSuccess(response); - -// response = get(URL_CLUSTER + "/" + clusterName); -// checkStatusForFailure(response); - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ElementStarTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ElementStarTest.java deleted file mode 100644 index b5bd9bcea97..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ElementStarTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; -import jakarta.ws.rs.core.Response; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -/** - * This class tests the changes to the handling of @Element("*") instances - * @author jasonlee - */ -public class ElementStarTest extends RestTestBase { - protected static final String URL_CREATE_INSTANCE = "/domain/create-instance"; - - protected String instanceName1; - protected String instanceName2; - - @BeforeMethod - public void before() { - instanceName1 = "instance_" + generateRandomString(); - instanceName2 = "instance_" + generateRandomString(); - - Response response = post(URL_CREATE_INSTANCE, new HashMap() {{ put("id", instanceName1); put("node", "localhost-domain1"); }}); - checkStatusForSuccess(response); - response = post(URL_CREATE_INSTANCE, new HashMap() {{ put("id", instanceName2); put("node", "localhost-domain1"); }}); - checkStatusForSuccess(response); - } - - @AfterMethod - public void after() { - Response response = delete("/domain/servers/server/" + instanceName1 + "/delete-instance"); // TODO: This url should be fixed - checkStatusForSuccess(response); - response = delete("/domain/servers/server/" + instanceName2 + "/delete-instance"); - checkStatusForSuccess(response); - } - - @Test(enabled=false) - public void testApplications() throws URISyntaxException { - ApplicationTest at = getTestClass(ApplicationTest.class); - final String app1 = "app" + generateRandomString(); - final String app2 = "app" + generateRandomString(); - - at.deployApp("test.war", app1, app1); - at.deployApp("test.war", app2, app2); - at.addAppRef(app1, instanceName1); - at.addAppRef(app2, instanceName1); - - Response response = get("/domain/servers/server/"+instanceName1+"/application-ref"); - Map children = this.getChildResources(response); - assertEquals(2, children.size()); - } - - @Test - public void testResources() { - // The DAS should already have two resource-refs (jdbc/__TimerPool and jdbc/__default) - Response response = get ("/domain/servers/server/server/resource-ref"); - Map children = this.getChildResources(response); - assertTrue(children.size() >= 2); - } - - @Test(enabled=false) - public void testLoadBalancerConfigs() { - final String lbName = "lbconfig-" + generateRandomString(); - Response response = post ("/domain/lb-configs/lb-config/", - new HashMap() {{ - put("id", lbName); - put("target", instanceName1); - }}); - checkStatusForSuccess(response); - - response = post("/domain/lb-configs/lb-config/" + lbName + "/create-http-lb-ref", - new HashMap() {{ - put ("id", instanceName2); - }}); - checkStatusForSuccess(response); - - response = get ("/domain/lb-configs/lb-config/" + lbName + "/server-ref"); - Map children = this.getChildResources(response); - assertTrue(!children.isEmpty()); - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ExternalResourceTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ExternalResourceTest.java deleted file mode 100644 index 7f93ef2bbd7..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ExternalResourceTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.util.HashMap; -import java.util.Map; -import jakarta.ws.rs.core.Response; -import org.testng.annotations.Test; - -/** - * - * @author jasonlee - */ -public class ExternalResourceTest extends RestTestBase { - protected static final String URL_EXTERNAL_RESOURCE = "/domain/resources/external-jndi-resource"; - @Test(enabled=false) - public void createAndDeleteExternalResource() { - final String resourceName = "resource_" + generateRandomString(); - final String jndiName = "jndi/"+resourceName; - Map newResource = new HashMap() {{ - put("id", resourceName); - put("jndilookupname", jndiName); - put("factoryClass", "org.glassfish.resources.custom.factory.PrimitivesAndStringFactory"); - put("restype", "java.lang.Double"); - }}; - Response response = post (URL_EXTERNAL_RESOURCE, newResource); - checkStatusForSuccess(response); - - response = get(URL_EXTERNAL_RESOURCE + "/" + resourceName); - checkStatusForSuccess(response); - - response = delete(URL_EXTERNAL_RESOURCE + "/" + resourceName); - checkStatusForSuccess(response); - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JdbcTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JdbcTest.java deleted file mode 100644 index 188c9a94545..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JdbcTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import jakarta.ws.rs.core.Response; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -/** - * - * @author jasonlee - */ -public class JdbcTest extends RestTestBase { - public static final String BASE_JDBC_RESOURCE_URL = "/domain/resources/jdbc-resource"; - public static final String BASE_JDBC_CONNECTION_POOL_URL = "/domain/resources/jdbc-connection-pool"; - - @Test(enabled=false) - public void testReadingPoolEntity() { - Map entity = getEntityValues(get(BASE_JDBC_CONNECTION_POOL_URL + "/__TimerPool")); - assertEquals("__TimerPool", entity.get("name")); - } - - @Test(enabled=false) - public void testCreateAndDeletePool() { - String poolName = "TestPool" + generateRandomString(); - Map params = new HashMap(); - params.put("name", poolName); - params.put("datasourceClassname","org.apache.derby.jdbc.ClientDataSource"); - Response response = post(BASE_JDBC_CONNECTION_POOL_URL, params); - assertTrue(isSuccess(response)); - - Map entity = getEntityValues(get(BASE_JDBC_CONNECTION_POOL_URL + "/"+poolName)); - assertNotSame(0, entity.size()); - - response = delete(BASE_JDBC_CONNECTION_POOL_URL+"/"+poolName, new HashMap()); - assertTrue(isSuccess(response)); - - response = get(BASE_JDBC_CONNECTION_POOL_URL + "/" + poolName); - assertEquals(404, response.getStatus()); - } - -// @Test(enabled=false) - // TODO: Disabled until 13348 is resolved - public void testCreateResourceWithBackslash() { - String poolName = "TestPool\\" + generateRandomString(); - String encodedPoolName = poolName; - try { - encodedPoolName = URLEncoder.encode(poolName, "UTF-8"); - } catch (UnsupportedEncodingException ex) { - Logger.getLogger(JdbcTest.class.getName()).log(Level.SEVERE, null, ex); - } - Map params = new HashMap(); - params.put("name", poolName); - params.put("poolName", "DerbyPool"); - - Response response = post (BASE_JDBC_RESOURCE_URL, params); - assertTrue(isSuccess(response)); - - Map entity = getEntityValues(get(BASE_JDBC_CONNECTION_POOL_URL + "/" + encodedPoolName)); - assertNotSame(0, entity.size()); - - response = delete("/" + encodedPoolName, new HashMap()); - assertTrue(isSuccess(response)); - - response = get(BASE_JDBC_CONNECTION_POOL_URL + "/" + encodedPoolName); - assertEquals(404, response.getStatus()); - } - - @Test(enabled=false) - public void createDuplicateResource() { - final String resourceName = "jdbc/__default"; - Map params = new HashMap() {{ - put("id", resourceName); - put("poolName", "DerbyPool"); - }}; - - Response response = post (BASE_JDBC_RESOURCE_URL, params); - assertFalse(isSuccess(response)); - } - - @Test(enabled=false) - public void createDuplicateConnectionPool() { - final String poolName = "DerbyPool"; - Map params = new HashMap() {{ - put("id", poolName); - put("datasourceClassname", "org.apache.derby.jdbc.ClientDataSource"); - }}; - - Response response = post (BASE_JDBC_CONNECTION_POOL_URL, params); - assertFalse(isSuccess(response)); - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JmsTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JmsTest.java deleted file mode 100644 index 0712cbca719..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JmsTest.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (c) 2010, 2020 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.Map; -import jakarta.ws.rs.core.Response; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -/** - * Created by IntelliJ IDEA. - * User: jasonlee - * Date: May 26, 2010 - * Time: 2:28:27 PM - * To change this template use File | Settings | File Templates. - */ -public class JmsTest extends RestTestBase { - static final String URL_ADMIN_OBJECT_RESOURCE = "/domain/resources/admin-object-resource"; - static final String URL_CONNECTOR_CONNECTION_POOL = "/domain/resources/connector-connection-pool"; - static final String URL_CONNECTOR_RESOURCE = "/domain/resources/connector-resource"; - static final String URL_JMS_HOST = "/domain/configs/config/server-config/jms-service/jms-host"; - static final String URL_SEVER_JMS_DEST = "/domain/servers/server/server"; - static final String DEST_TYPE = "topic"; - - @Test(enabled=false) - public void testJmsConnectionFactories() { - final String poolName = "JmsConnectionFactory" + generateRandomString(); - Map ccp_attrs = new HashMap() { - { - put("name", poolName); - put("connectiondefinition", "jakarta.jms.ConnectionFactory"); - put("raname", "jmsra"); - } - }; - Map cr_attrs = new HashMap() { - { - put("id", poolName); - put("poolname", poolName); - } - }; - - // Create connection pool - Response response = post(URL_CONNECTOR_CONNECTION_POOL, ccp_attrs); - checkStatusForSuccess(response); - - // Check connection pool creation - Map pool = getEntityValues(get(URL_CONNECTOR_CONNECTION_POOL + "/" + poolName)); - assertFalse(pool.isEmpty()); - - // Create connector resource - response = post(URL_CONNECTOR_RESOURCE, cr_attrs); - checkStatusForSuccess(response); - - // Check connector resource - Map resource = getEntityValues(get(URL_CONNECTOR_RESOURCE + "/" + poolName)); - assertFalse(resource.isEmpty()); - - // Edit and check ccp - response = post(URL_CONNECTOR_CONNECTION_POOL + "/" + poolName, new HashMap() { - { - put("description", poolName); - } - }); - checkStatusForSuccess(response); - - pool = getEntityValues(get(URL_CONNECTOR_CONNECTION_POOL + "/" + poolName)); - assertTrue(pool.get("description").equals(poolName)); - - // Edit and check cr - response = post(URL_CONNECTOR_RESOURCE + "/" + poolName, new HashMap() { - { - put("description", poolName); - } - }); - checkStatusForSuccess(response); - - resource = getEntityValues(get(URL_CONNECTOR_RESOURCE + "/" + poolName)); - assertTrue(pool.get("description").equals(poolName)); - - // Delete objects - response = delete(URL_CONNECTOR_CONNECTION_POOL + "/" + poolName, new HashMap() { - { - put("cascade", "true"); - } - }); - checkStatusForSuccess(response); - } - - @Test(enabled=false) - public void testJmsDestinationResources() { - final String jndiName = "jndi/" + generateRandomString(); - String encodedJndiName = jndiName; - try { - encodedJndiName = URLEncoder.encode(jndiName, "UTF-8"); - } catch (UnsupportedEncodingException e) { - } - - Map attrs = new HashMap() { - { - put("id", jndiName); - put("raname", "jmsra"); - put("restype", "jakarta.jms.Topic"); - } - }; - - Response response = post(URL_ADMIN_OBJECT_RESOURCE, attrs); - checkStatusForSuccess(response); - - Map entity = getEntityValues(get(URL_ADMIN_OBJECT_RESOURCE + "/" + encodedJndiName)); - assertFalse(entity.isEmpty()); - - response = delete(URL_ADMIN_OBJECT_RESOURCE + "/" + encodedJndiName); - checkStatusForSuccess(response); - } - - @Test(enabled=false) - public void testJmsPhysicalDestination() { - final String destName = "jmsDest" + generateRandomString(); - final int maxNumMsgs = generateRandomNumber(500); - final int consumerFlowLimit = generateRandomNumber(500); - - createJmsPhysicalDestination(destName, DEST_TYPE, URL_SEVER_JMS_DEST); - - final HashMap newDest = new HashMap() { - { - put("id", destName); - put("desttype", DEST_TYPE); - } - }; - Map destProps = new HashMap() { - { - putAll(newDest); - put("property", "MaxNumMsgs=" + maxNumMsgs + ":ConsumerFlowLimit=" + consumerFlowLimit); - } - }; - - Response response = get(URL_SEVER_JMS_DEST + "/__get-jmsdest", newDest); - checkStatusForSuccess(response); - - response = post(URL_SEVER_JMS_DEST + "/__update-jmsdest", destProps); - checkStatusForSuccess(response); - response = get(URL_SEVER_JMS_DEST + "/__get-jmsdest", newDest); - checkStatusForSuccess(response); - Map entity = this.getEntityValues(response); - assertEquals(maxNumMsgs, entity.get("MaxNumMsgs")); - assertEquals(consumerFlowLimit, entity.get("ConsumerFlowLimit")); - - deleteJmsPhysicalDestination(destName, URL_SEVER_JMS_DEST); - } - - @Test(enabled=false) - public void testJmsPhysicalDestionationsWithClusters() { - final String destName = "jmsDest" + generateRandomString(); - ClusterTest ct = getTestClass(ClusterTest.class); - final String clusterName = ct.createCluster(); - ct.createClusterInstance(clusterName, "in1_"+clusterName); - ct.startCluster(clusterName); - final String endpoint = "/domain/clusters/cluster/" + clusterName; - try { - - createJmsPhysicalDestination(destName, "topic", endpoint); - final HashMap newDest = new HashMap() { - { - put("id", destName); - put("desttype", DEST_TYPE); - } - }; - - Response response = get(endpoint + "/__get-jmsdest", newDest); - checkStatusForSuccess(response); - - response = get(URL_SEVER_JMS_DEST + "/__get-jmsdest", newDest); - checkStatusForFailure(response); - } - finally { - deleteJmsPhysicalDestination(destName, endpoint); - ct.stopCluster(clusterName); - ct.deleteCluster(clusterName); - } - } - - @Test(enabled=false) - public void testJmsPing() { - String results = get(URL_SEVER_JMS_DEST + "/jms-ping").readEntity(String.class); - assertTrue(results.contains("JMS-ping command executed successfully")); - } - - @Test(enabled=false) - public void testJmsFlush() { - Map payload = new HashMap() { - { - put("id", "mq.sys.dmq"); - put("destType", "queue"); - } - }; - - Response response = post(URL_SEVER_JMS_DEST + "/flush-jmsdest", payload); - checkStatusForSuccess(response); - } - - @Test(enabled=false) - public void testJmsHosts() { - final String jmsHostName = "jmshost" + generateRandomString(); - Map newHost = new HashMap() { - { - put("id", jmsHostName); - put("adminPassword", "admin"); - put("port", "7676"); - put("adminUserName", "admin"); - put("host", "localhost"); - } - }; - - // Test create - Response response = post(URL_JMS_HOST, newHost); - checkStatusForSuccess(response); - - // Test edit - Map entity = getEntityValues(get(URL_JMS_HOST + "/" + jmsHostName)); - assertFalse(entity.isEmpty()); - assertEquals(jmsHostName, entity.get("name")); - entity.put("port", "8686"); - response = post(URL_JMS_HOST + "/" + jmsHostName, entity); - checkStatusForSuccess(response); - entity = getEntityValues(get(URL_JMS_HOST + "/" + jmsHostName)); - assertEquals("8686", entity.get("port")); - - // Test delete - response = delete(URL_JMS_HOST + "/" + jmsHostName); - checkStatusForSuccess(response); - } - - public void createJmsPhysicalDestination(final String destName, final String type, String endpoint) { - final Map newDest = new HashMap() { - { - put("id", destName); - put("desttype", type); - } - }; - - // Test Create - Response response = post(endpoint + "/create-jmsdest", newDest); - // This command returns 200 instead of 201, for some reason. Odd. - checkStatusForSuccess(response); - } - - public void deleteJmsPhysicalDestination(final String destName, String endpoint) { - final HashMap newDest = new HashMap() { - { - put("id", destName); - put("desttype", DEST_TYPE); - } - }; - - // Test deletion - Response response = delete(endpoint + "/delete-jmsdest", newDest); // You POST to commands - checkStatusForSuccess(response); - - response = get(endpoint + "__get-jmsdest", newDest); - assertFalse(response.getStatus() == 200); - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JobsResourceTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JobsResourceTest.java deleted file mode 100644 index 249a2fea978..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JobsResourceTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.util.Locale; -import jakarta.ws.rs.core.Response; -import org.codehaus.jettison.json.JSONArray; -import org.codehaus.jettison.json.JSONException; -import org.codehaus.jettison.json.JSONObject; -import org.glassfish.admin.rest.Constants; -import org.glassfish.admin.rest.composite.CompositeUtil; -import org.glassfish.admin.rest.resources.composite.Job; -import static org.glassfish.tests.utils.NucleusTestUtils.nadminWithOutput; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -/** - * - * @author jdlee - */ -@Test(testName="JobsResourceTest") -public class JobsResourceTest extends RestTestBase { - public static final String URL_JOBS = "/jobs"; - - public void testJobsListing() { - assertTrue(isSuccess(get(URL_JOBS))); - } - - public void testGetJob() throws JSONException { - // make sure we have at least one job - issueDetachedCommand(); - - // verify getting the collection - Response response = get(URL_JOBS); - assertTrue(isSuccess(response)); - - // verify the overall structure - JSONObject json = response.readEntity(JSONObject.class); - JSONArray resources = json.getJSONArray("resources"); - assertNotNull(resources); - assertTrue(resources.length() > 0); - JSONArray items = json.getJSONArray("items"); - assertNotNull(items); - assertTrue(items.length() > 0); - - // unlike most resources that also return a parent link, - // the jobs resource only returns child links. - // verify the first of them - JSONObject resource = resources.getJSONObject(0); - String uri = resource.getString("uri"); - assertNotNull(uri); - assertEquals("job", resource.getString("rel")); - String jobId = resource.getString("title"); - assertNotNull(jobId); - assertTrue(uri.endsWith(URL_JOBS + "/id/" + jobId)); - - // verify the job it refers to by following the link. - // it should only have a parent link - response = get(uri); - assertTrue(isSuccess(response)); - json = response.readEntity(JSONObject.class); - JSONObject item = json.getJSONObject("item"); - verifyItem(jobId, item); - resources = json.getJSONArray("resources"); - assertNotNull(resources); - assertTrue(resources.length() == 1); - resource = resources.getJSONObject(0); - assertEquals("parent", resource.getString("rel")); - assertTrue(resource.getString("uri").endsWith(URL_JOBS)); - - // verify that the collection returned the item too - item = null; - for (int i = 0; item == null && i < items.length(); i++) { - JSONObject thisItem = items.getJSONObject(i); - if (jobId.equals(thisItem.getString("jobId"))) { - item = thisItem; - } - } - verifyItem(jobId, item); - } - - private void verifyItem(String jobIdWant, JSONObject itemHave) throws JSONException { - assertNotNull(itemHave); - Locale locale = null; - Job job = CompositeUtil.instance().unmarshallClass(locale, Job.class, itemHave); - assertNotNull(job); - assertEquals(jobIdWant, job.getJobId()); - } - - private void issueDetachedCommand() { - nadminWithOutput("--detach", "uptime"); - } - - @Override - protected String getResponseType() { - return Constants.MEDIA_TYPE_JSON; - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JvmOptionsTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JvmOptionsTest.java deleted file mode 100644 index 95fb0ae7fb1..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/JvmOptionsTest.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import jakarta.ws.rs.core.MultivaluedHashMap; -import jakarta.ws.rs.core.MultivaluedMap; -import jakarta.ws.rs.core.Response; -import org.glassfish.admin.rest.client.utils.MarshallingUtils; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -/** - * - * @author jasonlee - */ -public class JvmOptionsTest extends RestTestBase { - protected static final String URL_SERVER_JVM_OPTIONS = "/domain/configs/config/server-config/java-config/jvm-options"; - protected static final String URL_DEFAULT_JVM_OPTIONS = "/domain/configs/config/default-config/java-config/jvm-options"; - - protected static final String URL_SERVER_CONFIG_CREATE_PROFILER = "/domain/configs/config/server-config/java-config/create-profiler"; - protected static final String URL_SERVER_CONFIG_DELETE_PROFILER = "/domain/configs/config/server-config/java-config/profiler/delete-profiler"; - protected static final String URL_SERVER_CONFIG_PROFILER_JVM_OPTIONS = "/domain/configs/config/server-config/java-config/profiler/jvm-options"; - - protected static final String URL_DEFAULT_CONFIG_CREATE_PROFILER = "/domain/configs/config/default-config/java-config/create-profiler"; - protected static final String URL_DEFAULT_CONFIG_DELETE_PROFILER = "/domain/configs/config/default-config/java-config/profiler/delete-profiler"; - protected static final String URL_DEFAULT_CONFIG_PROFILER_JVM_OPTIONS = "/domain/configs/config/default-config/java-config/profiler/jvm-options"; - - private ConfigTest configTest; - private String testConfigName; - private String URL_TEST_CONFIG; - private String URL_TEST_CONFIG_JVM_OPTIONS; - - @BeforeMethod - public void createConfig() { - if (configTest == null) { - configTest = getTestClass(ConfigTest.class); - } - - testConfigName = "config-" + generateRandomString(); - MultivaluedMap formData = new MultivaluedHashMap() {{ - add("id", "default-config"); - add("id", testConfigName); - }}; - configTest.createAndVerifyConfig(testConfigName, formData); - - URL_TEST_CONFIG = "/domain/configs/config/" + testConfigName; - URL_TEST_CONFIG_JVM_OPTIONS = URL_TEST_CONFIG + "/java-config/jvm-options"; - } - - @AfterMethod - public void deleteConfig() { - configTest.deleteAndVerifyConfig(testConfigName); - } - - - @Test - public void getJvmOptions() { - Response response = get(URL_SERVER_JVM_OPTIONS); - assertTrue(isSuccess(response)); - Map responseMap = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); - List jvmOptions = (List)((Map)responseMap.get("extraProperties")).get("leafList"); - assertTrue(jvmOptions.size() > 0); - } - - @Test - public void createAndDeleteOptions() { - final String option1Name = "-Doption" + generateRandomString(); - Map newOptions = new HashMap() {{ - put(option1Name, "someValue"); - }}; - - Response response = post(URL_TEST_CONFIG_JVM_OPTIONS, newOptions); - assertTrue(isSuccess(response)); - response = get(URL_TEST_CONFIG_JVM_OPTIONS); - List jvmOptions = getJvmOptions(response); - assertTrue(jvmOptions.contains(option1Name+"=someValue")); - - response = delete(URL_TEST_CONFIG_JVM_OPTIONS, newOptions); - assertTrue(isSuccess(response)); - response = get(URL_TEST_CONFIG_JVM_OPTIONS); - jvmOptions = getJvmOptions(response); - assertFalse(jvmOptions.contains(option1Name+"=someValue")); - } - - // http://java.net/jira/browse/GLASSFISH-19069 - @Test - public void createAndDeleteOptionsWithBackslashes() { - final String optionName = "-Dfile" + generateRandomString(); - final String optionValue = "C:\\ABC\\DEF\\"; - Map newOptions = new HashMap() {{ - put(optionName, escape(optionValue)); - }}; - - Response response = post(URL_TEST_CONFIG_JVM_OPTIONS, newOptions); - assertTrue(isSuccess(response)); - response = get(URL_TEST_CONFIG_JVM_OPTIONS); - List jvmOptions = getJvmOptions(response); - assertTrue(jvmOptions.contains(optionName+"="+optionValue)); - - response = delete(URL_TEST_CONFIG_JVM_OPTIONS, newOptions); - assertTrue(isSuccess(response)); - response = get(URL_TEST_CONFIG_JVM_OPTIONS); - jvmOptions = getJvmOptions(response); - assertFalse(jvmOptions.contains(optionName+"="+optionValue)); - } - - @Test - public void createAndDeleteOptionsWithoutValues() { - final String option1Name = "-Doption" + generateRandomString(); - final String option2Name = "-Doption" + generateRandomString(); - Map newOptions = new HashMap() {{ - put(option1Name, ""); - put(option2Name, ""); - }}; - - Response response = post(URL_TEST_CONFIG_JVM_OPTIONS, newOptions); - assertTrue(isSuccess(response)); - response = get(URL_TEST_CONFIG_JVM_OPTIONS); - List jvmOptions = getJvmOptions(response); - assertTrue(jvmOptions.contains(option1Name)); - assertFalse(jvmOptions.contains(option1Name+"=")); - assertTrue(jvmOptions.contains(option2Name)); - assertFalse(jvmOptions.contains(option2Name+"=")); - - response = delete(URL_TEST_CONFIG_JVM_OPTIONS, newOptions); - assertTrue(isSuccess(response)); - response = get(URL_TEST_CONFIG_JVM_OPTIONS); - jvmOptions = getJvmOptions(response); - assertFalse(jvmOptions.contains(option1Name)); - assertFalse(jvmOptions.contains(option2Name)); - } - - @Test - public void testIsolatedOptionsCreationOnNewConfig() { - final String optionName = "-Doption" + generateRandomString(); - - Map newOptions = new HashMap() {{ - put(optionName, ""); - put("target", testConfigName); - }}; - - // Test new config to make sure option is there - Response response = post(URL_TEST_CONFIG_JVM_OPTIONS, newOptions); - assertTrue(isSuccess(response)); - response = get(URL_TEST_CONFIG_JVM_OPTIONS); - List jvmOptions = getJvmOptions(response); - assertTrue(jvmOptions.contains(optionName)); - - // Test server-config to make sure the options are NOT there - response = get(URL_SERVER_JVM_OPTIONS); - jvmOptions = getJvmOptions(response); - assertFalse(jvmOptions.contains(optionName)); - } - - @Test - public void testProfilerJvmOptions() { - final String profilerName = "profiler" + generateRandomString(); - final String optionName = "-Doption" + generateRandomString(); - Map attrs = new HashMap() {{ - put("name", profilerName); - put("target", testConfigName); - }}; - Map newOptions = new HashMap() {{ -// put("target", testConfigName); -// put("profiler", "true"); - put(optionName, ""); - }}; - - deleteProfiler(URL_TEST_CONFIG + "/java-config/profiler/delete-profiler", testConfigName, false); - - Response response = post(URL_TEST_CONFIG + "/java-config/create-profiler", attrs); - assertTrue(isSuccess(response)); - - response = post(URL_TEST_CONFIG + "/java-config/profiler/jvm-options", newOptions); - assertTrue(isSuccess(response)); - - response = get(URL_TEST_CONFIG + "/java-config/profiler/jvm-options"); - List jvmOptions = getJvmOptions(response); - assertTrue(jvmOptions.contains(optionName)); - - deleteProfiler(URL_TEST_CONFIG + "/java-config/profiler/delete-profiler", testConfigName, true); - } - - @Test - public void testJvmOptionWithColon() { - final String optionName = "-XX:MaxPermSize"; - final String optionValue = "152m"; - Map newOptions = new HashMap() {{ - put(escape(optionName), optionValue); - }}; - - Response response = post(URL_TEST_CONFIG_JVM_OPTIONS, newOptions); - assertTrue(isSuccess(response)); - response = get(URL_TEST_CONFIG_JVM_OPTIONS); -// assertTrue(isSuccess(response)); - List jvmOptions = getJvmOptions(response); - assertTrue(jvmOptions.contains(optionName+"="+optionValue)); - - response = delete(URL_TEST_CONFIG_JVM_OPTIONS, newOptions); - assertTrue(isSuccess(response)); - response = get(URL_TEST_CONFIG_JVM_OPTIONS); - jvmOptions = getJvmOptions(response); - assertFalse(jvmOptions.contains(optionName+"="+optionValue)); - } - - protected void deleteProfiler(final String url, final String target, final boolean failOnError) { - Response response = delete (url, new HashMap() {{ put ("target", target); }}); - if (failOnError) { - assertTrue(isSuccess(response)); - } - } - - protected List getJvmOptions(Response response) { - Map responseMap = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); - List jvmOptions = (List)((Map)responseMap.get("extraProperties")).get("leafList"); - - return jvmOptions; - } - - protected String escape(String part) { - String changed = part - .replace("\\", "\\\\") - .replace(":", "\\:"); - return changed; - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/MonitoringTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/MonitoringTest.java deleted file mode 100644 index 5a5f98b45d0..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/MonitoringTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - - -import java.util.HashMap; -import java.util.Map; -import jakarta.ws.rs.core.Response; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - - -/** - * - * @author Mitesh Meswani - */ -public class MonitoringTest extends RestTestBase { - private static final String MONITORING_RESOURCE_URL = "/domain/configs/config/server-config/monitoring-service/module-monitoring-levels"; - private static final String JDBC_CONNECTION_POOL_URL = "/domain/resources/jdbc-connection-pool"; - private static final String PING_CONNECTION_POOL_URL = "/domain/resources/ping-connection-pool"; - private static final String CONTEXT_ROOT_MONITORING = "monitoring"; - - @Override - protected String getContextRoot() { - return CONTEXT_ROOT_MONITORING; - } - - @Test(enabled=false) - public void initializeMonitoring() { - // Enable monitoring - String url = getManagementURL(MONITORING_RESOURCE_URL); - Map payLoad = new HashMap() { - { - put("ThreadPool", "HIGH"); - put("Orb", "HIGH"); - put("EjbContainer", "HIGH"); - put("WebContainer", "HIGH"); - put("Deployment", "HIGH"); - put("TransactionService", "HIGH"); - put("HttpService", "HIGH"); - put("JdbcConnectionPool", "HIGH"); - put("ConnectorConnectionPool", "HIGH"); - put("ConnectorService", "HIGH"); - put("JmsService", "HIGH"); - put("Jvm", "HIGH"); - put("Security", "HIGH"); - put("WebServicesContainer", "HIGH"); - put("Jpa", "HIGH"); - put("Jersey", "HIGH"); - } - }; - Response response = post(url, payLoad); - checkStatusForSuccess(response); - } - - /** - * Objective - Verify that basic monitoring is working - * Strategy - Call /monitoring/domain and assert that "server" is present as child element - */ - @Test(enabled=false) - public void testBaseURL() { - Map entity = getChildResources(get("/domain")); // monitoring/domain - assertNotNull(entity.get("server")); - } - - /** - * Objective - Verify that resources with dot work - * Strategy - create a resource with "." in name and then try to access it - */ - @Test(enabled=false) - public void testDot() { - // Step 1- Create a resource with "." - final String POOL_NAME = "poolNameWith.dot"; - - // Clean up from leftover from previous run - String url = getManagementURL(JDBC_CONNECTION_POOL_URL + '/' + POOL_NAME); - delete(url); - - url = getManagementURL(JDBC_CONNECTION_POOL_URL); - Map payLoad = new HashMap() { - { - put("name", POOL_NAME); - put("resType", "javax.sql.DataSource"); - put("datasourceClassname", "foo.bar"); - } - }; - Response response = post(url, payLoad); - checkStatusForSuccess(response); - - - // Step 2- Ping the connection pool to generate some monitoring data - url = getManagementURL(PING_CONNECTION_POOL_URL); - payLoad.clear(); - payLoad.put("id", POOL_NAME); - get(url, payLoad); - - // Step 3 - Access monitoring tree to assert it is accessible - response = get("/domain/server/resources/"+ POOL_NAME); - checkStatusForSuccess(response); - Map responseEntity = getEntityValues(response); - assertTrue("No Monitoring data found for pool " + POOL_NAME, responseEntity.size() > 0 ); - } - - /** - * Objective - Verify that invalid resources returns 404 - * Strategy - Request an invalid resource under monitoring and ensure that 404 is returned - */ - @Test(enabled=false) - public void testInvalidResource() { - Response response = get("/domain/server/foo"); - assertTrue("Did not receive ", response.getStatus() == jakarta.ws.rs.core.Response.Status.NOT_FOUND.getStatusCode() ) ; - } - - - private String getManagementURL(String targetResourceURL) { - return getBaseUrl() + CONTEXT_ROOT_MANAGEMENT + targetResourceURL; - - } - - -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/NetworkListenerTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/NetworkListenerTest.java deleted file mode 100644 index 25721ce2e1b..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/NetworkListenerTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.util.HashMap; -import java.util.Map; -import jakarta.ws.rs.core.Response; -import org.codehaus.jettison.json.JSONObject; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -/** - * - * @author jasonlee - */ -public class NetworkListenerTest extends RestTestBase { - protected static final String URL_PROTOCOL = "/domain/configs/config/server-config/network-config/protocols/protocol"; - protected static final String URL_SSL = "/domain/configs/config/server-config/network-config/protocols/protocol/http-listener-2/ssl"; - - @Test(enabled=false) - public void createHttpListener() { - final String redirectProtocolName = "http-redirect"; //protocol_" + generateRandomString(); - final String portUniProtocolName = "pu-protocol"; //protocol_" + generateRandomString(); - - final String redirectFilterName = "redirect-filter"; //filter_" + generateRandomString(); - final String finderName1 = "http-finder"; //finder" + generateRandomString(); - final String finderName2 = "http-redirect"; //finder" + generateRandomString(); - - try { - Response response = post("/domain/set", new HashMap() {{ - put("configs.config.server-config.network-config.network-listeners.network-listener.http-listener-1.protocol", "http-listener-1"); - }}); - checkStatusForSuccess(response); - delete(URL_PROTOCOL + "/" + portUniProtocolName); - checkStatusForSuccess(response); - delete(URL_PROTOCOL + "/" + redirectProtocolName); - checkStatusForSuccess(response); -// asadmin commands taken from: http://www.antwerkz.com/port-unification-in-glassfish-3-part-1/ -// asadmin create-protocol --securityenabled=false http-redirect -// asadmin create-protocol --securityenabled=false pu-protocol - response = post(URL_PROTOCOL, new HashMap() {{ put ("securityenabled", "false"); put("id", redirectProtocolName); }}); - checkStatusForSuccess(response); - response = post(URL_PROTOCOL, new HashMap() {{ put ("securityenabled", "false"); put("id", portUniProtocolName); }}); - checkStatusForSuccess(response); - -// asadmin create-protocol-filter --protocol http-redirect --classname org.glassfish.grizzly.config.portunif.HttpRedirectFilter redirect-filter - response = post (URL_PROTOCOL + "/" + redirectProtocolName + "/create-protocol-filter", - new HashMap() {{ - put ("id", redirectFilterName); - put ("protocol", redirectProtocolName); - put ("classname", "org.glassfish.grizzly.config.portunif.HttpRedirectFilter"); - }}); - checkStatusForSuccess(response); - -// asadmin create-protocol-finder --protocol pu-protocol --targetprotocol http-listener-2 --classname org.glassfish.grizzly.config.portunif.HttpProtocolFinder http-finder -// asadmin create-protocol-finder --protocol pu-protocol --targetprotocol http-redirect --classname org.glassfish.grizzly.config.portunif.HttpProtocolFinder http-redirect - response = post (URL_PROTOCOL + "/" + portUniProtocolName + "/create-protocol-finder", - new HashMap() {{ - put ("id", finderName1); - put ("protocol", portUniProtocolName); - put ("targetprotocol", "http-listener-2"); - put ("classname", "org.glassfish.grizzly.config.portunif.HttpProtocolFinder"); - }}); - checkStatusForSuccess(response); - response = post (URL_PROTOCOL + "/" + portUniProtocolName + "/create-protocol-finder", - new HashMap() {{ - put ("id", finderName2); - put ("protocol", portUniProtocolName); - put ("targetprotocol", redirectProtocolName); - put ("classname", "org.glassfish.grizzly.config.portunif.HttpProtocolFinder"); - }}); - checkStatusForSuccess(response); - - -// asadmin set configs.config.server-config.network-config.network-listeners.network-listener.http-listener-1.protocol=pu-protocol - response = post("/domain/configs/config/server-config/network-config/network-listeners/network-listener/http-listener-1", new HashMap() {{ - put("protocol", portUniProtocolName); - }}); - checkStatusForSuccess(response); - - response = get("/domain/configs/config/server-config/network-config/network-listeners/network-listener/http-listener-1/find-http-protocol"); - assertTrue(response.readEntity(String.class).contains("http-listener-2")); - } finally { -// ClientResponse response = post("/domain/set", new HashMap() {{ - Response response = post("/domain/configs/config/server-config/network-config/network-listeners/network-listener/http-listener-1", new HashMap() {{ - put("protocol", "http-listener-1"); - }}); - checkStatusForSuccess(response); - response = delete(URL_PROTOCOL + "/" + portUniProtocolName + "/delete-protocol-finder", - new HashMap() {{ - put("protocol", portUniProtocolName); - put("id", finderName1); - }} ); - checkStatusForSuccess(response); - response = delete(URL_PROTOCOL + "/" + portUniProtocolName + "/delete-protocol-finder", - new HashMap() {{ - put("protocol", portUniProtocolName); - put("id", finderName2); - }} ); - checkStatusForSuccess(response); - response = delete(URL_PROTOCOL + "/" + redirectProtocolName + "/protocol-chain-instance-handler/protocol-chain/protocol-filter/" + redirectFilterName, - new HashMap() {{ put("protocol", redirectProtocolName); }} ); - checkStatusForSuccess(response); - response = delete(URL_PROTOCOL + "/" + portUniProtocolName); - checkStatusForSuccess(response); - response = delete(URL_PROTOCOL + "/" + redirectProtocolName); - checkStatusForSuccess(response); - } - - } - - @Test - public void testClearingProperties() { - Map params = new HashMap() {{ - put("keyStore", "foo"); - put("trustAlgorithm", "bar"); - put("trustMaxCertLength", "15"); - put("trustStore", "baz"); - }}; - - Response response = post(URL_SSL, params); - assertTrue(isSuccess(response)); - response = get(URL_SSL, params); - Map entity = this.getEntityValues(response); - assertEquals(params.get("keyStore"), entity.get("keyStore")); - assertEquals(params.get("trustAlgorithm"), entity.get("trustAlgorithm")); - assertEquals(params.get("trustMaxCertLength"), entity.get("trustMaxCertLength")); - assertEquals(params.get("trustStore"), entity.get("trustStore")); - - params.put("keyStore", ""); - params.put("trustAlgorithm", ""); - params.put("trustStore", ""); - response = post(URL_SSL, params); - assertTrue(isSuccess(response)); - response = get(URL_SSL, params); - entity = this.getEntityValues(response); - assertEquals(JSONObject.NULL, entity.get("keyStore")); - assertEquals(JSONObject.NULL, entity.get("trustAlgorithm")); - assertEquals(JSONObject.NULL, entity.get("trustStore")); - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/NoCLICommandResourceCreationTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/NoCLICommandResourceCreationTest.java deleted file mode 100644 index e33e87a252e..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/NoCLICommandResourceCreationTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.util.HashMap; -import java.util.Map; -import jakarta.ws.rs.client.Entity; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; -import org.glassfish.admin.rest.client.utils.MarshallingUtils; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -/** - * @author Mitesh Meswani - */ -public class NoCLICommandResourceCreationTest extends RestTestBase { - private static final String URL_SERVER_PROPERTY = "/domain/servers/server/server/property"; - - @Test - public void testPropertyCreation() { - final String propertyKey = "propertyName" + generateRandomString(); - String propertyValue = generateRandomString(); - - //Create a property - Map param = new HashMap(); - param.put("name", propertyKey); - param.put("value",propertyValue); - Response response = getClient().target(getAddress(URL_SERVER_PROPERTY)) - .request(RESPONSE_TYPE) - .post(Entity.entity(MarshallingUtils.getXmlForProperties(param), MediaType.APPLICATION_XML), Response.class); - assertTrue(isSuccess(response)); - - //Verify the property got created - String propertyURL = URL_SERVER_PROPERTY + "/" + propertyKey; - response = get (propertyURL); - assertTrue(isSuccess(response)); - Map entity = getEntityValues(response); - assertTrue(entity.get("name").equals(propertyKey)); - assertTrue(entity.get("value").equals(propertyValue)); - - // Verify property update - propertyValue = generateRandomString(); - param.put("value", propertyValue); - response = getClient().target(getAddress(URL_SERVER_PROPERTY)) - .request(RESPONSE_TYPE) - .put(Entity.entity(MarshallingUtils.getXmlForProperties(param), MediaType.APPLICATION_XML), Response.class); - assertTrue(isSuccess(response)); - response = get (propertyURL); - assertTrue(isSuccess(response)); - entity = getEntityValues(response); - assertTrue(entity.get("name").equals(propertyKey)); - assertTrue(entity.get("value").equals(propertyValue)); - - //Clean up to leave domain.xml good for next run - response = delete(propertyURL, new HashMap()); - assertTrue(isSuccess(response)); - } - -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ProvidersTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ProvidersTest.java deleted file mode 100644 index 4c48b5251fb..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ProvidersTest.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import jakarta.ws.rs.core.Response; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -/** - * - * @author jasonlee - */ -public class ProvidersTest extends RestTestBase { - private static final String URL_ACTION_REPORT_RESULT = "/domain/uptime"; - private static final String URL_COMMAND_RESOURCE_GET_RESULT = "/domain/stop"; - private static final String URL_GET_RESULT = "/domain"; - private static final String URL_GET_RESULT_LIST = "/domain/servers/server"; - private static final String URL_OPTIONS_RESULT = "/domain"; - private static final String URL_STRING_LIST_RESULT = "/domain/configs/config/server-config/java-config/jvm-options"; - private static String URL_TREE_NODE; - - public ProvidersTest() { - URL_TREE_NODE = "http://localhost:" + getParameter("admin.port", "4848") + "/monitoring/domain"; - } - - @Test - public void testActionReportResultHtmlProvider() { - Response response = get(URL_ACTION_REPORT_RESULT + ".html"); - assertTrue(isSuccess(response)); - } - - @Test - public void testActionReportResultXmlProvider() { - Response response = get(URL_ACTION_REPORT_RESULT + ".xml"); - assertTrue(isSuccess(response)); - } - - @Test - public void testActionReportResultJsonProvider() { - Response response = get(URL_ACTION_REPORT_RESULT + ".json"); - assertTrue(isSuccess(response)); - } - - @Test - public void testCommandResourceGetResultHtmlProvider() { - Response response = get(URL_COMMAND_RESOURCE_GET_RESULT + ".html"); - assertTrue(isSuccess(response)); - } - - @Test - public void testCommandResourceGetResultXmlProvider() { - Response response = get(URL_COMMAND_RESOURCE_GET_RESULT + ".xml"); - assertTrue(isSuccess(response)); - } - - @Test - public void testCommandResourceGetResultJsonProvider() { - Response response = get(URL_COMMAND_RESOURCE_GET_RESULT + ".json"); - assertTrue(isSuccess(response)); - } - - @Test - public void testGetResultHtmlProvider() { - Response response = get(URL_GET_RESULT + ".html"); - assertTrue(isSuccess(response)); - } - - @Test - public void testGetResultXmlProvider() { - Response response = get(URL_GET_RESULT + ".xml"); - assertTrue(isSuccess(response)); - } - - @Test - public void testGetResultJsonProvider() { - Response response = get(URL_GET_RESULT + ".json"); - assertTrue(isSuccess(response)); - } - - @Test - public void testGetResultListHtmlProvider() { - Response response = get(URL_GET_RESULT_LIST + ".html"); - assertTrue(isSuccess(response)); - } - - @Test - public void testGetResultListXmlProvider() { - Response response = get(URL_GET_RESULT_LIST + ".xml"); - assertTrue(isSuccess(response)); - } - - @Test - public void testGetResultListJsonProvider() { - Response response = get(URL_GET_RESULT_LIST + ".json"); - assertTrue(isSuccess(response)); - } - - @Test - public void testOptionsResultXmlProvider() { - Response response = options(URL_OPTIONS_RESULT + ".xml"); - assertTrue(isSuccess(response)); - } - - @Test - public void testOptionsResultJsonProvider() { - Response response = options(URL_OPTIONS_RESULT + ".json"); - assertTrue(isSuccess(response)); - } - - @Test - public void testStringListResultHtmlProvider() { - Response response = get(URL_STRING_LIST_RESULT + ".html"); - assertTrue(isSuccess(response)); - } - - @Test - public void testStringListResultXmlProvider() { - Response response = get(URL_STRING_LIST_RESULT + ".xml"); - assertTrue(isSuccess(response)); - } - - @Test - public void testStringListResultJsonProvider() { - Response response = get(URL_STRING_LIST_RESULT + ".json"); - assertTrue(isSuccess(response)); - } - - @Test - public void testTreeNodeHtmlProvider() { - Response response = get(URL_TREE_NODE + ".html"); - assertTrue(isSuccess(response)); - } - - @Test - public void testTreeNodeXmlProvider() { - Response response = get(URL_TREE_NODE + ".xml"); - assertTrue(isSuccess(response)); - } - - @Test - public void testTreeNodeJsonProvider() { - Response response = get(URL_TREE_NODE + ".json"); - assertTrue(isSuccess(response)); - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ResourceRefTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ResourceRefTest.java deleted file mode 100644 index ca924dc38d0..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/ResourceRefTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.util.HashMap; -import java.util.Map; -import jakarta.ws.rs.core.Response; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -/** - * - * @author jasonlee - */ -public class ResourceRefTest extends RestTestBase { - private static final String URL_CREATE_INSTANCE = "/domain/create-instance"; - private static final String URL_JDBC_RESOURCE = "/domain/resources/jdbc-resource"; - private static final String URL_RESOURCE_REF = "/domain/servers/server/server/resource-ref"; - - @Test(enabled=false) - public void testCreatingResourceRef() { - final String instanceName = "instance_" + generateRandomString(); - final String jdbcResourceName = "jdbc_" + generateRandomString(); - Map newInstance = new HashMap() {{ - put("id", instanceName); - put("node", "localhost-domain1"); - }}; - Map jdbcResource = new HashMap() {{ - put("id", jdbcResourceName); - put("connectionpoolid", "DerbyPool"); - put("target", instanceName); - }}; - Map resourceRef = new HashMap() {{ - put("id", jdbcResourceName); - put("target", "server"); - }}; - - try { - Response response = post(URL_CREATE_INSTANCE, newInstance); - assertTrue(isSuccess(response)); - - response = post(URL_JDBC_RESOURCE, jdbcResource); - assertTrue(isSuccess(response)); - - response = post(URL_RESOURCE_REF, resourceRef); - assertTrue(isSuccess(response)); - } catch (Exception e) { - e.printStackTrace(); - } finally { - Response response = delete("/domain/servers/server/" + instanceName + "/resource-ref/" + jdbcResourceName, new HashMap() {{ - put("target", instanceName); - }}); - assertTrue(isSuccess(response)); - response = get("/domain/servers/server/" + instanceName + "/resource-ref/" + jdbcResourceName); - assertFalse(isSuccess(response)); - - response = delete(URL_JDBC_RESOURCE + "/" + jdbcResourceName); - assertTrue(isSuccess(response)); - response = get(URL_JDBC_RESOURCE + "/" + jdbcResourceName); - assertFalse(isSuccess(response)); - - response = delete("/domain/servers/server/" + instanceName + "/delete-instance"); - assertTrue(isSuccess(response)); - response = get("/domain/servers/server/" + instanceName); - assertFalse(isSuccess(response)); - } - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/RestTestBase.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/RestTestBase.java deleted file mode 100644 index 5d79268eaf2..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/RestTestBase.java +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileWriter; -import java.io.PrintWriter; -import java.math.BigInteger; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.logging.Level; -import java.util.logging.Logger; -import jakarta.ws.rs.client.Client; -import jakarta.ws.rs.client.Entity; -import jakarta.ws.rs.client.WebTarget; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.MultivaluedHashMap; -import jakarta.ws.rs.core.MultivaluedMap; -import jakarta.ws.rs.core.Response; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import org.glassfish.admin.rest.client.ClientWrapper; -import org.glassfish.admin.rest.client.utils.MarshallingUtils; - -import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; -import org.glassfish.jersey.logging.LoggingFeature; -import org.glassfish.jersey.media.multipart.FormDataMultiPart; -import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; -import static org.testng.AssertJUnit.*; -import org.w3c.dom.Document; - -public class RestTestBase { - protected static String baseUrl = "http://localhost:4848"; - protected static final String RESPONSE_TYPE = MediaType.APPLICATION_JSON;//APPLICATION_XML; - protected static final String AUTH_USER_NAME = "dummyuser"; - protected static final String AUTH_PASSWORD = "dummypass"; - protected static final String CONTEXT_ROOT_MANAGEMENT = "/management"; - private static final HttpAuthenticationFeature basicAuthFilter = HttpAuthenticationFeature.basic(AUTH_USER_NAME, AUTH_PASSWORD); - protected static String adminHost; - protected static String adminPort; - protected static String adminUser; - protected static String adminPass; - protected static String instancePort; - - private static String currentTestClass = ""; - protected Client client; - -// @BeforeClass - public static void initialize() { - adminPort = getParameter("admin.port", "4848"); - instancePort = getParameter("instance.port", "8080"); - adminHost = getParameter("instance.host", "localhost"); - adminUser = getParameter("user.name", "admin"); - adminPass = getParameter("user.pass", ""); - baseUrl = "http://" + adminHost + ':' + adminPort + '/'; - - final RestTestBase rtb = new RestTestBase(); - rtb.get("/domain/rotate-log"); - } - -// @AfterClass - public static void captureLog() { - try { - - if (!currentTestClass.isEmpty()) { - RestTestBase rtb = new RestTestBase(); - Client client = new ClientWrapper(new HashMap(), adminUser, adminPass); - Response cr = client.target(rtb.getAddress("/domain/view-log")). - request(). - get(Response.class); - - PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("target/surefire-reports/" + currentTestClass + "-server.log"))); - out.write(cr.readEntity(String.class)); - out.close(); - } - } catch (Exception ex) { - Logger.getLogger(RestTestBase.class.getName()). - log(Level.INFO, null, ex); - } - } - - protected static String getBaseUrl() { - return baseUrl; - } - - protected String getContextRoot() { - return CONTEXT_ROOT_MANAGEMENT; - } - -// @BeforeMethod(alwaysRun = true) - public void setup() { - currentTestClass = this.getClass().getName(); - } - - protected String getAddress(String address) { - if (address.startsWith("http://")) { - return address; - } - - return baseUrl + getContextRoot() + address; - } - -// @BeforeMethod - protected Client getClient() { - if (client == null) { - client = new ClientWrapper(new HashMap(), adminUser, adminPass); - if (Boolean.parseBoolean(System.getProperty("DEBUG"))) { - client.register(LoggingFeature.class); - } - } - return client; - } - - protected void resetClient() { - client = null; - getClient(); - } - - protected void authenticate() { - getClient().register(basicAuthFilter); - } - - protected T getTestClass(Class clazz) { - try { - T test = clazz.newInstance(); - ((RestTestBase) test).setup(); - return test; - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } - - protected static String generateRandomString() { - SecureRandom random = new SecureRandom(); - - return new BigInteger(130, random).toString(16); - } - - protected static int generateRandomNumber() { - Random r = new Random(); - return Math.abs(r.nextInt()) + 1; - } - - protected int generateRandomNumber(int max) { - Random r = new Random(); - return Math.abs(r.nextInt(max - 1)) + 1; - } - - protected boolean isSuccess(Response response) { - int status = response.getStatus(); - return ((status >= 200) && (status <= 299)); - } - - protected void checkStatusForSuccess(Response cr) { - int status = cr.getStatus(); - if (!isSuccess(cr)) { - String message = getErrorMessage(cr); - fail("Expected a status between 200 and 299 (inclusive). Found " + status - + ((message != null) ? ": " + message : "")); - } - } - - protected void checkStatusForFailure(Response cr) { - int status = cr.getStatus(); - if (isSuccess(cr)) { - fail("Expected a status less than 200 or greater than 299 (inclusive). Found " + status); - } - } - - protected String getResponseType() { - return RESPONSE_TYPE; - } - - protected Response get(String address) { - return get(address, new HashMap()); - } - - protected Response get(String address, Map payload) { - WebTarget target = getClient().target(getAddress(address)); - for (Map.Entry entry : payload.entrySet()) { - target = target.queryParam(entry.getKey(), entry.getValue()); - } - return target.request(getResponseType()) - .get(Response.class); - } - - protected Response options(String address) { - return getClient().target(getAddress(address)). - request(getResponseType()). - options(Response.class); - } - - protected Response post(String address, Map payload) { - return getClient().target(getAddress(address)). - request(getResponseType()). - post(Entity.entity(buildMultivaluedMap(payload), MediaType.APPLICATION_FORM_URLENCODED), Response.class); - } - - protected Response post(String address) { - return getClient().target(getAddress(address)). - request(getResponseType()). - post(Entity.entity(null, MediaType.APPLICATION_FORM_URLENCODED), Response.class); - } - - protected Response put(String address, Map payload) { - return getClient().target(getAddress(address)). - request(getResponseType()). - put(Entity.entity(buildMultivaluedMap(payload), MediaType.APPLICATION_FORM_URLENCODED), Response.class); - } - - protected Response put(String address) { - return getClient().target(getAddress(address)). - request(getResponseType()). - put(Entity.entity(null, MediaType.APPLICATION_FORM_URLENCODED), Response.class); - } - - protected Response postWithUpload(String address, Map payload) { - FormDataMultiPart form = new FormDataMultiPart(); - for (Map.Entry entry : payload.entrySet()) { - if ((entry.getValue() instanceof File)) { - form.getBodyParts(). - add((new FileDataBodyPart(entry.getKey(), (File) entry.getValue()))); - } else { - form.field(entry.getKey(), entry.getValue(), MediaType.TEXT_PLAIN_TYPE); - } - } - return getClient().target(getAddress(address)). - request(getResponseType()). - post(Entity.entity(form, MediaType.MULTIPART_FORM_DATA), Response.class); - } - - protected Response delete(String address) { - return delete(address, new HashMap()); - } - - protected Response delete(String address, Map payload) { - WebTarget target = getClient().target(getAddress(address)); - for (Map.Entry entry : payload.entrySet()) { - target = target.queryParam(entry.getKey(), entry.getValue()); - } - return target.request(getResponseType()) - .delete(Response.class); - } - - /** - * This method will parse the provided XML document and return a map of the attributes and values on the root - * element - * - * @param response - * @return - */ - protected Map getEntityValues(Response response) { - Map map = new HashMap(); - - String xml = response.readEntity(String.class); - Map responseMap = MarshallingUtils.buildMapFromDocument(xml); - Object obj = responseMap.get("extraProperties"); - if (obj != null) { - return (Map) ((Map) obj).get("entity"); - } else { - return map; - } - } - - protected List getCommandResults(Response response) { - String document = response.readEntity(String.class); - List results = new ArrayList(); - Map map = MarshallingUtils.buildMapFromDocument(document); - String message = (String) map.get("message"); - if (message != null && !"".equals(message)) { - results.add(message); - } - - Object children = map.get("children"); - if (children instanceof List) { - for (Object child : (List) children) { - Map childMap = (Map) child; - message = (String) childMap.get("message"); - if (message != null) { - results.add(message); - } - } - } - - return results; - } - - protected Map getChildResources(Response response) { - Map responseMap = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); - Map extraProperties = (Map) responseMap.get("extraProperties"); - if (extraProperties != null) { - return (Map) extraProperties.get("childResources"); - } - - return new HashMap(); - } - - public Document getDocument(String input) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document doc = db.parse(new ByteArrayInputStream(input.getBytes())); - return doc; - } catch (Exception ex) { - return null; - } - } - - public List> getProperties(Response response) { - Map responseMap = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); - Map extraProperties = (Map) responseMap.get("extraProperties"); - if (extraProperties != null) { - return (List) extraProperties.get("properties"); - } - return new ArrayList>(); - } - - private MultivaluedMap buildMultivaluedMap(Map payload) { - if (payload instanceof MultivaluedMap) { - return (MultivaluedMap) payload; - } - MultivaluedMap formData = new MultivaluedHashMap(); - if (payload != null) { - for (final Map.Entry entry : payload.entrySet()) { - formData.add(entry.getKey(), entry.getValue()); - } - } - return formData; - } - - protected String getErrorMessage(Response cr) { - String message = null; - Map map = MarshallingUtils.buildMapFromDocument(cr.readEntity(String.class)); - if (map != null) { - message = (String) map.get("message"); - } - - return message; - } - - protected static String getParameter(String paramName, String defaultValue) { - String value = System.getenv(paramName); - if (value == null) { - value = System.getProperty(paramName); - } - if (value == null) { - value = defaultValue; - } - - return value; - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/TokenAuthenticationTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/TokenAuthenticationTest.java deleted file mode 100644 index 416ee214800..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/TokenAuthenticationTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -import java.util.HashMap; -import java.util.Map; -import jakarta.ws.rs.core.Cookie; -import jakarta.ws.rs.core.Response; -import org.glassfish.admin.rest.client.utils.MarshallingUtils; -import static org.testng.AssertJUnit.*; -import org.testng.annotations.Test; - -/** - * @author Mitesh Meswani - */ -public class TokenAuthenticationTest extends RestTestBase { - private static final String URL_DOMAIN_SESSIONS = "/sessions"; - private static final String URL_CREATE_USER = "/domain/configs/config/server-config/security-service/auth-realm/admin-realm/create-user"; - private static final String URL_DELETE_USER = "/domain/configs/config/server-config/security-service/auth-realm/admin-realm/delete-user"; - private static final String GF_REST_TOKEN_COOKIE_NAME = "gfresttoken"; - private static final String TEST_GROUP = "newgroup"; - - @Test - public void testTokenCreateAndDelete() { - deleteUserAuthTestUser(null); // just in case - //Verify a session token got created - String token = getSessionToken(); - - // Verify we can use the session token. - Response response = getClient().target(getAddress("/domain")).request().cookie(new Cookie(GF_REST_TOKEN_COOKIE_NAME, token)).get(Response.class); - assertTrue(isSuccess(response)); - - //Delete the token - response = getClient().target(getAddress(URL_DOMAIN_SESSIONS) + "/" + token).request().cookie(new Cookie(GF_REST_TOKEN_COOKIE_NAME, token)).delete(Response.class); - delete(URL_DOMAIN_SESSIONS); - assertTrue(isSuccess(response)); - } - - @Test - public void testAuthRequired() { - Map newUser = new HashMap() {{ - put("id", AUTH_USER_NAME); - put("groups", "asadmin"); - put("authrealmname", "admin-realm"); - put("AS_ADMIN_USERPASSWORD", AUTH_PASSWORD); - }}; - String token = null; - - try { - // Delete the test user if it exists - deleteUserAuthTestUser(token); - - // Verify that we can get unauthenticated access to the server - Response response = get("/domain"); - assertTrue(isSuccess(response)); - - // Create the new user - response = post(URL_CREATE_USER, newUser); - assertTrue(isSuccess(response)); - - // Verify that we must now authentication (response.status = 401) - response = get("/domain"); - assertFalse(isSuccess(response)); - - // Authenticate, get the token, then "clear" the authentication - authenticate(); - token = getSessionToken(); - resetClient(); - - // Build this request manually so we can pass the cookie - response = getClient().target(getAddress("/domain")).request().cookie(new Cookie(GF_REST_TOKEN_COOKIE_NAME, token)).get(Response.class); - assertTrue(isSuccess(response)); - resetClient(); - - // Request again w/o the cookie. This should fail. - response = getClient().target(getAddress("/domain")).request().get(Response.class); - assertFalse(isSuccess(response)); - authenticate(); - } finally { - // Clean up after ourselves - deleteUserAuthTestUser(token); - } - } - - protected String getSessionToken() { - Response response = post(URL_DOMAIN_SESSIONS); - assertTrue(isSuccess(response)); - Map responseMap = MarshallingUtils.buildMapFromDocument(response.readEntity(String.class)); - Map extraProperties = (Map)responseMap.get("extraProperties"); - return (String)extraProperties.get("token"); - } - - private void deleteUserAuthTestUser(String token) { - if (token != null) { - final String address = getAddress(URL_DELETE_USER); - Response response = getClient().target(address).queryParam("id", AUTH_USER_NAME).request() - .cookie(new Cookie(GF_REST_TOKEN_COOKIE_NAME, token)).delete(Response.class); - assertTrue(isSuccess(response)); - resetClient(); - } else { - Response response = delete(URL_DELETE_USER, new HashMap() {{ put("id", AUTH_USER_NAME); }}); - if (response.getStatus() == 401) { - authenticate(); - response = delete(URL_DELETE_USER, new HashMap() {{ put("id", AUTH_USER_NAME); }}); - assertTrue(isSuccess(response)); - resetClient(); - } - } - } -} diff --git a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/UtilityTest.java b/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/UtilityTest.java deleted file mode 100644 index 4d8b5263e52..00000000000 --- a/nucleus/tests/admin/src/test/java/org/glassfish/nucleus/admin/rest/UtilityTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package org.glassfish.nucleus.admin.rest; - -/** - * - * @author jdlee - */ -public class UtilityTest { - - // TODO - JERSEY2 -// @Test -// public void parameterResolutionTest() { -// WebApplicationImpl wai = new WebApplicationImpl(); -// ContainerRequest r = new TestHttpRequestContext(wai, -// "GET", -// null, -// "/management/domain/one/two/three/four/five/six/seven/eight/nine/ten/endpoint", -// "/management/domain/"); -// UriInfo ui = new WebApplicationContext(wai, r, null); -// Map commandParams = new HashMap() {{ -// put("foo", "$parent"); -// put("bar", "$grandparent3"); -// put("baz", "$grandparent5"); -// }}; -// -// ResourceUtil.resolveParamValues(commandParams, ui); -// assertEquals("ten", commandParams.get("foo")); -// assertEquals("seven", commandParams.get("bar")); -// assertEquals("five", commandParams.get("baz")); -// } -// -// private class TestHttpRequestContext extends ContainerRequest { -// -// public TestHttpRequestContext( -// WebApplication wa, -// String method, -// InputStream entity, -// String completeUri, -// String baseUri) { -// -// super(wa, method, URI.create(baseUri), URI.create(completeUri), new InBoundHeaders(), entity); -// } -// } -} diff --git a/nucleus/tests/pom.xml b/nucleus/tests/pom.xml deleted file mode 100755 index aa0dc2c1db0..00000000000 --- a/nucleus/tests/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - - 4.0.0 - - - org.glassfish.main - glassfish-nucleus-parent - 6.2.6-SNAPSHOT - - - org.glassfish.main.tests - nucleus-tests - pom - - Nucleus Tests - - - admin - - - - - - jakarta.servlet - jakarta.servlet-api - ${servlet-api.version} - - - - - - - - - org.codehaus.mojo - findbugs-maven-plugin - - true - - - - - - - - maven-javadoc-plugin - - true - - - - maven-deploy-plugin - - true - - - - -