diff options
| author | Alex Rudyy <orudyy@apache.org> | 2015-04-15 09:47:28 +0000 |
|---|---|---|
| committer | Alex Rudyy <orudyy@apache.org> | 2015-04-15 09:47:28 +0000 |
| commit | 0a0baee45ebcff44635907d457c4ff6810b09c87 (patch) | |
| tree | 8bfb0f9eddbc23cff88af69be80ab3ce7d47011c /qpid/java/broker-plugins | |
| parent | 54aa3d7070da16ce55c28ccad3f7d0871479e461 (diff) | |
| download | qpid-python-0a0baee45ebcff44635907d457c4ff6810b09c87.tar.gz | |
QPID-6481: Move java source tree to top level
git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1673693 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'qpid/java/broker-plugins')
514 files changed, 0 insertions, 80111 deletions
diff --git a/qpid/java/broker-plugins/access-control/pom.xml b/qpid/java/broker-plugins/access-control/pom.xml deleted file mode 100644 index ab6cf90a21..0000000000 --- a/qpid/java/broker-plugins/access-control/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-access-control</artifactId> - <name>Qpid Access Control Broker Plug-in</name> - <description>Access Control broker plug-in</description> - - <properties> - <generated-logmessages-dir>${project.build.directory}/generated-sources/generated-logmessages</generated-logmessages-dir> - </properties> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <version>${log4j-version}</version> - </dependency> - - <!-- test dependencies --> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-test-utils</artifactId> - <version>${project.version}</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <type>test-jar</type> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <resources> - <resource> - <directory>src/main/java</directory> - <excludes> - <exclude>**/*.java</exclude> - </excludes> - </resource> - <resource> - <directory>src/main/resources</directory> - <includes> - <include>META-INF/</include> - </includes> - </resource> - </resources> - </build> - -</project> diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclAction.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclAction.java deleted file mode 100644 index e4bf21a082..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclAction.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.config; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.firewall.FirewallRule; - -public class AclAction -{ - private Action _action; - private FirewallRule _firewallRule; - - public AclAction(Operation operation, ObjectType object, AclRulePredicates predicates) - { - _action = new Action(operation, object, predicates.getObjectProperties()); - _firewallRule = predicates.getFirewallRule(); - } - - public AclAction(Operation operation) - { - _action = new Action(operation); - } - - public AclAction(Operation operation, ObjectType object, ObjectProperties properties) - { - _action = new Action(operation, object, properties); - } - - public FirewallRule getFirewallRule() - { - return _firewallRule; - } - - public Action getAction() - { - return _action; - } - - public boolean isAllowed() - { - return _action.isAllowed(); - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(_action) - .append(_firewallRule).toHashCode(); - } - - @Override - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - if (obj == this) - { - return true; - } - if (obj.getClass() != getClass()) - { - return false; - } - AclAction rhs = (AclAction) obj; - return new EqualsBuilder() - .append(_action, rhs._action) - .append(_firewallRule, rhs._firewallRule).isEquals(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_action) - .append(_firewallRule).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclRulePredicates.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclRulePredicates.java deleted file mode 100644 index ebe6df126f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclRulePredicates.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.config; - -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectProperties.Property; -import org.apache.qpid.server.security.access.firewall.FirewallRule; -import org.apache.qpid.server.security.access.firewall.FirewallRuleFactory; - -/** - * Represents the predicates on an ACL rule by combining predicates relating to the object being operated on - * (e.g. name=foo) with firewall rules. - */ -public class AclRulePredicates -{ - private static final Logger _logger = LoggerFactory.getLogger(AclRulePredicates.class); - - private static final String SEPARATOR = ","; - - private ObjectProperties _properties = new ObjectProperties(); - - private FirewallRule _firewallRule; - - private FirewallRuleFactory _firewallRuleFactory = new FirewallRuleFactory(); - - public void parse(String key, String value) - { - ObjectProperties.Property property = ObjectProperties.Property.parse(key); - - if(property == Property.FROM_HOSTNAME) - { - checkFirewallRuleNotAlreadyDefined(key, value); - _firewallRule = _firewallRuleFactory.createForHostname(value.split(SEPARATOR)); - } - else if(property == Property.FROM_NETWORK) - { - checkFirewallRuleNotAlreadyDefined(key, value); - _firewallRule = _firewallRuleFactory.createForNetwork(value.split(SEPARATOR)); - } - else - { - _properties.put(property, value); - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Parsed " + property + " with value " + value); - } - } - - private void checkFirewallRuleNotAlreadyDefined(String key, String value) - { - if(_firewallRule != null) - { - throw new IllegalStateException( - "Cannot parse " + key + "=" + value - + " because firewall rule " + _firewallRule + " has already been defined"); - } - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_properties) - .append(_firewallRule).toString(); - } - - public FirewallRule getFirewallRule() - { - return _firewallRule; - } - - public ObjectProperties getObjectProperties() - { - return _properties; - } - - void setFirewallRuleFactory(FirewallRuleFactory firewallRuleFactory) - { - _firewallRuleFactory = firewallRuleFactory; - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java deleted file mode 100644 index e09935cf5c..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access.config; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; - -/** - * An access control v2 rule action. - * - * An action consists of an {@link Operation} on an {@link ObjectType} with certain properties, stored in a {@link java.util.Map}. - * The operation and object should be an allowable combination, based on the {@link ObjectType#isAllowed(Operation)} - * method of the object, which is exposed as the {@link #isAllowed()} method here. The internal #propertiesMatch(Map) - * and #valueMatches(String, String) methods are used to determine wildcarded matching of properties, with - * the empty string or "*" matching all values, and "*" at the end of a rule value indicating prefix matching. - * <p> - * The {@link #matches(Action)} method is intended to be used when determining precedence of rules, and - * {@link #equals(Object)} and {@link #hashCode()} are intended for use in maps. This is due to the wildcard matching - * described above. - */ -public class Action -{ - private final Operation _operation; - private final ObjectType _object; - private final ObjectProperties _properties; - - public Action(Operation operation) - { - this(operation, ObjectType.ALL); - } - - public Action(Operation operation, ObjectType object, String name) - { - this(operation, object, new ObjectProperties(name)); - } - - public Action(Operation operation, ObjectType object) - { - this(operation, object, ObjectProperties.EMPTY); - } - - public Action(Operation operation, ObjectType object, ObjectProperties properties) - { - _operation = operation; - _object = object; - _properties = properties; - } - - public Operation getOperation() - { - return _operation; - } - - public ObjectType getObjectType() - { - return _object; - } - - public ObjectProperties getProperties() - { - return _properties; - } - - public boolean isAllowed() - { - return _object.isAllowed(_operation); - } - - public boolean matches(Action a) - { - if (!operationsMatch(a)) - { - return false; - } - - if (!objectTypesMatch(a)) - { - return false; - } - - if (!propertiesMatch(a)) - { - return false; - } - - return true; - } - - private boolean operationsMatch(Action a) - { - return Operation.ALL == a.getOperation() || getOperation() == a.getOperation(); - } - - private boolean objectTypesMatch(Action a) - { - return ObjectType.ALL == a.getObjectType() || getObjectType() == a.getObjectType(); - } - - private boolean propertiesMatch(Action a) - { - boolean propertiesMatch = false; - if (_properties != null) - { - propertiesMatch = _properties.matches(a.getProperties()); - } - else if (a.getProperties() == null) - { - propertiesMatch = true; - } - return propertiesMatch; - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof Action)) - { - return false; - } - Action a = (Action) o; - - return new EqualsBuilder() - .append(_operation, a.getOperation()) - .append(_object, a.getObjectType()) - .append(_properties, a.getProperties()) - .isEquals(); - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(_operation) - .append(_object) - .append(_properties) - .toHashCode(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("operation", _operation) - .append("objectType", _object) - .append("properties", _properties) - .toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ClientAction.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ClientAction.java deleted file mode 100644 index fed20a56c8..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ClientAction.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.config; - -import java.net.InetAddress; - -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.firewall.FirewallRule; - -/** - * I represent an {@link Action} taken by a client from a known address. The address is used to - * determine if I match an {@link AclAction}, which may contain firewall rules. - */ -public class ClientAction -{ - private Action _clientAction; - - public ClientAction(Action clientAction) - { - _clientAction = clientAction; - } - - public ClientAction(Operation operation, ObjectType objectType, ObjectProperties properties) - { - _clientAction = new Action(operation, objectType, properties); - } - - public boolean matches(AclAction ruleAction, InetAddress addressOfClient) - { - return _clientAction.matches(ruleAction.getAction()) - && addressOfClientMatches(ruleAction, addressOfClient); - } - - private boolean addressOfClientMatches(AclAction ruleAction, InetAddress addressOfClient) - { - FirewallRule firewallRule = ruleAction.getFirewallRule(); - if(firewallRule == null || addressOfClient == null) - { - return true; - } - else - { - return firewallRule.matches(addressOfClient); - } - } - - public Operation getOperation() - { - return _clientAction.getOperation(); - } - - public ObjectType getObjectType() - { - return _clientAction.getObjectType(); - } - - public ObjectProperties getProperties() - { - return _clientAction.getProperties(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_clientAction).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java deleted file mode 100644 index 3405b6c155..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.access.config; - -import java.io.Reader; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; - -public interface ConfigurationFile -{ - /** - * Load this configuration file's contents into a {@link RuleSet}. - * @throws IllegalConfigurationException if the configuration file has errors. - * @throws IllegalArgumentException if individual tokens cannot be parsed. - * @param configReader - */ - RuleSet load(final Reader configReader) throws IllegalConfigurationException; - - RuleSet getConfiguration(); - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java deleted file mode 100644 index 92b870f740..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.access.config; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.Reader; -import java.io.StreamTokenizer; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Stack; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.Permission; - -public class PlainConfiguration implements ConfigurationFile -{ - private static final Logger _logger = LoggerFactory.getLogger(PlainConfiguration.class); - - public static final Character COMMENT = '#'; - public static final Character CONTINUATION = '\\'; - - public static final String ACL = "acl"; - public static final String CONFIG = "config"; - - static final String UNRECOGNISED_INITIAL_MSG = "Unrecognised initial token '%s' at line %d"; - static final String NOT_ENOUGH_TOKENS_MSG = "Not enough tokens at line %d"; - static final String NUMBER_NOT_ALLOWED_MSG = "Number not allowed before '%s' at line %d"; - static final String CANNOT_LOAD_MSG = "Cannot load config file %s"; - static final String CANNOT_CLOSE_MSG = "Cannot close config file %s"; - static final String PREMATURE_CONTINUATION_MSG = "Premature continuation character at line %d"; - static final String PREMATURE_EOF_MSG = "Premature end of file reached at line %d"; - static final String PARSE_TOKEN_FAILED_MSG = "Failed to parse token at line %d"; - static final String CONFIG_NOT_FOUND_MSG = "Cannot find config file %s"; - static final String NOT_ENOUGH_ACL_MSG = "Not enough data for an acl at line %d"; - static final String NOT_ENOUGH_CONFIG_MSG = "Not enough data for config at line %d"; - static final String BAD_ACL_RULE_NUMBER_MSG = "Invalid rule number at line %d"; - static final String PROPERTY_KEY_ONLY_MSG = "Incomplete property (key only) at line %d"; - static final String PROPERTY_NO_EQUALS_MSG = "Incomplete property (no equals) at line %d"; - static final String PROPERTY_NO_VALUE_MSG = "Incomplete property (no value) at line %d"; - private final EventLoggerProvider _eventLogger; - private final String _name; - - private StreamTokenizer _st; - private RuleSet _config; - - public PlainConfiguration(String name, final EventLoggerProvider eventLogger) - { - _eventLogger = eventLogger; - _name = name; - } - - @Override - public RuleSet load(final Reader configReader) - { - _config = new RuleSet(_eventLogger); - - try(Reader fileReader = configReader) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("About to load ACL file"); - } - - _st = new StreamTokenizer(new BufferedReader(fileReader)); - _st.resetSyntax(); // setup the tokenizer - - _st.commentChar(COMMENT); // single line comments - _st.eolIsSignificant(true); // return EOL as a token - _st.ordinaryChar('='); // equals is a token - _st.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) - _st.quoteChar('"'); // double quote - _st.quoteChar('\''); // single quote - _st.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly - _st.wordChars('a', 'z'); // unquoted token characters [a-z] - _st.wordChars('A', 'Z'); // [A-Z] - _st.wordChars('0', '9'); // [0-9] - _st.wordChars('_', '_'); // underscore - _st.wordChars('-', '-'); // dash - _st.wordChars('.', '.'); // dot - _st.wordChars('*', '*'); // star - _st.wordChars('@', '@'); // at - _st.wordChars(':', ':'); // colon - - // parse the acl file lines - Stack<String> stack = new Stack<String>(); - int current; - do { - current = _st.nextToken(); - switch (current) - { - case StreamTokenizer.TT_EOF: - case StreamTokenizer.TT_EOL: - if (stack.isEmpty()) - { - break; // blank line - } - - // pull out the first token from the bottom of the stack and check arguments exist - String first = stack.firstElement(); - stack.removeElementAt(0); - if (stack.isEmpty()) - { - throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, getLine())); - } - - // check for and parse optional initial number for ACL lines - Integer number = null; - if (StringUtils.isNumeric(first)) - { - // set the acl number and get the next element - number = Integer.valueOf(first); - first = stack.firstElement(); - stack.removeElementAt(0); - } - - if (StringUtils.equalsIgnoreCase(ACL, first)) - { - parseAcl(number, stack); - } - else if (number == null) - { - if(StringUtils.equalsIgnoreCase("GROUP", first)) - { - throw new IllegalConfigurationException(String.format("GROUP keyword not supported at line %d. Groups should defined via a Group Provider, not in the ACL file.", getLine())); - } - else if (StringUtils.equalsIgnoreCase(CONFIG, first)) - { - parseConfig(stack); - } - else - { - throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, getLine())); - } - } - else - { - throw new IllegalConfigurationException(String.format(NUMBER_NOT_ALLOWED_MSG, first, getLine())); - } - - // reset stack, start next line - stack.clear(); - break; - case StreamTokenizer.TT_NUMBER: - stack.push(Integer.toString(Double.valueOf(_st.nval).intValue())); - break; - case StreamTokenizer.TT_WORD: - stack.push(_st.sval); // token - break; - default: - if (_st.ttype == CONTINUATION) - { - int next = _st.nextToken(); - if (next == StreamTokenizer.TT_EOL) - { - break; // continue reading next line - } - - // invalid location for continuation character (add one to line because we ate the EOL) - throw new IllegalConfigurationException(String.format(PREMATURE_CONTINUATION_MSG, getLine() + 1)); - } - else if (_st.ttype == '\'' || _st.ttype == '"') - { - stack.push(_st.sval); // quoted token - } - else - { - stack.push(Character.toString((char) _st.ttype)); // single character - } - } - } while (current != StreamTokenizer.TT_EOF); - - if (!stack.isEmpty()) - { - throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, getLine())); - } - } - catch (IllegalArgumentException iae) - { - throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, getLine()), iae); - } - catch (FileNotFoundException fnfe) - { - throw new IllegalConfigurationException(String.format(CONFIG_NOT_FOUND_MSG, _name), fnfe); - } - catch (IOException ioe) - { - throw new IllegalConfigurationException(String.format(CANNOT_LOAD_MSG, _name), ioe); - } - - return _config; - } - - private void parseAcl(Integer number, List<String> args) - { - if (args.size() < 3) - { - throw new IllegalConfigurationException(String.format(NOT_ENOUGH_ACL_MSG, getLine())); - } - - Permission permission = Permission.parse(args.get(0)); - String identity = args.get(1); - Operation operation = Operation.parse(args.get(2)); - - if (number != null && !getConfiguration().isValidNumber(number)) - { - throw new IllegalConfigurationException(String.format(BAD_ACL_RULE_NUMBER_MSG, getLine())); - } - - if (args.size() == 3) - { - getConfiguration().grant(number, identity, permission, operation); - } - else - { - ObjectType object = ObjectType.parse(args.get(3)); - AclRulePredicates predicates = toRulePredicates(args.subList(4, args.size())); - - getConfiguration().grant(number, identity, permission, operation, object, predicates); - } - } - - private void parseConfig(List<String> args) - { - if (args.size() < 3) - { - throw new IllegalConfigurationException(String.format(NOT_ENOUGH_CONFIG_MSG, getLine())); - } - - Map<String, Boolean> properties = toPluginProperties(args); - - getConfiguration().configure(properties); - } - - private AclRulePredicates toRulePredicates(List<String> args) - { - AclRulePredicates predicates = new AclRulePredicates(); - Iterator<String> i = args.iterator(); - while (i.hasNext()) - { - String key = i.next(); - if (!i.hasNext()) - { - throw new IllegalConfigurationException(String.format(PROPERTY_KEY_ONLY_MSG, getLine())); - } - if (!"=".equals(i.next())) - { - throw new IllegalConfigurationException(String.format(PROPERTY_NO_EQUALS_MSG, getLine())); - } - if (!i.hasNext()) - { - throw new IllegalConfigurationException(String.format(PROPERTY_NO_VALUE_MSG, getLine())); - } - String value = i.next(); - - predicates.parse(key, value); - } - return predicates; - } - - /** Converts a {@link List} of "name", "=", "value" tokens into a {@link Map}. */ - protected Map<String, Boolean> toPluginProperties(List<String> args) - { - Map<String, Boolean> properties = new HashMap<String, Boolean>(); - Iterator<String> i = args.iterator(); - while (i.hasNext()) - { - String key = i.next().toLowerCase(); - if (!i.hasNext()) - { - throw new IllegalConfigurationException(String.format(PROPERTY_KEY_ONLY_MSG, getLine())); - } - if (!"=".equals(i.next())) - { - throw new IllegalConfigurationException(String.format(PROPERTY_NO_EQUALS_MSG, getLine())); - } - if (!i.hasNext()) - { - throw new IllegalConfigurationException(String.format(PROPERTY_NO_VALUE_MSG, getLine())); - } - - // parse property value and save - Boolean value = Boolean.valueOf(i.next()); - properties.put(key, value); - } - return properties; - } - - protected int getLine() - { - return _st.lineno() - 1; - } - - public RuleSet getConfiguration() - { - return _config; - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java deleted file mode 100644 index 9e9b33194e..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.security.access.config; - -import org.apache.commons.lang.builder.CompareToBuilder; -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.apache.qpid.server.security.access.Permission; - -/** - * An access control v2 rule. - * - * A rule consists of {@link Permission} for a particular identity to perform an {@link Action}. The identity - * may be either a user or a group. - */ -public class Rule implements Comparable<Rule> -{ - /** String indicating all identified. */ - public static final String ALL = "all"; - - private Integer _number; - private Boolean _enabled = Boolean.TRUE; - private String _identity; - private AclAction _action; - private Permission _permission; - - public Rule(Integer number, String identity, AclAction action, Permission permission) - { - setNumber(number); - setIdentity(identity); - setAction(action); - setPermission(permission); - } - - public Rule(String identity, AclAction action, Permission permission) - { - this(null, identity, action, permission); - } - - public boolean isEnabled() - { - return _enabled; - } - - public void setEnabled(boolean enabled) - { - _enabled = enabled; - } - - public void enable() - { - _enabled = Boolean.TRUE; - } - - public void disable() - { - _enabled = Boolean.FALSE; - } - - public Integer getNumber() - { - return _number; - } - - public void setNumber(Integer number) - { - _number = number; - } - - public String getIdentity() - { - return _identity; - } - - public void setIdentity(String identity) - { - _identity = identity; - } - - public Action getAction() - { - return _action.getAction(); - } - - public AclAction getAclAction() - { - return _action; - } - - public void setAction(AclAction action) - { - _action = action; - } - - public Permission getPermission() - { - return _permission; - } - - public void setPermission(Permission permission) - { - _permission = permission; - } - - @Override - public int compareTo(Rule r) - { - return new CompareToBuilder() - .append(getAction(), r.getAction()) - .append(getIdentity(), r.getIdentity()) - .append(getPermission(), r.getPermission()) - .toComparison(); - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof Rule)) - { - return false; - } - Rule r = (Rule) o; - - return new EqualsBuilder() - .append(getIdentity(), r.getIdentity()) - .append(getAclAction(), r.getAclAction()) - .append(getPermission(), r.getPermission()) - .isEquals(); - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(getIdentity()) - .append(getAclAction()) - .append(getPermission()) - .toHashCode(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("#", getNumber()) - .append("identity", getIdentity()) - .append("action", getAclAction()) - .append("permission", getPermission()) - .append("enabled", isEnabled()) - .toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java deleted file mode 100644 index 7661951d8b..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java +++ /dev/null @@ -1,447 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.config; - -import java.net.InetAddress; -import java.security.Principal; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.WeakHashMap; - -import javax.security.auth.Subject; - -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.logging.messages.AccessControlMessages; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.Permission; - -/** - * Models the rule configuration for the access control plugin. - */ -public class RuleSet implements EventLoggerProvider -{ - private static final Logger _logger = LoggerFactory.getLogger(RuleSet.class); - - private static final String AT = "@"; - private static final String SLASH = "/"; - - public static final String DEFAULT_ALLOW = "defaultallow"; - public static final String DEFAULT_DENY = "defaultdeny"; - - public static final List<String> CONFIG_PROPERTIES = Arrays.asList(DEFAULT_ALLOW, DEFAULT_DENY); - - private static final Integer _increment = 10; - - private final SortedMap<Integer, Rule> _rules = new TreeMap<Integer, Rule>(); - private final Map<Subject, Map<Operation, Map<ObjectType, List<Rule>>>> _cache = - new WeakHashMap<Subject, Map<Operation, Map<ObjectType, List<Rule>>>>(); - private final Map<String, Boolean> _config = new HashMap<String, Boolean>(); - private final EventLoggerProvider _eventLogger; - - public RuleSet(EventLoggerProvider eventLogger) - { - _eventLogger = eventLogger; - // set some default configuration properties - configure(DEFAULT_DENY, Boolean.TRUE); - } - - /** - * Clear the contents, including acl rules and configuration. - */ - public void clear() - { - _rules.clear(); - _cache.clear(); - _config.clear(); - } - - public int getRuleCount() - { - return _rules.size(); - } - - /** - * Filtered rules list based on a subject and operation. - * - * Allows only enabled rules with identity equal to all, the same, or a group with identity as a member, - * and operation is either all or the same operation. - */ - public List<Rule> getRules(final Subject subject, final Operation operation, final ObjectType objectType) - { - final Map<ObjectType, List<Rule>> objects = getObjectToRuleCache(subject, operation); - - // Lookup object type rules for the operation - if (!objects.containsKey(objectType)) - { - final Set<Principal> principals = subject.getPrincipals(); - boolean controlled = false; - List<Rule> filtered = new LinkedList<Rule>(); - for (Rule rule : _rules.values()) - { - final Action ruleAction = rule.getAction(); - if (rule.isEnabled() - && (ruleAction.getOperation() == Operation.ALL || ruleAction.getOperation() == operation) - && (ruleAction.getObjectType() == ObjectType.ALL || ruleAction.getObjectType() == objectType)) - { - controlled = true; - - if (isRelevant(principals,rule)) - { - filtered.add(rule); - } - } - } - - // Return null if there are no rules at all for this operation and object type - if (filtered.isEmpty() && controlled == false) - { - filtered = null; - } - - // Save the rules we selected - objects.put(objectType, filtered); - if(_logger.isDebugEnabled()) - { - _logger.debug("Cached " + objectType + " RulesList: " + filtered); - } - } - - // Return the cached rules - List<Rule> rules = objects.get(objectType); - if(_logger.isDebugEnabled()) - { - _logger.debug("Returning RuleList: " + rules); - } - - return rules; - } - - public boolean isValidNumber(Integer number) - { - return !_rules.containsKey(number); - } - - public void grant(Integer number, String identity, Permission permission, Operation operation) - { - AclAction action = new AclAction(operation); - addRule(number, identity, permission, action); - } - - public void grant(Integer number, String identity, Permission permission, Operation operation, ObjectType object, ObjectProperties properties) - { - AclAction action = new AclAction(operation, object, properties); - addRule(number, identity, permission, action); - } - - public void grant(Integer number, String identity, Permission permission, Operation operation, ObjectType object, AclRulePredicates predicates) - { - AclAction aclAction = new AclAction(operation, object, predicates); - addRule(number, identity, permission, aclAction); - } - - public boolean ruleExists(String identity, AclAction action) - { - for (Rule rule : _rules.values()) - { - if (rule.getIdentity().equals(identity) && rule.getAclAction().equals(action)) - { - return true; - } - } - return false; - } - - public void addRule(Integer number, String identity, Permission permission, AclAction action) - { - - if (!action.isAllowed()) - { - throw new IllegalArgumentException("Action is not allowed: " + action); - } - if (ruleExists(identity, action)) - { - return; - } - - // set rule number if needed - Rule rule = new Rule(number, identity, action, permission); - if (rule.getNumber() == null) - { - if (_rules.isEmpty()) - { - rule.setNumber(0); - } - else - { - rule.setNumber(_rules.lastKey() + _increment); - } - } - - // save rule - _cache.clear(); - _rules.put(rule.getNumber(), rule); - } - - public void enableRule(int ruleNumber) - { - _rules.get(Integer.valueOf(ruleNumber)).enable(); - } - - public void disableRule(int ruleNumber) - { - _rules.get(Integer.valueOf(ruleNumber)).disable(); - } - - /** Return true if the name is well-formed (contains legal characters). */ - protected boolean checkName(String name) - { - for (int i = 0; i < name.length(); i++) - { - Character c = name.charAt(i); - if (!Character.isLetterOrDigit(c) && c != '-' && c != '_' && c != '@' && c != '.' && c != '/') - { - return false; - } - } - return true; - } - - /** Returns true if a username has the name[@domain][/realm] format */ - protected boolean isvalidUserName(String name) - { - // check for '@' and '/' in name - int atPos = name.indexOf(AT); - int slashPos = name.indexOf(SLASH); - boolean atFound = atPos != StringUtils.INDEX_NOT_FOUND && atPos == name.lastIndexOf(AT); - boolean slashFound = slashPos != StringUtils.INDEX_NOT_FOUND && slashPos == name.lastIndexOf(SLASH); - - // must be at least one character after '@' or '/' - if (atFound && atPos > name.length() - 2) - { - return false; - } - if (slashFound && slashPos > name.length() - 2) - { - return false; - } - - // must be at least one character between '@' and '/' - if (atFound && slashFound) - { - return (atPos < (slashPos - 1)); - } - - // otherwise all good - return true; - } - - /** - * Checks for the case when the client's address is not known. - * - * @see #check(Subject, Operation, ObjectType, ObjectProperties, InetAddress) - */ - public Result check(Subject subject, Operation operation, ObjectType objectType, ObjectProperties properties) - { - return check(subject, operation, objectType, properties, null); - } - - /** - * Check the authorisation granted to a particular identity for an operation on an object type with - * specific properties. - * - * Looks up the entire ruleset, which may be cached, for the user and operation and goes through the rules - * in order to find the first one that matches. Either defers if there are no rules, returns the result of - * the first match found, or denies access if there are no matching rules. Normally, it would be expected - * to have a default deny or allow rule at the end of an access configuration however. - */ - public Result check(Subject subject, Operation operation, ObjectType objectType, ObjectProperties properties, InetAddress addressOfClient) - { - ClientAction action = new ClientAction(operation, objectType, properties); - - if(_logger.isDebugEnabled()) - { - _logger.debug("Checking action: " + action); - } - - // get the list of rules relevant for this request - List<Rule> rules = getRules(subject, operation, objectType); - if (rules == null) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("No rules found, returning default result"); - } - return getDefault(); - } - - // Iterate through a filtered set of rules dealing with this identity and operation - for (Rule rule : rules) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("Checking against rule: " + rule); - } - - if (action.matches(rule.getAclAction(), addressOfClient)) - { - Permission permission = rule.getPermission(); - - switch (permission) - { - case ALLOW_LOG: - getEventLogger().message(AccessControlMessages.ALLOWED( - action.getOperation().toString(), - action.getObjectType().toString(), - action.getProperties().toString())); - case ALLOW: - return Result.ALLOWED; - case DENY_LOG: - getEventLogger().message(AccessControlMessages.DENIED( - action.getOperation().toString(), - action.getObjectType().toString(), - action.getProperties().toString())); - case DENY: - return Result.DENIED; - } - - return Result.DENIED; - } - } - - // Defer to the next plugin of this type, if it exists - return Result.DEFER; - } - - /** Default deny. */ - public Result getDefault() - { - if (isSet(DEFAULT_ALLOW)) - { - return Result.ALLOWED; - } - if (isSet(DEFAULT_DENY)) - { - return Result.DENIED; - } - return Result.ABSTAIN; - } - - /** - * Check if a configuration property is set. - */ - protected boolean isSet(String key) - { - return BooleanUtils.isTrue(_config.get(key)); - } - - /** - * Configure properties for the plugin instance. - * - * @param properties - */ - public void configure(Map<String, Boolean> properties) - { - _config.putAll(properties); - } - - /** - * Configure a single property for the plugin instance. - * - * @param key - * @param value - */ - public void configure(String key, Boolean value) - { - _config.put(key, value); - } - - /** - * Returns all rules in the {@link RuleSet}. Primarily intended to support unit-testing. - * @return map of rules - */ - public Map<Integer, Rule> getAllRules() - { - return Collections.unmodifiableMap(_rules); - } - - private boolean isRelevant(final Set<Principal> principals, final Rule rule) - { - if (rule.getIdentity().equalsIgnoreCase(Rule.ALL)) - { - return true; - } - else - { - for (Iterator<Principal> iterator = principals.iterator(); iterator.hasNext();) - { - final Principal principal = iterator.next(); - - if (rule.getIdentity().equalsIgnoreCase(principal.getName())) - { - return true; - } - } - } - - return false; - } - - private Map<ObjectType, List<Rule>> getObjectToRuleCache(final Subject subject, final Operation operation) - { - // Lookup identity in cache and create empty operation map if required - Map<Operation, Map<ObjectType, List<Rule>>> operations = _cache.get(subject); - if (operations == null) - { - operations = new EnumMap<Operation, Map<ObjectType, List<Rule>>>(Operation.class); - _cache.put(subject, operations); - } - - // Lookup operation and create empty object type map if required - Map<ObjectType, List<Rule>> objects = operations.get(operation); - if (objects == null) - { - objects = new EnumMap<ObjectType, List<Rule>>(ObjectType.class); - operations.put(operation, objects); - } - return objects; - } - - public EventLogger getEventLogger() - { - return _eventLogger.getEventLogger(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/AccessControlFirewallException.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/AccessControlFirewallException.java deleted file mode 100644 index d08a052efd..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/AccessControlFirewallException.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.access.firewall; - -public class AccessControlFirewallException extends RuntimeException -{ - /** serialVersionUID */ - private static final long serialVersionUID = 4526157149690917805L; - - public AccessControlFirewallException() - { - super(); - } - - public AccessControlFirewallException(String message) - { - super(message); - } - - public AccessControlFirewallException(String message, Throwable cause) - { - super(message, cause); - } - - public AccessControlFirewallException(Throwable cause) - { - super(cause); - } -}
\ No newline at end of file diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRule.java deleted file mode 100644 index 482a795693..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRule.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.firewall; - -import java.net.InetAddress; - -public interface FirewallRule -{ - boolean matches(InetAddress addressOfClient); -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRuleFactory.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRuleFactory.java deleted file mode 100644 index 64be26c209..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRuleFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.firewall; - -public class FirewallRuleFactory -{ - public FirewallRule createForHostname(String[] hostnames) - { - return new HostnameFirewallRule(hostnames); - } - - public FirewallRule createForNetwork(String[] networks) - { - return new NetworkFirewallRule(networks); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRule.java deleted file mode 100644 index 9d62c44658..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRule.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.firewall; - -import java.net.InetAddress; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.FutureTask; -import java.util.concurrent.TimeUnit; -import java.util.regex.Pattern; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class HostnameFirewallRule implements FirewallRule -{ - private static final Logger _logger = LoggerFactory.getLogger(HostnameFirewallRule.class); - - private static final long DNS_TIMEOUT = 30000; - private static final ExecutorService DNS_LOOKUP = Executors.newCachedThreadPool(); - - private Pattern[] _hostnamePatterns; - private String[] _hostnames; - - public HostnameFirewallRule(String... hostnames) - { - _hostnames = hostnames; - - int i = 0; - _hostnamePatterns = new Pattern[hostnames.length]; - for (String hostname : hostnames) - { - _hostnamePatterns[i++] = Pattern.compile(hostname); - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Created " + this); - } - } - - @Override - public boolean matches(InetAddress remote) - { - String hostname = getHostname(remote); - if (hostname == null) - { - throw new AccessControlFirewallException("DNS lookup failed for address " + remote); - } - for (Pattern pattern : _hostnamePatterns) - { - boolean hostnameMatches = pattern.matcher(hostname).matches(); - - if (hostnameMatches) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("Hostname " + hostname + " matches rule " + pattern.toString()); - } - return true; - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Hostname " + hostname + " matches no configured hostname patterns"); - } - - return false; - } - - - /** - * @param remote - * the InetAddress to look up - * @return the hostname, null if not found, takes longer than - * {@value #DNS_LOOKUP} to find or otherwise fails - */ - private String getHostname(final InetAddress remote) throws AccessControlFirewallException - { - FutureTask<String> lookup = new FutureTask<String>(new Callable<String>() - { - public String call() - { - return remote.getCanonicalHostName(); - } - }); - DNS_LOOKUP.execute(lookup); - - try - { - return lookup.get(DNS_TIMEOUT, TimeUnit.MILLISECONDS); - } - catch (Exception e) - { - _logger.warn("Unable to look up hostname from address " + remote, e); - return null; - } - finally - { - lookup.cancel(true); - } - } - - @Override - public int hashCode() - { - return new HashCodeBuilder().append(_hostnames).toHashCode(); - } - - @Override - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - if (obj == this) - { - return true; - } - if (obj.getClass() != getClass()) - { - return false; - } - HostnameFirewallRule rhs = (HostnameFirewallRule) obj; - return new EqualsBuilder().append(_hostnames, rhs._hostnames).isEquals(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_hostnames).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/InetNetwork.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/InetNetwork.java deleted file mode 100644 index 7294d9c5e8..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/InetNetwork.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.firewall; - -import java.net.InetAddress; - -class InetNetwork -{ - /* - * Implements network masking, and is compatible with RFC 1518 and - * RFC 1519, which describe CIDR: Classless Inter-Domain Routing. - */ - - private InetAddress network; - private InetAddress netmask; - - public InetNetwork(InetAddress ip, InetAddress netmask) - { - this.network = maskIP(ip, netmask); - this.netmask = netmask; - } - - public boolean contains(final String name) throws java.net.UnknownHostException - { - return network.equals(maskIP(InetAddress.getByName(name), netmask)); - } - - public boolean contains(final InetAddress ip) - { - return network.equals(maskIP(ip, netmask)); - } - - @Override - public String toString() - { - return network.getHostAddress() + "/" + netmask.getHostAddress(); - } - - @Override - public int hashCode() - { - return maskIP(network, netmask).hashCode(); - } - - @Override - public boolean equals(Object obj) - { - return (obj != null) && - (obj instanceof InetNetwork) && - ((InetNetwork) obj).network.equals(network) && - ((InetNetwork) obj).netmask.equals(netmask); - } - - public static InetNetwork getFromString(String netspec) throws java.net.UnknownHostException - { - if (netspec.endsWith("*")) - { - netspec = normalizeFromAsterisk(netspec); - } - else - { - int iSlash = netspec.indexOf('/'); - if (iSlash == -1) - { - netspec += "/255.255.255.255"; - } - else if (netspec.indexOf('.', iSlash) == -1) - { - netspec = normalizeFromCIDR(netspec); - } - } - - return new InetNetwork( - InetAddress.getByName(netspec.substring(0, netspec.indexOf('/'))), - InetAddress.getByName(netspec.substring(netspec.indexOf('/') + 1))); - } - - public static InetAddress maskIP(final byte[] ip, final byte[] mask) - { - try - { - return InetAddress.getByAddress(new byte[] - { - (byte) (mask[0] & ip[0]), - (byte) (mask[1] & ip[1]), - (byte) (mask[2] & ip[2]), - (byte) (mask[3] & ip[3]) - }); - } - catch (Exception _) - { - return null; - } - } - - public static InetAddress maskIP(final InetAddress ip, final InetAddress mask) - { - return maskIP(ip.getAddress(), mask.getAddress()); - } - - /* - * This converts from an uncommon "wildcard" CIDR format - * to "address + mask" format: - * - * * => 000.000.000.0/000.000.000.0 - * xxx.* => xxx.000.000.0/255.000.000.0 - * xxx.xxx.* => xxx.xxx.000.0/255.255.000.0 - * xxx.xxx.xxx.* => xxx.xxx.xxx.0/255.255.255.0 - */ - static private String normalizeFromAsterisk(final String netspec) - { - String[] masks = {"0.0.0.0/0.0.0.0", "0.0.0/255.0.0.0", "0.0/255.255.0.0", "0/255.255.255.0"}; - char[] srcb = netspec.toCharArray(); - int octets = 0; - for (int i = 1; i < netspec.length(); i++) - { - if (srcb[i] == '.') - { - octets++; - } - } - return (octets == 0) ? masks[0] : netspec.substring(0, netspec.length() - 1).concat(masks[octets]); - } - - /* - * RFC 1518, 1519 - Classless Inter-Domain Routing (CIDR) - * This converts from "prefix + prefix-length" format to - * "address + mask" format, e.g. from xxx.xxx.xxx.xxx/yy - * to xxx.xxx.xxx.xxx/yyy.yyy.yyy.yyy. - */ - static private String normalizeFromCIDR(final String netspec) - { - final int bits = 32 - Integer.parseInt(netspec.substring(netspec.indexOf('/') + 1)); - final int mask = (bits == 32) ? 0 : 0xFFFFFFFF - ((1 << bits) - 1); - - return netspec.substring(0, netspec.indexOf('/') + 1) + - Integer.toString(mask >> 24 & 0xFF, 10) + "." + - Integer.toString(mask >> 16 & 0xFF, 10) + "." + - Integer.toString(mask >> 8 & 0xFF, 10) + "." + - Integer.toString(mask >> 0 & 0xFF, 10); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRule.java deleted file mode 100644 index 4d635a600e..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRule.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.firewall; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NetworkFirewallRule implements FirewallRule -{ - private static final Logger _logger = LoggerFactory.getLogger(NetworkFirewallRule.class); - - private List<InetNetwork> _networks; - - public NetworkFirewallRule(String... networks) - { - _networks = new ArrayList<InetNetwork>(); - for (int i = 0; i < networks.length; i++) - { - String network = networks[i]; - try - { - InetNetwork inetNetwork = InetNetwork.getFromString(network); - if (!_networks.contains(inetNetwork)) - { - _networks.add(inetNetwork); - } - } - catch (java.net.UnknownHostException uhe) - { - _logger.error("Cannot resolve address: " + network, uhe); - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Created " + this); - } - } - - @Override - public boolean matches(InetAddress ip) - { - for (InetNetwork network : _networks) - { - if (network.contains(ip)) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("Client address " + ip + " matches configured network " + network); - } - return true; - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Client address " + ip + " does not match any configured networks"); - } - - return false; - } - - @Override - public int hashCode() - { - return new HashCodeBuilder().append(_networks).toHashCode(); - } - - @Override - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - if (obj == this) - { - return true; - } - if (obj.getClass() != getClass()) - { - return false; - } - NetworkFirewallRule rhs = (NetworkFirewallRule) obj; - return new EqualsBuilder().append(_networks, rhs._networks).isEquals(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_networks).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProvider.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProvider.java deleted file mode 100644 index 3e0f5b63f0..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProvider.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.access.plugins; - -import org.apache.qpid.server.model.AccessControlProvider; -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.model.ManagedObject; - -@ManagedObject( category = false, type="AclFile" ) -public interface ACLFileAccessControlProvider<X extends ACLFileAccessControlProvider<X>> extends AccessControlProvider<X> -{ - @ManagedAttribute( mandatory = true, description = "File location", oversize = true, oversizedAltText = OVER_SIZED_ATTRIBUTE_ALTERNATIVE_TEXT) - String getPath(); -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImpl.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImpl.java deleted file mode 100644 index 7023a9a03b..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImpl.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.access.plugins; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.SettableFuture; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.AbstractConfiguredObject; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.StateTransition; -import org.apache.qpid.server.security.AccessControl; -import org.apache.qpid.server.util.urlstreamhandler.data.Handler; - -public class ACLFileAccessControlProviderImpl - extends AbstractConfiguredObject<ACLFileAccessControlProviderImpl> - implements ACLFileAccessControlProvider<ACLFileAccessControlProviderImpl> -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ACLFileAccessControlProviderImpl.class); - - static - { - Handler.register(); - } - - protected DefaultAccessControl _accessControl; - protected final Broker _broker; - - @ManagedAttributeField( afterSet = "reloadAclFile") - private String _path; - - @ManagedObjectFactoryConstructor - public ACLFileAccessControlProviderImpl(Map<String, Object> attributes, Broker broker) - { - super(parentsMap(broker), attributes); - - - _broker = broker; - - } - - @Override - public void onValidate() - { - super.onValidate(); - if(!isDurable()) - { - throw new IllegalArgumentException(getClass().getSimpleName() + " must be durable"); - } - } - - @Override - protected void validateChange(final ConfiguredObject<?> proxyForValidation, final Set<String> changedAttributes) - { - super.validateChange(proxyForValidation, changedAttributes); - if(changedAttributes.contains(DURABLE) && !proxyForValidation.isDurable()) - { - throw new IllegalArgumentException(getClass().getSimpleName() + " must be durable"); - } - } - - @Override - protected void validateOnCreate() - { - DefaultAccessControl accessControl = null; - try - { - accessControl = new DefaultAccessControl(getPath(), _broker); - accessControl.validate(); - accessControl.open(); - } - catch(RuntimeException e) - { - throw new IllegalConfigurationException(e.getMessage(), e); - } - finally - { - if (accessControl != null) - { - accessControl.close(); - } - } - } - - @Override - protected void onOpen() - { - super.onOpen(); - _accessControl = new DefaultAccessControl(getPath(), _broker); - } - - @SuppressWarnings("unused") - private void reloadAclFile() - { - try - { - DefaultAccessControl accessControl = new DefaultAccessControl(getPath(), _broker); - accessControl.open(); - DefaultAccessControl oldAccessControl = _accessControl; - _accessControl = accessControl; - if(oldAccessControl != null) - { - oldAccessControl.close(); - } - } - catch(RuntimeException e) - { - throw new IllegalConfigurationException(e.getMessage(), e); - } - } - - @Override - public String getPath() - { - return _path; - } - - @Override - public <C extends ConfiguredObject> Collection<C> getChildren(Class<C> clazz) - { - return Collections.emptySet(); - } - - - @StateTransition(currentState = {State.UNINITIALIZED, State.QUIESCED, State.ERRORED}, desiredState = State.ACTIVE) - private ListenableFuture<Void> activate() - { - - if(_broker.isManagementMode()) - { - - setState(_accessControl.validate() ? State.QUIESCED : State.ERRORED); - } - else - { - try - { - _accessControl.open(); - setState(State.ACTIVE); - } - catch (RuntimeException e) - { - setState(State.ERRORED); - if (_broker.isManagementMode()) - { - LOGGER.warn("Failed to activate ACL provider: " + getName(), e); - } - else - { - throw e; - } - } - } - return Futures.immediateFuture(null); - } - - @Override - protected void onClose() - { - super.onClose(); - if (_accessControl != null) - { - _accessControl.close(); - } - } - - @StateTransition(currentState = State.UNINITIALIZED, desiredState = State.QUIESCED) - private ListenableFuture<Void> startQuiesced() - { - setState(State.QUIESCED); - return Futures.immediateFuture(null); - } - - @StateTransition(currentState = {State.ACTIVE, State.QUIESCED, State.ERRORED}, desiredState = State.DELETED) - private ListenableFuture<Void> doDelete() - { - final SettableFuture<Void> returnVal = SettableFuture.create(); - closeAsync().addListener( - new Runnable() - { - @Override - public void run() - { - try - { - - setState(State.DELETED); - deleted(); - } - finally - { - returnVal.set(null); - } - } - }, getTaskExecutor().getExecutor() - ); - return returnVal; - } - - public AccessControl getAccessControl() - { - return _accessControl; - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControl.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControl.java deleted file mode 100644 index 8533166023..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControl.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.access.plugins; - -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.SocketAddress; -import java.net.URL; -import java.security.AccessController; -import java.util.Set; - -import javax.security.auth.Subject; - -import org.apache.commons.lang.ObjectUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.security.AccessControl; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.config.ConfigurationFile; -import org.apache.qpid.server.security.access.config.PlainConfiguration; -import org.apache.qpid.server.security.access.config.RuleSet; - -public class DefaultAccessControl implements AccessControl -{ - private static final Logger _logger = LoggerFactory.getLogger(DefaultAccessControl.class); - private final String _fileName; - - private RuleSet _ruleSet; - private final EventLoggerProvider _eventLogger; - - public DefaultAccessControl(String name, final EventLoggerProvider eventLogger) - { - _fileName = name; - _eventLogger = eventLogger; - if (_logger.isDebugEnabled()) - { - _logger.debug("Creating AccessControl instance"); - } - } - - DefaultAccessControl(RuleSet rs) - { - _fileName = null; - _ruleSet = rs; - _eventLogger = rs; - } - - public void open() - { - if(_fileName != null) - { - ConfigurationFile configFile = new PlainConfiguration(_fileName, _eventLogger); - _ruleSet = configFile.load(getReaderFromURLString(_fileName)); - } - } - - @Override - public boolean validate() - { - try - { - getReaderFromURLString(_fileName); - return true; - } - catch(IllegalConfigurationException e) - { - return false; - } - } - - - private static Reader getReaderFromURLString(String urlString) - { - try - { - URL url; - - try - { - url = new URL(urlString); - } - catch (MalformedURLException e) - { - File file = new File(urlString); - try - { - url = file.toURI().toURL(); - } - catch (MalformedURLException notAFile) - { - throw new IllegalConfigurationException("Cannot convert " + urlString + " to a readable resource"); - } - - } - return new InputStreamReader(url.openStream()); - } - catch (IOException e) - { - throw new IllegalConfigurationException("Cannot convert " + urlString + " to a readable resource"); - } - } - - @Override - public void close() - { - //no-op - } - - @Override - public void onDelete() - { - //no-op - } - - @Override - public void onCreate() - { - if(_fileName != null) - { - //verify it is parsable - new PlainConfiguration(_fileName, _eventLogger).load(getReaderFromURLString(_fileName)); - } - } - - public Result getDefault() - { - return _ruleSet.getDefault(); - } - - /** - * Check if an operation is authorised by asking the configuration object about the access - * control rules granted to the current thread's {@link Subject}. If there is no current - * user the plugin will abstain. - */ - public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties) - { - InetAddress addressOfClient = null; - final Subject subject = Subject.getSubject(AccessController.getContext()); - - // Abstain if there is no subject/principal associated with this thread - if (subject == null || subject.getPrincipals().size() == 0) - { - return Result.ABSTAIN; - } - - Set<ConnectionPrincipal> principals = subject.getPrincipals(ConnectionPrincipal.class); - if(!principals.isEmpty()) - { - SocketAddress address = principals.iterator().next().getConnection().getRemoteAddress(); - if(address instanceof InetSocketAddress) - { - addressOfClient = ((InetSocketAddress) address).getAddress(); - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Checking " + operation + " " + objectType + " " + ObjectUtils.defaultIfNull(addressOfClient, "")); - } - - try - { - return _ruleSet.check(subject, operation, objectType, properties, addressOfClient); - } - catch(Exception e) - { - _logger.error("Unable to check " + operation + " " + objectType + " " + ObjectUtils.defaultIfNull(addressOfClient, ""), e); - return Result.DENIED; - } - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/resources/acl.xsd b/qpid/java/broker-plugins/access-control/src/main/resources/acl.xsd deleted file mode 100644 index 9a165b50b8..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/resources/acl.xsd +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<xs:schema - xmlns="http://qpid.apache.org/schema/qpid/broker/security/acl.xsd" - xmlns:xs="http://www.w3.org/2001/XMLSchema" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - targetNamespace="http://qpid.apache.org/schema/qpid/broker/security/acl.xsd" - elementFormDefault="qualified"> - <xs:element name="aclv2" type="xs:string" /> -</xs:schema> diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclActionTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclActionTest.java deleted file mode 100644 index 14620cff70..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclActionTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.config; - -import static org.mockito.Mockito.*; - -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.firewall.FirewallRule; - -import junit.framework.TestCase; - -public class AclActionTest extends TestCase -{ - public void testEqualsAndHashCode() - { - AclRulePredicates predicates = createAclRulePredicates(); - ObjectType objectType = ObjectType.EXCHANGE; - Operation operation = Operation.ACCESS; - - AclAction aclAction = new AclAction(operation, objectType, predicates); - AclAction equalAclAction = new AclAction(operation, objectType, predicates); - - assertTrue(aclAction.equals(aclAction)); - assertTrue(aclAction.equals(equalAclAction)); - assertTrue(equalAclAction.equals(aclAction)); - - assertTrue(aclAction.hashCode() == equalAclAction.hashCode()); - - assertFalse("Different operation should cause aclActions to be unequal", - aclAction.equals(new AclAction(Operation.BIND, objectType, predicates))); - - assertFalse("Different operation type should cause aclActions to be unequal", - aclAction.equals(new AclAction(operation, ObjectType.GROUP, predicates))); - - assertFalse("Different predicates should cause aclActions to be unequal", - aclAction.equals(new AclAction(operation, objectType, createAclRulePredicates()))); - - } - - private AclRulePredicates createAclRulePredicates() - { - AclRulePredicates predicates = mock(AclRulePredicates.class); - when(predicates.getFirewallRule()).thenReturn(mock(FirewallRule.class)); - when(predicates.getObjectProperties()).thenReturn(mock(ObjectProperties.class)); - return predicates; - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclRulePredicatesTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclRulePredicatesTest.java deleted file mode 100644 index 93b765d0fb..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclRulePredicatesTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.config; - -import static org.apache.qpid.server.security.access.ObjectProperties.Property.*; - -import org.apache.qpid.server.security.access.firewall.FirewallRule; -import org.apache.qpid.server.security.access.firewall.FirewallRuleFactory; - -import static org.mockito.Mockito.*; - -import junit.framework.TestCase; - -public class AclRulePredicatesTest extends TestCase -{ - private AclRulePredicates _aclRulePredicates = new AclRulePredicates(); - private FirewallRuleFactory _firewallRuleFactory = mock(FirewallRuleFactory.class); - - @Override - protected void setUp() throws Exception - { - _aclRulePredicates.setFirewallRuleFactory(_firewallRuleFactory); - - when(_firewallRuleFactory.createForHostname((String[]) any())).thenReturn(mock(FirewallRule.class)); - when(_firewallRuleFactory.createForNetwork((String[]) any())).thenReturn(mock(FirewallRule.class)); - } - - public void testParse() - { - String name = "name"; - String className = "class"; - - _aclRulePredicates.parse(NAME.name(), name); - _aclRulePredicates.parse(CLASS.name(), className); - - assertEquals(name, _aclRulePredicates.getObjectProperties().get(NAME)); - assertEquals(className, _aclRulePredicates.getObjectProperties().get(CLASS)); - } - - public void testParseHostnameFirewallRule() - { - String hostname = "hostname1,hostname2"; - _aclRulePredicates.parse(FROM_HOSTNAME.name(), hostname); - - verify(_firewallRuleFactory).createForHostname(new String[] {"hostname1", "hostname2"}); - } - - public void testParseNetworkFirewallRule() - { - _aclRulePredicates.setFirewallRuleFactory(_firewallRuleFactory); - - String networks = "network1,network2"; - _aclRulePredicates.parse(FROM_NETWORK.name(), networks); - - verify(_firewallRuleFactory).createForNetwork(new String[] {"network1", "network2"}); - } - - public void testParseThrowsExceptionIfBothHostnameAndNetworkSpecified() - { - _aclRulePredicates.parse(FROM_NETWORK.name(), "network1,network2"); - try - { - _aclRulePredicates.parse(FROM_HOSTNAME.name(), "hostname1,hostname2"); - fail("Exception not thrown"); - } - catch(IllegalStateException e) - { - // pass - } - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ActionTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ActionTest.java deleted file mode 100644 index 00e06106bf..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ActionTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.config; - -import static org.mockito.Mockito.*; - -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; - -import junit.framework.TestCase; - -public class ActionTest extends TestCase -{ - private ObjectProperties _properties1 = mock(ObjectProperties.class); - private ObjectProperties _properties2 = mock(ObjectProperties.class); - - public void testMatchesReturnsTrueForMatchingActions() - { - when(_properties1.matches(_properties2)).thenReturn(true); - - assertMatches( - new Action(Operation.CONSUME, ObjectType.QUEUE, _properties1), - new Action(Operation.CONSUME, ObjectType.QUEUE, _properties2)); - } - - public void testMatchesReturnsFalseWhenOperationsDiffer() - { - assertDoesntMatch( - new Action(Operation.CONSUME, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1)); - } - - public void testMatchesReturnsFalseWhenOperationTypesDiffer() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.EXCHANGE, _properties1)); - } - - public void testMatchesReturnsFalseWhenOperationPropertiesDiffer() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.QUEUE, _properties2)); - } - - public void testMatchesReturnsFalseWhenMyOperationPropertiesIsNull() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null), - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1)); - } - - public void testMatchesReturnsFalseWhenOtherOperationPropertiesIsNull() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null)); - } - - public void testMatchesReturnsTrueWhenBothOperationPropertiesAreNull() - { - assertMatches( - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null), - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null)); - } - - private void assertMatches(Action action1, Action action2) - { - assertTrue(action1 + " should match " + action2, action1.matches(action2)); - } - - private void assertDoesntMatch(Action action1, Action action2) - { - assertFalse(action1 + " should not match " + action2, action1.matches(action2)); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ClientActionTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ClientActionTest.java deleted file mode 100644 index ae5d3fda74..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ClientActionTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.config; - -import static org.mockito.Mockito.*; - -import java.net.InetAddress; - -import org.apache.qpid.server.security.access.firewall.FirewallRule; - -import junit.framework.TestCase; - -public class ClientActionTest extends TestCase -{ - private Action _action = mock(Action.class); - private AclAction _ruleAction = mock(AclAction.class); - private InetAddress _addressOfClient = mock(InetAddress.class); - - private ClientAction _clientAction = new ClientAction(_action); - - public void testMatches_returnsTrueWhenActionsMatchAndNoFirewallRule() - { - when(_action.matches(any(Action.class))).thenReturn(true); - when(_ruleAction.getFirewallRule()).thenReturn(null); - - assertTrue(_clientAction.matches(_ruleAction, _addressOfClient)); - } - - public void testMatches_returnsFalseWhenActionsDontMatch() - { - FirewallRule firewallRule = mock(FirewallRule.class); - when(firewallRule.matches(_addressOfClient)).thenReturn(true); - - when(_action.matches(any(Action.class))).thenReturn(false); - when(_ruleAction.getFirewallRule()).thenReturn(firewallRule); - - assertFalse(_clientAction.matches(_ruleAction, _addressOfClient)); - } - - public void testMatches_returnsTrueWhenActionsAndFirewallRuleMatch() - { - FirewallRule firewallRule = mock(FirewallRule.class); - when(firewallRule.matches(_addressOfClient)).thenReturn(true); - - when(_action.matches(any(Action.class))).thenReturn(true); - when(_ruleAction.getFirewallRule()).thenReturn(firewallRule); - - assertTrue(_clientAction.matches(_ruleAction, _addressOfClient)); - } - - public void testMatches_ignoresFirewallRuleIfClientAddressIsNull() - { - FirewallRule firewallRule = mock(FirewallRule.class); - - when(_action.matches(any(Action.class))).thenReturn(true); - when(_ruleAction.getFirewallRule()).thenReturn(firewallRule); - - assertTrue(_clientAction.matches(_ruleAction, null)); - - verifyZeroInteractions(firewallRule); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/PlainConfigurationTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/PlainConfigurationTest.java deleted file mode 100644 index 76435cbae4..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/PlainConfigurationTest.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.config; - -import static org.mockito.Mockito.mock; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.PrintWriter; -import java.util.Map; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectProperties.Property; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; - -public class PlainConfigurationTest extends TestCase -{ - private PlainConfiguration writeACLConfig(String...aclData) throws Exception - { - File acl = File.createTempFile(getClass().getName() + getName(), "acl"); - acl.deleteOnExit(); - - // Write ACL file - PrintWriter aclWriter = new PrintWriter(new FileWriter(acl)); - for (String line : aclData) - { - aclWriter.println(line); - } - aclWriter.close(); - - // Load ruleset - PlainConfiguration configFile = new PlainConfiguration(acl.getName(), mock(EventLoggerProvider.class)); - configFile.load(new FileReader(acl)); - return configFile; - } - - public void testACLFileSyntaxContinuation() throws Exception - { - try - { - writeACLConfig("ACL ALLOW ALL \\ ALL"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.PREMATURE_CONTINUATION_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxTokens() throws Exception - { - try - { - writeACLConfig("ACL unparsed ALL ALL"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.PARSE_TOKEN_FAILED_MSG, 1), ce.getMessage()); - assertTrue(ce.getCause() instanceof IllegalArgumentException); - assertEquals("Not a valid permission: unparsed", ce.getCause().getMessage()); - } - } - - public void testACLFileSyntaxNotEnoughACL() throws Exception - { - try - { - writeACLConfig("ACL ALLOW"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_ACL_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxNotEnoughConfig() throws Exception - { - try - { - writeACLConfig("CONFIG"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_TOKENS_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxNotEnough() throws Exception - { - try - { - writeACLConfig("INVALID"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_TOKENS_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxPropertyKeyOnly() throws Exception - { - try - { - writeACLConfig("ACL ALLOW adk CREATE QUEUE name"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.PROPERTY_KEY_ONLY_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxPropertyNoEquals() throws Exception - { - try - { - writeACLConfig("ACL ALLOW adk CREATE QUEUE name test"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.PROPERTY_NO_EQUALS_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxPropertyNoValue() throws Exception - { - try - { - writeACLConfig("ACL ALLOW adk CREATE QUEUE name ="); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.PROPERTY_NO_VALUE_MSG, 1), ce.getMessage()); - } - } - - /** - * Tests interpretation of an acl rule with no object properties. - * - */ - public void testValidRule() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL DENY-LOG user1 ACCESS VIRTUALHOST"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with object properties quoted in single quotes. - */ - public void testValidRuleWithSingleQuotedProperty() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW all CREATE EXCHANGE name = \'value\'"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "all", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.CREATE, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties(); - expectedProperties.setName("value"); - assertEquals("Rule has unexpected object properties", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with object properties quoted in double quotes. - */ - public void testValidRuleWithDoubleQuotedProperty() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW all CREATE EXCHANGE name = \"value\""); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "all", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.CREATE, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties(); - expectedProperties.setName("value"); - assertEquals("Rule has unexpected object properties", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with many object properties. - */ - public void testValidRuleWithManyProperties() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW admin DELETE QUEUE name=name1 owner = owner1"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "admin", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.DELETE, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.QUEUE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties(); - expectedProperties.setName("name1"); - expectedProperties.put(Property.OWNER, "owner1"); - assertEquals("Rule has unexpected operation", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with object properties containing wildcards. Values containing - * hashes must be quoted otherwise they are interpreted as comments. - */ - public void testValidRuleWithWildcardProperties() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW all CREATE EXCHANGE routingKey = \'news.#\'", - "ACL ALLOW all CREATE EXCHANGE routingKey = \'news.co.#\'", - "ACL ALLOW all CREATE EXCHANGE routingKey = *.co.medellin"); - final RuleSet rs = config.getConfiguration(); - assertEquals(3, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(3, rules.size()); - final Rule rule1 = rules.get(0); - assertEquals("Rule has unexpected identity", "all", rule1.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.CREATE, rule1.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule1.getAction().getObjectType()); - final ObjectProperties expectedProperties1 = new ObjectProperties(); - expectedProperties1.put(Property.ROUTING_KEY,"news.#"); - assertEquals("Rule has unexpected object properties", expectedProperties1, rule1.getAction().getProperties()); - - final Rule rule2 = rules.get(10); - final ObjectProperties expectedProperties2 = new ObjectProperties(); - expectedProperties2.put(Property.ROUTING_KEY,"news.co.#"); - assertEquals("Rule has unexpected object properties", expectedProperties2, rule2.getAction().getProperties()); - - final Rule rule3 = rules.get(20); - final ObjectProperties expectedProperties3 = new ObjectProperties(); - expectedProperties3.put(Property.ROUTING_KEY,"*.co.medellin"); - assertEquals("Rule has unexpected object properties", expectedProperties3, rule3.getAction().getProperties()); - } - - /** - * Tests that rules are case insignificant. - */ - public void testMixedCaseRuleInterpretation() throws Exception - { - final PlainConfiguration config = writeACLConfig("AcL deny-LOG User1 BiND Exchange Name=AmQ.dIrect"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "User1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.BIND, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties("AmQ.dIrect"); - assertEquals("Rule has unexpected object properties", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests whitespace is supported. Note that currently the Java implementation permits comments to - * be introduced anywhere in the ACL, whereas the C++ supports only whitespace at the beginning of - * of line. - */ - public void testCommentsSupported() throws Exception - { - final PlainConfiguration config = writeACLConfig("#Comment", - "ACL DENY-LOG user1 ACCESS VIRTUALHOST # another comment", - " # final comment with leading whitespace"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule using mixtures of tabs/spaces as token separators. - * - */ - public void testWhitespace() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL\tDENY-LOG\t\t user1\t \tACCESS VIRTUALHOST"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl utilising line continuation. - */ - public void testLineContinuation() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL DENY-LOG user1 \\", - "ACCESS VIRTUALHOST"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - public void testUserRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 CREATE USER"), - "user1", Operation.CREATE, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 CREATE USER name=\"otherUser\""), - "user1", Operation.CREATE, ObjectType.USER, new ObjectProperties("otherUser")); - - validateRule(writeACLConfig("ACL ALLOW user1 DELETE USER"), - "user1", Operation.DELETE, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 DELETE USER name=\"otherUser\""), - "user1", Operation.DELETE, ObjectType.USER, new ObjectProperties("otherUser")); - - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE USER"), - "user1", Operation.UPDATE, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE USER name=\"otherUser\""), - "user1", Operation.UPDATE, ObjectType.USER, new ObjectProperties("otherUser")); - - validateRule(writeACLConfig("ACL ALLOW user1 ALL USER"), - "user1", Operation.ALL, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 ALL USER name=\"otherUser\""), - "user1", Operation.ALL, ObjectType.USER, new ObjectProperties("otherUser")); - } - - public void testGroupRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 CREATE GROUP"), - "user1", Operation.CREATE, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 CREATE GROUP name=\"groupName\""), - "user1", Operation.CREATE, ObjectType.GROUP, new ObjectProperties("groupName")); - - validateRule(writeACLConfig("ACL ALLOW user1 DELETE GROUP"), - "user1", Operation.DELETE, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 DELETE GROUP name=\"groupName\""), - "user1", Operation.DELETE, ObjectType.GROUP, new ObjectProperties("groupName")); - - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE GROUP"), - "user1", Operation.UPDATE, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE GROUP name=\"groupName\""), - "user1", Operation.UPDATE, ObjectType.GROUP, new ObjectProperties("groupName")); - - validateRule(writeACLConfig("ACL ALLOW user1 ALL GROUP"), - "user1", Operation.ALL, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 ALL GROUP name=\"groupName\""), - "user1", Operation.ALL, ObjectType.GROUP, new ObjectProperties("groupName")); - } - - /** explicitly test for exception indicating that this functionality has been moved to Group Providers */ - public void testGroupDefinitionThrowsException() throws Exception - { - try - { - writeACLConfig("GROUP group1 bob alice"); - fail("Expected exception not thrown"); - } - catch(IllegalConfigurationException e) - { - assertTrue(e.getMessage().contains("GROUP keyword not supported")); - } - } - - public void testManagementRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 ALL MANAGEMENT"), - "user1", Operation.ALL, ObjectType.MANAGEMENT, ObjectProperties.EMPTY); - - validateRule(writeACLConfig("ACL ALLOW user1 ACCESS MANAGEMENT"), - "user1", Operation.ACCESS, ObjectType.MANAGEMENT, ObjectProperties.EMPTY); - } - - public void testBrokerRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 CONFIGURE BROKER"), "user1", Operation.CONFIGURE, ObjectType.BROKER, - ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 ALL BROKER"), "user1", Operation.ALL, ObjectType.BROKER, ObjectProperties.EMPTY); - } - - private void validateRule(final PlainConfiguration config, String username, Operation operation, ObjectType objectType, ObjectProperties objectProperties) - { - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map<Integer, Rule> rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", username, rule.getIdentity()); - assertEquals("Rule has unexpected operation", operation, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", objectType, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", objectProperties, rule.getAction().getProperties()); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/RuleTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/RuleTest.java deleted file mode 100644 index 2ae7759679..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/RuleTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.config; - -import static org.mockito.Mockito.*; - -import org.apache.qpid.server.security.access.Permission; - -import junit.framework.TestCase; - -public class RuleTest extends TestCase -{ - public void testEqualsAndHashCode() - { - AclAction aclAction = mock(AclAction.class); - String identity = "identity"; - Permission allow = Permission.ALLOW; - - Rule rule = new Rule(identity, aclAction, allow); - Rule equalRule = new Rule(identity, aclAction, allow); - - assertTrue(rule.equals(rule)); - assertTrue(rule.equals(equalRule)); - assertTrue(equalRule.equals(rule)); - - assertTrue(rule.hashCode() == equalRule.hashCode()); - - assertFalse("Different identity should cause rules to be unequal", - rule.equals(new Rule("identity2", aclAction, allow))); - - assertFalse("Different action should cause rules to be unequal", - rule.equals(new Rule(identity, mock(AclAction.class), allow))); - - assertFalse("Different permission should cause rules to be unequal", - rule.equals(new Rule(identity, aclAction, Permission.DENY))); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRuleTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRuleTest.java deleted file mode 100644 index d2beebfb0f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRuleTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.firewall; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.net.InetAddress; - -import org.apache.qpid.server.security.access.firewall.HostnameFirewallRule; - -import junit.framework.TestCase; - -public class HostnameFirewallRuleTest extends TestCase -{ - private InetAddress _addressNotInRule; - - private HostnameFirewallRule _HostnameFirewallRule; - - @Override - protected void setUp() throws Exception - { - _addressNotInRule = InetAddress.getByName("127.0.0.1"); - } - - public void testSingleHostname() throws Exception - { - String hostnameInRule = "hostnameInRule"; - InetAddress addressWithMatchingHostname = mock(InetAddress.class); - when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn(hostnameInRule); - - _HostnameFirewallRule = new HostnameFirewallRule(hostnameInRule); - - assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); - assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); - } - - public void testSingleHostnameWildcard() throws Exception - { - String hostnameInRule = ".*FOO.*"; - InetAddress addressWithMatchingHostname = mock(InetAddress.class); - when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn("xxFOOxx"); - - _HostnameFirewallRule = new HostnameFirewallRule(hostnameInRule); - - assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); - assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); - } - - public void testMultipleHostnames() throws Exception - { - String[] hostnamesInRule = new String[] {"hostnameInRule1", "hostnameInRule2"}; - - _HostnameFirewallRule = new HostnameFirewallRule(hostnamesInRule); - - assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); - for (String hostnameInRule : hostnamesInRule) - { - InetAddress addressWithMatchingHostname = mock(InetAddress.class); - when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn(hostnameInRule); - - assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); - } - } - - public void testEqualsAndHashCode() - { - String hostname1 = "hostname1"; - String hostname2 = "hostname2"; - - HostnameFirewallRule rule = new HostnameFirewallRule(hostname1, hostname2); - HostnameFirewallRule equalRule = new HostnameFirewallRule(hostname1, hostname2); - - assertTrue(rule.equals(rule)); - assertTrue(rule.equals(equalRule)); - assertTrue(equalRule.equals(rule)); - - assertTrue(rule.hashCode() == equalRule.hashCode()); - - assertFalse("Different hostnames should cause rules to be unequal", - rule.equals(new HostnameFirewallRule(hostname1, "different-hostname"))); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRuleTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRuleTest.java deleted file mode 100644 index e521039db2..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRuleTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.security.access.firewall; - -import java.net.InetAddress; - -import org.apache.qpid.server.security.access.firewall.NetworkFirewallRule; - -import junit.framework.TestCase; - -public class NetworkFirewallRuleTest extends TestCase -{ - private static final String LOCALHOST_IP = "127.0.0.1"; - private static final String OTHER_IP_1 = "192.168.23.1"; - private static final String OTHER_IP_2 = "192.168.23.2"; - - private InetAddress _addressNotInRule; - - private NetworkFirewallRule _networkFirewallRule; - - @Override - protected void setUp() throws Exception - { - _addressNotInRule = InetAddress.getByName(LOCALHOST_IP); - } - - public void testIpRule() throws Exception - { - String ipAddressInRule = OTHER_IP_1; - - _networkFirewallRule = new NetworkFirewallRule(ipAddressInRule); - - assertFalse(_networkFirewallRule.matches(_addressNotInRule)); - assertTrue(_networkFirewallRule.matches(InetAddress.getByName(ipAddressInRule))); - } - - public void testNetMask() throws Exception - { - String ipAddressInRule = "192.168.23.0/24"; - _networkFirewallRule = new NetworkFirewallRule(ipAddressInRule); - - assertFalse(_networkFirewallRule.matches(InetAddress.getByName("192.168.24.1"))); - assertTrue(_networkFirewallRule.matches(InetAddress.getByName("192.168.23.0"))); - assertTrue(_networkFirewallRule.matches(InetAddress.getByName("192.168.23.255"))); - } - - public void testWildcard() throws Exception - { - // Test xxx.xxx.* - - assertFalse(new NetworkFirewallRule("192.168.*") - .matches(InetAddress.getByName("192.169.1.0"))); - - assertTrue(new NetworkFirewallRule("192.168.*") - .matches(InetAddress.getByName("192.168.1.0"))); - - assertTrue(new NetworkFirewallRule("192.168.*") - .matches(InetAddress.getByName("192.168.255.255"))); - - // Test xxx.xxx.xxx.* - - assertFalse(new NetworkFirewallRule("192.168.1.*") - .matches(InetAddress.getByName("192.169.2.0"))); - - assertTrue(new NetworkFirewallRule("192.168.1.*") - .matches(InetAddress.getByName("192.168.1.0"))); - - assertTrue(new NetworkFirewallRule("192.168.1.*") - .matches(InetAddress.getByName("192.168.1.255"))); - } - - public void testMultipleNetworks() throws Exception - { - String[] ipAddressesInRule = new String[] {OTHER_IP_1, OTHER_IP_2}; - - _networkFirewallRule = new NetworkFirewallRule(ipAddressesInRule); - - assertFalse(_networkFirewallRule.matches(_addressNotInRule)); - for (String ipAddressInRule : ipAddressesInRule) - { - assertTrue(_networkFirewallRule.matches(InetAddress.getByName(ipAddressInRule))); - } - } - - public void testEqualsAndHashCode() - { - NetworkFirewallRule rule = new NetworkFirewallRule(LOCALHOST_IP, OTHER_IP_1); - NetworkFirewallRule equalRule = new NetworkFirewallRule(LOCALHOST_IP, OTHER_IP_1); - - assertTrue(rule.equals(rule)); - assertTrue(rule.equals(equalRule)); - assertTrue(equalRule.equals(rule)); - - assertTrue(rule.hashCode() == equalRule.hashCode()); - - assertFalse("Different networks should cause rules to be unequal", - rule.equals(new NetworkFirewallRule(LOCALHOST_IP, OTHER_IP_2))); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderFactoryTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderFactoryTest.java deleted file mode 100644 index c51ea64d9c..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderFactoryTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.access.plugins; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.regex.Pattern; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.model.AccessControlProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.ConfiguredObjectFactoryImpl; -import org.apache.qpid.server.security.access.FileAccessControlProviderConstants; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; - -public class ACLFileAccessControlProviderFactoryTest extends QpidTestCase -{ - private Broker _broker; - private ConfiguredObjectFactoryImpl _objectFactory; - - @Override - public void setUp() throws Exception - { - super.setUp(); - _broker = mock(Broker.class); - _objectFactory = new ConfiguredObjectFactoryImpl(BrokerModel.getInstance()); - - when(_broker.getObjectFactory()).thenReturn(_objectFactory); - when(_broker.getModel()).thenReturn(_objectFactory.getModel()); - when(_broker.getCategoryClass()).thenReturn(Broker.class); - TaskExecutor taskExecutor = new CurrentThreadTaskExecutor(); - taskExecutor.start(); - when(_broker.getTaskExecutor()).thenReturn(taskExecutor); - when(_broker.getChildExecutor()).thenReturn(taskExecutor); - - } - - public void testCreateInstanceWhenAclFileIsNotPresent() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(AccessControlProvider.ID, UUID.randomUUID()); - attributes.put(AccessControlProvider.NAME, "acl"); - attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); - - try - { - AccessControlProvider acl = _objectFactory.create(AccessControlProvider.class, attributes, _broker); - fail("ACL was created without a configuration file path specified"); - } - catch(IllegalArgumentException e) - { - // pass - } - } - - - public void testCreateInstanceWhenAclFileIsSpecified() - { - File aclFile = TestFileUtils.createTempFile(this, ".acl", "ACL ALLOW all all"); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(AccessControlProvider.ID, UUID.randomUUID()); - attributes.put(AccessControlProvider.NAME, "acl"); - attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); - attributes.put(FileAccessControlProviderConstants.PATH, aclFile.getAbsolutePath()); - AccessControlProvider acl = _objectFactory.create(AccessControlProvider.class, attributes, _broker); - acl.getAccessControl().open(); - - assertNotNull("ACL was not created from acl file: " + aclFile.getAbsolutePath(), acl); - } - - public void testCreateInstanceWhenAclFileIsSpecifiedButDoesNotExist() - { - File aclFile = new File(TMP_FOLDER, "my-non-existing-acl-" + System.currentTimeMillis()); - assertFalse("ACL file " + aclFile.getAbsolutePath() + " actually exists but should not", aclFile.exists()); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(AccessControlProvider.ID, UUID.randomUUID()); - attributes.put(AccessControlProvider.NAME, "acl"); - attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); - attributes.put(FileAccessControlProviderConstants.PATH, aclFile.getAbsolutePath()); - try - { - AccessControlProvider control = _objectFactory.create(AccessControlProvider.class, attributes, _broker); - control.getAccessControl().open(); - fail("It should not be possible to create and initialise ACL with non existing file"); - } - catch (IllegalConfigurationException e) - { - assertTrue("Unexpected exception message: " + e.getMessage(), Pattern.matches("Cannot convert .* to a readable resource", e.getMessage())); - } - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImplTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImplTest.java deleted file mode 100644 index abe8c6fd9f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImplTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.security.access.plugins; - - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.Model; -import org.apache.qpid.test.utils.QpidTestCase; - -public class ACLFileAccessControlProviderImplTest extends QpidTestCase -{ - private TaskExecutor _taskExecutor; - private Model _model; - private Broker _broker; - - public void setUp() throws Exception - { - super.setUp(); - _taskExecutor = CurrentThreadTaskExecutor.newStartedInstance(); - _model = BrokerModel.getInstance(); - - _broker = mock(Broker.class); - when(_broker.getTaskExecutor()).thenReturn(_taskExecutor); - when(_broker.getChildExecutor()).thenReturn(_taskExecutor); - when(_broker.getModel()).thenReturn(_model); - when(_broker.getId()).thenReturn(UUID.randomUUID()); - } - - public void testValidationOnCreateWithNonExistingACLFile() - { - Map<String,Object> attributes = new HashMap<>(); - String aclFilePath = new File(TMP_FOLDER, "test_" + getTestName() + System.nanoTime() + ".acl").getAbsolutePath(); - - attributes.put("path", aclFilePath); - attributes.put(ACLFileAccessControlProvider.NAME, getTestName()); - - - ACLFileAccessControlProviderImpl aclProvider = new ACLFileAccessControlProviderImpl(attributes, _broker); - try - { - aclProvider.create(); - fail("Exception is expected on validation with non-existing ACL file"); - } - catch (IllegalConfigurationException e) - { - assertEquals("Unexpected exception message:" + e.getMessage(), String.format("Cannot convert %s to a readable resource", aclFilePath ), e.getMessage()); - } - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControlTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControlTest.java deleted file mode 100644 index 072bd6a87f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControlTest.java +++ /dev/null @@ -1,471 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.access.plugins; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; - -import javax.security.auth.Subject; - -import junit.framework.TestCase; - -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.logging.UnitTestMessageLogger; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.Permission; -import org.apache.qpid.server.security.access.config.Rule; -import org.apache.qpid.server.security.access.config.RuleSet; -import org.apache.qpid.server.security.auth.TestPrincipalUtils; - -/** - * In these tests, the ruleset is configured programmatically rather than from an external file. - * - * @see RuleSetTest - */ -public class DefaultAccessControlTest extends TestCase -{ - private static final String ALLOWED_GROUP = "allowed_group"; - private static final String DENIED_GROUP = "denied_group"; - - private DefaultAccessControl _plugin = null; // Class under test - private UnitTestMessageLogger _messageLogger; - private EventLogger _eventLogger; - - public void setUp() throws Exception - { - super.setUp(); - _messageLogger = new UnitTestMessageLogger(); - _eventLogger = new EventLogger(_messageLogger); - _plugin = null; - } - - private void setUpGroupAccessControl() - { - configureAccessControl(createGroupRuleSet()); - } - - private void configureAccessControl(final RuleSet rs) - { - _plugin = new DefaultAccessControl(rs); - } - - private RuleSet createGroupRuleSet() - { - final EventLoggerProvider provider = mock(EventLoggerProvider.class); - when(provider.getEventLogger()).thenReturn(_eventLogger); - final RuleSet rs = new RuleSet(provider); - - // Rule expressed with username - rs.grant(0, "user1", Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - // Rules expressed with groups - rs.grant(1, ALLOWED_GROUP, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - rs.grant(2, DENIED_GROUP, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - // Catch all rule - rs.grant(3, Rule.ALL, Permission.DENY_LOG, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - return rs; - } - - /** - * ACL plugin must always abstain if there is no subject attached to the thread. - */ - public void testNoSubjectAlwaysAbstains() - { - setUpGroupAccessControl(); - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.ABSTAIN, result); - } - - /** - * Tests that an allow rule expressed with a username allows an operation performed by a thread running - * with the same username. - */ - public void testUsernameAllowsOperation() - { - setUpGroupAccessControl(); - Subject.doAs(TestPrincipalUtils.createTestSubject("user1"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.ALLOWED, result); - return null; - } - }); - } - - /** - * Tests that an allow rule expressed with an <b>ACL groupname</b> allows an operation performed by a thread running - * by a user who belongs to the same group.. - */ - public void testGroupMembershipAllowsOperation() - { - setUpGroupAccessControl(); - - authoriseAndAssertResult(Result.ALLOWED, "member of allowed group", ALLOWED_GROUP); - authoriseAndAssertResult(Result.DENIED, "member of denied group", DENIED_GROUP); - authoriseAndAssertResult(Result.ALLOWED, "another member of allowed group", ALLOWED_GROUP); - } - - /** - * Tests that a deny rule expressed with a <b>groupname</b> denies an operation performed by a thread running - * by a user who belongs to the same group. - */ - public void testGroupMembershipDeniesOperation() - { - setUpGroupAccessControl(); - authoriseAndAssertResult(Result.DENIED, "user3", DENIED_GROUP); - } - - /** - * Tests that the catch all deny denies the operation and logs with the logging actor. - */ - public void testCatchAllRuleDeniesUnrecognisedUsername() - { - setUpGroupAccessControl(); - Subject.doAs(TestPrincipalUtils.createTestSubject("unknown", "unkgroup1", "unkgroup2"), - new PrivilegedAction<Object>() - { - @Override - public Object run() - { - assertEquals("Expecting zero messages before test", - 0, - _messageLogger.getLogMessages().size()); - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.DENIED, result); - - assertEquals("Expecting one message before test", 1, _messageLogger.getLogMessages().size()); - assertTrue("Logged message does not contain expected string", - _messageLogger.messageContains(0, "ACL-1002")); - return null; - } - }); - - } - - /** - * Tests that a grant access method rule allows any access operation to be performed on any component - */ - public void testAuthoriseAccessMethodWhenAllAccessOperationsAllowedOnAllComponents() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user4 access right on any method in any component - rs.grant(1, "user4", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, new ObjectProperties(ObjectProperties.WILD_CARD)); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user4"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties actionProperties = new ObjectProperties("getName"); - actionProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); - assertEquals(Result.ALLOWED, result); - return null; - } - }); - - } - - /** - * Tests that a grant access method rule allows any access operation to be performed on a specified component - */ - public void testAuthoriseAccessMethodWhenAllAccessOperationsAllowedOnSpecifiedComponent() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user5 access right on any methods in "Test" component - ObjectProperties ruleProperties = new ObjectProperties(ObjectProperties.WILD_CARD); - ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - rs.grant(1, "user5", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user5"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties actionProperties = new ObjectProperties("getName"); - actionProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); - assertEquals(Result.ALLOWED, result); - - actionProperties.put(ObjectProperties.Property.COMPONENT, "Test2"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); - assertEquals(Result.DEFER, result); - return null; - } - }); - - - } - - public void testAccess() throws Exception - { - final Subject subject = TestPrincipalUtils.createTestSubject("user1"); - final String testVirtualHost = getName(); - final InetAddress inetAddress = InetAddress.getLocalHost(); - final InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 1); - - AMQConnectionModel connectionModel = mock(AMQConnectionModel.class); - when(connectionModel.getRemoteAddress()).thenReturn(inetSocketAddress); - - subject.getPrincipals().add(new ConnectionPrincipal(connectionModel)); - - Subject.doAs(subject, new PrivilegedExceptionAction<Object>() - { - @Override - public Object run() throws Exception - { - RuleSet mockRuleSet = mock(RuleSet.class); - - DefaultAccessControl accessControl = new DefaultAccessControl(mockRuleSet); - - ObjectProperties properties = new ObjectProperties(testVirtualHost); - accessControl.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, properties); - - verify(mockRuleSet).check(subject, Operation.ACCESS, ObjectType.VIRTUALHOST, properties, inetAddress); - return null; - } - }); - - } - - public void testAccessIsDeniedIfRuleThrowsException() throws Exception - { - final Subject subject = TestPrincipalUtils.createTestSubject("user1"); - final InetAddress inetAddress = InetAddress.getLocalHost(); - final InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 1); - - AMQConnectionModel connectionModel = mock(AMQConnectionModel.class); - when(connectionModel.getRemoteAddress()).thenReturn(inetSocketAddress); - - subject.getPrincipals().add(new ConnectionPrincipal(connectionModel)); - - Subject.doAs(subject, new PrivilegedExceptionAction<Object>() - { - @Override - public Object run() throws Exception - { - - - RuleSet mockRuleSet = mock(RuleSet.class); - when(mockRuleSet.check( - subject, - Operation.ACCESS, - ObjectType.VIRTUALHOST, - ObjectProperties.EMPTY, - inetAddress)).thenThrow(new RuntimeException()); - - DefaultAccessControl accessControl = new DefaultAccessControl(mockRuleSet); - Result result = accessControl.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - assertEquals(Result.DENIED, result); - return null; - } - }); - - } - - - /** - * Tests that a grant access method rule allows any access operation to be performed on a specified component - */ - public void testAuthoriseAccessMethodWhenSpecifiedAccessOperationsAllowedOnSpecifiedComponent() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user6 access right on "getAttribute" method in "Test" component - ObjectProperties ruleProperties = new ObjectProperties("getAttribute"); - ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - rs.grant(1, "user6", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user6"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties.put(ObjectProperties.Property.COMPONENT, "Test2"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - - properties = new ObjectProperties("getAttribute2"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - - return null; - } - }); - - } - - /** - * Tests that granting of all method rights on a method allows a specified operation to be performed on any component - */ - public void testAuthoriseAccessUpdateMethodWhenAllRightsGrantedOnSpecifiedMethodForAllComponents() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user8 all rights on method queryNames in all component - rs.grant(1, "user8", Permission.ALLOW, Operation.ALL, ObjectType.METHOD, new ObjectProperties("queryNames")); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user8"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties(); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - properties.put(ObjectProperties.Property.NAME, "queryNames"); - - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - return null; - } - }); - - - } - - /** - * Tests that granting of all method rights allows any operation to be performed on any component - */ - public void testAuthoriseAccessUpdateMethodWhenAllRightsGrantedOnAllMethodsInAllComponents() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user9 all rights on any method in all component - rs.grant(1, "user9", Permission.ALLOW, Operation.ALL, ObjectType.METHOD, new ObjectProperties()); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user9"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties("queryNames"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - return null; - } - }); - - - } - - /** - * Tests that granting of access method rights with mask allows matching operations to be performed on the specified component - */ - public void testAuthoriseAccessMethodWhenMatchingAccessOperationsAllowedOnSpecifiedComponent() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user9 all rights on "getAttribute*" methods in Test component - ObjectProperties ruleProperties = new ObjectProperties(); - ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - ruleProperties.put(ObjectProperties.Property.NAME, "getAttribute*"); - - rs.grant(1, "user9", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user9"), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties("getAttributes"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribut"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - return null; - } - }); - } - - private void authoriseAndAssertResult(final Result expectedResult, String userName, String... groups) - { - - Subject.doAs(TestPrincipalUtils.createTestSubject(userName, groups), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(expectedResult, result); - return null; - } - }); - - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java deleted file mode 100644 index 5301d2e49d..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java +++ /dev/null @@ -1,468 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.security.access.plugins; - -import static org.mockito.Mockito.mock; - -import javax.security.auth.Subject; - -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.access.Permission; -import org.apache.qpid.server.security.access.ObjectProperties.Property; -import org.apache.qpid.server.security.access.config.Rule; -import org.apache.qpid.server.security.access.config.RuleSet; -import org.apache.qpid.server.security.auth.TestPrincipalUtils; -import org.apache.qpid.test.utils.QpidTestCase; - -/** - * This test checks that the {@link RuleSet} object which forms the core of the access control plugin performs correctly. - * - * The ruleset is configured directly rather than using an external file by adding rules individually, calling the - * {@link RuleSet#grant(Integer, String, Permission, Operation, ObjectType, ObjectProperties)} method. Then, the - * access control mechanism is validated by checking whether operations would be authorised by calling the - * {@link RuleSet#check(Subject, Operation, ObjectType, ObjectProperties)} method. - * - * It ensure that permissions can be granted correctly on users directly and on groups. - */ -public class RuleSetTest extends QpidTestCase -{ - private static final String DENIED_VH = "deniedVH"; - private static final String ALLOWED_VH = "allowedVH"; - - private RuleSet _ruleSet; // Object under test - - private static final String TEST_USER = "user"; - - // Common things that are passed to frame constructors - private String _queueName = this.getClass().getName() + "queue"; - private String _exchangeName = "amq.direct"; - private String _exchangeType = "direct"; - private Subject _testSubject = TestPrincipalUtils.createTestSubject(TEST_USER); - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _ruleSet = new RuleSet(mock(EventLoggerProvider.class)); - } - - @Override - public void tearDown() throws Exception - { - _ruleSet.clear(); - super.tearDown(); - } - - public void assertDenyGrantAllow(Subject subject, Operation operation, ObjectType objectType) - { - assertDenyGrantAllow(subject, operation, objectType, ObjectProperties.EMPTY); - } - - public void assertDenyGrantAllow(Subject subject, Operation operation, ObjectType objectType, ObjectProperties properties) - { - assertEquals(Result.DENIED, _ruleSet.check(subject, operation, objectType, properties)); - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, operation, objectType, properties); - assertEquals(1, _ruleSet.getRuleCount()); - assertEquals(Result.ALLOWED, _ruleSet.check(subject, operation, objectType, properties)); - } - - public void testEmptyRuleSet() - { - assertNotNull(_ruleSet); - assertEquals(_ruleSet.getRuleCount(), 0); - assertEquals(_ruleSet.getDefault(), _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - public void testVirtualHostNodeCreateAllowPermissionWithVirtualHostName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.DELETE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY)); - } - - public void testVirtualHostAccessAllowPermissionWithVirtualHostName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowPermissionWithNameSetToWildCard() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ObjectProperties.WILD_CARD)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowPermissionWithNoName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessDenyPermissionWithNoName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessDenyPermissionWithNameSetToWildCard() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ObjectProperties.WILD_CARD)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowDenyPermissions() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH)); - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowPermissionWithVirtualHostNameOtherPredicate() throws Exception - { - ObjectProperties properties = new ObjectProperties(); - properties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); - - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, properties); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, properties)); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - - public void testQueueCreateNamed() throws Exception - { - assertDenyGrantAllow(_testSubject, Operation.CREATE, ObjectType.QUEUE, new ObjectProperties(_queueName)); - } - - public void testQueueCreateNamedVirtualHost() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, new ObjectProperties(Property.VIRTUALHOST_NAME, ALLOWED_VH)); - - ObjectProperties allowedQueueObjectProperties = new ObjectProperties(_queueName); - allowedQueueObjectProperties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, new ObjectProperties(allowedQueueObjectProperties))); - - ObjectProperties deniedQueueObjectProperties = new ObjectProperties(_queueName); - deniedQueueObjectProperties.put(Property.VIRTUALHOST_NAME, DENIED_VH); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, deniedQueueObjectProperties)); - } - - public void testQueueCreateNamedNullRoutingKey() - { - ObjectProperties properties = new ObjectProperties(_queueName); - properties.put(ObjectProperties.Property.ROUTING_KEY, (String) null); - - assertDenyGrantAllow(_testSubject, Operation.CREATE, ObjectType.QUEUE, properties); - } - - public void testExchangeCreateNamedVirtualHost() - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.EXCHANGE, new ObjectProperties(Property.VIRTUALHOST_NAME, ALLOWED_VH)); - - ObjectProperties allowedExchangeProperties = new ObjectProperties(_exchangeName); - allowedExchangeProperties.put(Property.TYPE, _exchangeType); - allowedExchangeProperties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.EXCHANGE, allowedExchangeProperties)); - - ObjectProperties deniedExchangeProperties = new ObjectProperties(_exchangeName); - deniedExchangeProperties.put(Property.TYPE, _exchangeType); - deniedExchangeProperties.put(Property.VIRTUALHOST_NAME, DENIED_VH); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.EXCHANGE, deniedExchangeProperties)); - } - - public void testExchangeCreate() - { - ObjectProperties properties = new ObjectProperties(_exchangeName); - properties.put(ObjectProperties.Property.TYPE, _exchangeType); - - assertDenyGrantAllow(_testSubject, Operation.CREATE, ObjectType.EXCHANGE, properties); - } - - public void testConsume() - { - assertDenyGrantAllow(_testSubject, Operation.CONSUME, ObjectType.QUEUE); - } - - public void testPublish() - { - assertDenyGrantAllow(_testSubject, Operation.PUBLISH, ObjectType.EXCHANGE); - } - - /** - * If the consume permission for temporary queues is for an unnamed queue then it should - * be global for any temporary queue but not for any non-temporary queue - */ - public void testTemporaryUnnamedQueueConsume() - { - ObjectProperties temporary = new ObjectProperties(); - temporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - ObjectProperties normal = new ObjectProperties(); - normal.put(ObjectProperties.Property.AUTO_DELETE, Boolean.FALSE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary); - assertEquals(1, _ruleSet.getRuleCount()); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - - // defer to global if exists, otherwise default answer - this is handled by the security manager - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, normal)); - } - - /** - * Test that temporary queue permissions before queue perms in the ACL config work correctly - */ - public void testTemporaryQueueFirstConsume() - { - ObjectProperties temporary = new ObjectProperties(_queueName); - temporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - ObjectProperties normal = new ObjectProperties(_queueName); - normal.put(ObjectProperties.Property.AUTO_DELETE, Boolean.FALSE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - - // should not matter if the temporary permission is processed first or last - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, normal); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, normal)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - } - - /** - * Test that temporary queue permissions after queue perms in the ACL config work correctly - */ - public void testTemporaryQueueLastConsume() - { - ObjectProperties temporary = new ObjectProperties(_queueName); - temporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - ObjectProperties normal = new ObjectProperties(_queueName); - normal.put(ObjectProperties.Property.AUTO_DELETE, Boolean.FALSE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - - // should not matter if the temporary permission is processed first or last - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, normal); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, normal)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - } - - /* - * Test different rules for temporary queues. - */ - - /** - * The more generic rule first is used, so both requests are allowed. - */ - public void testFirstNamedSecondTemporaryQueueDenied() - { - ObjectProperties named = new ObjectProperties(_queueName); - ObjectProperties namedTemporary = new ObjectProperties(_queueName); - namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - _ruleSet.grant(2, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - } - - /** - * The more specific rule is first, so those requests are denied. - */ - public void testFirstTemporarySecondNamedQueueDenied() - { - ObjectProperties named = new ObjectProperties(_queueName); - ObjectProperties namedTemporary = new ObjectProperties(_queueName); - namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - } - - /** - * The more specific rules are first, so those requests are denied. - */ - public void testFirstTemporarySecondDurableThirdNamedQueueDenied() - { - ObjectProperties named = new ObjectProperties(_queueName); - ObjectProperties namedTemporary = new ObjectProperties(_queueName); - namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - ObjectProperties namedDurable = new ObjectProperties(_queueName); - namedDurable.put(ObjectProperties.Property.DURABLE, Boolean.TRUE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedDurable)); - - _ruleSet.grant(1, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedDurable); - _ruleSet.grant(3, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(3, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedDurable)); - } - - public void testNamedTemporaryQueueAllowed() - { - ObjectProperties named = new ObjectProperties(_queueName); - ObjectProperties namedTemporary = new ObjectProperties(_queueName); - namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - } - - public void testNamedTemporaryQueueDeniedAllowed() - { - ObjectProperties named = new ObjectProperties(_queueName); - ObjectProperties namedTemporary = new ObjectProperties(_queueName); - namedTemporary.put(ObjectProperties.Property.AUTO_DELETE, Boolean.TRUE); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - } - - /** - * Tests support for the {@link Rule#ALL} keyword. - */ - public void testAllowToAll() - { - _ruleSet.grant(1, Rule.ALL, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(1, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject("usera"),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject("userb"),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - public void testGroupsSupported() - { - String allowGroup = "allowGroup"; - String deniedGroup = "deniedGroup"; - - _ruleSet.grant(1, allowGroup, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, deniedGroup, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject("usera", allowGroup),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - assertEquals(Result.DENIED, _ruleSet.check(TestPrincipalUtils.createTestSubject("userb", deniedGroup),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - assertEquals(Result.DEFER, _ruleSet.check(TestPrincipalUtils.createTestSubject("user", "group not mentioned in acl"),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - /** - * Rule order in the ACL determines the outcome of the check. This test ensures that a user who is - * granted explicit permission on an object, is granted that access even though a group - * to which the user belongs is later denied the permission. - */ - public void testAllowDeterminedByRuleOrder() - { - String group = "group"; - String user = "user"; - - _ruleSet.grant(1, user, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, group, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject(user, group),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - /** - * Rule order in the ACL determines the outcome of the check. This tests ensures that a user who is denied - * access by group, is denied access, despite there being a later rule granting permission to that user. - */ - public void testDenyDeterminedByRuleOrder() - { - String group = "aclgroup"; - String user = "usera"; - - _ruleSet.grant(1, group, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, user, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.DENIED, _ruleSet.check(TestPrincipalUtils.createTestSubject(user, group),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - public void testUserInMultipleGroups() - { - String allowedGroup = "group1"; - String deniedGroup = "group2"; - - _ruleSet.grant(1, allowedGroup, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, deniedGroup, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - Subject subjectInBothGroups = TestPrincipalUtils.createTestSubject("user", allowedGroup, deniedGroup); - Subject subjectInDeniedGroupAndOneOther = TestPrincipalUtils.createTestSubject("user", deniedGroup, "some other group"); - Subject subjectInAllowedGroupAndOneOther = TestPrincipalUtils.createTestSubject("user", allowedGroup, "some other group"); - - assertEquals(Result.ALLOWED, _ruleSet.check(subjectInBothGroups,Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - - assertEquals(Result.DENIED, _ruleSet.check(subjectInDeniedGroupAndOneOther,Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - - assertEquals(Result.ALLOWED, _ruleSet.check(subjectInAllowedGroupAndOneOther,Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/pom.xml b/qpid/java/broker-plugins/amqp-0-10-protocol/pom.xml deleted file mode 100644 index 6006a2a723..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-amqp-0-10-protocol</artifactId> - <name>Qpid AMQP 0-10 Protocol Plug-in</name> - <description>AMQP 0-10 protocol broker plug-in</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <version>${log4j-version}</version> - </dependency> - - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-api</artifactId> - <version>${slf4j-version}</version> - </dependency> - - <!-- test dependencies --> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-test-utils</artifactId> - <version>${project.version}</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <type>test-jar</type> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - </build> - -</project> diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java deleted file mode 100644 index db053eef26..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java +++ /dev/null @@ -1,669 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import java.nio.ByteBuffer; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.qpid.server.consumer.AbstractConsumerTarget; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.flow.FlowCreditManager; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.messages.ChannelMessages; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Exchange; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.protocol.MessageConverterRegistry; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueConsumer; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageAcceptMode; -import org.apache.qpid.transport.MessageAcquireMode; -import org.apache.qpid.transport.MessageCreditUnit; -import org.apache.qpid.transport.MessageFlowMode; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.MessageTransfer; -import org.apache.qpid.transport.Method; -import org.apache.qpid.transport.Option; -import org.apache.qpid.util.GZIPUtils; - -public class ConsumerTarget_0_10 extends AbstractConsumerTarget implements FlowCreditManager.FlowCreditManagerListener -{ - - private static final Option[] BATCHED = new Option[] { Option.BATCH }; - - private final AtomicBoolean _deleted = new AtomicBoolean(false); - private final String _name; - - - private FlowCreditManager_0_10 _creditManager; - - private final MessageAcceptMode _acceptMode; - private final MessageAcquireMode _acquireMode; - private MessageFlowMode _flowMode; - private final ServerSession _session; - private final AtomicBoolean _stopped = new AtomicBoolean(true); - - private final AtomicLong _unacknowledgedCount = new AtomicLong(0); - private final AtomicLong _unacknowledgedBytes = new AtomicLong(0); - - private final Map<String, Object> _arguments; - private int _deferredMessageCredit; - private long _deferredSizeCredit; - private final List<ConsumerImpl> _consumers = new CopyOnWriteArrayList<>(); - - - public ConsumerTarget_0_10(ServerSession session, - String name, - MessageAcceptMode acceptMode, - MessageAcquireMode acquireMode, - MessageFlowMode flowMode, - FlowCreditManager_0_10 creditManager, - Map<String, Object> arguments) - { - super(State.SUSPENDED); - _session = session; - _postIdSettingAction = new AddMessageDispositionListenerAction(session); - _acceptMode = acceptMode; - _acquireMode = acquireMode; - _creditManager = creditManager; - _flowMode = flowMode; - _creditManager.addStateListener(this); - _arguments = arguments == null ? Collections.<String, Object> emptyMap() : - Collections.<String, Object> unmodifiableMap(arguments); - _name = name; - } - - @Override - public boolean doIsSuspended() - { - return getState()!=State.ACTIVE || _deleted.get() || _session.isClosing() || _session.getConnectionModel().isStopped(); // TODO check for Session suspension - } - - public boolean close() - { - boolean closed = false; - State state = getState(); - - getSendLock(); - try - { - while(!closed && state != State.CLOSED) - { - closed = updateState(state, State.CLOSED); - if(!closed) - { - state = getState(); - } - } - _creditManager.removeListener(this); - } - finally - { - releaseSendLock(); - } - - return closed; - - } - - public void creditStateChanged(boolean hasCredit) - { - - if(hasCredit) - { - if(!updateState(State.SUSPENDED, State.ACTIVE)) - { - // this is a hack to get round the issue of increasing bytes credit - notifyCurrentState(); - } - } - else - { - updateState(State.ACTIVE, State.SUSPENDED); - } - } - - public String getName() - { - return _name; - } - - public void transportStateChanged() - { - _creditManager.restoreCredit(0, 0); - } - - public static class AddMessageDispositionListenerAction implements Runnable - { - private MessageTransfer _xfr; - private ServerSession.MessageDispositionChangeListener _action; - private ServerSession _session; - - public AddMessageDispositionListenerAction(ServerSession session) - { - _session = session; - } - - public void setXfr(MessageTransfer xfr) - { - _xfr = xfr; - } - - public void setAction(ServerSession.MessageDispositionChangeListener action) - { - _action = action; - } - - public void run() - { - if(_action != null) - { - _session.onMessageDispositionChange(_xfr, _action); - } - } - } - - private final AddMessageDispositionListenerAction _postIdSettingAction; - - public void doSend(final ConsumerImpl consumer, final MessageInstance entry, boolean batch) - { - ServerMessage serverMsg = entry.getMessage(); - - - MessageTransfer xfr; - - DeliveryProperties deliveryProps; - MessageProperties messageProps = null; - - MessageTransferMessage msg; - - if(serverMsg instanceof MessageTransferMessage) - { - - msg = (MessageTransferMessage) serverMsg; - - } - else - { - MessageConverter converter = - MessageConverterRegistry.getConverter(serverMsg.getClass(), MessageTransferMessage.class); - - - msg = (MessageTransferMessage) converter.convert(serverMsg, _session.getVirtualHost()); - } - DeliveryProperties origDeliveryProps = msg.getHeader() == null ? null : msg.getHeader().getDeliveryProperties(); - messageProps = msg.getHeader() == null ? null : msg.getHeader().getMessageProperties(); - - deliveryProps = new DeliveryProperties(); - if(origDeliveryProps != null) - { - if(origDeliveryProps.hasDeliveryMode()) - { - deliveryProps.setDeliveryMode(origDeliveryProps.getDeliveryMode()); - } - if(origDeliveryProps.hasExchange()) - { - deliveryProps.setExchange(origDeliveryProps.getExchange()); - } - if(origDeliveryProps.hasExpiration()) - { - deliveryProps.setExpiration(origDeliveryProps.getExpiration()); - } - if(origDeliveryProps.hasPriority()) - { - deliveryProps.setPriority(origDeliveryProps.getPriority()); - } - if(origDeliveryProps.hasRoutingKey()) - { - deliveryProps.setRoutingKey(origDeliveryProps.getRoutingKey()); - } - if(origDeliveryProps.hasTimestamp()) - { - deliveryProps.setTimestamp(origDeliveryProps.getTimestamp()); - } - if(origDeliveryProps.hasTtl()) - { - deliveryProps.setTtl(origDeliveryProps.getTtl()); - } - - - } - - deliveryProps.setRedelivered(entry.isRedelivered()); - - boolean msgCompressed = messageProps != null && GZIPUtils.GZIP_CONTENT_ENCODING.equals(messageProps.getContentEncoding()); - - - ByteBuffer body = msg.getBody(); - - boolean compressionSupported = _session.getConnection().getConnectionDelegate().isCompressionSupported(); - - if(msgCompressed && !compressionSupported) - { - byte[] uncompressed = GZIPUtils.uncompressBufferToArray(body); - if(uncompressed != null) - { - messageProps.setContentEncoding(null); - body = ByteBuffer.wrap(uncompressed); - } - } - else if(!msgCompressed - && compressionSupported - && (messageProps == null || messageProps.getContentEncoding()==null) - && body != null - && body.remaining() > _session.getConnection().getMessageCompressionThreshold()) - { - byte[] compressed = GZIPUtils.compressBufferToArray(body); - if(compressed != null) - { - if(messageProps == null) - { - messageProps = new MessageProperties(); - } - messageProps.setContentEncoding(GZIPUtils.GZIP_CONTENT_ENCODING); - body = ByteBuffer.wrap(compressed); - } - } - long size = body == null ? 0 : body.remaining(); - - Header header = new Header(deliveryProps, messageProps, msg.getHeader() == null ? null : msg.getHeader().getNonStandardProperties()); - - xfr = batch ? new MessageTransfer(_name,_acceptMode,_acquireMode,header, body, BATCHED) - : new MessageTransfer(_name,_acceptMode,_acquireMode,header, body); - - if(_acceptMode == MessageAcceptMode.NONE && _acquireMode != MessageAcquireMode.PRE_ACQUIRED) - { - xfr.setCompletionListener(new MessageAcceptCompletionListener(this, consumer, _session, entry, _flowMode == MessageFlowMode.WINDOW)); - } - else if(_flowMode == MessageFlowMode.WINDOW) - { - xfr.setCompletionListener(new Method.CompletionListener() - { - public void onComplete(Method method) - { - deferredAddCredit(1, entry.getMessage().getSize()); - } - }); - } - - - _postIdSettingAction.setXfr(xfr); - if(_acceptMode == MessageAcceptMode.EXPLICIT) - { - _postIdSettingAction.setAction(new ExplicitAcceptDispositionChangeListener(entry, this, consumer)); - } - else if(_acquireMode != MessageAcquireMode.PRE_ACQUIRED) - { - _postIdSettingAction.setAction(new ImplicitAcceptDispositionChangeListener(entry, this, consumer)); - } - else - { - _postIdSettingAction.setAction(null); - } - - - _session.sendMessage(xfr, _postIdSettingAction); - - _postIdSettingAction.setAction(null); - _postIdSettingAction.setXfr(null); - - entry.incrementDeliveryCount(); - if(_acceptMode == MessageAcceptMode.NONE && _acquireMode == MessageAcquireMode.PRE_ACQUIRED) - { - forceDequeue(entry, false); - } - else if(_acquireMode == MessageAcquireMode.PRE_ACQUIRED) - { - recordUnacknowledged(entry); - } - } - - void recordUnacknowledged(MessageInstance entry) - { - _unacknowledgedCount.incrementAndGet(); - _unacknowledgedBytes.addAndGet(entry.getMessage().getSize()); - } - - private void deferredAddCredit(final int deferredMessageCredit, final long deferredSizeCredit) - { - _deferredMessageCredit += deferredMessageCredit; - _deferredSizeCredit += deferredSizeCredit; - - } - - public void flushCreditState(boolean strict) - { - if(strict || !isSuspended() || _deferredMessageCredit >= 200 - || !(_creditManager instanceof WindowCreditManager) - || ((WindowCreditManager)_creditManager).getMessageCreditLimit() < 400 ) - { - _creditManager.restoreCredit(_deferredMessageCredit, _deferredSizeCredit); - _deferredMessageCredit = 0; - _deferredSizeCredit = 0l; - } - } - - private void forceDequeue(final MessageInstance entry, final boolean restoreCredit) - { - AutoCommitTransaction dequeueTxn = new AutoCommitTransaction(_session.getVirtualHost().getMessageStore()); - dequeueTxn.dequeue(entry.getEnqueueRecord(), - new ServerTransaction.Action() - { - public void postCommit() - { - if (restoreCredit) - { - restoreCredit(entry.getMessage()); - } - entry.delete(); - } - - public void onRollback() - { - - } - }); - } - - void reject(final MessageInstance entry) - { - entry.setRedelivered(); - entry.routeToAlternate(null, null); - if(isAcquiredByConsumer(entry)) - { - entry.delete(); - } - } - - private boolean isAcquiredByConsumer(final MessageInstance entry) - { - ConsumerImpl acquiringConsumer = entry.getAcquiringConsumer(); - if(acquiringConsumer instanceof QueueConsumer) - { - return ((QueueConsumer)acquiringConsumer).getTarget() == this; - } - - return false; - } - - void release(final MessageInstance entry, final boolean setRedelivered) - { - if (setRedelivered) - { - entry.setRedelivered(); - } - - if (getSessionModel().isClosing() || !setRedelivered) - { - entry.decrementDeliveryCount(); - } - - if (isMaxDeliveryLimitReached(entry)) - { - sendToDLQOrDiscard(entry); - } - else - { - entry.release(); - } - } - - protected void sendToDLQOrDiscard(MessageInstance entry) - { - final ServerMessage msg = entry.getMessage(); - - int requeues = entry.routeToAlternate(new Action<MessageInstance>() - { - @Override - public void performAction(final MessageInstance requeueEntry) - { - getEventLogger().message(ChannelMessages.DEADLETTERMSG(msg.getMessageNumber(), - requeueEntry.getOwningResource() - .getName())); - } - }, null); - - if (requeues == 0) - { - TransactionLogResource owningResource = entry.getOwningResource(); - if(owningResource instanceof AMQQueue) - { - final AMQQueue queue = (AMQQueue)owningResource; - final Exchange alternateExchange = queue.getAlternateExchange(); - - if(alternateExchange != null) - { - getEventLogger().message(ChannelMessages.DISCARDMSG_NOROUTE(msg.getMessageNumber(), - alternateExchange.getName())); - } - else - { - getEventLogger().message(ChannelMessages.DISCARDMSG_NOALTEXCH(msg.getMessageNumber(), - queue.getName(), - msg.getInitialRoutingAddress())); - } - } - } - } - - protected EventLogger getEventLogger() - { - return getSessionModel().getVirtualHost().getEventLogger(); - } - - private boolean isMaxDeliveryLimitReached(MessageInstance entry) - { - final int maxDeliveryLimit = entry.getMaximumDeliveryCount(); - return (maxDeliveryLimit > 0 && entry.getDeliveryCount() >= maxDeliveryLimit); - } - - public void queueDeleted() - { - _deleted.set(true); - } - - public boolean allocateCredit(ServerMessage message) - { - return _creditManager.useCreditForMessage(message.getSize()); - } - - public void restoreCredit(ServerMessage message) - { - _creditManager.restoreCredit(1, message.getSize()); - } - - public FlowCreditManager_0_10 getCreditManager() - { - return _creditManager; - } - - - public void stop() - { - try - { - getSendLock(); - - updateState(State.ACTIVE, State.SUSPENDED); - _stopped.set(true); - FlowCreditManager_0_10 creditManager = getCreditManager(); - creditManager.clearCredit(); - } - finally - { - releaseSendLock(); - } - } - - public void addCredit(MessageCreditUnit unit, long value) - { - FlowCreditManager_0_10 creditManager = getCreditManager(); - - switch (unit) - { - case MESSAGE: - - creditManager.addCredit(value, 0L); - break; - case BYTE: - creditManager.addCredit(0l, value); - break; - } - - _stopped.set(false); - - if(creditManager.hasCredit()) - { - updateState(State.SUSPENDED, State.ACTIVE); - } - - } - - public void setFlowMode(MessageFlowMode flowMode) - { - - - _creditManager.removeListener(this); - - switch(flowMode) - { - case CREDIT: - _creditManager = new CreditCreditManager(0l, 0l, _session.getConnection().getProtocolEngine()); - break; - case WINDOW: - _creditManager = new WindowCreditManager(0l, 0l, _session.getConnection().getProtocolEngine()); - break; - default: - // this should never happen, as 0-10 is finalised and so the enum should never change - throw new ConnectionScopedRuntimeException("Unknown message flow mode: " + flowMode); - } - _flowMode = flowMode; - updateState(State.ACTIVE, State.SUSPENDED); - - _creditManager.addStateListener(this); - - } - - public boolean isStopped() - { - return _stopped.get(); - } - - public boolean deleteAcquired(MessageInstance entry) - { - if(isAcquiredByConsumer(entry)) - { - acquisitionRemoved(entry); - entry.delete(); - return true; - } - else - { - return false; - } - } - - @Override - public void acquisitionRemoved(final MessageInstance entry) - { - _unacknowledgedBytes.addAndGet(-entry.getMessage().getSize()); - _unacknowledgedCount.decrementAndGet(); - } - - public void flush() - { - flushCreditState(true); - for(ConsumerImpl consumer : _consumers) - { - consumer.flush(); - } - stop(); - } - - public ServerSession getSessionModel() - { - return _session; - } - - public boolean isDurable() - { - return false; - } - - public Map<String, Object> getArguments() - { - return _arguments; - } - - public void queueEmpty() - { - } - - public void flushBatched() - { - } - - - @Override - public void consumerAdded(final ConsumerImpl sub) - { - _consumers.add(sub); - } - - @Override - public void consumerRemoved(final ConsumerImpl sub) - { - _consumers.remove(sub); - if(_consumers.isEmpty()) - { - close(); - } - } - - public long getUnacknowledgedBytes() - { - return _unacknowledgedBytes.longValue(); - } - - public long getUnacknowledgedMessages() - { - return _unacknowledgedCount.longValue(); - } - - @Override - protected void processClosed() - { - - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/CreditCreditManager.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/CreditCreditManager.java deleted file mode 100644 index dd43ae7e11..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/CreditCreditManager.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.flow.AbstractFlowCreditManager; - -public class CreditCreditManager extends AbstractFlowCreditManager implements FlowCreditManager_0_10 -{ - private final ServerProtocolEngine _serverProtocolEngine; - private volatile long _bytesCredit; - private volatile long _messageCredit; - - public CreditCreditManager(long bytesCredit, long messageCredit, final ServerProtocolEngine serverProtocolEngine) - { - _serverProtocolEngine = serverProtocolEngine; - _bytesCredit = bytesCredit; - _messageCredit = messageCredit; - setSuspended(!hasCredit()); - - } - - public synchronized void restoreCredit(final long messageCredit, final long bytesCredit) - { - setSuspended(!hasCredit()); - } - - - public synchronized void addCredit(final long messageCredit, final long bytesCredit) - { - boolean notifyIncrease = true; - if(_messageCredit >= 0L && messageCredit > 0L) - { - notifyIncrease = _messageCredit != 0L; - _messageCredit += messageCredit; - } - - - - if(_bytesCredit >= 0L && bytesCredit > 0L) - { - notifyIncrease = notifyIncrease && bytesCredit>0; - _bytesCredit += bytesCredit; - - - - if(notifyIncrease) - { - notifyIncreaseBytesCredit(); - } - } - - - - setSuspended(!hasCredit()); - - } - - public void clearCredit() - { - _bytesCredit = 0l; - _messageCredit = 0l; - setSuspended(true); - } - - - public synchronized boolean hasCredit() - { - // Note !=, if credit is < 0 that indicates infinite credit - return (_bytesCredit != 0L && _messageCredit != 0L && !_serverProtocolEngine.isTransportBlockedForWriting()); - } - - public synchronized boolean useCreditForMessage(long msgSize) - { - if (_serverProtocolEngine.isTransportBlockedForWriting()) - { - setSuspended(true); - return false; - } - else if(_messageCredit >= 0L) - { - if(_messageCredit > 0) - { - if(_bytesCredit < 0L) - { - _messageCredit--; - - return true; - } - else if(msgSize <= _bytesCredit) - { - _messageCredit--; - _bytesCredit -= msgSize; - - return true; - } - else - { - return false; - } - } - else - { - setSuspended(true); - return false; - } - } - else if(_bytesCredit >= 0L) - { - if(msgSize <= _bytesCredit) - { - _bytesCredit -= msgSize; - - return true; - } - else - { - return false; - } - - } - else - { - return true; - } - - } - - public synchronized void stop() - { - if(_bytesCredit > 0) - { - _bytesCredit = 0; - } - if(_messageCredit > 0) - { - _messageCredit = 0; - } - - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ExplicitAcceptDispositionChangeListener.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ExplicitAcceptDispositionChangeListener.java deleted file mode 100755 index 2118a00477..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ExplicitAcceptDispositionChangeListener.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; - - -class ExplicitAcceptDispositionChangeListener implements ServerSession.MessageDispositionChangeListener -{ - private static final Logger _logger = LoggerFactory.getLogger(ExplicitAcceptDispositionChangeListener.class); - - - private final MessageInstance _entry; - private final ConsumerTarget_0_10 _target; - private final ConsumerImpl _consumer; - - public ExplicitAcceptDispositionChangeListener(MessageInstance entry, - ConsumerTarget_0_10 target, - final ConsumerImpl consumer) - { - _entry = entry; - _target = target; - _consumer = consumer; - } - - public void onAccept() - { - if(_target != null && _entry.isAcquiredBy(_consumer) && _entry.lockAcquisition()) - { - _target.getSessionModel().acknowledge(_target, _entry); - } - else - { - _logger.debug("MessageAccept received for message which is not been acquired - message may have expired or been removed"); - } - - } - - public void onRelease(boolean setRedelivered) - { - if(_target != null && _entry.isAcquiredBy(_consumer)) - { - _target.release(_entry, setRedelivered); - } - else - { - _logger.debug("MessageRelease received for message which has not been acquired - message may have expired or been removed"); - } - } - - public void onReject() - { - if(_target != null && _entry.isAcquiredBy(_consumer)) - { - _target.reject(_entry); - } - else - { - _logger.debug("MessageReject received for message which has not been acquired - message may have expired or been removed"); - } - - } - - public boolean acquire() - { - return _entry.acquire(_consumer); - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/FlowCreditManager_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/FlowCreditManager_0_10.java deleted file mode 100755 index 7f092814da..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/FlowCreditManager_0_10.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import org.apache.qpid.server.flow.FlowCreditManager; - -public interface FlowCreditManager_0_10 extends FlowCreditManager -{ - public void addCredit(long count, long bytes); - - void clearCredit(); -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ImplicitAcceptDispositionChangeListener.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ImplicitAcceptDispositionChangeListener.java deleted file mode 100755 index c918016fb1..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ImplicitAcceptDispositionChangeListener.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; - -class ImplicitAcceptDispositionChangeListener implements ServerSession.MessageDispositionChangeListener -{ - private static final Logger _logger = LoggerFactory.getLogger(ImplicitAcceptDispositionChangeListener.class); - - - private final MessageInstance _entry; - private final ConsumerTarget_0_10 _target; - private final ConsumerImpl _consumer; - - public ImplicitAcceptDispositionChangeListener(MessageInstance entry, - ConsumerTarget_0_10 target, - final ConsumerImpl consumer) - { - _entry = entry; - _target = target; - _consumer = consumer; - } - - public void onAccept() - { - _logger.warn("MessageAccept received for message which is using NONE as the accept mode (likely client error)"); - } - - public void onRelease(boolean setRedelivered) - { - if(_entry.isAcquiredBy(_consumer)) - { - _target.release(_entry, setRedelivered); - } - else - { - _logger.warn("MessageRelease received for message which has not been acquired (likely client error)"); - } - } - - public void onReject() - { - if(_entry.isAcquiredBy(_consumer)) - { - _target.reject(_entry); - } - else - { - _logger.warn("MessageReject received for message which has not been acquired (likely client error)"); - } - - } - - public boolean acquire() - { - boolean acquired = _entry.acquire(_consumer); - if(acquired) - { - _target.recordUnacknowledged(_entry); - } - return acquired; - - } - - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageAcceptCompletionListener.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageAcceptCompletionListener.java deleted file mode 100755 index d581d146a8..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageAcceptCompletionListener.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.protocol.v0_10; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.transport.Method; - -public class MessageAcceptCompletionListener implements Method.CompletionListener -{ - private final ConsumerTarget_0_10 _sub; - private final MessageInstance _entry; - private final ServerSession _session; - private final ConsumerImpl _consumer; - private long _messageSize; - private boolean _restoreCredit; - - public MessageAcceptCompletionListener(ConsumerTarget_0_10 sub, - final ConsumerImpl consumer, - ServerSession session, - MessageInstance entry, - boolean restoreCredit) - { - super(); - _sub = sub; - _entry = entry; - _session = session; - _restoreCredit = restoreCredit; - _consumer = consumer; - if(restoreCredit) - { - _messageSize = entry.getMessage().getSize(); - } - } - - public void onComplete(Method method) - { - if(_restoreCredit) - { - _sub.getCreditManager().restoreCredit(1l, _messageSize); - } - if(_entry.isAcquiredBy(_consumer) && _entry.lockAcquisition()) - { - _session.acknowledge(_sub, _entry); - } - - _session.removeDispositionListener(method); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java deleted file mode 100644 index bd04db11ae..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import java.nio.ByteBuffer; - -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; - -@PluggableService -public class MessageConverter_Internal_to_v0_10 implements MessageConverter<InternalMessage, MessageTransferMessage> -{ - @Override - public Class<InternalMessage> getInputClass() - { - return InternalMessage.class; - } - - @Override - public Class<MessageTransferMessage> getOutputClass() - { - return MessageTransferMessage.class; - } - - @Override - public MessageTransferMessage convert(InternalMessage serverMsg, VirtualHostImpl vhost) - { - return new MessageTransferMessage(convertToStoredMessage(serverMsg), null); - } - - private StoredMessage<MessageMetaData_0_10> convertToStoredMessage(final InternalMessage serverMsg) - { - final byte[] messageContent = MessageConverter_v0_10.convertToBody(serverMsg.getMessageBody()); - final MessageMetaData_0_10 messageMetaData_0_10 = convertMetaData(serverMsg, - MessageConverter_v0_10.getBodyMimeType( - serverMsg.getMessageBody()), - messageContent.length); - - return new StoredMessage<MessageMetaData_0_10>() - { - @Override - public MessageMetaData_0_10 getMetaData() - { - return messageMetaData_0_10; - } - - @Override - public long getMessageNumber() - { - return serverMsg.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - int size = messageContent.length - offsetInMessage; - if(dst.remaining() < size) - { - size = dst.remaining(); - } - ByteBuffer buf = ByteBuffer.wrap(messageContent, offsetInMessage, size); - dst.put(buf); - return size; - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return ByteBuffer.wrap(messageContent, offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData_0_10 convertMetaData(InternalMessage serverMsg, final String bodyMimeType, final int size) - { - DeliveryProperties deliveryProps = new DeliveryProperties(); - MessageProperties messageProps = new MessageProperties(); - - - - deliveryProps.setExpiration(serverMsg.getExpiration()); - deliveryProps.setPriority(MessageDeliveryPriority.get(serverMsg.getMessageHeader().getPriority())); - deliveryProps.setRoutingKey(serverMsg.getInitialRoutingAddress()); - deliveryProps.setTimestamp(serverMsg.getMessageHeader().getTimestamp()); - - messageProps.setContentEncoding(serverMsg.getMessageHeader().getEncoding()); - messageProps.setContentLength(size); - messageProps.setContentType(bodyMimeType); - if(serverMsg.getMessageHeader().getCorrelationId() != null) - { - messageProps.setCorrelationId(serverMsg.getMessageHeader().getCorrelationId().getBytes()); - } - messageProps.setApplicationHeaders(serverMsg.getMessageHeader().getHeaderMap()); - Header header = new Header(deliveryProps, messageProps, null); - return new MessageMetaData_0_10(header, size, serverMsg.getArrivalTime()); - } - - - @Override - public String getType() - { - return "Internal to v0-10"; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.java deleted file mode 100644 index bd99458d51..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.codec.BBEncoder; - -@PluggableService -public class MessageConverter_v0_10 implements MessageConverter<ServerMessage, MessageTransferMessage> -{ - - public static final Charset UTF_8 = Charset.forName("UTF-8"); - - @Override - public Class<ServerMessage> getInputClass() - { - return ServerMessage.class; - } - - @Override - public Class<MessageTransferMessage> getOutputClass() - { - return MessageTransferMessage.class; - } - - @Override - public MessageTransferMessage convert(ServerMessage serverMsg, VirtualHostImpl vhost) - { - return new MessageTransferMessage(convertToStoredMessage(serverMsg), null); - } - - private StoredMessage<MessageMetaData_0_10> convertToStoredMessage(final ServerMessage serverMsg) - { - final MessageMetaData_0_10 messageMetaData_0_10 = convertMetaData(serverMsg); - - return new StoredMessage<MessageMetaData_0_10>() - { - @Override - public MessageMetaData_0_10 getMetaData() - { - return messageMetaData_0_10; - } - - @Override - public long getMessageNumber() - { - return serverMsg.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - return serverMsg.getContent(dst, offsetInMessage); - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return serverMsg.getContent(offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData_0_10 convertMetaData(ServerMessage serverMsg) - { - DeliveryProperties deliveryProps = new DeliveryProperties(); - MessageProperties messageProps = new MessageProperties(); - - int size = (int) serverMsg.getSize(); - ByteBuffer body = ByteBuffer.allocate(size); - serverMsg.getContent(body, 0); - body.flip(); - - - deliveryProps.setExpiration(serverMsg.getExpiration()); - deliveryProps.setPriority(MessageDeliveryPriority.get(serverMsg.getMessageHeader().getPriority())); - deliveryProps.setRoutingKey(serverMsg.getInitialRoutingAddress()); - deliveryProps.setTimestamp(serverMsg.getMessageHeader().getTimestamp()); - - messageProps.setContentEncoding(serverMsg.getMessageHeader().getEncoding()); - messageProps.setContentLength(size); - messageProps.setContentType(serverMsg.getMessageHeader().getMimeType()); - if(serverMsg.getMessageHeader().getCorrelationId() != null) - { - messageProps.setCorrelationId(serverMsg.getMessageHeader().getCorrelationId().getBytes()); - } - - Header header = new Header(deliveryProps, messageProps, null); - return new MessageMetaData_0_10(header, size, serverMsg.getArrivalTime()); - } - - - public static byte[] convertToBody(Object object) - { - if(object instanceof String) - { - return ((String)object).getBytes(UTF_8); - } - else if(object instanceof byte[]) - { - return (byte[]) object; - } - else if(object instanceof Map) - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeMap((Map)object); - ByteBuffer buf = encoder.segment(); - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - - } - else if(object instanceof List) - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeList((List) object); - ByteBuffer buf = encoder.segment(); - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - } - else - { - ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - try - { - ObjectOutputStream os = new ObjectOutputStream(bytesOut); - os.writeObject(object); - return bytesOut.toByteArray(); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - } - - public static String getBodyMimeType(Object object) - { - if(object instanceof String) - { - return "text/plain"; - } - else if(object instanceof byte[]) - { - return "application/octet-stream"; - } - else if(object instanceof Map) - { - return "amqp/map"; - } - else if(object instanceof List) - { - return "amqp/list"; - } - else - { - return "application/java-object-stream"; - } - } - - - @Override - public String getType() - { - return "Unknown to v0-10"; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java deleted file mode 100644 index 52bef63f7b..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import java.io.EOFException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.ReplyTo; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.typedmessage.TypedBytesContentReader; -import org.apache.qpid.typedmessage.TypedBytesFormatException; - -@PluggableService -public class MessageConverter_v0_10_to_Internal implements MessageConverter<MessageTransferMessage, InternalMessage> -{ - @Override - public Class<MessageTransferMessage> getInputClass() - { - return MessageTransferMessage.class; - } - - @Override - public Class<InternalMessage> getOutputClass() - { - return InternalMessage.class; - } - - @Override - public InternalMessage convert(MessageTransferMessage serverMessage, VirtualHostImpl vhost) - { - final String mimeType = serverMessage.getMessageHeader().getMimeType(); - byte[] data = new byte[(int) serverMessage.getSize()]; - serverMessage.getContent(ByteBuffer.wrap(data), 0); - - Object body = convertMessageBody(mimeType, data); - MessageProperties messageProps = serverMessage.getHeader().getMessageProperties(); - AMQMessageHeader fixedHeader = new DelegatingMessageHeader(serverMessage.getMessageHeader(), messageProps == null ? null : messageProps.getReplyTo()); - return InternalMessage.convert(serverMessage.getMessageNumber(), serverMessage.isPersistent(), fixedHeader, body); - } - - private static class DelegatingMessageHeader implements AMQMessageHeader - { - private final AMQMessageHeader _delegate; - private final ReplyTo _replyTo; - - - private DelegatingMessageHeader(final AMQMessageHeader delegate, final ReplyTo replyTo) - { - _delegate = delegate; - _replyTo = replyTo; - } - - @Override - public String getCorrelationId() - { - return _delegate.getCorrelationId(); - } - - @Override - public long getExpiration() - { - return _delegate.getExpiration(); - } - - @Override - public String getUserId() - { - return _delegate.getUserId(); - } - - @Override - public String getAppId() - { - return _delegate.getAppId(); - } - - @Override - public String getMessageId() - { - return _delegate.getMessageId(); - } - - @Override - public String getMimeType() - { - return _delegate.getMimeType(); - } - - @Override - public String getEncoding() - { - return _delegate.getEncoding(); - } - - @Override - public byte getPriority() - { - return _delegate.getPriority(); - } - - @Override - public long getTimestamp() - { - return _delegate.getTimestamp(); - } - - @Override - public String getType() - { - return _delegate.getType(); - } - - @Override - public String getReplyTo() - { - return _replyTo == null - ? null - : _replyTo.getExchange() == null || _replyTo.getExchange().equals("") - ? _replyTo.getRoutingKey() - : _replyTo.getRoutingKey() == null || _replyTo.getRoutingKey().equals("") - ? _replyTo.getExchange() - : _replyTo.getExchange() + "/" + _replyTo.getRoutingKey(); - } - - @Override - public Object getHeader(final String name) - { - return _delegate.getHeader(name); - } - - @Override - public boolean containsHeaders(final Set<String> names) - { - return _delegate.containsHeaders(names); - } - - @Override - public boolean containsHeader(final String name) - { - return _delegate.containsHeader(name); - } - - @Override - public Collection<String> getHeaderNames() - { - return _delegate.getHeaderNames(); - } - } - - private static Object convertMessageBody(String mimeType, byte[] data) - { - if("text/plain".equals(mimeType) || "text/xml".equals(mimeType)) - { - String text = new String(data); - return text; - } - else if("jms/map-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - LinkedHashMap map = new LinkedHashMap(); - final int entries = reader.readIntImpl(); - for (int i = 0; i < entries; i++) - { - try - { - String propName = reader.readStringImpl(); - Object value = reader.readObject(); - - map.put(propName, value); - } - catch (EOFException e) - { - throw new IllegalArgumentException(e); - } - catch (TypedBytesFormatException e) - { - throw new IllegalArgumentException(e); - } - - } - - return map; - - } - else if("amqp/map".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - final Map<String,Object> map = decoder.readMap(); - - return map; - - } - else if("amqp/list".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - return decoder.readList(); - } - else if("jms/stream-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - List list = new ArrayList(); - while (reader.remaining() != 0) - { - try - { - list.add(reader.readObject()); - } - catch (TypedBytesFormatException e) - { - throw new ConnectionScopedRuntimeException(e); - } - catch (EOFException e) - { - throw new ConnectionScopedRuntimeException(e); // TODO - Implement - } - } - return list; - } - else - { - return data; - - } - } - - @Override - public String getType() - { - return "v0-10 to Internal"; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.java deleted file mode 100644 index bac7e2d01f..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import java.nio.ByteBuffer; - -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; - -@PluggableService -public class MessageMetaDataType_0_10 implements MessageMetaDataType<MessageMetaData_0_10> -{ - - public static final int TYPE = 1; - public static final String V0_10 = "v0_10"; - - @Override - public int ordinal() - { - return TYPE; - } - - @Override - public MessageMetaData_0_10 createMetaData(ByteBuffer buf) - { - return MessageMetaData_0_10.FACTORY.createMetaData(buf); - } - - @Override - public ServerMessage<MessageMetaData_0_10> createMessage(StoredMessage<MessageMetaData_0_10> msg) - { - return new MessageTransferMessage(msg, null); - } - - public int hashCode() - { - return ordinal(); - } - - public boolean equals(Object o) - { - return o != null && o.getClass() == getClass(); - } - - @Override - public String getType() - { - return V0_10; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.java deleted file mode 100755 index 687331e51d..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.java +++ /dev/null @@ -1,256 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.protocol.v0_10; - -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.store.StorableMessageMetaData; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryMode; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.MessageTransfer; -import org.apache.qpid.transport.Struct; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.transport.codec.BBEncoder; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -public class MessageMetaData_0_10 implements StorableMessageMetaData -{ - private Header _header; - private DeliveryProperties _deliveryProps; - private MessageProperties _messageProps; - private MessageTransferHeader _messageHeader; - private long _arrivalTime; - private int _bodySize; - - private static final int ENCODER_SIZE = 1 << 10; - - public static final MessageMetaDataType.Factory<MessageMetaData_0_10> FACTORY = new MetaDataFactory(); - - private static final MessageMetaDataType_0_10 TYPE = new MessageMetaDataType_0_10(); - - private volatile ByteBuffer _encoded; - - public MessageMetaData_0_10(MessageTransfer xfr) - { - this(xfr.getHeader(), xfr.getBodySize(), System.currentTimeMillis()); - } - - public MessageMetaData_0_10(Header header, int bodySize, long arrivalTime) - { - _header = header; - if(_header != null) - { - _deliveryProps = _header.getDeliveryProperties(); - _messageProps = _header.getMessageProperties(); - } - else - { - _deliveryProps = null; - _messageProps = null; - } - _messageHeader = new MessageTransferHeader(_deliveryProps, _messageProps); - _arrivalTime = arrivalTime; - _bodySize = bodySize; - - } - - - - public MessageMetaDataType getType() - { - return TYPE; - } - - public int getStorableSize() - { - ByteBuffer buf = _encoded; - - if(buf == null) - { - buf = encodeAsBuffer(); - _encoded = buf; - } - - //TODO -- need to add stuff - return buf.limit(); - } - - private ByteBuffer encodeAsBuffer() - { - BBEncoder encoder = new BBEncoder(ENCODER_SIZE); - - encoder.writeInt64(_arrivalTime); - encoder.writeInt32(_bodySize); - int headersLength = 0; - if(_header.getDeliveryProperties() != null) - { - headersLength++; - } - if(_header.getMessageProperties() != null) - { - headersLength++; - } - if(_header.getNonStandardProperties() != null) - { - headersLength += _header.getNonStandardProperties().size(); - } - - encoder.writeInt32(headersLength); - - if(_header.getDeliveryProperties() != null) - { - encoder.writeStruct32(_header.getDeliveryProperties()); - } - if(_header.getMessageProperties() != null) - { - encoder.writeStruct32(_header.getMessageProperties()); - } - if(_header.getNonStandardProperties() != null) - { - - for(Struct header : _header.getNonStandardProperties()) - { - encoder.writeStruct32(header); - } - - } - ByteBuffer buf = encoder.buffer(); - return buf; - } - - public int writeToBuffer(ByteBuffer dest) - { - ByteBuffer buf = _encoded; - - if(buf == null) - { - buf = encodeAsBuffer(); - _encoded = buf; - } - - buf = buf.duplicate(); - - buf.position(0); - - if(dest.remaining() < buf.limit()) - { - buf.limit(dest.remaining()); - } - dest.put(buf); - return buf.limit(); - } - - public int getContentSize() - { - return _bodySize; - } - - public boolean isPersistent() - { - return _deliveryProps == null ? false : _deliveryProps.getDeliveryMode() == MessageDeliveryMode.PERSISTENT; - } - - public String getRoutingKey() - { - return _deliveryProps == null ? null : _deliveryProps.getRoutingKey(); - } - - public AMQMessageHeader getMessageHeader() - { - return _messageHeader; - } - - public long getSize() - { - - return _bodySize; - } - - public boolean isImmediate() - { - return _deliveryProps != null && _deliveryProps.getImmediate(); - } - - public long getExpiration() - { - return _deliveryProps == null ? 0L : _deliveryProps.getExpiration(); - } - - public long getArrivalTime() - { - return _arrivalTime; - } - - public Header getHeader() - { - return _header; - } - - private static class MetaDataFactory implements MessageMetaDataType.Factory<MessageMetaData_0_10> - { - public MessageMetaData_0_10 createMetaData(ByteBuffer buf) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(buf); - - long arrivalTime = decoder.readInt64(); - int bodySize = decoder.readInt32(); - int headerCount = decoder.readInt32(); - - DeliveryProperties deliveryProperties = null; - MessageProperties messageProperties = null; - List<Struct> otherProps = null; - - for(int i = 0 ; i < headerCount; i++) - { - Struct struct = decoder.readStruct32(); - if(struct instanceof DeliveryProperties && deliveryProperties == null) - { - deliveryProperties = (DeliveryProperties) struct; - } - else if(struct instanceof MessageProperties && messageProperties == null) - { - messageProperties = (MessageProperties) struct; - } - else - { - if(otherProps == null) - { - otherProps = new ArrayList<Struct>(); - - } - otherProps.add(struct); - } - } - Header header = new Header(deliveryProperties,messageProperties,otherProps); - - return new MessageMetaData_0_10(header, bodySize, arrivalTime); - - } - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferHeader.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferHeader.java deleted file mode 100644 index 1b506d9bf8..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferHeader.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import java.util.*; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; - -class MessageTransferHeader implements AMQMessageHeader -{ - - - public static final String JMS_TYPE = "x-jms-type"; - - private final DeliveryProperties _deliveryProps; - private final MessageProperties _messageProps; - - public MessageTransferHeader(DeliveryProperties deliveryProps, MessageProperties messageProps) - { - _deliveryProps = deliveryProps; - _messageProps = messageProps; - } - - public String getCorrelationId() - { - if (_messageProps != null && _messageProps.getCorrelationId() != null) - { - return new String(_messageProps.getCorrelationId()); - } - else - { - return null; - } - } - - public long getExpiration() - { - return _deliveryProps == null ? 0L : _deliveryProps.getExpiration(); - } - - public String getUserId() - { - byte[] userIdBytes = _messageProps == null ? null : _messageProps.getUserId(); - return userIdBytes == null ? null : new String(userIdBytes); - } - - public String getAppId() - { - byte[] appIdBytes = _messageProps == null ? null : _messageProps.getAppId(); - return appIdBytes == null ? null : new String(appIdBytes); - } - - public String getMessageId() - { - UUID id = _messageProps == null ? null : _messageProps.getMessageId(); - - return id == null ? null : String.valueOf(id); - } - - public String getMimeType() - { - return _messageProps == null ? null : _messageProps.getContentType(); - } - - public String getEncoding() - { - return _messageProps == null ? null : _messageProps.getContentEncoding(); - } - - public byte getPriority() - { - MessageDeliveryPriority priority = _deliveryProps == null || !_deliveryProps.hasPriority() - ? MessageDeliveryPriority.MEDIUM - : _deliveryProps.getPriority(); - return (byte) priority.getValue(); - } - - public long getTimestamp() - { - return _deliveryProps == null ? 0L : _deliveryProps.getTimestamp(); - } - - public String getType() - { - Object type = getHeader(JMS_TYPE); - return type instanceof String ? (String) type : null; - } - - public String getReplyTo() - { - if (_messageProps != null && _messageProps.getReplyTo() != null) - { - return _messageProps.getReplyTo().toString(); - } - else - { - return null; - } - } - - public String getReplyToExchange() - { - if (_messageProps != null && _messageProps.getReplyTo() != null) - { - return _messageProps.getReplyTo().getExchange(); - } - else - { - return null; - } - } - - public String getReplyToRoutingKey() - { - if (_messageProps != null && _messageProps.getReplyTo() != null) - { - return _messageProps.getReplyTo().getRoutingKey(); - } - else - { - return null; - } - } - - public Object getHeader(String name) - { - Map<String, Object> appHeaders = _messageProps == null ? null : _messageProps.getApplicationHeaders(); - return appHeaders == null ? null : appHeaders.get(name); - } - - public boolean containsHeaders(Set<String> names) - { - Map<String, Object> appHeaders = _messageProps == null ? null : _messageProps.getApplicationHeaders(); - return appHeaders != null && appHeaders.keySet().containsAll(names); - - } - - @Override - public Collection<String> getHeaderNames() - { - Map<String, Object> appHeaders = _messageProps == null ? null : _messageProps.getApplicationHeaders(); - return appHeaders != null ? Collections.unmodifiableCollection(appHeaders.keySet()) : Collections.EMPTY_SET ; - - } - - public boolean containsHeader(String name) - { - Map<String, Object> appHeaders = _messageProps == null ? null : _messageProps.getApplicationHeaders(); - return appHeaders != null && appHeaders.containsKey(name); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.java deleted file mode 100644 index cca376c54c..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import java.nio.ByteBuffer; - -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.AbstractServerMessageImpl; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.transport.Header; - - -public class MessageTransferMessage extends AbstractServerMessageImpl<MessageTransferMessage, MessageMetaData_0_10> -{ - - public MessageTransferMessage(StoredMessage<MessageMetaData_0_10> storeMessage, Object connectionRef) - { - super(storeMessage, connectionRef); - } - - private MessageMetaData_0_10 getMetaData() - { - return getStoredMessage().getMetaData(); - } - - public String getInitialRoutingAddress() - { - return getMetaData().getRoutingKey(); - } - - public AMQMessageHeader getMessageHeader() - { - return getMetaData().getMessageHeader(); - } - - public long getSize() - { - return getMetaData().getSize(); - } - - public boolean isImmediate() - { - return getMetaData().isImmediate(); - } - - public long getExpiration() - { - return getMetaData().getExpiration(); - } - - public long getArrivalTime() - { - return getMetaData().getArrivalTime(); - } - - public Header getHeader() - { - return getMetaData().getHeader(); - } - - public ByteBuffer getBody() - { - return getContent(0, (int)getSize()); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngineCreator_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngineCreator_0_10.java deleted file mode 100644 index 08eb06111e..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngineCreator_0_10.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.ProtocolEngineCreator; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.transport.ConnectionDelegate; -import org.apache.qpid.transport.network.NetworkConnection; - -@PluggableService -public class ProtocolEngineCreator_0_10 implements ProtocolEngineCreator -{ - - private static final byte[] AMQP_0_10_HEADER = - new byte[] { (byte) 'A', - (byte) 'M', - (byte) 'Q', - (byte) 'P', - (byte) 1, - (byte) 1, - (byte) 0, - (byte) 10 - }; - - - public ProtocolEngineCreator_0_10() - { - } - - public Protocol getVersion() - { - return Protocol.AMQP_0_10; - } - - - public byte[] getHeaderIdentifier() - { - return AMQP_0_10_HEADER; - } - - public ServerProtocolEngine newProtocolEngine(Broker<?> broker, - NetworkConnection network, - AmqpPort<?> port, - Transport transport, - long id) - { - String fqdn = null; - SocketAddress address = network.getLocalAddress(); - if (address instanceof InetSocketAddress) - { - fqdn = ((InetSocketAddress) address).getHostName(); - } - SubjectCreator subjectCreator = port.getAuthenticationProvider().getSubjectCreator(transport.isSecure()); - ConnectionDelegate connDelegate = new ServerConnectionDelegate(broker, fqdn, subjectCreator); - - ServerConnection conn = new ServerConnection(id, broker, port, transport); - - conn.setConnectionDelegate(connDelegate); - conn.setRemoteAddress(network.getRemoteAddress()); - conn.setLocalAddress(network.getLocalAddress()); - - ProtocolEngine_0_10 protocolEngine = new ProtocolEngine_0_10(conn, network); - conn.setProtocolEngine(protocolEngine); - - return protocolEngine; - } - - - private static ProtocolEngineCreator INSTANCE = new ProtocolEngineCreator_0_10(); - - public static ProtocolEngineCreator getInstance() - { - return INSTANCE; - } - - @Override - public String getType() - { - return getVersion().toString(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngine_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngine_0_10.java deleted file mode 100755 index dd20ff52ab..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngine_0_10.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.logging.messages.ConnectionMessages; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.Constant; -import org.apache.qpid.transport.network.Assembler; -import org.apache.qpid.transport.network.InputHandler; -import org.apache.qpid.transport.network.NetworkConnection; - - -public class ProtocolEngine_0_10 extends InputHandler implements ServerProtocolEngine -{ - public static final int MAX_FRAME_SIZE = 64 * 1024 - 1; - private static final Logger _logger = LoggerFactory.getLogger(ProtocolEngine_0_10.class); - - - private NetworkConnection _network; - private long _readBytes; - private long _writtenBytes; - private ServerConnection _connection; - - private long _createTime = System.currentTimeMillis(); - private volatile long _lastReadTime = _createTime; - private volatile long _lastWriteTime = _createTime; - private volatile boolean _transportBlockedForWriting; - - private final AtomicReference<Thread> _messageAssignmentSuspended = new AtomicReference<>(); - - private final AtomicBoolean _stateChanged = new AtomicBoolean(); - private final AtomicReference<Action<ServerProtocolEngine>> _workListener = new AtomicReference<>(); - - - public ProtocolEngine_0_10(ServerConnection conn, - NetworkConnection network) - { - super(new ServerAssembler(conn)); - _connection = conn; - - if(network != null) - { - setNetworkConnection(network, network.getSender()); - } - } - - @Override - public boolean isMessageAssignmentSuspended() - { - Thread lock = _messageAssignmentSuspended.get(); - return lock != null && _messageAssignmentSuspended.get() != Thread.currentThread(); - } - - @Override - public void setMessageAssignmentSuspended(final boolean messageAssignmentSuspended) - { - _messageAssignmentSuspended.set(messageAssignmentSuspended ? Thread.currentThread() : null); - - for(AMQSessionModel<?,?> session : _connection.getSessionModels()) - { - for (Consumer<?> consumer : session.getConsumers()) - { - ConsumerImpl consumerImpl = (ConsumerImpl) consumer; - if (!messageAssignmentSuspended) - { - consumerImpl.getTarget().notifyCurrentState(); - } - else - { - // ensure that by the time the method returns, no consumer can be in the process of - // delivering a message. - consumerImpl.getSendLock(); - consumerImpl.releaseSendLock(); - } - } - } - } - - - - public void setNetworkConnection(final NetworkConnection network, final ByteBufferSender sender) - { - if(!getSubject().equals(Subject.getSubject(AccessController.getContext()))) - { - Subject.doAs(getSubject(), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - setNetworkConnection(network,sender); - return null; - } - }); - } - else - { - _connection.getEventLogger().message(ConnectionMessages.OPEN(null, null, null, null, false, false, false, false)); - _network = network; - - _connection.setNetworkConnection(network); - ServerDisassembler disassembler = new ServerDisassembler(wrapSender(sender), Constant.MIN_MAX_FRAME_SIZE); - _connection.setSender(disassembler); - _connection.addFrameSizeObserver(disassembler); - // FIXME Two log messages to maintain compatibility with earlier protocol versions - _connection.getEventLogger().message(ConnectionMessages.OPEN(null, "0-10", null, null, false, true, false, false)); - - } - } - - private ByteBufferSender wrapSender(final ByteBufferSender sender) - { - return new ByteBufferSender() - { - @Override - public void send(ByteBuffer msg) - { - _lastWriteTime = System.currentTimeMillis(); - sender.send(msg); - } - - @Override - public void flush() - { - sender.flush(); - - } - - @Override - public void close() - { - sender.close(); - - } - }; - } - - @Override - public long getLastReadTime() - { - return _lastReadTime; - } - - @Override - public long getLastWriteTime() - { - return _lastWriteTime; - } - - public SocketAddress getRemoteAddress() - { - return _network.getRemoteAddress(); - } - - public SocketAddress getLocalAddress() - { - return _network.getLocalAddress(); - } - - public void received(final ByteBuffer buf) - { - _lastReadTime = System.currentTimeMillis(); - if(_connection.getAuthorizedPrincipal() == null && - (_lastReadTime - _createTime) > _connection.getPort().getContextValue(Long.class, - Port.CONNECTION_MAXIMUM_AUTHENTICATION_DELAY) ) - { - Subject.doAs(_connection.getAuthorizedSubject(), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - - _logger.warn("Connection has taken more than " - + _connection.getPort() - .getContextValue(Long.class, Port.CONNECTION_MAXIMUM_AUTHENTICATION_DELAY) - + "ms to establish identity. Closing as possible DoS."); - _connection.getEventLogger().message(ConnectionMessages.IDLE_CLOSE()); - _network.close(); - return null; - } - }); - } - super.received(buf); - _connection.receivedComplete(); - } - - public long getReadBytes() - { - return _readBytes; - } - - public long getWrittenBytes() - { - return _writtenBytes; - } - - @Override - public void encryptedTransport() - { - } - - public void writerIdle() - { - _connection.doHeartBeat(); - } - - public void readerIdle() - { - Subject.doAs(_connection.getAuthorizedSubject(), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - _connection.getEventLogger().message(ConnectionMessages.IDLE_CLOSE()); - _network.close(); - return null; - } - }); - - } - - public String getAddress() - { - return getRemoteAddress().toString(); - } - - public boolean isDurable() - { - return false; - } - - @Override - public void closed() - { - super.closed(); - } - - public long getCreateTime() - { - return _createTime; - } - - public long getConnectionId() - { - return _connection.getConnectionId(); - } - - @Override - public Subject getSubject() - { - return _connection.getAuthorizedSubject(); - } - - @Override - public boolean isTransportBlockedForWriting() - { - return _transportBlockedForWriting; - } - - @Override - public void setTransportBlockedForWriting(final boolean blocked) - { - _transportBlockedForWriting = blocked; - _connection.transportStateChanged(); - } - - @Override - public void processPending() - { - _connection.processPending(); - - } - - @Override - public boolean hasWork() - { - return _stateChanged.get(); - } - - @Override - public void notifyWork() - { - _stateChanged.set(true); - - final Action<ServerProtocolEngine> listener = _workListener.get(); - if(listener != null) - { - listener.performAction(this); - } - } - - @Override - public void clearWork() - { - _stateChanged.set(false); - } - - @Override - public void setWorkListener(final Action<ServerProtocolEngine> listener) - { - _workListener.set(listener); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.java deleted file mode 100644 index 456c9d36d9..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.transport.network.Assembler; -import org.apache.qpid.transport.network.NetworkEvent; - -public class ServerAssembler extends Assembler -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ServerAssembler.class); - - - private final ServerConnection _connection; - - public ServerAssembler(final ServerConnection connection) - { - super(connection); - _connection = connection; - } - - @Override - public void received(final NetworkEvent event) - { - if (!_connection.isIgnoreFutureInput()) - { - super.received(event); - } - else - { - LOGGER.debug("Ignored network event " + event + " as connection is ignoring further input "); - } - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java deleted file mode 100644 index e3b7a9282f..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java +++ /dev/null @@ -1,770 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CONNECTION_FORMAT; -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.SOCKET_FORMAT; -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.USER_FORMAT; -import static org.apache.qpid.transport.Connection.State.CLOSING; - -import java.net.SocketAddress; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -import javax.security.auth.Subject; - -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.logging.messages.ConnectionMessages; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.SessionModelListener; -import org.apache.qpid.server.security.AuthorizationHolder; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.stats.StatisticsCounter; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.Connection; -import org.apache.qpid.transport.ConnectionClose; -import org.apache.qpid.transport.ConnectionCloseCode; -import org.apache.qpid.transport.ConnectionCloseOk; -import org.apache.qpid.transport.ExecutionErrorCode; -import org.apache.qpid.transport.ExecutionException; -import org.apache.qpid.transport.Method; -import org.apache.qpid.transport.ProtocolEvent; -import org.apache.qpid.transport.Session; - -public class ServerConnection extends Connection implements AMQConnectionModel<ServerConnection, ServerSession>, - LogSubject, AuthorizationHolder -{ - - private final Broker<?> _broker; - private AtomicBoolean _logClosed = new AtomicBoolean(false); - - private final Subject _authorizedSubject = new Subject(); - private Principal _authorizedPrincipal = null; - private final StatisticsCounter _messagesDelivered, _dataDelivered, _messagesReceived, _dataReceived; - private final long _connectionId; - private final Object _reference = new Object(); - private VirtualHostImpl<?,?,?> _virtualHost; - private final AmqpPort<?> _port; - private final AtomicLong _lastIoTime = new AtomicLong(); - private boolean _blocking; - private final Transport _transport; - - private final CopyOnWriteArrayList<Action<? super ServerConnection>> _connectionCloseTaskList = - new CopyOnWriteArrayList<Action<? super ServerConnection>>(); - - private final Queue<Action<? super ServerConnection>> _asyncTaskList = - new ConcurrentLinkedQueue<>(); - - private final CopyOnWriteArrayList<SessionModelListener> _sessionListeners = - new CopyOnWriteArrayList<SessionModelListener>(); - - private volatile boolean _stopped; - private int _messageCompressionThreshold; - private final int _maxMessageSize; - - private ServerProtocolEngine _serverProtocolEngine; - private boolean _ignoreFutureInput; - private boolean _ignoreAllButConnectionCloseOk; - - public ServerConnection(final long connectionId, - Broker<?> broker, - final AmqpPort<?> port, - final Transport transport) - { - _connectionId = connectionId; - _authorizedSubject.getPrincipals().add(new ConnectionPrincipal(this)); - _broker = broker; - - _port = port; - _transport = transport; - - int maxMessageSize = port.getContextValue(Integer.class, AmqpPort.PORT_MAX_MESSAGE_SIZE); - _maxMessageSize = (maxMessageSize > 0) ? maxMessageSize : Integer.MAX_VALUE; - - - _messagesDelivered = new StatisticsCounter("messages-delivered-" + getConnectionId()); - _dataDelivered = new StatisticsCounter("data-delivered-" + getConnectionId()); - _messagesReceived = new StatisticsCounter("messages-received-" + getConnectionId()); - _dataReceived = new StatisticsCounter("data-received-" + getConnectionId()); - } - - public Object getReference() - { - return _reference; - } - - public Broker<?> getBroker() - { - return _broker; - } - - @Override - protected void invoke(Method method) - { - super.invoke(method); - if (method instanceof ConnectionClose) - { - _ignoreAllButConnectionCloseOk = true; - } - } - - EventLogger getEventLogger() - { - return _virtualHost == null ? _broker.getEventLogger() : _virtualHost.getEventLogger(); - } - - @Override - protected void setState(State state) - { - super.setState(state); - - if (state == State.OPEN) - { - getEventLogger().message(ConnectionMessages.OPEN(getClientId(), - "0-10", - getClientVersion(), - getClientProduct(), - true, - true, - true, - true)); - - getVirtualHost().getConnectionRegistry().registerConnection(this); - } - - if (state == State.CLOSE_RCVD || state == State.CLOSED || state == State.CLOSING) - { - if(_virtualHost != null) - { - _virtualHost.getConnectionRegistry().deregisterConnection(this); - } - } - - if (state == State.CLOSED) - { - logClosed(); - } - } - - protected void logClosed() - { - if(_logClosed.compareAndSet(false, true)) - { - getEventLogger().message(this, isConnectionLost() ? ConnectionMessages.DROPPED_CONNECTION() : ConnectionMessages.CLOSE()); - } - } - - @Override - public ServerConnectionDelegate getConnectionDelegate() - { - return (ServerConnectionDelegate) super.getConnectionDelegate(); - } - - public void setConnectionDelegate(ServerConnectionDelegate delegate) - { - super.setConnectionDelegate(delegate); - } - - public ServerProtocolEngine getProtocolEngine() - { - return _serverProtocolEngine; - } - - public void setProtocolEngine(final ServerProtocolEngine serverProtocolEngine) - { - _serverProtocolEngine = serverProtocolEngine; - } - - public VirtualHostImpl<?,?,?> getVirtualHost() - { - return _virtualHost; - } - - public void setVirtualHost(VirtualHostImpl<?,?,?> virtualHost) - { - _virtualHost = virtualHost; - _messageCompressionThreshold = - virtualHost.getContextValue(Integer.class, - Broker.MESSAGE_COMPRESSION_THRESHOLD_SIZE); - - if(_messageCompressionThreshold <= 0) - { - _messageCompressionThreshold = Integer.MAX_VALUE; - } - } - - @Override - public String getVirtualHostName() - { - return _virtualHost == null ? null : _virtualHost.getName(); - } - - @Override - public AmqpPort<?> getPort() - { - return _port; - } - - @Override - public Transport getTransport() - { - return _transport; - } - - @Override - public void stop() - { - _stopped = true; - } - - @Override - public boolean isStopped() - { - return _stopped; - } - - public void closeSessionAsync(final ServerSession session, final AMQConstant cause, final String message) - { - addAsyncTask(new Action<ServerConnection>() - { - - @Override - public void performAction(final ServerConnection conn) - { - if(!session.isClosing()) - { - ExecutionException ex = new ExecutionException(); - ExecutionErrorCode code = ExecutionErrorCode.INTERNAL_ERROR; - try - { - code = ExecutionErrorCode.get(cause.getCode()); - } - catch (IllegalArgumentException iae) - { - // Ignore, already set to INTERNAL_ERROR - } - ex.setErrorCode(code); - ex.setDescription(message); - session.invoke(ex); - - session.close(cause, message); - } - } - }); - - } - - public LogSubject getLogSubject() - { - return this; - } - - @Override - public void exception(final Throwable t) - { - try - { - super.exception(t); - } - finally - { - if(t instanceof Error) - { - throw (Error) t; - } - if(t instanceof ServerScopedRuntimeException) - { - throw (ServerScopedRuntimeException) t; - } - } - } - - @Override - public void received(final ProtocolEvent event) - { - _lastIoTime.set(System.currentTimeMillis()); - Subject subject; - if (event.isConnectionControl()) - { - subject = _authorizedSubject; - } - else - { - ServerSession channel = (ServerSession) getSession(event.getChannel()); - if (channel != null) - { - subject = channel.getAuthorizedSubject(); - } - else - { - subject = _authorizedSubject; - } - } - - if(!_ignoreAllButConnectionCloseOk || (event instanceof ConnectionCloseOk)) - { - Subject.doAs(subject, new PrivilegedAction<Void>() - { - @Override - public Void run() - { - ServerConnection.super.received(event); - return null; - } - }); - } - } - - public String toLogString() - { - boolean hasVirtualHost = (null != this.getVirtualHost()); - boolean hasClientId = (null != getClientId()); - - if (hasClientId && hasVirtualHost) - { - return "[" + - MessageFormat.format(CONNECTION_FORMAT, - getConnectionId(), - getClientId(), - getRemoteAddressString(), - getVirtualHost().getName()) - + "] "; - } - else if (hasClientId) - { - return "[" + - MessageFormat.format(USER_FORMAT, - getConnectionId(), - getClientId(), - getRemoteAddressString()) - + "] "; - - } - else - { - return "[" + - MessageFormat.format(SOCKET_FORMAT, - getConnectionId(), - getRemoteAddressString()) - + "] "; - } - } - - public void closeAsync(final AMQConstant cause, final String message) - { - - addAsyncTask(new Action<ServerConnection>() - { - @Override - public void performAction(final ServerConnection object) - { - if(!isClosing()) - { - markAllSessionsClosed(); - - performDeleteTasks(); - - setState(CLOSING); - ConnectionCloseCode replyCode = ConnectionCloseCode.NORMAL; - try - { - replyCode = ConnectionCloseCode.get(cause.getCode()); - } - catch (IllegalArgumentException iae) - { - // Ignore - } - sendConnectionClose(replyCode, message); - } - } - }); - } - - protected void performDeleteTasks() - { - for(Action<? super ServerConnection> task : _connectionCloseTaskList) - { - task.performAction(this); - } - } - - public synchronized void block() - { - if(!_blocking) - { - _blocking = true; - for(AMQSessionModel ssn : getSessionModels()) - { - ssn.block(); - } - } - } - - public synchronized void unblock() - { - if(_blocking) - { - _blocking = false; - for(AMQSessionModel ssn : getSessionModels()) - { - ssn.unblock(); - } - } - } - - @Override - public synchronized void registerSession(final Session ssn) - { - super.registerSession(ssn); - sessionAdded((ServerSession)ssn); - if(_blocking) - { - ((ServerSession)ssn).block(); - } - } - - @Override - public synchronized void removeSession(final Session ssn) - { - sessionRemoved((ServerSession)ssn); - super.removeSession(ssn); - } - - public List<ServerSession> getSessionModels() - { - List<ServerSession> sessions = new ArrayList<ServerSession>(); - for (Session ssn : getChannels()) - { - sessions.add((ServerSession) ssn); - } - return sessions; - } - - public void registerMessageDelivered(long messageSize) - { - _messagesDelivered.registerEvent(1L); - _dataDelivered.registerEvent(messageSize); - _virtualHost.registerMessageDelivered(messageSize); - } - - public void registerMessageReceived(long messageSize, long timestamp) - { - _messagesReceived.registerEvent(1L, timestamp); - _dataReceived.registerEvent(messageSize, timestamp); - _virtualHost.registerMessageReceived(messageSize, timestamp); - } - - public StatisticsCounter getMessageReceiptStatistics() - { - return _messagesReceived; - } - - public StatisticsCounter getDataReceiptStatistics() - { - return _dataReceived; - } - - public StatisticsCounter getMessageDeliveryStatistics() - { - return _messagesDelivered; - } - - public StatisticsCounter getDataDeliveryStatistics() - { - return _dataDelivered; - } - - public void resetStatistics() - { - _messagesDelivered.reset(); - _dataDelivered.reset(); - _messagesReceived.reset(); - _dataReceived.reset(); - } - - /** - * @return authorizedSubject - */ - public Subject getAuthorizedSubject() - { - return _authorizedSubject; - } - - /** - * Sets the authorized subject. It also extracts the UsernamePrincipal from the subject - * and caches it for optimisation purposes. - * - * @param authorizedSubject - */ - public void setAuthorizedSubject(final Subject authorizedSubject) - { - if (authorizedSubject == null) - { - _authorizedPrincipal = null; - } - else - { - _authorizedSubject.getPrincipals().addAll(authorizedSubject.getPrincipals()); - - _authorizedPrincipal = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(authorizedSubject); - } - } - - public Principal getAuthorizedPrincipal() - { - return _authorizedPrincipal; - } - - public long getConnectionId() - { - return _connectionId; - } - - public String getRemoteAddressString() - { - return String.valueOf(getRemoteAddress()); - } - - @Override - public String getRemoteProcessPid() - { - return getConnectionDelegate().getRemoteProcessPid(); - } - - @Override - public void closed() - { - performDeleteTasks(); - closeSubscriptions(); - super.closed(); - } - - private void closeSubscriptions() - { - for (Session ssn : getChannels()) - { - ((ServerSession)ssn).unregisterSubscriptions(); - } - } - - private void markAllSessionsClosed() - { - for (Session ssn : getChannels()) - { - final ServerSession session = (ServerSession) ssn; - ((ServerSession) ssn).setClose(true); - session.closed(); - } - } - - public void receivedComplete() - { - for (Session ssn : getChannels()) - { - ((ServerSession)ssn).receivedComplete(); - } - } - - @Override - public void send(ProtocolEvent event) - { - _lastIoTime.set(System.currentTimeMillis()); - super.send(event); - } - - public long getLastIoTime() - { - return _lastIoTime.longValue(); - } - - @Override - public String getClientId() - { - return getConnectionDelegate().getClientId(); - } - - @Override - public String getRemoteContainerName() - { - return getConnectionDelegate().getClientId(); - } - - @Override - public void addSessionListener(final SessionModelListener listener) - { - _sessionListeners.add(listener); - } - - @Override - public void removeSessionListener(final SessionModelListener listener) - { - _sessionListeners.remove(listener); - } - - private void sessionAdded(final AMQSessionModel<?,?> session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionAdded(session); - } - } - - private void sessionRemoved(final AMQSessionModel<?,?> session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionRemoved(session); - } - } - - - @Override - public String getClientVersion() - { - return getConnectionDelegate().getClientVersion(); - } - - @Override - public String getClientProduct() - { - return getConnectionDelegate().getClientProduct(); - } - - public long getSessionCountLimit() - { - return getChannelMax(); - } - - public Principal getPeerPrincipal() - { - return getNetworkConnection().getPeerPrincipal(); - } - - @Override - public void setRemoteAddress(SocketAddress remoteAddress) - { - super.setRemoteAddress(remoteAddress); - } - - @Override - public void setLocalAddress(SocketAddress localAddress) - { - super.setLocalAddress(localAddress); - } - - public void doHeartBeat() - { - super.doHeartBeat(); - } - - @Override - public void addDeleteTask(final Action<? super ServerConnection> task) - { - _connectionCloseTaskList.add(task); - } - - private void addAsyncTask(final Action<ServerConnection> action) - { - _asyncTaskList.add(action); - notifyWork(); - } - - @Override - public void removeDeleteTask(final Action<? super ServerConnection> task) - { - _connectionCloseTaskList.remove(task); - } - - public int getMessageCompressionThreshold() - { - return _messageCompressionThreshold; - } - - public int getMaxMessageSize() - { - return _maxMessageSize; - } - - public void transportStateChanged() - { - for (AMQSessionModel ssn : getSessionModels()) - { - ssn.transportStateChanged(); - } - } - - @Override - public void notifyWork() - { - _serverProtocolEngine.notifyWork(); - } - - - @Override - public boolean isMessageAssignmentSuspended() - { - return _serverProtocolEngine.isMessageAssignmentSuspended(); - } - - public void processPending() - { - - for (AMQSessionModel session : getSessionModels()) - { - session.processPending(); - } - - while(_asyncTaskList.peek() != null) - { - Action<? super ServerConnection> asyncAction = _asyncTaskList.poll(); - asyncAction.performAction(this); - } - } - - public void closeAndIgnoreFutureInput() - { - _ignoreFutureInput = true; - getSender().close(); - } - - public boolean isIgnoreFutureInput() - { - return _ignoreFutureInput; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnectionDelegate.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnectionDelegate.java deleted file mode 100644 index b4c0b15dc0..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnectionDelegate.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import static org.apache.qpid.transport.Connection.State.CLOSE_RCVD; - -import java.security.AccessControlException; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.common.QpidProperties; -import org.apache.qpid.common.ServerPropertyNames; -import org.apache.qpid.properties.ConnectionStartProperties; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; -import org.apache.qpid.server.security.auth.SubjectAuthenticationResult; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.*; -import org.apache.qpid.transport.network.NetworkConnection; - -public class ServerConnectionDelegate extends ServerDelegate -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ServerConnectionDelegate.class); - - private final Broker _broker; - private final String _localFQDN; - private int _maxNoOfChannels; - private Map<String,Object> _clientProperties; - private final SubjectCreator _subjectCreator; - private int _maximumFrameSize; - - private boolean _compressionSupported; - - public ServerConnectionDelegate(Broker<?> broker, String localFQDN, SubjectCreator subjectCreator) - { - this(createConnectionProperties(broker), Collections.singletonList((Object)"en_US"), broker, localFQDN, subjectCreator); - } - - private ServerConnectionDelegate(Map<String, Object> properties, - List<Object> locales, - Broker<?> broker, - String localFQDN, - SubjectCreator subjectCreator) - { - super(properties, (List) subjectCreator.getMechanisms(), locales); - - _broker = broker; - _localFQDN = localFQDN; - _maxNoOfChannels = broker.getConnection_sessionCountLimit(); - _subjectCreator = subjectCreator; - _maximumFrameSize = (int) Math.min(0xffffl, broker.getContextValue(Integer.class, Broker.BROKER_FRAME_SIZE)); - } - - private static List<String> getFeatures(Broker<?> broker) - { - String brokerDisabledFeatures = System.getProperty(BrokerProperties.PROPERTY_DISABLED_FEATURES); - final List<String> features = new ArrayList<String>(); - if (brokerDisabledFeatures == null || !brokerDisabledFeatures.contains(ServerPropertyNames.FEATURE_QPID_JMS_SELECTOR)) - { - features.add(ServerPropertyNames.FEATURE_QPID_JMS_SELECTOR); - } - - return Collections.unmodifiableList(features); - } - - private static Map<String, Object> createConnectionProperties(final Broker<?> broker) - { - final Map<String,Object> map = new HashMap<String,Object>(); - // Federation tag is used by the client to identify the broker instance - map.put(ServerPropertyNames.FEDERATION_TAG, broker.getId().toString()); - final List<String> features = getFeatures(broker); - if (features != null && features.size() > 0) - { - map.put(ServerPropertyNames.QPID_FEATURES, features); - } - - map.put(ServerPropertyNames.PRODUCT, QpidProperties.getProductName()); - map.put(ServerPropertyNames.VERSION, QpidProperties.getReleaseVersion()); - map.put(ServerPropertyNames.QPID_BUILD, QpidProperties.getBuildVersion()); - map.put(ServerPropertyNames.QPID_INSTANCE_NAME, broker.getName()); - map.put(ConnectionStartProperties.QPID_MESSAGE_COMPRESSION_SUPPORTED, String.valueOf(broker.isMessageCompressionEnabled())); - - return map; - } - - public ServerSession getSession(Connection conn, SessionAttach atc) - { - SessionDelegate serverSessionDelegate = new ServerSessionDelegate(); - - ServerSession ssn = new ServerSession(conn, serverSessionDelegate, new Binary(atc.getName()), 0); - - return ssn; - } - - protected SaslServer createSaslServer(Connection conn, String mechanism) throws SaslException - { - return _subjectCreator.createSaslServer(mechanism, _localFQDN, ((ServerConnection) conn).getPeerPrincipal()); - - } - - protected void secure(final SaslServer ss, final Connection conn, final byte[] response) - { - final ServerConnection sconn = (ServerConnection) conn; - final SubjectAuthenticationResult authResult = _subjectCreator.authenticate(ss, response); - - if (AuthenticationStatus.SUCCESS.equals(authResult.getStatus())) - { - tuneAuthorizedConnection(sconn); - sconn.setAuthorizedSubject(authResult.getSubject()); - } - else if (AuthenticationStatus.CONTINUE.equals(authResult.getStatus())) - { - connectionAuthContinue(sconn, authResult.getChallenge()); - } - else - { - connectionAuthFailed(sconn, authResult.getCause()); - } - } - - @Override - public void connectionClose(Connection conn, ConnectionClose close) - { - final ServerConnection sconn = (ServerConnection) conn; - try - { - sconn.logClosed(); - } - finally - { - sconn.closeCode(close); - sconn.setState(CLOSE_RCVD); - sendConnectionCloseOkAndCloseSender(conn); - } - } - - public void connectionOpen(Connection conn, ConnectionOpen open) - { - final ServerConnection sconn = (ServerConnection) conn; - - VirtualHostImpl vhost; - String vhostName; - if(open.hasVirtualHost()) - { - vhostName = open.getVirtualHost(); - } - else - { - vhostName = ""; - } - - AmqpPort port = (AmqpPort) sconn.getPort(); - vhost = port.getVirtualHost(vhostName); - - - - if(vhost != null) - { - if (vhost.getState() != State.ACTIVE) - { - sconn.setState(Connection.State.CLOSING); - final String redirectHost = vhost.getRedirectHost(port); - if(redirectHost == null) - { - sconn.invoke(new ConnectionClose(ConnectionCloseCode.CONNECTION_FORCED, - "Virtual host '" + vhostName + "' is not active")); - } - else - { - sconn.invoke(new ConnectionRedirect(redirectHost, new ArrayList<Object>())); - } - return; - } - - sconn.setVirtualHost(vhost); - try - { - if(!vhost.authoriseCreateConnection(sconn)) - { - sconn.setState(Connection.State.CLOSING); - sconn.invoke(new ConnectionClose(ConnectionCloseCode.CONNECTION_FORCED, "Connection not authorized")); - return; - } - } - catch (AccessControlException e) - { - sconn.setState(Connection.State.CLOSING); - sconn.invoke(new ConnectionClose(ConnectionCloseCode.CONNECTION_FORCED, e.getMessage())); - return; - } - - sconn.setState(Connection.State.OPEN); - sconn.invoke(new ConnectionOpenOk(Collections.emptyList())); - } - else - { - sconn.setState(Connection.State.CLOSING); - sconn.invoke(new ConnectionClose(ConnectionCloseCode.INVALID_PATH, - "Unknown virtualhost '" + vhostName + "'")); - } - - } - - @Override - public void connectionTuneOk(final Connection conn, final ConnectionTuneOk ok) - { - ServerConnection sconn = (ServerConnection) conn; - int okChannelMax = ok.getChannelMax(); - int okMaxFrameSize = ok.getMaxFrameSize(); - - if (okChannelMax > getChannelMax()) - { - LOGGER.error("Connection '" + sconn.getConnectionId() + "' being severed, " + - "client connectionTuneOk returned a channelMax (" + okChannelMax + - ") above the server's offered limit (" + getChannelMax() +")"); - - //Due to the error we must forcefully close the connection without negotiation - sconn.closeAndIgnoreFutureInput(); - return; - } - - if(okMaxFrameSize > getFrameMax()) - { - LOGGER.error("Connection '" + sconn.getConnectionId() + "' being severed, " + - "client connectionTuneOk returned a frameMax (" + okMaxFrameSize + - ") above the server's offered limit (" + getFrameMax() +")"); - - //Due to the error we must forcefully close the connection without negotiation - sconn.closeAndIgnoreFutureInput(); - - return; - } - else if(okMaxFrameSize > 0 && okMaxFrameSize < Constant.MIN_MAX_FRAME_SIZE) - { - LOGGER.error("Connection '" + sconn.getConnectionId() + "' being severed, " + - "client connectionTuneOk returned a frameMax (" + okMaxFrameSize + - ") below the minimum permitted size (" + Constant.MIN_MAX_FRAME_SIZE +")"); - - //Due to the error we must forcefully close the connection without negotiation - sconn.closeAndIgnoreFutureInput(); - return; - } - else if(okMaxFrameSize == 0) - { - okMaxFrameSize = getFrameMax(); - } - - final NetworkConnection networkConnection = sconn.getNetworkConnection(); - if(ok.hasHeartbeat()) - { - int heartbeat = ok.getHeartbeat(); - if(heartbeat < 0) - { - heartbeat = 0; - } - - networkConnection.setMaxReadIdle(2 * heartbeat); - networkConnection.setMaxWriteIdle(heartbeat); - - } - else - { - networkConnection.setMaxReadIdle(0); - networkConnection.setMaxWriteIdle(0); - } - - setConnectionTuneOkChannelMax(sconn, okChannelMax); - - conn.setMaxFrameSize(okMaxFrameSize); - } - - @Override - public int getChannelMax() - { - return _maxNoOfChannels; - } - - protected void setChannelMax(int channelMax) - { - _maxNoOfChannels = channelMax; - } - - @Override - protected int getFrameMax() - { - return _maximumFrameSize; - } - - @Override public void sessionDetach(Connection conn, SessionDetach dtc) - { - // To ensure a clean detach, we stop any remaining subscriptions. Stop ensures - // that any in-progress delivery (QueueRunner) is completed before the stop - // completes. - stopAllSubscriptions(conn, dtc); - Session ssn = conn.getSession(dtc.getChannel()); - ((ServerSession)ssn).setClose(true); - super.sessionDetach(conn, dtc); - } - - private void stopAllSubscriptions(Connection conn, SessionDetach dtc) - { - final ServerSession ssn = (ServerSession) conn.getSession(dtc.getChannel()); - final Collection<ConsumerTarget_0_10> subs = ssn.getSubscriptions(); - for (ConsumerTarget_0_10 subscription_0_10 : subs) - { - subscription_0_10.stop(); - } - } - - - @Override - public void sessionAttach(final Connection conn, final SessionAttach atc) - { - final Session ssn; - - if(isSessionNameUnique(atc.getName(), conn)) - { - super.sessionAttach(conn, atc); - } - else - { - ssn = getSession(conn, atc); - ssn.invoke(new SessionDetached(atc.getName(), SessionDetachCode.SESSION_BUSY)); - ssn.closed(); - } - } - - private boolean isSessionNameUnique(final byte[] name, final Connection conn) - { - final ServerConnection sconn = (ServerConnection) conn; - final Principal authorizedPrincipal = sconn.getAuthorizedPrincipal(); - final String userId = authorizedPrincipal == null ? "" : authorizedPrincipal.getName(); - - final Iterator<AMQConnectionModel> connections = - ((ServerConnection)conn).getVirtualHost().getConnectionRegistry().getConnections().iterator(); - while(connections.hasNext()) - { - final AMQConnectionModel amqConnectionModel = connections.next(); - if (amqConnectionModel instanceof ServerConnection) - { - ServerConnection otherConnection = (ServerConnection)amqConnectionModel; - - final String userName = amqConnectionModel.getAuthorizedPrincipal() == null - ? "" - : amqConnectionModel.getAuthorizedPrincipal().getName(); - if (userId.equals(userName) && otherConnection.hasSessionWithName(name)) - { - return false; - } - } - } - return true; - } - - @Override - public void connectionStartOk(Connection conn, ConnectionStartOk ok) - { - _clientProperties = ok.getClientProperties(); - if(_clientProperties != null) - { - Object compressionSupported = - _clientProperties.get(ConnectionStartProperties.QPID_MESSAGE_COMPRESSION_SUPPORTED); - if (compressionSupported != null) - { - _compressionSupported = Boolean.parseBoolean(String.valueOf(compressionSupported)); - - } - } - super.connectionStartOk(conn, ok); - } - - public Map<String,Object> getClientProperties() - { - return _clientProperties; - } - - public String getClientId() - { - return _clientProperties == null ? null : (String) _clientProperties.get(ConnectionStartProperties.CLIENT_ID_0_10); - } - - public String getClientVersion() - { - return _clientProperties == null ? null : (String) _clientProperties.get(ConnectionStartProperties.VERSION_0_10); - } - - public String getClientProduct() - { - return _clientProperties == null ? null : (String) _clientProperties.get(ConnectionStartProperties.PRODUCT); - } - - public String getRemoteProcessPid() - { - return (_clientProperties == null || _clientProperties.get(ConnectionStartProperties.PID) == null) ? null : String.valueOf(_clientProperties.get(ConnectionStartProperties.PID)); - } - - @Override - protected int getHeartbeatMax() - { - int delay = (Integer)_broker.getAttribute(Broker.CONNECTION_HEART_BEAT_DELAY); - return delay == 0 ? super.getHeartbeatMax() : delay; - } - - public boolean isCompressionSupported() - { - return _compressionSupported && _broker.isMessageCompressionEnabled(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.java deleted file mode 100644 index a42238a40d..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import static java.lang.Math.min; -import static org.apache.qpid.transport.network.Frame.FIRST_FRAME; -import static org.apache.qpid.transport.network.Frame.FIRST_SEG; -import static org.apache.qpid.transport.network.Frame.HEADER_SIZE; -import static org.apache.qpid.transport.network.Frame.LAST_FRAME; -import static org.apache.qpid.transport.network.Frame.LAST_SEG; - -import java.nio.ByteBuffer; - -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.FrameSizeObserver; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.Method; -import org.apache.qpid.transport.ProtocolDelegate; -import org.apache.qpid.transport.ProtocolError; -import org.apache.qpid.transport.ProtocolEvent; -import org.apache.qpid.transport.ProtocolEventSender; -import org.apache.qpid.transport.ProtocolHeader; -import org.apache.qpid.transport.SegmentType; -import org.apache.qpid.transport.Struct; -import org.apache.qpid.transport.codec.Encoder; -import org.apache.qpid.transport.network.Frame; - -/** - * Disassembler - */ -public final class ServerDisassembler implements ProtocolEventSender, ProtocolDelegate<Void>, FrameSizeObserver -{ - private final ByteBufferSender _sender; - private int _maxPayload; - private final Object _sendLock = new Object(); - private final Encoder _encoder = new ServerEncoder(); - - public ServerDisassembler(ByteBufferSender sender, int maxFrame) - { - _sender = sender; - if (maxFrame <= HEADER_SIZE || maxFrame >= 64 * 1024) - { - throw new IllegalArgumentException("maxFrame must be > HEADER_SIZE and < 64K: " + maxFrame); - } - _maxPayload = maxFrame - HEADER_SIZE; - } - - public void send(ProtocolEvent event) - { - synchronized (_sendLock) - { - event.delegate(null, this); - } - } - - public void flush() - { - synchronized (_sendLock) - { - _sender.flush(); - } - } - - public void close() - { - synchronized (_sendLock) - { - _sender.close(); - } - } - - private void frame(byte flags, byte type, byte track, int channel, int size, ByteBuffer buf) - { - ByteBuffer data = ByteBuffer.wrap(new byte[HEADER_SIZE]); - - data.put(0, flags); - data.put(1, type); - data.putShort(2, (short) (size + HEADER_SIZE)); - data.put(5, track); - data.putShort(6, (short) channel); - - - ByteBuffer dup = buf.duplicate(); - dup.limit(dup.position() + size); - buf.position(buf.position() + size); - _sender.send(data); - _sender.send(dup); - - - } - - private void fragment(byte flags, SegmentType type, ProtocolEvent event, ByteBuffer buf) - { - byte typeb = (byte) type.getValue(); - byte track = event.getEncodedTrack() == Frame.L4 ? (byte) 1 : (byte) 0; - - int remaining = buf.remaining(); - boolean first = true; - while (true) - { - int size = min(_maxPayload, remaining); - remaining -= size; - - byte newflags = flags; - if (first) - { - newflags |= FIRST_FRAME; - first = false; - } - if (remaining == 0) - { - newflags |= LAST_FRAME; - } - - frame(newflags, typeb, track, event.getChannel(), size, buf); - - if (remaining == 0) - { - break; - } - } - } - - public void init(Void v, ProtocolHeader header) - { - _sender.send(header.toByteBuffer()); - _sender.flush(); -} - - public void control(Void v, Method method) - { - method(method, SegmentType.CONTROL); - } - - public void command(Void v, Method method) - { - method(method, SegmentType.COMMAND); - } - - private void method(Method method, SegmentType type) - { - Encoder enc = _encoder; - enc.init(); - enc.writeUint16(method.getEncodedType()); - if (type == SegmentType.COMMAND) - { - if (method.isSync()) - { - enc.writeUint16(0x0101); - } - else - { - enc.writeUint16(0x0100); - } - } - method.write(enc); - int methodLimit = enc.position(); - - byte flags = FIRST_SEG; - - boolean payload = method.hasPayload(); - if (!payload) - { - flags |= LAST_SEG; - } - - int headerLimit = -1; - if (payload) - { - final Header hdr = method.getHeader(); - if (hdr != null) - { - if (hdr.getDeliveryProperties() != null) - { - enc.writeStruct32(hdr.getDeliveryProperties()); - } - if (hdr.getMessageProperties() != null) - { - enc.writeStruct32(hdr.getMessageProperties()); - } - if (hdr.getNonStandardProperties() != null) - { - for (Struct st : hdr.getNonStandardProperties()) - { - enc.writeStruct32(st); - } - } - } - - headerLimit = enc.position(); - } - synchronized (_sendLock) - { - ByteBuffer buf = enc.underlyingBuffer(); - buf.position(0); - buf.limit(methodLimit); - - fragment(flags, type, method, buf.duplicate()); - if (payload) - { - ByteBuffer body = method.getBody(); - buf.limit(headerLimit); - buf.position(methodLimit); - - fragment(body == null ? LAST_SEG : 0x0, SegmentType.HEADER, method, buf.duplicate()); - if (body != null) - { - fragment(LAST_SEG, SegmentType.BODY, method, body.duplicate()); - } - - } - } - } - - public void error(Void v, ProtocolError error) - { - throw new IllegalArgumentException(String.valueOf(error)); - } - - @Override - public void setMaxFrameSize(final int maxFrame) - { - if (maxFrame <= HEADER_SIZE || maxFrame >= 64*1024) - { - throw new IllegalArgumentException("maxFrame must be > HEADER_SIZE and < 64K: " + maxFrame); - } - this._maxPayload = maxFrame - HEADER_SIZE; - - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerEncoder.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerEncoder.java deleted file mode 100644 index 6437015208..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerEncoder.java +++ /dev/null @@ -1,371 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import java.nio.BufferOverflowException; -import java.nio.ByteBuffer; -import java.util.UUID; - -import org.apache.qpid.transport.codec.AbstractEncoder; - - -public final class ServerEncoder extends AbstractEncoder -{ - public static final int DEFAULT_CAPACITY = 8192; - private final int _threshold; - private ByteBuffer _out; - private int _segment; - private int _initialCapacity; - - public ServerEncoder() - { - this(DEFAULT_CAPACITY); - } - - public ServerEncoder(int capacity) - { - _initialCapacity = capacity; - _threshold = capacity/16; - _out = ByteBuffer.allocate(capacity); - _segment = 0; - } - - public void init() - { - _out.position(_out.limit()); - _out.limit(_out.capacity()); - _out = _out.slice(); - if(_out.remaining() < _threshold) - { - _out = ByteBuffer.allocate(_initialCapacity); - } - _segment = 0; - } - - public ByteBuffer buffer() - { - int pos = _out.position(); - _out.position(_segment); - ByteBuffer slice = _out.slice(); - slice.limit(pos - _segment); - _out.position(pos); - return slice; - } - - public int position() - { - return _out.position(); - } - - public ByteBuffer underlyingBuffer() - { - return _out; - } - - private void grow(int size) - { - ByteBuffer old = _out; - int capacity = old.capacity(); - _out = ByteBuffer.allocate(Math.max(Math.max(capacity + size, 2*capacity), _initialCapacity)); - old.flip(); - _out.put(old); - } - - protected void doPut(byte b) - { - try - { - _out.put(b); - } - catch (BufferOverflowException e) - { - grow(1); - _out.put(b); - } - } - - protected void doPut(ByteBuffer src) - { - try - { - _out.put(src); - } - catch (BufferOverflowException e) - { - grow(src.remaining()); - _out.put(src); - } - } - - protected void put(byte[] bytes) - { - try - { - _out.put(bytes); - } - catch (BufferOverflowException e) - { - grow(bytes.length); - _out.put(bytes); - } - } - - public void writeUint8(short b) - { - assert b < 0x100; - - try - { - _out.put((byte) b); - } - catch (BufferOverflowException e) - { - grow(1); - _out.put((byte) b); - } - } - - public void writeUint16(int s) - { - assert s < 0x10000; - - try - { - _out.putShort((short) s); - } - catch (BufferOverflowException e) - { - grow(2); - _out.putShort((short) s); - } - } - - public void writeUint32(long i) - { - assert i < 0x100000000L; - - try - { - _out.putInt((int) i); - } - catch (BufferOverflowException e) - { - grow(4); - _out.putInt((int) i); - } - } - - public void writeUint64(long l) - { - try - { - _out.putLong(l); - } - catch (BufferOverflowException e) - { - grow(8); - _out.putLong(l); - } - } - - public int beginSize8() - { - int pos = _out.position(); - try - { - _out.put((byte) 0); - } - catch (BufferOverflowException e) - { - grow(1); - _out.put((byte) 0); - } - return pos; - } - - public void endSize8(int pos) - { - int cur = _out.position(); - _out.put(pos, (byte) (cur - pos - 1)); - } - - public int beginSize16() - { - int pos = _out.position(); - try - { - _out.putShort((short) 0); - } - catch (BufferOverflowException e) - { - grow(2); - _out.putShort((short) 0); - } - return pos; - } - - public void endSize16(int pos) - { - int cur = _out.position(); - _out.putShort(pos, (short) (cur - pos - 2)); - } - - public int beginSize32() - { - int pos = _out.position(); - try - { - _out.putInt(0); - } - catch (BufferOverflowException e) - { - grow(4); - _out.putInt(0); - } - return pos; - - } - - public void endSize32(int pos) - { - int cur = _out.position(); - _out.putInt(pos, (cur - pos - 4)); - - } - - public void writeDouble(double aDouble) - { - try - { - _out.putDouble(aDouble); - } - catch(BufferOverflowException exception) - { - grow(8); - _out.putDouble(aDouble); - } - } - - public void writeInt16(short aShort) - { - try - { - _out.putShort(aShort); - } - catch(BufferOverflowException exception) - { - grow(2); - _out.putShort(aShort); - } - } - - public void writeInt32(int anInt) - { - try - { - _out.putInt(anInt); - } - catch(BufferOverflowException exception) - { - grow(4); - _out.putInt(anInt); - } - } - - public void writeInt64(long aLong) - { - try - { - _out.putLong(aLong); - } - catch(BufferOverflowException exception) - { - grow(8); - _out.putLong(aLong); - } - } - - public void writeInt8(byte aByte) - { - try - { - _out.put(aByte); - } - catch(BufferOverflowException exception) - { - grow(1); - _out.put(aByte); - } - } - - public void writeBin128(byte[] byteArray) - { - byteArray = (byteArray != null) ? byteArray : new byte [16]; - - assert byteArray.length == 16; - - try - { - _out.put(byteArray); - } - catch(BufferOverflowException exception) - { - grow(16); - _out.put(byteArray); - } - } - - public void writeBin128(UUID id) - { - byte[] data = new byte[16]; - - long msb = id.getMostSignificantBits(); - long lsb = id.getLeastSignificantBits(); - - assert data.length == 16; - for (int i=7; i>=0; i--) - { - data[i] = (byte)(msb & 0xff); - msb = msb >> 8; - } - - for (int i=15; i>=8; i--) - { - data[i] = (byte)(lsb & 0xff); - lsb = (lsb >> 8); - } - writeBin128(data); - } - - public void writeFloat(float aFloat) - { - try - { - _out.putFloat(aFloat); - } - catch(BufferOverflowException exception) - { - grow(4); - _out.putFloat(aFloat); - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java deleted file mode 100644 index 12f79cf203..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java +++ /dev/null @@ -1,1221 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CHANNEL_FORMAT; -import static org.apache.qpid.util.Serial.gt; - -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentSkipListMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.TransactionTimeoutHelper; -import org.apache.qpid.server.TransactionTimeoutHelper.CloseAction; -import org.apache.qpid.server.connection.SessionPrincipal; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.consumer.ConsumerTarget; -import org.apache.qpid.server.logging.LogMessage; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.logging.messages.ChannelMessages; -import org.apache.qpid.server.logging.subjects.ChannelLogSubject; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfigurationChangeListener; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.CapacityChecker; -import org.apache.qpid.server.protocol.ConsumerListener; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.security.AuthorizationHolder; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.server.util.FutureResult; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.txn.AlreadyKnownDtxException; -import org.apache.qpid.server.txn.AsyncAutoCommitTransaction; -import org.apache.qpid.server.txn.DistributedTransaction; -import org.apache.qpid.server.txn.DtxNotSelectedException; -import org.apache.qpid.server.txn.IncorrectDtxStateException; -import org.apache.qpid.server.txn.JoinAndResumeDtxException; -import org.apache.qpid.server.txn.LocalTransaction; -import org.apache.qpid.server.txn.NotAssociatedDtxException; -import org.apache.qpid.server.txn.RollbackOnlyDtxException; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.txn.SuspendAndFailDtxException; -import org.apache.qpid.server.txn.TimeoutDtxException; -import org.apache.qpid.server.txn.UnknownDtxBranchException; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.Deletable; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.Binary; -import org.apache.qpid.transport.Connection; -import org.apache.qpid.transport.MessageCreditUnit; -import org.apache.qpid.transport.MessageFlow; -import org.apache.qpid.transport.MessageFlowMode; -import org.apache.qpid.transport.MessageSetFlowMode; -import org.apache.qpid.transport.MessageStop; -import org.apache.qpid.transport.MessageTransfer; -import org.apache.qpid.transport.Method; -import org.apache.qpid.transport.Range; -import org.apache.qpid.transport.RangeSet; -import org.apache.qpid.transport.RangeSetFactory; -import org.apache.qpid.transport.Session; -import org.apache.qpid.transport.SessionDelegate; -import org.apache.qpid.transport.Xid; - -public class ServerSession extends Session - implements AuthorizationHolder, - AMQSessionModel<ServerSession,ServerConnection>, LogSubject, AsyncAutoCommitTransaction.FutureRecorder, - Deletable<ServerSession> - -{ - private static final Logger _logger = LoggerFactory.getLogger(ServerSession.class); - - private static final String NULL_DESTINATION = UUID.randomUUID().toString(); - private static final int PRODUCER_CREDIT_TOPUP_THRESHOLD = 1 << 30; - private static final int UNFINISHED_COMMAND_QUEUE_THRESHOLD = 500; - - private final UUID _id = UUID.randomUUID(); - private final Subject _subject = new Subject(); - private long _createTime = System.currentTimeMillis(); - - private final Set<Object> _blockingEntities = Collections.synchronizedSet(new HashSet<Object>()); - - private final AtomicBoolean _blocking = new AtomicBoolean(false); - private ChannelLogSubject _logSubject; - private final AtomicInteger _outstandingCredit = new AtomicInteger(UNLIMITED_CREDIT); - private final CheckCapacityAction _checkCapacityAction = new CheckCapacityAction(); - private final CopyOnWriteArrayList<ConsumerListener> _consumerListeners = new CopyOnWriteArrayList<ConsumerListener>(); - private final ConfigurationChangeListener _consumerClosedListener = new ConsumerClosedListener(); - private org.apache.qpid.server.model.Session<?> _modelObject; - private long _blockTime; - private long _blockingTimeout; - private boolean _wireBlockingState; - - public static interface MessageDispositionChangeListener - { - public void onAccept(); - - public void onRelease(boolean setRedelivered); - - public void onReject(); - - public boolean acquire(); - - - } - - private final SortedMap<Integer, MessageDispositionChangeListener> _messageDispositionListenerMap = - new ConcurrentSkipListMap<Integer, MessageDispositionChangeListener>(); - - private ServerTransaction _transaction; - - private final AtomicLong _txnStarts = new AtomicLong(0); - private final AtomicLong _txnCommits = new AtomicLong(0); - private final AtomicLong _txnRejects = new AtomicLong(0); - private final AtomicLong _txnCount = new AtomicLong(0); - - private Map<String, ConsumerTarget_0_10> _subscriptions = new ConcurrentHashMap<String, ConsumerTarget_0_10>(); - private final CopyOnWriteArrayList<Consumer<?>> _consumers = new CopyOnWriteArrayList<Consumer<?>>(); - - private final List<Action<? super ServerSession>> _taskList = new CopyOnWriteArrayList<Action<? super ServerSession>>(); - - private final TransactionTimeoutHelper _transactionTimeoutHelper; - - private AtomicReference<LogMessage> _forcedCloseLogMessage = new AtomicReference<LogMessage>(); - - private volatile long _uncommittedMessageSize; - private final List<StoredMessage<MessageMetaData_0_10>> _uncommittedMessages = new ArrayList<>(); - private long _maxUncommittedInMemorySize; - - - public ServerSession(Connection connection, SessionDelegate delegate, Binary name, long expiry) - { - super(connection, delegate, name, expiry); - _transaction = new AsyncAutoCommitTransaction(this.getMessageStore(),this); - _logSubject = new ChannelLogSubject(this); - - _subject.getPrincipals().addAll(((ServerConnection) connection).getAuthorizedSubject().getPrincipals()); - _subject.getPrincipals().add(new SessionPrincipal(this)); - - _transactionTimeoutHelper = new TransactionTimeoutHelper(_logSubject, new CloseAction() - { - @Override - public void doTimeoutAction(String reason) - { - getConnectionModel().closeSessionAsync(ServerSession.this, AMQConstant.RESOURCE_ERROR, reason); - } - }, getVirtualHost()); - - _blockingTimeout = ((ServerConnection)connection).getBroker().getContextValue(Long.class, - Broker.CHANNEL_FLOW_CONTROL_ENFORCEMENT_TIMEOUT); - _maxUncommittedInMemorySize = getVirtualHost().getContextValue(Long.class, org.apache.qpid.server.model.Connection.MAX_UNCOMMITTED_IN_MEMORY_SIZE); - - } - - protected void setState(final State state) - { - if(runningAsSubject()) - { - super.setState(state); - - if (state == State.OPEN) - { - getVirtualHost().getEventLogger().message(ChannelMessages.CREATE()); - } - } - else - { - runAsSubject(new PrivilegedAction<Void>() { - - @Override - public Void run() - { - setState(state); - return null; - } - }); - - } - } - - private <T> T runAsSubject(final PrivilegedAction<T> privilegedAction) - { - return Subject.doAs(getAuthorizedSubject(), privilegedAction); - } - - private boolean runningAsSubject() - { - return getAuthorizedSubject().equals(Subject.getSubject(AccessController.getContext())); - } - - private void invokeBlock() - { - invoke(new MessageSetFlowMode("", MessageFlowMode.CREDIT)); - invoke(new MessageStop("")); - } - - private void invokeUnblock() - { - MessageFlow mf = new MessageFlow(); - mf.setUnit(MessageCreditUnit.MESSAGE); - mf.setDestination(""); - _outstandingCredit.set(Integer.MAX_VALUE); - mf.setValue(Integer.MAX_VALUE); - invoke(mf); - } - - - @Override - protected boolean isFull(int id) - { - return isCommandsFull(id); - } - - public int enqueue(final MessageTransferMessage message, - final InstanceProperties instanceProperties, - final MessageDestination exchange) - { - if(_outstandingCredit.get() != UNLIMITED_CREDIT - && _outstandingCredit.decrementAndGet() == (Integer.MAX_VALUE - PRODUCER_CREDIT_TOPUP_THRESHOLD)) - { - _outstandingCredit.addAndGet(PRODUCER_CREDIT_TOPUP_THRESHOLD); - invoke(new MessageFlow("",MessageCreditUnit.MESSAGE, PRODUCER_CREDIT_TOPUP_THRESHOLD)); - } - int enqueues = exchange.send(message, - message.getInitialRoutingAddress(), - instanceProperties, _transaction, _checkCapacityAction - ); - getConnectionModel().registerMessageReceived(message.getSize(), message.getArrivalTime()); - incrementOutstandingTxnsIfNecessary(); - incrementUncommittedMessageSize(message.getStoredMessage()); - return enqueues; - } - - private void resetUncommittedMessages() - { - _uncommittedMessageSize = 0l; - _uncommittedMessages.clear(); - } - - private void incrementUncommittedMessageSize(final StoredMessage<MessageMetaData_0_10> handle) - { - if (isTransactional() && !(_transaction instanceof DistributedTransaction)) - { - _uncommittedMessageSize += handle.getMetaData().getContentSize(); - if (_uncommittedMessageSize > getMaxUncommittedInMemorySize()) - { - handle.flowToDisk(); - if(!_uncommittedMessages.isEmpty() || _uncommittedMessageSize == handle.getMetaData().getContentSize()) - { - getVirtualHost().getEventLogger() - .message(_logSubject, ChannelMessages.LARGE_TRANSACTION_WARN(_uncommittedMessageSize)); - } - - if(!_uncommittedMessages.isEmpty()) - { - for (StoredMessage<MessageMetaData_0_10> uncommittedHandle : _uncommittedMessages) - { - uncommittedHandle.flowToDisk(); - } - _uncommittedMessages.clear(); - } - } - else - { - _uncommittedMessages.add(handle); - } - } - } - - - public void sendMessage(MessageTransfer xfr, - Runnable postIdSettingAction) - { - getConnectionModel().registerMessageDelivered(xfr.getBodySize()); - invoke(xfr, postIdSettingAction); - } - - public void onMessageDispositionChange(MessageTransfer xfr, MessageDispositionChangeListener acceptListener) - { - _messageDispositionListenerMap.put(xfr.getId(), acceptListener); - } - - - private static interface MessageDispositionAction - { - void performAction(MessageDispositionChangeListener listener); - } - - public void accept(RangeSet ranges) - { - dispositionChange(ranges, new MessageDispositionAction() - { - public void performAction(MessageDispositionChangeListener listener) - { - listener.onAccept(); - } - }); - } - - - public void release(RangeSet ranges, final boolean setRedelivered) - { - dispositionChange(ranges, new MessageDispositionAction() - { - public void performAction(MessageDispositionChangeListener listener) - { - listener.onRelease(setRedelivered); - } - }); - } - - public void reject(RangeSet ranges) - { - dispositionChange(ranges, new MessageDispositionAction() - { - public void performAction(MessageDispositionChangeListener listener) - { - listener.onReject(); - } - }); - } - - public RangeSet acquire(RangeSet transfers) - { - RangeSet acquired = RangeSetFactory.createRangeSet(); - - if(!_messageDispositionListenerMap.isEmpty()) - { - Iterator<Integer> unacceptedMessages = _messageDispositionListenerMap.keySet().iterator(); - Iterator<Range> rangeIter = transfers.iterator(); - - if(rangeIter.hasNext()) - { - Range range = rangeIter.next(); - - while(range != null && unacceptedMessages.hasNext()) - { - int next = unacceptedMessages.next(); - while(gt(next, range.getUpper())) - { - if(rangeIter.hasNext()) - { - range = rangeIter.next(); - } - else - { - range = null; - break; - } - } - if(range != null && range.includes(next)) - { - MessageDispositionChangeListener changeListener = _messageDispositionListenerMap.get(next); - if(changeListener != null && changeListener.acquire()) - { - acquired.add(next); - } - } - - - } - - } - - - } - - return acquired; - } - - public void dispositionChange(RangeSet ranges, MessageDispositionAction action) - { - if(ranges != null) - { - - if(ranges.size() == 1) - { - Range r = ranges.getFirst(); - for(int i = r.getLower(); i <= r.getUpper(); i++) - { - MessageDispositionChangeListener changeListener = _messageDispositionListenerMap.remove(i); - if(changeListener != null) - { - action.performAction(changeListener); - } - } - } - else if(!_messageDispositionListenerMap.isEmpty()) - { - Iterator<Integer> unacceptedMessages = _messageDispositionListenerMap.keySet().iterator(); - Iterator<Range> rangeIter = ranges.iterator(); - - if(rangeIter.hasNext()) - { - Range range = rangeIter.next(); - - while(range != null && unacceptedMessages.hasNext()) - { - int next = unacceptedMessages.next(); - while(gt(next, range.getUpper())) - { - if(rangeIter.hasNext()) - { - range = rangeIter.next(); - } - else - { - range = null; - break; - } - } - if(range != null && range.includes(next)) - { - MessageDispositionChangeListener changeListener = _messageDispositionListenerMap.remove(next); - action.performAction(changeListener); - } - - - } - - } - } - } - } - - public void removeDispositionListener(Method method) - { - _messageDispositionListenerMap.remove(method.getId()); - } - - public void onClose() - { - if(_transaction instanceof LocalTransaction) - { - _transaction.rollback(); - } - else if(_transaction instanceof DistributedTransaction) - { - getVirtualHost().getDtxRegistry().endAssociations(this); - } - - for(MessageDispositionChangeListener listener : _messageDispositionListenerMap.values()) - { - listener.onRelease(true); - } - _messageDispositionListenerMap.clear(); - - for (Action<? super ServerSession> task : _taskList) - { - task.performAction(this); - } - - LogMessage operationalLoggingMessage = _forcedCloseLogMessage.get(); - if (operationalLoggingMessage == null) - { - operationalLoggingMessage = ChannelMessages.CLOSE(); - } - getVirtualHost().getEventLogger().message(getLogSubject(), operationalLoggingMessage); - } - - @Override - protected void awaitClose() - { - // Broker shouldn't block awaiting close - thus do override this method to do nothing - } - - public void acknowledge(final ConsumerTarget_0_10 sub, final MessageInstance entry) - { - _transaction.dequeue(entry.getEnqueueRecord(), - new ServerTransaction.Action() - { - - public void postCommit() - { - sub.deleteAcquired(entry); - } - - public void onRollback() - { - // The client has acknowledge the message and therefore have seen it. - // In the event of rollback, the message must be marked as redelivered. - entry.setRedelivered(); - entry.release(); - } - }); - } - - public Collection<ConsumerTarget_0_10> getSubscriptions() - { - return _subscriptions.values(); - } - - public void register(String destination, ConsumerTarget_0_10 sub) - { - _subscriptions.put(destination == null ? NULL_DESTINATION : destination, sub); - } - - - public void register(final ConsumerImpl consumerImpl) - { - if(consumerImpl instanceof Consumer<?>) - { - final Consumer<?> consumer = (Consumer<?>) consumerImpl; - _consumers.add(consumer); - consumer.addChangeListener(_consumerClosedListener); - consumerAdded(consumer); - } - } - - public ConsumerTarget_0_10 getSubscription(String destination) - { - return _subscriptions.get(destination == null ? NULL_DESTINATION : destination); - } - - public void unregister(ConsumerTarget_0_10 sub) - { - _subscriptions.remove(sub.getName()); - sub.close(); - - } - - public boolean isTransactional() - { - return _transaction.isTransactional(); - } - - public void selectTx() - { - _transaction = new LocalTransaction(this.getMessageStore()); - _txnStarts.incrementAndGet(); - } - - public void selectDtx() - { - _transaction = new DistributedTransaction(this, getMessageStore(), getVirtualHost()); - - } - - - public void startDtx(Xid xid, boolean join, boolean resume) - throws JoinAndResumeDtxException, - UnknownDtxBranchException, - AlreadyKnownDtxException, - DtxNotSelectedException - { - DistributedTransaction distributedTransaction = assertDtxTransaction(); - distributedTransaction.start(xid, join, resume); - } - - - public void endDtx(Xid xid, boolean fail, boolean suspend) - throws NotAssociatedDtxException, - UnknownDtxBranchException, - DtxNotSelectedException, - SuspendAndFailDtxException, TimeoutDtxException - { - DistributedTransaction distributedTransaction = assertDtxTransaction(); - distributedTransaction.end(xid, fail, suspend); - } - - - public long getTimeoutDtx(Xid xid) - throws UnknownDtxBranchException - { - return getVirtualHost().getDtxRegistry().getTimeout(xid); - } - - - public void setTimeoutDtx(Xid xid, long timeout) - throws UnknownDtxBranchException - { - getVirtualHost().getDtxRegistry().setTimeout(xid, timeout); - } - - - public void prepareDtx(Xid xid) - throws UnknownDtxBranchException, - IncorrectDtxStateException, StoreException, RollbackOnlyDtxException, TimeoutDtxException - { - getVirtualHost().getDtxRegistry().prepare(xid); - } - - public void commitDtx(Xid xid, boolean onePhase) - throws UnknownDtxBranchException, - IncorrectDtxStateException, StoreException, RollbackOnlyDtxException, TimeoutDtxException - { - getVirtualHost().getDtxRegistry().commit(xid, onePhase); - } - - - public void rollbackDtx(Xid xid) - throws UnknownDtxBranchException, - IncorrectDtxStateException, StoreException, TimeoutDtxException - { - getVirtualHost().getDtxRegistry().rollback(xid); - } - - - public void forgetDtx(Xid xid) throws UnknownDtxBranchException, IncorrectDtxStateException - { - getVirtualHost().getDtxRegistry().forget(xid); - } - - public List<Xid> recoverDtx() - { - return getVirtualHost().getDtxRegistry().recover(); - } - - private DistributedTransaction assertDtxTransaction() throws DtxNotSelectedException - { - if(_transaction instanceof DistributedTransaction) - { - return (DistributedTransaction) _transaction; - } - else - { - throw new DtxNotSelectedException(); - } - } - - - public void commit() - { - _transaction.commit(); - - _txnCommits.incrementAndGet(); - _txnStarts.incrementAndGet(); - decrementOutstandingTxnsIfNecessary(); - resetUncommittedMessages(); - } - - public void rollback() - { - _transaction.rollback(); - - _txnRejects.incrementAndGet(); - _txnStarts.incrementAndGet(); - decrementOutstandingTxnsIfNecessary(); - resetUncommittedMessages(); - } - - - private void incrementOutstandingTxnsIfNecessary() - { - if(isTransactional()) - { - //There can currently only be at most one outstanding transaction - //due to only having LocalTransaction support. Set value to 1 if 0. - _txnCount.compareAndSet(0,1); - } - } - - private void decrementOutstandingTxnsIfNecessary() - { - if(isTransactional()) - { - //There can currently only be at most one outstanding transaction - //due to only having LocalTransaction support. Set value to 0 if 1. - _txnCount.compareAndSet(1,0); - } - } - - public Long getTxnCommits() - { - return _txnCommits.get(); - } - - public Long getTxnRejects() - { - return _txnRejects.get(); - } - - public int getChannelId() - { - return getChannel(); - } - - public Long getTxnCount() - { - return _txnCount.get(); - } - - public Long getTxnStart() - { - return _txnStarts.get(); - } - - public Principal getAuthorizedPrincipal() - { - return getConnection().getAuthorizedPrincipal(); - } - - public Subject getAuthorizedSubject() - { - return _subject; - } - - public void addDeleteTask(Action<? super ServerSession> task) - { - _taskList.add(task); - } - - public void removeDeleteTask(Action<? super ServerSession> task) - { - _taskList.remove(task); - } - - public Object getReference() - { - return getConnection().getReference(); - } - - public MessageStore getMessageStore() - { - return getVirtualHost().getMessageStore(); - } - - public VirtualHostImpl<?,?,?> getVirtualHost() - { - return getConnection().getVirtualHost(); - } - - public boolean isDurable() - { - return false; - } - - - public long getCreateTime() - { - return _createTime; - } - - @Override - public UUID getId() - { - return _id; - } - - public ServerConnection getConnectionModel() - { - return getConnection(); - } - - public String getClientID() - { - return getConnection().getClientId(); - } - - @Override - public ServerConnection getConnection() - { - return (ServerConnection) super.getConnection(); - } - - - public LogSubject getLogSubject() - { - return this; - } - - public void checkTransactionStatus(long openWarn, long openClose, long idleWarn, long idleClose) - { - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, openWarn, openClose, idleWarn, idleClose); - } - - public void block(AMQQueue queue) - { - block(queue, queue.getName()); - } - - public void block() - { - block(this, "** All Queues **"); - } - - - private void block(final Object queue, final String name) - { - synchronized (_blockingEntities) - { - if(_blockingEntities.add(queue)) - { - - if(_blocking.compareAndSet(false,true)) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW_ENFORCED(name)); - if(getState() == State.OPEN) - { - getConnection().notifyWork(); - } - } - - - } - } - } - - public void unblock(AMQQueue queue) - { - unblock((Object)queue); - } - - public void unblock() - { - unblock(this); - } - - private void unblock(final Object queue) - { - if(_blockingEntities.remove(queue) && _blockingEntities.isEmpty()) - { - if(_blocking.compareAndSet(true,false) && !isClosing()) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW_REMOVED()); - getConnection().notifyWork(); - } - } - } - - - boolean blockingTimeoutExceeded() - { - long blockTime = _blockTime; - boolean b = _wireBlockingState && blockTime != 0 && (System.currentTimeMillis() - blockTime) > _blockingTimeout; - return b; - } - - @Override - public void transportStateChanged() - { - for(ConsumerTarget_0_10 consumerTarget : getSubscriptions()) - { - consumerTarget.transportStateChanged(); - } - } - - @Override - public Object getConnectionReference() - { - return getConnection().getReference(); - } - - public String toLogString() - { - long connectionId = super.getConnection() instanceof ServerConnection - ? getConnection().getConnectionId() - : -1; - - String remoteAddress = String.valueOf(getConnection().getRemoteAddress()); - return "[" + - MessageFormat.format(CHANNEL_FORMAT, - connectionId, - getClientID(), - remoteAddress, - getVirtualHost().getName(), - getChannel()) - + "] "; - } - - @Override - public void close(AMQConstant cause, String message) - { - if (cause == null) - { - close(); - } - else - { - close(cause.getCode(), message); - } - } - - void close(int cause, String message) - { - _forcedCloseLogMessage.compareAndSet(null, ChannelMessages.CLOSE_FORCED(cause, message)); - close(); - } - - @Override - public void close() - { - // unregister subscriptions in order to prevent sending of new messages - // to subscriptions with closing session - unregisterSubscriptions(); - if(_modelObject != null) - { - _modelObject.delete(); - } - super.close(); - } - - void unregisterSubscriptions() - { - final Collection<ConsumerTarget_0_10> subscriptions = getSubscriptions(); - for (ConsumerTarget_0_10 subscription_0_10 : subscriptions) - { - unregister(subscription_0_10); - } - } - - void stopSubscriptions() - { - final Collection<ConsumerTarget_0_10> subscriptions = getSubscriptions(); - for (ConsumerTarget_0_10 subscription_0_10 : subscriptions) - { - subscription_0_10.stop(); - } - } - - - public void receivedComplete() - { - final Collection<ConsumerTarget_0_10> subscriptions = getSubscriptions(); - for (ConsumerTarget_0_10 subscription_0_10 : subscriptions) - { - subscription_0_10.flushCreditState(false); - } - awaitCommandCompletion(); - } - - public int getUnacknowledgedMessageCount() - { - return _messageDispositionListenerMap.size(); - } - - public boolean getBlocking() - { - return _blocking.get(); - } - - private final LinkedList<AsyncCommand> _unfinishedCommandsQueue = new LinkedList<AsyncCommand>(); - - public void completeAsyncCommands() - { - AsyncCommand cmd; - while((cmd = _unfinishedCommandsQueue.peek()) != null && cmd.isReadyForCompletion()) - { - cmd.complete(); - _unfinishedCommandsQueue.poll(); - } - while(_unfinishedCommandsQueue.size() > UNFINISHED_COMMAND_QUEUE_THRESHOLD) - { - cmd = _unfinishedCommandsQueue.poll(); - cmd.awaitReadyForCompletion(); - cmd.complete(); - } - } - - - public void awaitCommandCompletion() - { - AsyncCommand cmd; - while((cmd = _unfinishedCommandsQueue.poll()) != null) - { - cmd.awaitReadyForCompletion(); - cmd.complete(); - } - } - - - public Object getAsyncCommandMark() - { - return _unfinishedCommandsQueue.isEmpty() ? null : _unfinishedCommandsQueue.getLast(); - } - - public void recordFuture(final FutureResult future, final ServerTransaction.Action action) - { - _unfinishedCommandsQueue.add(new AsyncCommand(future, action)); - } - - private static class AsyncCommand - { - private final FutureResult _future; - private ServerTransaction.Action _action; - - public AsyncCommand(final FutureResult future, final ServerTransaction.Action action) - { - _future = future; - _action = action; - } - - void awaitReadyForCompletion() - { - _future.waitForCompletion(); - } - - void complete() - { - if(!_future.isComplete()) - { - _future.waitForCompletion(); - } - _action.postCommit(); - _action = null; - } - - boolean isReadyForCompletion() - { - return _future.isComplete(); - } - } - - protected void setClose(boolean close) - { - super.setClose(close); - } - - @Override - public int getConsumerCount() - { - return _subscriptions.values().size(); - } - - @Override - public Collection<Consumer<?>> getConsumers() - { - - return Collections.unmodifiableCollection(_consumers); - } - - @Override - public void addConsumerListener(final ConsumerListener listener) - { - _consumerListeners.add(listener); - } - - @Override - public void removeConsumerListener(final ConsumerListener listener) - { - _consumerListeners.remove(listener); - } - - @Override - public void setModelObject(final org.apache.qpid.server.model.Session<?> session) - { - _modelObject = session; - } - - @Override - public org.apache.qpid.server.model.Session<?> getModelObject() - { - return _modelObject; - } - - @Override - public long getTransactionStartTime() - { - ServerTransaction serverTransaction = _transaction; - if (serverTransaction.isTransactional()) - { - return serverTransaction.getTransactionStartTime(); - } - else - { - return 0L; - } - } - - @Override - public long getTransactionUpdateTime() - { - ServerTransaction serverTransaction = _transaction; - if (serverTransaction.isTransactional()) - { - return serverTransaction.getTransactionUpdateTime(); - } - else - { - return 0L; - } - } - - private void consumerAdded(Consumer<?> consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerAdded(consumer); - } - } - - private void consumerRemoved(Consumer<?> consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerRemoved(consumer); - } - } - - @Override - public void processPending() - { - boolean desiredBlockingState = _blocking.get(); - if (desiredBlockingState != _wireBlockingState) - { - _wireBlockingState = desiredBlockingState; - - if (desiredBlockingState) - { - invokeBlock(); - } - else - { - invokeUnblock(); - } - _blockTime = desiredBlockingState ? System.currentTimeMillis() : 0; - } - - - for(ConsumerTarget target : getSubscriptions()) - { - target.processPending(); - } - } - - - public final long getMaxUncommittedInMemorySize() - { - return _maxUncommittedInMemorySize; - } - - @Override - public int compareTo(AMQSessionModel o) - { - return getId().compareTo(o.getId()); - } - - private class CheckCapacityAction implements Action<MessageInstance> - { - @Override - public void performAction(final MessageInstance entry) - { - TransactionLogResource queue = entry.getOwningResource(); - if(queue instanceof CapacityChecker) - { - ((CapacityChecker)queue).checkCapacity(ServerSession.this); - } - } - } - - private class ConsumerClosedListener implements ConfigurationChangeListener - { - @Override - public void stateChanged(final ConfiguredObject object, final org.apache.qpid.server.model.State oldState, final org.apache.qpid.server.model.State newState) - { - if(newState == org.apache.qpid.server.model.State.DELETED) - { - consumerRemoved((Consumer<?>)object); - } - } - - @Override - public void childAdded(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void childRemoved(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void attributeSet(final ConfiguredObject object, - final String attributeName, - final Object oldAttributeValue, - final Object newAttributeValue) - { - - } - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java deleted file mode 100644 index 694dda4da2..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java +++ /dev/null @@ -1,1656 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import java.nio.ByteBuffer; -import java.security.AccessControlException; -import java.util.Collection; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.store.MessageHandle; -import org.apache.qpid.server.virtualhost.VirtualHostUnavailableException; -import org.apache.qpid.server.filter.AMQInvalidArgumentException; -import org.apache.qpid.server.filter.ArrivalTimeFilter; -import org.apache.qpid.server.filter.FilterManager; -import org.apache.qpid.server.filter.FilterManagerFactory; -import org.apache.qpid.server.filter.MessageFilter; -import org.apache.qpid.server.logging.messages.ChannelMessages; -import org.apache.qpid.server.logging.messages.ExchangeMessages; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.model.ExclusivityPolicy; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.NoFactoryForTypeException; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.UnknownConfiguredObjectException; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueArgumentsConverter; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.server.util.FutureResult; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.txn.AlreadyKnownDtxException; -import org.apache.qpid.server.txn.DtxNotSelectedException; -import org.apache.qpid.server.txn.IncorrectDtxStateException; -import org.apache.qpid.server.txn.JoinAndResumeDtxException; -import org.apache.qpid.server.txn.NotAssociatedDtxException; -import org.apache.qpid.server.txn.RollbackOnlyDtxException; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.txn.SuspendAndFailDtxException; -import org.apache.qpid.server.txn.TimeoutDtxException; -import org.apache.qpid.server.txn.UnknownDtxBranchException; -import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.server.virtualhost.ExchangeExistsException; -import org.apache.qpid.server.virtualhost.ExchangeIsAlternateException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.apache.qpid.server.virtualhost.RequiredExchangeException; -import org.apache.qpid.server.virtualhost.ReservedExchangeNameException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.*; - -public class ServerSessionDelegate extends SessionDelegate -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ServerSessionDelegate.class); - - public ServerSessionDelegate() - { - - } - - @Override - public void command(Session session, Method method) - { - try - { - if(!session.isClosing()) - { - Object asyncCommandMark = ((ServerSession)session).getAsyncCommandMark(); - super.command(session, method, false); - Object newOutstanding = ((ServerSession)session).getAsyncCommandMark(); - if(newOutstanding == null || newOutstanding == asyncCommandMark) - { - session.processed(method); - } - - if(newOutstanding != null) - { - ((ServerSession)session).completeAsyncCommands(); - } - - if (method.isSync()) - { - ((ServerSession)session).awaitCommandCompletion(); - session.flushProcessed(); - } - } - } - catch(RuntimeException e) - { - LOGGER.error("Exception processing command", e); - exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, "Exception processing command: " + e); - if(e instanceof ServerScopedRuntimeException) - { - throw e; - } - } - } - - @Override - public void messageAccept(Session session, MessageAccept method) - { - final ServerSession serverSession = (ServerSession) session; - serverSession.accept(method.getTransfers()); - if(!serverSession.isTransactional()) - { - serverSession.recordFuture(FutureResult.IMMEDIATE_FUTURE, - new CommandProcessedAction(serverSession, method)); - } - } - - @Override - public void messageReject(Session session, MessageReject method) - { - ((ServerSession)session).reject(method.getTransfers()); - } - - @Override - public void messageRelease(Session session, MessageRelease method) - { - ((ServerSession)session).release(method.getTransfers(), method.getSetRedelivered()); - } - - @Override - public void messageAcquire(Session session, MessageAcquire method) - { - RangeSet acquiredRanges = ((ServerSession)session).acquire(method.getTransfers()); - - Acquired result = new Acquired(acquiredRanges); - - - session.executionResult((int) method.getId(), result); - - - } - - @Override - public void messageResume(Session session, MessageResume method) - { - super.messageResume(session, method); - } - - @Override - public void messageSubscribe(Session session, MessageSubscribe method) - { - /* - TODO - work around broken Python tests - Correct code should read like - if not hasAcceptMode() exception ILLEGAL_ARGUMENT "Accept-mode not supplied" - else if not method.hasAcquireMode() exception ExecutionErrorCode.ILLEGAL_ARGUMENT, "Acquire-mode not supplied" - */ - if(!method.hasAcceptMode()) - { - method.setAcceptMode(MessageAcceptMode.EXPLICIT); - } - if(!method.hasAcquireMode()) - { - method.setAcquireMode(MessageAcquireMode.PRE_ACQUIRED); - - } - - if(!method.hasQueue()) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "queue not supplied"); - } - else - { - String destination = method.getDestination(); - - if(((ServerSession)session).getSubscription(destination)!=null) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Subscription already exists with destination '"+destination+"'"); - } - else - { - String queueName = method.getQueue(); - VirtualHostImpl<?,?,?> vhost = getVirtualHost(session); - - final Collection<MessageSource> sources = new HashSet<>(); - final MessageSource queue = vhost.getMessageSource(queueName); - if(queue != null) - { - sources.add(queue); - } - else if(vhost.getContextValue(Boolean.class, "qpid.enableMultiQueueConsumers") - && method.getArguments() != null - && method.getArguments().get("x-multiqueue") instanceof Collection) - { - for(Object object : (Collection<Object>)method.getArguments().get("x-multiqueue")) - { - String sourceName = String.valueOf(object); - sourceName = sourceName.trim(); - if(sourceName.length() != 0) - { - MessageSource source = vhost.getMessageSource(sourceName); - if(source == null) - { - sources.clear(); - break; - } - else - { - sources.add(source); - } - } - } - queueName = method.getArguments().get("x-multiqueue").toString(); - } - - if(sources.isEmpty()) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "Queue: " + queueName + " not found"); - } - else if(!verifySessionAccess((ServerSession) session, sources)) - { - exception(session,method,ExecutionErrorCode.RESOURCE_LOCKED, "Exclusive Queue: " + queueName + " owned exclusively by another session"); - } - else - { - ServerProtocolEngine serverProtocolEngine = getServerConnection(session).getProtocolEngine(); - FlowCreditManager_0_10 creditManager = new WindowCreditManager(0L,0L, serverProtocolEngine); - - FilterManager filterManager = null; - try - { - filterManager = FilterManagerFactory.createManager(method.getArguments()); - } - catch (AMQInvalidArgumentException amqe) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "Exception Creating FilterManager"); - return; - } - - - if(method.hasArguments() && method.getArguments().containsKey(AMQPFilterTypes.REPLAY_PERIOD.toString())) - { - Object value = method.getArguments().get(AMQPFilterTypes.REPLAY_PERIOD.toString()); - final long period; - if(value instanceof Number) - { - period = ((Number)value).longValue(); - } - else if(value instanceof String) - { - try - { - period = Long.parseLong(value.toString()); - } - catch (NumberFormatException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "Cannot parse value " + value + " as a number for filter " + AMQPFilterTypes.REPLAY_PERIOD.toString()); - return; - } - } - else - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "Cannot parse value " + value + " as a number for filter " + AMQPFilterTypes.REPLAY_PERIOD.toString()); - return; - } - final long startingFrom = System.currentTimeMillis() - (1000l * period); - if(filterManager == null) - { - filterManager = new FilterManager(); - } - MessageFilter filter = new ArrivalTimeFilter(startingFrom, period == 0); - filterManager.add(filter.getName(), filter); - - } - - - ConsumerTarget_0_10 target = new ConsumerTarget_0_10((ServerSession)session, destination, - method.getAcceptMode(), - method.getAcquireMode(), - MessageFlowMode.WINDOW, - creditManager, - method.getArguments() - ); - - ((ServerSession)session).register(destination, target); - try - { - EnumSet<ConsumerImpl.Option> options = EnumSet.noneOf(ConsumerImpl.Option.class); - if(method.getAcquireMode() == MessageAcquireMode.PRE_ACQUIRED) - { - options.add(ConsumerImpl.Option.ACQUIRES); - } - if(method.getAcquireMode() != MessageAcquireMode.NOT_ACQUIRED || method.getAcceptMode() == MessageAcceptMode.EXPLICIT) - { - options.add(ConsumerImpl.Option.SEES_REQUEUES); - } - if(method.getExclusive()) - { - options.add(ConsumerImpl.Option.EXCLUSIVE); - } - for(MessageSource source : sources) - { - ((ServerSession) session).register( - source.addConsumer(target, - filterManager, - MessageTransferMessage.class, - destination, - options)); - } - } - catch (AMQQueue.ExistingExclusiveConsumer existing) - { - exception(session, method, ExecutionErrorCode.RESOURCE_LOCKED, "Queue has an exclusive consumer"); - } - catch (AMQQueue.ExistingConsumerPreventsExclusive exclusive) - { - exception(session, method, ExecutionErrorCode.RESOURCE_LOCKED, "Queue has an existing consumer - can't subscribe exclusively"); - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - catch (MessageSource.ConsumerAccessRefused consumerAccessRefused) - { - exception(session, method, ExecutionErrorCode.RESOURCE_LOCKED, "Queue has an incompatible exclusivity policy"); - } - } - } - } - } - - protected boolean verifySessionAccess(final ServerSession session, final Collection<MessageSource> queues) - { - for(MessageSource source : queues) - { - if(!verifySessionAccess(session, source)) - { - return false; - } - } - return true; - } - - protected boolean verifySessionAccess(final ServerSession session, final MessageSource queue) - { - return queue.verifySessionAccess(session); - } - - @Override - public void messageTransfer(Session ssn, final MessageTransfer xfr) - { - ServerSession serverSession = (ServerSession) ssn; - if(serverSession.blockingTimeoutExceeded()) - { - getVirtualHost(ssn).getEventLogger().message(ChannelMessages.FLOW_CONTROL_IGNORED()); - - serverSession.close(AMQConstant.MESSAGE_TOO_LARGE, - "Session flow control was requested, but not enforced by sender"); - } - else if(xfr.getBodySize() > serverSession.getConnection().getMaxMessageSize()) - { - exception(ssn, xfr, ExecutionErrorCode.RESOURCE_LIMIT_EXCEEDED, - "Message size of " + xfr.getBodySize() + " greater than allowed maximum of " + serverSession.getConnection().getMaxMessageSize()); - } - else - { - final MessageDestination destination = getDestinationForMessage(ssn, xfr); - - final DeliveryProperties delvProps = - xfr.getHeader() == null ? null : xfr.getHeader().getDeliveryProperties(); - if (delvProps != null && delvProps.hasTtl() && !delvProps.hasExpiration()) - { - delvProps.setExpiration(System.currentTimeMillis() + delvProps.getTtl()); - } - - final MessageMetaData_0_10 messageMetaData = new MessageMetaData_0_10(xfr); - - final VirtualHostImpl virtualHost = getVirtualHost(ssn); - try - { - virtualHost.getSecurityManager() - .authorisePublish(messageMetaData.isImmediate(), - messageMetaData.getRoutingKey(), - destination.getName(), - virtualHost.getName()); - } - catch (AccessControlException e) - { - ExecutionErrorCode errorCode = ExecutionErrorCode.UNAUTHORIZED_ACCESS; - exception(ssn, xfr, errorCode, e.getMessage()); - - return; - } - - final MessageStore store = virtualHost.getMessageStore(); - final StoredMessage<MessageMetaData_0_10> storeMessage = createStoreMessage(xfr, messageMetaData, store); - final MessageTransferMessage message = - new MessageTransferMessage(storeMessage, serverSession.getReference()); - MessageReference<MessageTransferMessage> reference = message.newReference(); - - try - { - final InstanceProperties instanceProperties = new InstanceProperties() - { - @Override - public Object getProperty(final Property prop) - { - switch (prop) - { - case EXPIRATION: - return message.getExpiration(); - case IMMEDIATE: - return message.isImmediate(); - case MANDATORY: - return (delvProps == null || !delvProps.getDiscardUnroutable()) - && xfr.getAcceptMode() == MessageAcceptMode.EXPLICIT; - case PERSISTENT: - return message.isPersistent(); - case REDELIVERED: - return delvProps.getRedelivered(); - } - return null; - } - }; - - int enqueues = serverSession.enqueue(message, instanceProperties, destination); - - if (enqueues == 0) - { - if ((delvProps == null || !delvProps.getDiscardUnroutable()) - && xfr.getAcceptMode() == MessageAcceptMode.EXPLICIT) - { - RangeSet rejects = RangeSetFactory.createRangeSet(); - rejects.add(xfr.getId()); - MessageReject reject = new MessageReject(rejects, MessageRejectCode.UNROUTABLE, "Unroutable"); - ssn.invoke(reject); - } - else - { - virtualHost.getEventLogger().message(ExchangeMessages.DISCARDMSG(destination.getName(), - messageMetaData.getRoutingKey())); - } - } - - if (serverSession.isTransactional()) - { - serverSession.processed(xfr); - } - else - { - serverSession.recordFuture(FutureResult.IMMEDIATE_FUTURE, - new CommandProcessedAction(serverSession, xfr)); - } - } - catch (VirtualHostUnavailableException e) - { - getServerConnection(serverSession).closeAsync(AMQConstant.CONNECTION_FORCED, e.getMessage()); - } - finally - { - reference.release(); - } - - } - } - - private StoredMessage<MessageMetaData_0_10> createStoreMessage(final MessageTransfer xfr, - final MessageMetaData_0_10 messageMetaData, final MessageStore store) - { - final MessageHandle<MessageMetaData_0_10> addedMessage = store.addMessage(messageMetaData); - ByteBuffer body = xfr.getBody(); - if(body != null) - { - addedMessage.addContent(body); - } - final StoredMessage<MessageMetaData_0_10> storedMessage = addedMessage.allContentAdded(); - return storedMessage; - } - - @Override - public void messageCancel(Session session, MessageCancel method) - { - String destination = method.getDestination(); - - ConsumerTarget_0_10 sub = ((ServerSession)session).getSubscription(destination); - - if(sub == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "not-found: destination '"+destination+"'"); - } - else - { - ((ServerSession)session).unregister(sub); - } - } - - @Override - public void messageFlush(Session session, MessageFlush method) - { - String destination = method.getDestination(); - - ConsumerTarget_0_10 sub = ((ServerSession)session).getSubscription(destination); - - if(sub == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "not-found: destination '"+destination+"'"); - } - else - { - sub.flush(); - } - } - - @Override - public void txSelect(Session session, TxSelect method) - { - // TODO - check current tx mode - ((ServerSession)session).selectTx(); - } - - @Override - public void txCommit(Session session, TxCommit method) - { - // TODO - check current tx mode - ((ServerSession)session).commit(); - } - - @Override - public void txRollback(Session session, TxRollback method) - { - // TODO - check current tx mode - ((ServerSession)session).rollback(); - } - - @Override - public void dtxSelect(Session session, DtxSelect method) - { - // TODO - check current tx mode - ((ServerSession)session).selectDtx(); - } - - @Override - public void dtxStart(Session session, DtxStart method) - { - XaResult result = new XaResult(); - result.setStatus(DtxXaStatus.XA_OK); - try - { - ((ServerSession)session).startDtx(method.getXid(), method.getJoin(), method.getResume()); - session.executionResult(method.getId(), result); - } - catch(JoinAndResumeDtxException e) - { - exception(session, method, ExecutionErrorCode.COMMAND_INVALID, e.getMessage()); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Unknown xid " + method.getXid()); - } - catch(AlreadyKnownDtxException e) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Xid already started an neither join nor " + - "resume set" + method.getXid()); - } - catch(DtxNotSelectedException e) - { - exception(session, method, ExecutionErrorCode.COMMAND_INVALID, e.getMessage()); - } - - } - - @Override - public void dtxEnd(Session session, DtxEnd method) - { - XaResult result = new XaResult(); - result.setStatus(DtxXaStatus.XA_OK); - try - { - try - { - ((ServerSession) session).endDtx(method.getXid(), method.getFail(), method.getSuspend()); - } - catch (TimeoutDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBTIMEOUT); - } - session.executionResult(method.getId(), result); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(NotAssociatedDtxException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(DtxNotSelectedException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(SuspendAndFailDtxException e) - { - exception(session, method, ExecutionErrorCode.COMMAND_INVALID, e.getMessage()); - } - - } - - @Override - public void dtxCommit(Session session, DtxCommit method) - { - XaResult result = new XaResult(); - result.setStatus(DtxXaStatus.XA_OK); - try - { - try - { - ((ServerSession)session).commitDtx(method.getXid(), method.getOnePhase()); - } - catch (RollbackOnlyDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBROLLBACK); - } - catch (TimeoutDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBTIMEOUT); - } - session.executionResult(method.getId(), result); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - catch(IncorrectDtxStateException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(StoreException e) - { - exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, e.getMessage()); - throw e; - } - } - - @Override - public void dtxForget(Session session, DtxForget method) - { - try - { - ((ServerSession)session).forgetDtx(method.getXid()); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - catch(IncorrectDtxStateException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - - } - - @Override - public void dtxGetTimeout(Session session, DtxGetTimeout method) - { - GetTimeoutResult result = new GetTimeoutResult(); - try - { - result.setTimeout(((ServerSession) session).getTimeoutDtx(method.getXid())); - session.executionResult(method.getId(), result); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - } - - @Override - public void dtxPrepare(Session session, DtxPrepare method) - { - XaResult result = new XaResult(); - result.setStatus(DtxXaStatus.XA_OK); - try - { - try - { - ((ServerSession)session).prepareDtx(method.getXid()); - } - catch (RollbackOnlyDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBROLLBACK); - } - catch (TimeoutDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBTIMEOUT); - } - session.executionResult((int) method.getId(), result); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - catch(IncorrectDtxStateException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(StoreException e) - { - exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, e.getMessage()); - throw e; - } - } - - @Override - public void dtxRecover(Session session, DtxRecover method) - { - RecoverResult result = new RecoverResult(); - List inDoubt = ((ServerSession)session).recoverDtx(); - result.setInDoubt(inDoubt); - session.executionResult(method.getId(), result); - } - - @Override - public void dtxRollback(Session session, DtxRollback method) - { - - XaResult result = new XaResult(); - result.setStatus(DtxXaStatus.XA_OK); - try - { - try - { - ((ServerSession)session).rollbackDtx(method.getXid()); - } - catch (TimeoutDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBTIMEOUT); - } - session.executionResult(method.getId(), result); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - catch(IncorrectDtxStateException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(StoreException e) - { - exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, e.getMessage()); - throw e; - } - } - - @Override - public void dtxSetTimeout(Session session, DtxSetTimeout method) - { - try - { - ((ServerSession)session).setTimeoutDtx(method.getXid(), method.getTimeout()); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - } - - @Override - public void executionSync(final Session ssn, final ExecutionSync sync) - { - ((ServerSession)ssn).awaitCommandCompletion(); - super.executionSync(ssn, sync); - } - - @Override - public void exchangeDeclare(Session session, ExchangeDeclare method) - { - String exchangeName = method.getExchange(); - VirtualHostImpl virtualHost = getVirtualHost(session); - - //we must check for any unsupported arguments present and throw not-implemented - if(method.hasArguments()) - { - Map<String,Object> args = method.getArguments(); - //QPID-3392: currently we don't support any! - if(!args.isEmpty()) - { - exception(session, method, ExecutionErrorCode.NOT_IMPLEMENTED, "Unsupported exchange argument(s) found " + args.keySet().toString()); - return; - } - } - if(nameNullOrEmpty(method.getExchange())) - { - // special case handling to fake the existence of the default exchange for 0-10 - if(!ExchangeDefaults.DIRECT_EXCHANGE_CLASS.equals(method.getType())) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, - "Attempt to redeclare default exchange " - + " of type " + ExchangeDefaults.DIRECT_EXCHANGE_CLASS - + " to " + method.getType() +"."); - } - if(!nameNullOrEmpty(method.getAlternateExchange())) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, - "Attempt to set alternate exchange of the default exchange " - + " to " + method.getAlternateExchange() +"."); - } - } - else - { - if(method.getPassive()) - { - - ExchangeImpl exchange = getExchange(session, exchangeName); - - if(exchange == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "not-found: exchange-name '" + exchangeName + "'"); - } - else - { - if (!exchange.getType().equals(method.getType()) - && (method.getType() != null && method.getType().length() > 0)) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Attempt to redeclare exchange: " - + exchangeName + " of type " + exchange.getType() + " to " + method.getType() + "."); - } - } - } - else - { - - try - { - Map<String,Object> attributes = new HashMap<String, Object>(); - - attributes.put(org.apache.qpid.server.model.Exchange.ID, null); - attributes.put(org.apache.qpid.server.model.Exchange.NAME, method.getExchange()); - attributes.put(org.apache.qpid.server.model.Exchange.TYPE, method.getType()); - attributes.put(org.apache.qpid.server.model.Exchange.DURABLE, method.getDurable()); - attributes.put(org.apache.qpid.server.model.Exchange.LIFETIME_POLICY, - method.getAutoDelete() ? LifetimePolicy.DELETE_ON_NO_LINKS : LifetimePolicy.PERMANENT); - attributes.put(org.apache.qpid.server.model.Exchange.ALTERNATE_EXCHANGE, method.getAlternateExchange()); - virtualHost.createExchange(attributes); - } - catch(ReservedExchangeNameException e) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Attempt to declare exchange: " - + exchangeName + " which begins with reserved name or prefix."); - } - catch(UnknownConfiguredObjectException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, - "Unknown alternate exchange " + e.getName()); - } - catch(NoFactoryForTypeException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "Unknown Exchange Type: " + method.getType()); - } - catch(ExchangeExistsException e) - { - ExchangeImpl exchange = e.getExistingExchange(); - if(!exchange.getType().equals(method.getType())) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, - "Attempt to redeclare exchange: " + exchangeName - + " of type " + exchange.getType() - + " to " + method.getType() +"."); - } - else if(method.hasAlternateExchange() - && (exchange.getAlternateExchange() == null || - !method.getAlternateExchange().equals(exchange.getAlternateExchange().getName()))) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, - "Attempt to change alternate exchange of: " + exchangeName - + " from " + exchange.getAlternateExchange() - + " to " + method.getAlternateExchange() +"."); - } - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - - - } - } - } - - private void exception(Session session, Method method, ExecutionErrorCode errorCode, String description) - { - ExecutionException ex = new ExecutionException(); - ex.setErrorCode(errorCode); - ex.setCommandId(method.getId()); - ex.setDescription(description); - - session.invoke(ex); - - ((ServerSession)session).close(errorCode.getValue(), description); - } - - private ExchangeImpl getExchange(Session session, String exchangeName) - { - return getVirtualHost(session).getExchange(exchangeName); - } - - private MessageDestination getDestinationForMessage(Session ssn, MessageTransfer xfr) - { - VirtualHostImpl virtualHost = getVirtualHost(ssn); - - MessageDestination destination; - if(xfr.hasDestination()) - { - destination = virtualHost.getMessageDestination(xfr.getDestination()); - if(destination == null) - { - destination = virtualHost.getDefaultDestination(); - } - } - else - { - destination = virtualHost.getDefaultDestination(); - } - return destination; - } - - private VirtualHostImpl<?,?,?> getVirtualHost(Session session) - { - ServerConnection conn = getServerConnection(session); - return conn.getVirtualHost(); - } - - private ServerConnection getServerConnection(Session session) - { - return (ServerConnection) session.getConnection(); - } - - @Override - public void exchangeDelete(Session session, ExchangeDelete method) - { - VirtualHostImpl virtualHost = getVirtualHost(session); - - try - { - if (nameNullOrEmpty(method.getExchange())) - { - exception(session, method, ExecutionErrorCode.INVALID_ARGUMENT, "Delete not allowed for default exchange"); - return; - } - - ExchangeImpl exchange = getExchange(session, method.getExchange()); - - if(exchange == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "No such exchange '" + method.getExchange() + "'"); - } - else - { - virtualHost.removeExchange(exchange, !method.getIfUnused()); - } - } - catch (ExchangeIsAlternateException e) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Exchange in use as an alternate exchange"); - } - catch (RequiredExchangeException e) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Exchange '"+method.getExchange()+"' cannot be deleted"); - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - - private boolean nameNullOrEmpty(String name) - { - if(name == null || name.length() == 0) - { - return true; - } - - return false; - } - - @Override - public void exchangeQuery(Session session, ExchangeQuery method) - { - - ExchangeQueryResult result = new ExchangeQueryResult(); - - - final String exchangeName = method.getName(); - - if(nameNullOrEmpty(exchangeName)) - { - // Fake the existence of the "default" exchange for 0-10 - result.setDurable(true); - result.setType(ExchangeDefaults.DIRECT_EXCHANGE_CLASS); - result.setNotFound(false); - } - else - { - ExchangeImpl exchange = getExchange(session, exchangeName); - - if(exchange != null) - { - result.setDurable(exchange.isDurable()); - result.setType(exchange.getType()); - result.setNotFound(false); - } - else - { - result.setNotFound(true); - } - } - session.executionResult((int) method.getId(), result); - } - - @Override - public void exchangeBind(Session session, ExchangeBind method) - { - - VirtualHostImpl virtualHost = getVirtualHost(session); - - if (!method.hasQueue()) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "queue not set"); - } - else - { - final String exchangeName = method.getExchange(); - if (nameNullOrEmpty(exchangeName)) - { - exception(session, method, ExecutionErrorCode.INVALID_ARGUMENT, "Bind not allowed for default exchange"); - } - else - { - //TODO - here because of non-compliant python tests - // should raise exception ILLEGAL_ARGUMENT "binding-key not set" - if (!method.hasBindingKey()) - { - method.setBindingKey(method.getQueue()); - } - AMQQueue queue = virtualHost.getQueue(method.getQueue()); - ExchangeImpl exchange = virtualHost.getExchange(exchangeName); - if(queue == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "Queue: '" + method.getQueue() + "' not found"); - } - else if(exchange == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "Exchange: '" + exchangeName + "' not found"); - } - else if(exchange.getType().equals(ExchangeDefaults.HEADERS_EXCHANGE_CLASS) && (!method.hasArguments() || method.getArguments() == null || !method.getArguments().containsKey("x-match"))) - { - exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, "Bindings to an exchange of type " + ExchangeDefaults.HEADERS_EXCHANGE_CLASS + " require an x-match header"); - } - else - { - if (!exchange.isBound(method.getBindingKey(), method.getArguments(), queue)) - { - try - { - exchange.addBinding(method.getBindingKey(), queue, method.getArguments()); - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - else - { - // todo - } - } - - - } - } - - - - } - - @Override - public void exchangeUnbind(Session session, ExchangeUnbind method) - { - VirtualHostImpl virtualHost = getVirtualHost(session); - - if (!method.hasQueue()) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "queue not set"); - } - else if (nameNullOrEmpty(method.getExchange())) - { - exception(session, method, ExecutionErrorCode.INVALID_ARGUMENT, "Unbind not allowed for default exchange"); - } - else if (!method.hasBindingKey()) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "binding-key not set"); - } - else - { - AMQQueue queue = virtualHost.getQueue(method.getQueue()); - ExchangeImpl exchange = virtualHost.getExchange(method.getExchange()); - if(queue == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "Queue: '" + method.getQueue() + "' not found"); - } - else if(exchange == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "Exchange: '" + method.getExchange() + "' not found"); - } - else - { - try - { - if(exchange.hasBinding(method.getBindingKey(), queue)) - { - exchange.deleteBinding(method.getBindingKey(), queue); - } - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - } - } - - @Override - public void exchangeBound(Session session, ExchangeBound method) - { - - ExchangeBoundResult result = new ExchangeBoundResult(); - VirtualHostImpl virtualHost = getVirtualHost(session); - ExchangeImpl exchange; - AMQQueue queue; - boolean isDefaultExchange; - if(!nameNullOrEmpty(method.getExchange())) - { - isDefaultExchange = false; - exchange = virtualHost.getExchange(method.getExchange()); - - if(exchange == null) - { - result.setExchangeNotFound(true); - } - } - else - { - isDefaultExchange = true; - exchange = null; - } - - if(isDefaultExchange) - { - // fake the existence of the "default" exchange for 0-10 - if(method.hasQueue()) - { - queue = getQueue(session, method.getQueue()); - - if(queue == null) - { - result.setQueueNotFound(true); - } - else - { - if(method.hasBindingKey()) - { - if(!method.getBindingKey().equals(method.getQueue())) - { - result.setKeyNotMatched(true); - } - } - } - } - else if(method.hasBindingKey()) - { - if(getQueue(session, method.getBindingKey()) == null) - { - result.setKeyNotMatched(true); - } - } - - if(method.hasArguments() && !method.getArguments().isEmpty()) - { - result.setArgsNotMatched(true); - } - - - } - else if(method.hasQueue()) - { - - queue = getQueue(session, method.getQueue()); - if(queue == null) - { - result.setQueueNotFound(true); - } - - - if(exchange != null && queue != null) - { - - boolean queueMatched = exchange.isBound(queue); - - result.setQueueNotMatched(!queueMatched); - - - if(method.hasBindingKey()) - { - - if(queueMatched) - { - final boolean keyMatched = exchange.isBound(method.getBindingKey(), queue); - result.setKeyNotMatched(!keyMatched); - if(method.hasArguments()) - { - if(keyMatched) - { - result.setArgsNotMatched(!exchange.isBound(method.getBindingKey(), method.getArguments(), queue)); - } - else - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments(), queue)); - } - } - } - else - { - boolean keyMatched = exchange.isBound(method.getBindingKey()); - result.setKeyNotMatched(!keyMatched); - if(method.hasArguments()) - { - if(keyMatched) - { - result.setArgsNotMatched(!exchange.isBound(method.getBindingKey(), method.getArguments())); - } - else - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments())); - } - } - } - - } - else if (method.hasArguments()) - { - if(queueMatched) - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments(), queue)); - } - else - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments())); - } - } - - } - else if(exchange != null && method.hasBindingKey()) - { - final boolean keyMatched = exchange.isBound(method.getBindingKey()); - result.setKeyNotMatched(!keyMatched); - - if(method.hasArguments()) - { - if(keyMatched) - { - result.setArgsNotMatched(!exchange.isBound(method.getBindingKey(), method.getArguments())); - } - else - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments())); - } - } - - - } - - } - else if(exchange != null && method.hasBindingKey()) - { - final boolean keyMatched = exchange.isBound(method.getBindingKey()); - result.setKeyNotMatched(!keyMatched); - - if(method.hasArguments()) - { - if(keyMatched) - { - result.setArgsNotMatched(!exchange.isBound(method.getBindingKey(), method.getArguments())); - } - else - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments())); - } - } - - } - else if(exchange != null && method.hasArguments()) - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments())); - } - - - session.executionResult((int) method.getId(), result); - - - } - - private AMQQueue getQueue(Session session, String queue) - { - return getVirtualHost(session).getQueue(queue); - } - - @Override - public void queueDeclare(Session session, final QueueDeclare method) - { - - final VirtualHostImpl virtualHost = getVirtualHost(session); - - String queueName = method.getQueue(); - AMQQueue queue; - //TODO: do we need to check that the queue already exists with exactly the same "configuration"? - - final boolean exclusive = method.getExclusive(); - final boolean autoDelete = method.getAutoDelete(); - - if(method.getPassive()) - { - queue = virtualHost.getQueue(queueName); - - if (queue == null) - { - String description = "Queue: " + queueName + " not found on VirtualHost(" + virtualHost + ")."; - ExecutionErrorCode errorCode = ExecutionErrorCode.NOT_FOUND; - - exception(session, method, errorCode, description); - - } - else if (exclusive) - { - if (queue.getExclusive() == ExclusivityPolicy.NONE) - { - String description = "Cannot passively declare queue ('" + queueName + "')" - + " as exclusive as queue with same name is" + - " already declared as non-exclusive"; - ExecutionErrorCode errorCode = ExecutionErrorCode.RESOURCE_LOCKED; - exception(session, method, errorCode, description); - - } - else if (!verifySessionAccess((ServerSession) session, queue)) - { - String description = "Cannot passively declare queue('" + queueName + "')," - + " as exclusive queue with same name " - + "declared on another session"; - ExecutionErrorCode errorCode = ExecutionErrorCode.RESOURCE_LOCKED; - exception(session, method, errorCode, description); - } - } - } - else - { - - try - { - - final String alternateExchangeName = method.getAlternateExchange(); - - - final Map<String, Object> arguments = QueueArgumentsConverter.convertWireArgsToModel(method.getArguments()); - - if(alternateExchangeName != null && alternateExchangeName.length() != 0) - { - arguments.put(Queue.ALTERNATE_EXCHANGE, alternateExchangeName); - } - - final UUID id = UUID.randomUUID(); - - arguments.put(Queue.ID, id); - arguments.put(Queue.NAME, queueName); - - LifetimePolicy lifetime; - if(autoDelete) - { - lifetime = exclusive ? LifetimePolicy.DELETE_ON_SESSION_END - : LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS; - } - else - { - lifetime = LifetimePolicy.PERMANENT; - } - - arguments.put(Queue.LIFETIME_POLICY, lifetime); - - ExclusivityPolicy exclusivityPolicy = exclusive ? ExclusivityPolicy.SESSION : ExclusivityPolicy.NONE; - - - arguments.put(Queue.DURABLE, method.getDurable()); - - arguments.put(Queue.EXCLUSIVE, exclusivityPolicy); - - queue = virtualHost.createQueue(arguments); - - } - catch(QueueExistsException qe) - { - queue = qe.getExistingQueue(); - if (!verifySessionAccess((ServerSession) session, queue)) - { - String description = "Cannot declare queue('" + queueName + "')," - + " as exclusive queue with same name " - + "declared on another session"; - ExecutionErrorCode errorCode = ExecutionErrorCode.RESOURCE_LOCKED; - - exception(session, method, errorCode, description); - } - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - } - - @Override - public void queueDelete(Session session, QueueDelete method) - { - String queueName = method.getQueue(); - if(queueName == null || queueName.length()==0) - { - exception(session, method, ExecutionErrorCode.INVALID_ARGUMENT, "No queue name supplied"); - - } - else - { - AMQQueue queue = getQueue(session, queueName); - - - if (queue == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "No queue " + queueName + " found"); - } - else - { - if(!verifySessionAccess((ServerSession) session, queue)) - { - exception(session,method,ExecutionErrorCode.RESOURCE_LOCKED, "Exclusive Queue: " + queueName + " owned exclusively by another session"); - } - else if (method.getIfEmpty() && !queue.isEmpty()) - { - exception(session, method, ExecutionErrorCode.PRECONDITION_FAILED, "Queue " + queueName + " not empty"); - } - else if (method.getIfUnused() && !queue.isUnused()) - { - // TODO - Error code - exception(session, method, ExecutionErrorCode.PRECONDITION_FAILED, "Queue " + queueName + " in use"); - - } - else - { - VirtualHostImpl virtualHost = getVirtualHost(session); - - try - { - virtualHost.removeQueue(queue); - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - } - } - } - - @Override - public void queuePurge(Session session, QueuePurge method) - { - String queueName = method.getQueue(); - if(queueName == null || queueName.length()==0) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "No queue name supplied"); - } - else - { - AMQQueue queue = getQueue(session, queueName); - - if (queue == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "No queue " + queueName + " found"); - } - else - { - try - { - queue.clearQueue(); - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - } - } - - @Override - public void queueQuery(Session session, QueueQuery method) - { - QueueQueryResult result = new QueueQueryResult(); - - AMQQueue queue = getQueue(session, method.getQueue()); - - if(queue != null) - { - result.setQueue(queue.getName()); - result.setDurable(queue.isDurable()); - result.setExclusive(queue.isExclusive()); - result.setAutoDelete(queue.getLifetimePolicy() != LifetimePolicy.PERMANENT); - Map<String, Object> arguments = new LinkedHashMap<String, Object>(); - Collection<String> availableAttrs = queue.getAvailableAttributes(); - - for(String attrName : availableAttrs) - { - arguments.put(attrName, queue.getAttribute(attrName)); - } - result.setArguments(QueueArgumentsConverter.convertModelArgsToWire(arguments)); - result.setMessageCount(queue.getQueueDepthMessages()); - result.setSubscriberCount(queue.getConsumerCount()); - - } - - - session.executionResult((int) method.getId(), result); - - } - - @Override - public void messageSetFlowMode(Session session, MessageSetFlowMode sfm) - { - String destination = sfm.getDestination(); - - ConsumerTarget_0_10 sub = ((ServerSession)session).getSubscription(destination); - - if(sub == null) - { - exception(session, sfm, ExecutionErrorCode.NOT_FOUND, "not-found: destination '" + destination + "'"); - } - else if(sub.isStopped()) - { - sub.setFlowMode(sfm.getFlowMode()); - } - } - - @Override - public void messageStop(Session session, MessageStop stop) - { - String destination = stop.getDestination(); - - ConsumerTarget_0_10 sub = ((ServerSession)session).getSubscription(destination); - - if(sub == null) - { - exception(session, stop, ExecutionErrorCode.NOT_FOUND, "not-found: destination '"+destination+"'"); - } - else - { - sub.stop(); - } - - } - - @Override - public void messageFlow(Session session, MessageFlow flow) - { - String destination = flow.getDestination(); - - ConsumerTarget_0_10 sub = ((ServerSession)session).getSubscription(destination); - - if(sub == null) - { - exception(session, flow, ExecutionErrorCode.NOT_FOUND, "not-found: destination '"+destination+"'"); - } - else - { - sub.addCredit(flow.getUnit(), flow.getValue()); - } - - } - - @Override - public void closed(Session session) - { - ServerSession serverSession = (ServerSession)session; - - serverSession.stopSubscriptions(); - serverSession.onClose(); - serverSession.unregisterSubscriptions(); - } - - @Override - public void detached(Session session) - { - closed(session); - } - - private static class CommandProcessedAction implements ServerTransaction.Action - { - private final ServerSession _serverSession; - private final Method _method; - - public CommandProcessedAction(final ServerSession serverSession, final Method xfr) - { - _serverSession = serverSession; - _method = xfr; - } - - public void postCommit() - { - _serverSession.processed(_method); - } - - public void onRollback() - { - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManager.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManager.java deleted file mode 100644 index 6c400b8e24..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManager.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.flow.AbstractFlowCreditManager; - -public class WindowCreditManager extends AbstractFlowCreditManager implements FlowCreditManager_0_10 -{ - private static final Logger LOGGER = LoggerFactory.getLogger(WindowCreditManager.class); - private final ServerProtocolEngine _serverProtocolEngine; - - private volatile long _bytesCreditLimit; - private volatile long _messageCreditLimit; - - private volatile long _bytesUsed; - private volatile long _messageUsed; - - public WindowCreditManager(long bytesCreditLimit, - long messageCreditLimit, - ServerProtocolEngine serverProtocolEngine) - { - _serverProtocolEngine = serverProtocolEngine; - _bytesCreditLimit = bytesCreditLimit; - _messageCreditLimit = messageCreditLimit; - setSuspended(!hasCredit()); - - } - - public long getMessageCreditLimit() - { - return _messageCreditLimit; - } - - public long getMessageCredit() - { - return _messageCreditLimit == -1L - ? Long.MAX_VALUE - : _messageUsed < _messageCreditLimit ? _messageCreditLimit - _messageUsed : 0L; - } - - public long getBytesCredit() - { - return _bytesCreditLimit == -1L - ? Long.MAX_VALUE - : _bytesUsed < _bytesCreditLimit ? _bytesCreditLimit - _bytesUsed : 0L; - } - - public synchronized void restoreCredit(final long messageCredit, final long bytesCredit) - { - _messageUsed -= messageCredit; - if(_messageUsed < 0L) - { - LOGGER.error("Message credit used value was negative: "+ _messageUsed); - _messageUsed = 0; - } - - boolean notifyIncrease = true; - - if(_messageCreditLimit > 0L) - { - notifyIncrease = (_messageUsed != _messageCreditLimit); - } - - _bytesUsed -= bytesCredit; - if(_bytesUsed < 0L) - { - LOGGER.error("Bytes credit used value was negative: "+ _messageUsed); - _bytesUsed = 0; - } - - if(_bytesCreditLimit > 0L) - { - notifyIncrease = notifyIncrease && bytesCredit>0; - - if(notifyIncrease) - { - notifyIncreaseBytesCredit(); - } - } - - setSuspended(!hasCredit()); - } - - - - public synchronized boolean hasCredit() - { - return (_bytesCreditLimit < 0L || _bytesCreditLimit > _bytesUsed) - && (_messageCreditLimit < 0L || _messageCreditLimit > _messageUsed) - && !_serverProtocolEngine.isTransportBlockedForWriting(); - } - - public synchronized boolean useCreditForMessage(final long msgSize) - { - if (_serverProtocolEngine.isTransportBlockedForWriting()) - { - setSuspended(true); - return false; - } - else if(_messageCreditLimit >= 0L) - { - if(_messageUsed < _messageCreditLimit) - { - if(_bytesCreditLimit < 0L) - { - _messageUsed++; - - return true; - } - else if(_bytesUsed + msgSize <= _bytesCreditLimit) - { - _messageUsed++; - _bytesUsed += msgSize; - - return true; - } - else - { - return false; - } - } - else - { - setSuspended(true); - return false; - } - } - else if(_bytesCreditLimit >= 0L) - { - if(_bytesUsed + msgSize <= _bytesCreditLimit) - { - _bytesUsed += msgSize; - - return true; - } - else - { - return false; - } - - } - else - { - return true; - } - - } - - - public synchronized void addCredit(long count, long bytes) - { - if(bytes > 0) - { - _bytesCreditLimit += bytes; - } - else if(bytes == -1) - { - _bytesCreditLimit = -1; - } - - - if(count > 0) - { - _messageCreditLimit += count; - } - else if(count == -1) - { - _messageCreditLimit = -1; - } - } - - public void clearCredit() - { - _bytesCreditLimit = 0l; - _messageCreditLimit = 0l; - setSuspended(true); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.java deleted file mode 100644 index 2fc76d4f02..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.protocol.v0_10; - -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.transport.Binary; -import org.apache.qpid.transport.ExecutionErrorCode; -import org.apache.qpid.transport.ExecutionException; -import org.apache.qpid.transport.MessageTransfer; -import org.apache.qpid.transport.Method; - -public class ServerSessionTest extends QpidTestCase -{ - - private VirtualHostImpl _virtualHost; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _virtualHost = BrokerTestHelper.createVirtualHost(getName()); - } - - @Override - public void tearDown() throws Exception - { - try - { - if (_virtualHost != null) - { - _virtualHost.close(); - } - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - public void testCompareTo() throws Exception - { - final Broker<?> broker = mock(Broker.class); - when(broker.getContextValue(eq(Long.class), eq(Broker.CHANNEL_FLOW_CONTROL_ENFORCEMENT_TIMEOUT))).thenReturn(0l); - - AmqpPort amqpPort = mock(AmqpPort.class); - when(amqpPort.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(AmqpPort.DEFAULT_MAX_MESSAGE_SIZE); - - ServerConnection connection = new ServerConnection(1, broker, amqpPort, Transport.TCP); - connection.setVirtualHost(_virtualHost); - ServerSession session1 = new ServerSession(connection, new ServerSessionDelegate(), - new Binary(getName().getBytes()), 0); - - // create a session with the same name but on a different connection - ServerConnection connection2 = new ServerConnection(2, broker, amqpPort, Transport.TCP); - connection2.setVirtualHost(_virtualHost); - ServerSession session2 = new ServerSession(connection2, new ServerSessionDelegate(), - new Binary(getName().getBytes()), 0); - - assertFalse("Unexpected compare result", session1.compareTo(session2) == 0); - assertEquals("Unexpected compare result", 0, session1.compareTo(session1)); - } - - public void testOverlargeMessageTest() throws Exception - { - final Broker<?> broker = mock(Broker.class); - when(broker.getContextValue(eq(Long.class), eq(Broker.CHANNEL_FLOW_CONTROL_ENFORCEMENT_TIMEOUT))).thenReturn(0l); - - AmqpPort port = mock(AmqpPort.class); - when(port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(1024); - ServerConnection connection = new ServerConnection(1, broker, port, Transport.TCP); - connection.setVirtualHost(_virtualHost); - final List<Method> invokedMethods = new ArrayList<>(); - ServerSession session = new ServerSession(connection, new ServerSessionDelegate(), - new Binary(getName().getBytes()), 0) - { - @Override - public void invoke(final Method m) - { - invokedMethods.add(m); - } - }; - - ServerSessionDelegate delegate = new ServerSessionDelegate(); - - MessageTransfer xfr = new MessageTransfer(); - xfr.setBody(new byte[2048]); - delegate.messageTransfer(session, xfr); - - assertFalse("No methods invoked - expecting at least 1", invokedMethods.isEmpty()); - Method firstInvoked = invokedMethods.get(0); - assertTrue("First invoked method not execution error", firstInvoked instanceof ExecutionException); - assertEquals(ExecutionErrorCode.RESOURCE_LIMIT_EXCEEDED, ((ExecutionException)firstInvoked).getErrorCode()); - - invokedMethods.clear(); - - // test the boundary condition - - xfr.setBody(new byte[1024]); - delegate.messageTransfer(session, xfr); - - assertTrue("Methods invoked when not expecting any", invokedMethods.isEmpty()); - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManagerTest.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManagerTest.java deleted file mode 100644 index b9f013d253..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManagerTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_10; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.test.utils.QpidTestCase; - -public class WindowCreditManagerTest extends QpidTestCase -{ - private WindowCreditManager _creditManager; - private ServerProtocolEngine _protocolEngine; - - protected void setUp() throws Exception - { - super.setUp(); - - _protocolEngine = mock(ServerProtocolEngine.class); - when(_protocolEngine.isTransportBlockedForWriting()).thenReturn(false); - - _creditManager = new WindowCreditManager(0l, 0l, _protocolEngine); - } - - /** - * Tests that after the credit limit is cleared (e.g. from a message.stop command), credit is - * restored (e.g. from completed MessageTransfer) without increasing the available credit, and - * more credit is added, that the 'used' count is correct and the proper values for bytes - * and message credit are returned along with appropriate 'hasCredit' results (QPID-3592). - */ - public void testRestoreCreditDecrementsUsedCountAfterCreditClear() - { - assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); - assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); - - //give some message credit - _creditManager.addCredit(1, 0); - assertFalse("Manager should not 'haveCredit' due to having 0 bytes credit", _creditManager.hasCredit()); - assertEquals("unexpected credit value", 1, _creditManager.getMessageCredit()); - assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); - - //give some bytes credit - _creditManager.addCredit(0, 1); - assertTrue("Manager should 'haveCredit'", _creditManager.hasCredit()); - assertEquals("unexpected credit value", 1, _creditManager.getMessageCredit()); - assertEquals("unexpected credit value", 1, _creditManager.getBytesCredit()); - - //use all the credit - _creditManager.useCreditForMessage(1); - assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); - assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); - assertFalse("Manager should not 'haveCredit'", _creditManager.hasCredit()); - - //clear credit out (eg from a message.stop command) - _creditManager.clearCredit(); - assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); - assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); - assertFalse("Manager should not 'haveCredit'", _creditManager.hasCredit()); - - //restore credit (e.g the original message transfer command got completed) - //this should not increase credit, because it is now limited to 0 - _creditManager.restoreCredit(1, 1); - assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); - assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); - assertFalse("Manager should not 'haveCredit'", _creditManager.hasCredit()); - - //give more credit to open the window again - _creditManager.addCredit(1, 1); - assertEquals("unexpected credit value", 1, _creditManager.getBytesCredit()); - assertEquals("unexpected credit value", 1, _creditManager.getMessageCredit()); - assertTrue("Manager should 'haveCredit'", _creditManager.hasCredit()); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/pom.xml b/qpid/java/broker-plugins/amqp-0-8-protocol/pom.xml deleted file mode 100644 index e09a3ba922..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-amqp-0-8-protocol</artifactId> - <name>Qpid AMQP 0-8 Protocol Broker Plug-in</name> - <description>AMQP 0-8, 0-9 and 0-9-1 protocol broker plug-in</description> - - <properties> - <qpid.home>${basedir}/../</qpid.home> <!-- override for broker tests --> - </properties> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <version>${log4j-version}</version> - </dependency> - - <!-- test dependencies --> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-test-utils</artifactId> - <version>${project.version}</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <type>test-jar</type> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - </build> - -</project> diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java deleted file mode 100644 index 522408910d..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java +++ /dev/null @@ -1,3670 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import static org.apache.qpid.transport.util.Functions.hex; - -import java.nio.ByteBuffer; -import java.security.AccessControlException; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQConnectionException; -import org.apache.qpid.AMQException; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.*; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.TransactionTimeoutHelper; -import org.apache.qpid.server.TransactionTimeoutHelper.CloseAction; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.connection.SessionPrincipal; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.consumer.ConsumerTarget; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.filter.AMQInvalidArgumentException; -import org.apache.qpid.server.filter.ArrivalTimeFilter; -import org.apache.qpid.server.filter.FilterManager; -import org.apache.qpid.server.filter.FilterManagerFactory; -import org.apache.qpid.server.filter.Filterable; -import org.apache.qpid.server.filter.MessageFilter; -import org.apache.qpid.server.flow.FlowCreditManager; -import org.apache.qpid.server.logging.LogMessage; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.logging.messages.ChannelMessages; -import org.apache.qpid.server.logging.messages.ExchangeMessages; -import org.apache.qpid.server.logging.subjects.ChannelLogSubject; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfigurationChangeListener; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Connection; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.model.Exchange; -import org.apache.qpid.server.model.ExclusivityPolicy; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.NoFactoryForTypeException; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.Session; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.UnknownConfiguredObjectException; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.CapacityChecker; -import org.apache.qpid.server.protocol.ConsumerListener; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueArgumentsConverter; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.store.MessageHandle; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.txn.AsyncAutoCommitTransaction; -import org.apache.qpid.server.txn.LocalTransaction; -import org.apache.qpid.server.txn.LocalTransaction.ActivityTimeAccessor; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.util.FutureResult; -import org.apache.qpid.server.virtualhost.ExchangeExistsException; -import org.apache.qpid.server.virtualhost.ExchangeIsAlternateException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.apache.qpid.server.virtualhost.RequiredExchangeException; -import org.apache.qpid.server.virtualhost.ReservedExchangeNameException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.TransportException; - -public class AMQChannel - implements AMQSessionModel<AMQChannel, AMQProtocolEngine>, - AsyncAutoCommitTransaction.FutureRecorder, - ServerChannelMethodProcessor -{ - public static final int DEFAULT_PREFETCH = 4096; - - private static final Logger _logger = LoggerFactory.getLogger(AMQChannel.class); - private final DefaultQueueAssociationClearingTask - _defaultQueueAssociationClearingTask = new DefaultQueueAssociationClearingTask(); - - //TODO use Broker property to configure message authorization requirements - private boolean _messageAuthorizationRequired = Boolean.getBoolean(BrokerProperties.PROPERTY_MSG_AUTH); - - private final int _channelId; - - - private final Pre0_10CreditManager _creditManager; - private final FlowCreditManager _noAckCreditManager; - - /** - * The delivery tag is unique per channel. This is pre-incremented before putting into the deliver frame so that - * value of this represents the <b>last</b> tag sent out - */ - private long _deliveryTag = 0; - - /** A channel has a default queue (the last declared) that is used when no queue name is explicitly set */ - private volatile AMQQueue<?> _defaultQueue; - - /** This tag is unique per subscription to a queue. The server returns this in response to a basic.consume request. */ - private int _consumerTag; - - /** - * The current message - which may be partial in the sense that not all frames have been received yet - which has - * been received by this channel. As the frames are received the message gets updated and once all frames have been - * received the message can then be routed. - */ - private IncomingMessage _currentMessage; - - /** Maps from consumer tag to subscription instance. Allows us to unsubscribe from a queue. */ - private final Map<AMQShortString, ConsumerTarget_0_8> _tag2SubscriptionTargetMap = new HashMap<AMQShortString, ConsumerTarget_0_8>(); - - private final MessageStore _messageStore; - - private final LinkedList<AsyncCommand> _unfinishedCommandsQueue = new LinkedList<AsyncCommand>(); - - private UnacknowledgedMessageMap _unacknowledgedMessageMap = new UnacknowledgedMessageMapImpl(DEFAULT_PREFETCH); - - private final AtomicBoolean _suspended = new AtomicBoolean(false); - - private ServerTransaction _transaction; - - private final AtomicLong _txnStarts = new AtomicLong(0); - private final AtomicLong _txnCommits = new AtomicLong(0); - private final AtomicLong _txnRejects = new AtomicLong(0); - private final AtomicLong _txnCount = new AtomicLong(0); - - private final AMQProtocolEngine _connection; - private AtomicBoolean _closing = new AtomicBoolean(false); - - private final Set<Object> _blockingEntities = Collections.synchronizedSet(new HashSet<Object>()); - - private final AtomicBoolean _blocking = new AtomicBoolean(false); - - - private LogSubject _logSubject; - private volatile boolean _rollingBack; - - private List<MessageInstance> _resendList = new ArrayList<MessageInstance>(); - private static final - AMQShortString IMMEDIATE_DELIVERY_REPLY_TEXT = new AMQShortString("Immediate delivery is not possible."); - - private final ClientDeliveryMethod _clientDeliveryMethod; - - private final TransactionTimeoutHelper _transactionTimeoutHelper; - private final UUID _id = UUID.randomUUID(); - - private final List<Action<? super AMQChannel>> _taskList = - new CopyOnWriteArrayList<Action<? super AMQChannel>>(); - - - private final CapacityCheckAction _capacityCheckAction = new CapacityCheckAction(); - private final ImmediateAction _immediateAction = new ImmediateAction(); - private Subject _subject; - private final CopyOnWriteArrayList<Consumer<?>> _consumers = new CopyOnWriteArrayList<Consumer<?>>(); - private final ConfigurationChangeListener _consumerClosedListener = new ConsumerClosedListener(); - private final CopyOnWriteArrayList<ConsumerListener> _consumerListeners = new CopyOnWriteArrayList<ConsumerListener>(); - private Session<?> _modelObject; - private long _blockTime; - private long _blockingTimeout; - private boolean _confirmOnPublish; - private long _confirmedMessageCounter; - private volatile long _uncommittedMessageSize; - private final List<StoredMessage<MessageMetaData>> _uncommittedMessages = new ArrayList<>(); - private long _maxUncommittedInMemorySize; - - private boolean _wireBlockingState; - - public AMQChannel(AMQProtocolEngine connection, int channelId, final MessageStore messageStore) - { - _creditManager = new Pre0_10CreditManager(0l,0l, connection); - _noAckCreditManager = new NoAckCreditManager(connection); - - _connection = connection; - _channelId = channelId; - - _subject = new Subject(false, connection.getAuthorizedSubject().getPrincipals(), - connection.getAuthorizedSubject().getPublicCredentials(), - connection.getAuthorizedSubject().getPrivateCredentials()); - _subject.getPrincipals().add(new SessionPrincipal(this)); - _maxUncommittedInMemorySize = connection.getVirtualHost().getContextValue(Long.class, Connection.MAX_UNCOMMITTED_IN_MEMORY_SIZE); - _logSubject = new ChannelLogSubject(this); - - _messageStore = messageStore; - _blockingTimeout = connection.getBroker().getContextValue(Long.class, - Broker.CHANNEL_FLOW_CONTROL_ENFORCEMENT_TIMEOUT); - // by default the session is non-transactional - _transaction = new AsyncAutoCommitTransaction(_messageStore, this); - - _clientDeliveryMethod = connection.createDeliveryMethod(_channelId); - - _transactionTimeoutHelper = new TransactionTimeoutHelper(_logSubject, new CloseAction() - { - @Override - public void doTimeoutAction(String reason) - { - try - { - closeConnection(reason); - } - catch (AMQException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - }, getVirtualHost()); - - Subject.doAs(_subject, new PrivilegedAction<Object>() - { - @Override - public Object run() - { - getVirtualHost().getEventLogger().message(ChannelMessages.CREATE()); - - return null; - } - }); - - } - - private boolean performGet(final AMQQueue queue, - final boolean acks) - throws MessageSource.ExistingConsumerPreventsExclusive, - MessageSource.ExistingExclusiveConsumer, MessageSource.ConsumerAccessRefused - { - - final FlowCreditManager singleMessageCredit = new MessageOnlyCreditManager(1L); - - final GetDeliveryMethod getDeliveryMethod = - new GetDeliveryMethod(singleMessageCredit, queue); - final RecordDeliveryMethod getRecordMethod = new RecordDeliveryMethod() - { - - public void recordMessageDelivery(final ConsumerImpl sub, - final MessageInstance entry, - final long deliveryTag) - { - addUnacknowledgedMessage(entry, deliveryTag, null); - } - }; - - ConsumerTarget_0_8 target; - EnumSet<ConsumerImpl.Option> options = EnumSet.of(ConsumerImpl.Option.TRANSIENT, ConsumerImpl.Option.ACQUIRES, - ConsumerImpl.Option.SEES_REQUEUES); - if (acks) - { - - target = ConsumerTarget_0_8.createAckTarget(this, - AMQShortString.EMPTY_STRING, null, - singleMessageCredit, getDeliveryMethod, getRecordMethod); - } - else - { - target = ConsumerTarget_0_8.createGetNoAckTarget(this, - AMQShortString.EMPTY_STRING, null, - singleMessageCredit, getDeliveryMethod, getRecordMethod); - } - - ConsumerImpl sub = queue.addConsumer(target, null, AMQMessage.class, "", options); - sub.flush(); - sub.close(); - return getDeliveryMethod.hasDeliveredMessage(); - - - } - - /** Sets this channel to be part of a local transaction */ - public void setLocalTransactional() - { - _transaction = new LocalTransaction(_messageStore, new ActivityTimeAccessor() - { - @Override - public long getActivityTime() - { - return _connection.getLastReceivedTime(); - } - }); - _txnStarts.incrementAndGet(); - } - - public boolean isTransactional() - { - return _transaction.isTransactional(); - } - - public void receivedComplete() - { - sync(); - } - - private void incrementOutstandingTxnsIfNecessary() - { - if(isTransactional()) - { - //There can currently only be at most one outstanding transaction - //due to only having LocalTransaction support. Set value to 1 if 0. - _txnCount.compareAndSet(0,1); - } - } - - private void decrementOutstandingTxnsIfNecessary() - { - if(isTransactional()) - { - //There can currently only be at most one outstanding transaction - //due to only having LocalTransaction support. Set value to 0 if 1. - _txnCount.compareAndSet(1,0); - } - } - - public Long getTxnCommits() - { - return _txnCommits.get(); - } - - public Long getTxnRejects() - { - return _txnRejects.get(); - } - - public Long getTxnCount() - { - return _txnCount.get(); - } - - public Long getTxnStart() - { - return _txnStarts.get(); - } - - public int getChannelId() - { - return _channelId; - } - - public void setPublishFrame(MessagePublishInfo info, final MessageDestination e) - { - String routingKey = info.getRoutingKey() == null ? null : info.getRoutingKey().asString(); - VirtualHostImpl virtualHost = getVirtualHost(); - SecurityManager securityManager = virtualHost.getSecurityManager(); - - securityManager.authorisePublish(info.isImmediate(), routingKey, e.getName(), virtualHost.getName()); - - _currentMessage = new IncomingMessage(info); - _currentMessage.setMessageDestination(e); - } - - public void publishContentHeader(ContentHeaderBody contentHeaderBody) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Content header received on channel " + _channelId); - } - - _currentMessage.setContentHeaderBody(contentHeaderBody); - - deliverCurrentMessageIfComplete(); - } - - private void deliverCurrentMessageIfComplete() - { - // check and deliver if header says body length is zero - if (_currentMessage.allContentReceived()) - { - if(_confirmOnPublish) - { - _confirmedMessageCounter++; - } - Runnable finallyAction = null; - ContentHeaderBody contentHeader = _currentMessage.getContentHeader(); - - long bodySize = _currentMessage.getSize(); - long timestamp = contentHeader.getProperties().getTimestamp(); - - try - { - - final MessagePublishInfo messagePublishInfo = _currentMessage.getMessagePublishInfo(); - final MessageDestination destination = _currentMessage.getDestination(); - - final MessageMetaData messageMetaData = - new MessageMetaData(messagePublishInfo, - contentHeader, - getConnection().getLastReceivedTime()); - - final MessageHandle<MessageMetaData> handle = _messageStore.addMessage(messageMetaData); - int bodyCount = _currentMessage.getBodyCount(); - if(bodyCount > 0) - { - long bodyLengthReceived = 0; - for(int i = 0 ; i < bodyCount ; i++) - { - ContentBody contentChunk = _currentMessage.getContentChunk(i); - handle.addContent(ByteBuffer.wrap(contentChunk.getPayload())); - bodyLengthReceived += contentChunk.getSize(); - } - } - final StoredMessage<MessageMetaData> storedMessage = handle.allContentAdded(); - - final AMQMessage amqMessage = createAMQMessage(storedMessage); - MessageReference reference = amqMessage.newReference(); - try - { - - _currentMessage = null; - - if(!checkMessageUserId(contentHeader)) - { - if(_confirmOnPublish) - { - _connection.writeFrame(new AMQFrame(_channelId, new BasicNackBody(_confirmedMessageCounter, false, false))); - } - _transaction.addPostTransactionAction(new WriteReturnAction(AMQConstant.ACCESS_REFUSED, "Access Refused", amqMessage)); - } - else - { - final boolean immediate = messagePublishInfo.isImmediate(); - - final InstanceProperties instanceProperties = - new InstanceProperties() - { - @Override - public Object getProperty(final Property prop) - { - switch(prop) - { - case EXPIRATION: - return amqMessage.getExpiration(); - case IMMEDIATE: - return immediate; - case PERSISTENT: - return amqMessage.isPersistent(); - case MANDATORY: - return messagePublishInfo.isMandatory(); - case REDELIVERED: - return false; - } - return null; - } - }; - - int enqueues = destination.send(amqMessage, - amqMessage.getInitialRoutingAddress(), - instanceProperties, _transaction, - immediate ? _immediateAction : _capacityCheckAction - ); - if(enqueues == 0) - { - finallyAction = handleUnroutableMessage(amqMessage); - } - else - { - if(_confirmOnPublish) - { - BasicAckBody responseBody = _connection.getMethodRegistry() - .createBasicAckBody(_confirmedMessageCounter, false); - _connection.writeFrame(responseBody.generateFrame(_channelId)); - } - incrementUncommittedMessageSize(storedMessage); - incrementOutstandingTxnsIfNecessary(); - } - } - } - finally - { - reference.release(); - if(finallyAction != null) - { - finallyAction.run(); - } - } - - } - finally - { - _connection.registerMessageReceived(bodySize, timestamp); - _currentMessage = null; - } - } - - } - - private void incrementUncommittedMessageSize(final StoredMessage<MessageMetaData> handle) - { - if (isTransactional()) - { - _uncommittedMessageSize += handle.getMetaData().getContentSize(); - if (_uncommittedMessageSize > getMaxUncommittedInMemorySize()) - { - handle.flowToDisk(); - if(!_uncommittedMessages.isEmpty() || _uncommittedMessageSize == handle.getMetaData().getContentSize()) - { - getVirtualHost().getEventLogger() - .message(_logSubject, ChannelMessages.LARGE_TRANSACTION_WARN(_uncommittedMessageSize)); - } - - if(!_uncommittedMessages.isEmpty()) - { - for (StoredMessage<MessageMetaData> uncommittedHandle : _uncommittedMessages) - { - uncommittedHandle.flowToDisk(); - } - _uncommittedMessages.clear(); - } - } - else - { - _uncommittedMessages.add(handle); - } - } - } - - /** - * Either throws a {@link AMQConnectionException} or returns the message - * - * Pre-requisite: the current message is judged to have no destination queues. - * - * @throws AMQConnectionException if the message is mandatory close-on-no-route - * @see AMQProtocolEngine#isCloseWhenNoRoute() - */ - private Runnable handleUnroutableMessage(AMQMessage message) - { - boolean mandatory = message.isMandatory(); - - String exchangeName = message.getMessagePublishInfo().getExchange() == null - ? null : message.getMessagePublishInfo().getExchange().asString(); - String routingKey = message.getMessagePublishInfo().getRoutingKey() == null - ? null : message.getMessagePublishInfo().getRoutingKey().asString(); - - final String description = String.format( - "[Exchange: %s, Routing key: %s]", - exchangeName, - routingKey); - - boolean closeOnNoRoute = _connection.isCloseWhenNoRoute(); - Runnable returnVal = null; - if(_logger.isDebugEnabled()) - { - _logger.debug(String.format( - "Unroutable message %s, mandatory=%s, transactionalSession=%s, closeOnNoRoute=%s", - description, mandatory, isTransactional(), closeOnNoRoute)); - } - - if (mandatory && isTransactional() && !_confirmOnPublish && _connection.isCloseWhenNoRoute()) - { - returnVal = new Runnable() - { - @Override - public void run() - { - _connection.closeConnection(AMQConstant.NO_ROUTE, - "No route for message " + description, _channelId); - - } - }; - } - else - { - if (mandatory || message.isImmediate()) - { - if(_confirmOnPublish) - { - _connection.writeFrame(new AMQFrame(_channelId, new BasicNackBody(_confirmedMessageCounter, false, false))); - } - _transaction.addPostTransactionAction(new WriteReturnAction(AMQConstant.NO_ROUTE, - "No Route for message " - + description, - message)); - } - else - { - - getVirtualHost().getEventLogger().message(ExchangeMessages.DISCARDMSG(exchangeName, routingKey)); - } - } - return returnVal; - } - - public void publishContentBody(ContentBody contentBody) - { - if (_logger.isDebugEnabled()) - { - _logger.debug(debugIdentity() + " content body received on channel " + _channelId); - } - - try - { - long currentSize = _currentMessage.addContentBodyFrame(contentBody); - if(currentSize > _currentMessage.getSize()) - { - _connection.closeConnection(AMQConstant.FRAME_ERROR, - "More message data received than content header defined", - _channelId); - } - else - { - deliverCurrentMessageIfComplete(); - } - } - catch (RuntimeException e) - { - // we want to make sure we don't keep a reference to the message in the - // event of an error - _currentMessage = null; - throw e; - } - } - - public long getNextDeliveryTag() - { - return ++_deliveryTag; - } - - public int getNextConsumerTag() - { - return ++_consumerTag; - } - - - public ConsumerTarget getSubscription(AMQShortString tag) - { - return _tag2SubscriptionTargetMap.get(tag); - } - - /** - * Subscribe to a queue. We register all subscriptions in the channel so that if the channel is closed we can clean - * up all subscriptions, even if the client does not explicitly unsubscribe from all queues. - * - * - * @param tag the tag chosen by the client (if null, server will generate one) - * @param sources the queues to subscribe to - * @param acks Are acks enabled for this subscriber - * @param arguments Filters to apply to this subscriber - * - * @param exclusive Flag requesting exclusive access to the queue - * @return the consumer tag. This is returned to the subscriber and used in subsequent unsubscribe requests - * - * @throws org.apache.qpid.AMQException if something goes wrong - */ - public AMQShortString consumeFromSource(AMQShortString tag, Collection<MessageSource> sources, boolean acks, - FieldTable arguments, boolean exclusive, boolean noLocal) - throws MessageSource.ExistingConsumerPreventsExclusive, - MessageSource.ExistingExclusiveConsumer, - AMQInvalidArgumentException, - MessageSource.ConsumerAccessRefused, ConsumerTagInUseException - { - if (tag == null) - { - tag = new AMQShortString("sgen_" + getNextConsumerTag()); - } - - if (_tag2SubscriptionTargetMap.containsKey(tag)) - { - throw new ConsumerTagInUseException("Consumer already exists with same tag: " + tag); - } - - ConsumerTarget_0_8 target; - EnumSet<ConsumerImpl.Option> options = EnumSet.noneOf(ConsumerImpl.Option.class); - - if(arguments != null && Boolean.TRUE.equals(arguments.get(AMQPFilterTypes.NO_CONSUME.getValue()))) - { - target = ConsumerTarget_0_8.createBrowserTarget(this, tag, arguments, _noAckCreditManager); - } - else if(acks) - { - target = ConsumerTarget_0_8.createAckTarget(this, tag, arguments, _creditManager); - options.add(ConsumerImpl.Option.ACQUIRES); - options.add(ConsumerImpl.Option.SEES_REQUEUES); - } - else - { - target = ConsumerTarget_0_8.createNoAckTarget(this, tag, arguments, _noAckCreditManager); - options.add(ConsumerImpl.Option.ACQUIRES); - options.add(ConsumerImpl.Option.SEES_REQUEUES); - } - - if(exclusive) - { - options.add(ConsumerImpl.Option.EXCLUSIVE); - } - - - // So to keep things straight we put before the call and catch all exceptions from the register and tidy up. - // We add before we register as the Async Delivery process may AutoClose the subscriber - // so calling _cT2QM.remove before we have done put which was after the register succeeded. - // So to keep things straight we put before the call and catch all exceptions from the register and tidy up. - - _tag2SubscriptionTargetMap.put(tag, target); - - try - { - FilterManager filterManager = FilterManagerFactory.createManager(FieldTable.convertToMap(arguments)); - if(noLocal) - { - if(filterManager == null) - { - filterManager = new FilterManager(); - } - final Object connectionReference = getConnectionReference(); - MessageFilter filter = new MessageFilter() - { - - @Override - public String getName() - { - return AMQPFilterTypes.NO_LOCAL.toString(); - } - - @Override - public boolean matches(final Filterable message) - { - return message.getConnectionReference() != connectionReference; - } - - @Override - public boolean startAtTail() - { - return false; - } - }; - filterManager.add(filter.getName(), filter); - } - - if(arguments != null && arguments.containsKey(AMQPFilterTypes.REPLAY_PERIOD.toString())) - { - Object value = arguments.get(AMQPFilterTypes.REPLAY_PERIOD.toString()); - final long period; - if(value instanceof Number) - { - period = ((Number)value).longValue(); - } - else if(value instanceof String) - { - try - { - period = Long.parseLong(value.toString()); - } - catch (NumberFormatException e) - { - throw new AMQInvalidArgumentException("Cannot parse value " + value + " as a number for filter " + AMQPFilterTypes.REPLAY_PERIOD.toString()); - } - } - else - { - throw new AMQInvalidArgumentException("Cannot parse value " + value + " as a number for filter " + AMQPFilterTypes.REPLAY_PERIOD.toString()); - } - - final long startingFrom = System.currentTimeMillis() - (1000l * period); - if(filterManager == null) - { - filterManager = new FilterManager(); - } - MessageFilter filter = new ArrivalTimeFilter(startingFrom, period==0); - filterManager.add(filter.getName(), filter); - - } - - for(MessageSource source : sources) - { - ConsumerImpl sub = - source.addConsumer(target, - filterManager, - AMQMessage.class, - AMQShortString.toString(tag), - options); - if (sub instanceof Consumer<?>) - { - final Consumer<?> modelConsumer = (Consumer<?>) sub; - consumerAdded(modelConsumer); - modelConsumer.addChangeListener(_consumerClosedListener); - _consumers.add(modelConsumer); - } - } - } - catch (AccessControlException - | MessageSource.ExistingExclusiveConsumer - | MessageSource.ExistingConsumerPreventsExclusive - | AMQInvalidArgumentException - | MessageSource.ConsumerAccessRefused e) - { - _tag2SubscriptionTargetMap.remove(tag); - throw e; - } - return tag; - } - - /** - * Unsubscribe a consumer from a queue. - * @param consumerTag - * @return true if the consumerTag had a mapped queue that could be unregistered. - */ - public boolean unsubscribeConsumer(AMQShortString consumerTag) - { - - ConsumerTarget_0_8 target = _tag2SubscriptionTargetMap.remove(consumerTag); - Collection<ConsumerImpl> subs = target == null ? null : target.getConsumers(); - if (subs != null) - { - for(ConsumerImpl sub : subs) - { - sub.close(); - if (sub instanceof Consumer<?>) - { - _consumers.remove(sub); - } - } - return true; - } - else - { - _logger.warn("Attempt to unsubscribe consumer with tag '" + consumerTag + "' which is not registered."); - } - return false; - } - - @Override - public void close() - { - close(null, null); - } - - public void close(AMQConstant cause, String message) - { - if(!_closing.compareAndSet(false, true)) - { - //Channel is already closing - return; - } - - LogMessage operationalLogMessage = cause == null ? - ChannelMessages.CLOSE() : - ChannelMessages.CLOSE_FORCED(cause.getCode(), message); - getVirtualHost().getEventLogger().message(_logSubject, operationalLogMessage); - - unsubscribeAllConsumers(); - setDefaultQueue(null); - for (Action<? super AMQChannel> task : _taskList) - { - task.performAction(this); - } - - - _transaction.rollback(); - - try - { - requeue(); - } - catch (TransportException e) - { - _logger.error("Caught TransportException whilst attempting to requeue:" + e); - } - } - - private void unsubscribeAllConsumers() - { - if (_logger.isInfoEnabled()) - { - if (!_tag2SubscriptionTargetMap.isEmpty()) - { - _logger.info("Unsubscribing all consumers on channel " + toString()); - } - else - { - _logger.info("No consumers to unsubscribe on channel " + toString()); - } - } - - for (Map.Entry<AMQShortString, ConsumerTarget_0_8> me : _tag2SubscriptionTargetMap.entrySet()) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Unsubscribing consumer '" + me.getKey() + "' on channel " + toString()); - } - - Collection<ConsumerImpl> subs = me.getValue().getConsumers(); - - if(subs != null) - { - for(ConsumerImpl sub : subs) - { - sub.close(); - } - } - } - - _tag2SubscriptionTargetMap.clear(); - } - - /** - * Add a message to the channel-based list of unacknowledged messages - * - * @param entry the record of the message on the queue that was delivered - * @param deliveryTag the delivery tag used when delivering the message (see protocol spec for description of the - * delivery tag) - * @param consumer The consumer that is to acknowledge this message. - */ - public void addUnacknowledgedMessage(MessageInstance entry, long deliveryTag, ConsumerImpl consumer) - { - if (_logger.isDebugEnabled()) - { - _logger.debug(debugIdentity() + " Adding unacked message(" + entry.getMessage().toString() + " DT:" + deliveryTag - + ") for " + consumer + " on " + entry.getOwningResource().getName()); - - } - - _unacknowledgedMessageMap.add(deliveryTag, entry); - - } - - private final String id = "(" + System.identityHashCode(this) + ")"; - - public String debugIdentity() - { - return _channelId + id; - } - - /** - * Called to attempt re-delivery all outstanding unacknowledged messages on the channel. May result in delivery to - * this same channel or to other subscribers. - * - */ - public void requeue() - { - // we must create a new map since all the messages will get a new delivery tag when they are redelivered - Collection<MessageInstance> messagesToBeDelivered = _unacknowledgedMessageMap.cancelAllMessages(); - - if (!messagesToBeDelivered.isEmpty()) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Requeuing " + messagesToBeDelivered.size() + " unacked messages. for " + toString()); - } - - } - - for (MessageInstance unacked : messagesToBeDelivered) - { - // Mark message redelivered - unacked.setRedelivered(); - - // Ensure message is released for redelivery - unacked.release(); - } - - } - - /** - * Requeue a single message - * - * @param deliveryTag The message to requeue - * - */ - public void requeue(long deliveryTag) - { - MessageInstance unacked = _unacknowledgedMessageMap.remove(deliveryTag); - - if (unacked != null) - { - // Mark message redelivered - unacked.setRedelivered(); - - // Ensure message is released for redelivery - unacked.release(); - - } - else - { - _logger.warn("Requested requeue of message:" + deliveryTag + " but no such delivery tag exists." - + _unacknowledgedMessageMap.size()); - - } - - } - - public boolean isMaxDeliveryCountEnabled(final long deliveryTag) - { - final MessageInstance queueEntry = _unacknowledgedMessageMap.get(deliveryTag); - if (queueEntry != null) - { - final int maximumDeliveryCount = queueEntry.getMaximumDeliveryCount(); - return maximumDeliveryCount > 0; - } - - return false; - } - - public boolean isDeliveredTooManyTimes(final long deliveryTag) - { - final MessageInstance queueEntry = _unacknowledgedMessageMap.get(deliveryTag); - if (queueEntry != null) - { - final int maximumDeliveryCount = queueEntry.getMaximumDeliveryCount(); - final int numDeliveries = queueEntry.getDeliveryCount(); - return maximumDeliveryCount != 0 && numDeliveries >= maximumDeliveryCount; - } - - return false; - } - - /** - * Called to resend all outstanding unacknowledged messages to this same channel. - * - */ - public void resend() - { - - - final Map<Long, MessageInstance> msgToRequeue = new LinkedHashMap<Long, MessageInstance>(); - final Map<Long, MessageInstance> msgToResend = new LinkedHashMap<Long, MessageInstance>(); - - if (_logger.isDebugEnabled()) - { - _logger.debug("unacked map Size:" + _unacknowledgedMessageMap.size()); - } - - // Process the Unacked-Map. - // Marking messages who still have a consumer for to be resent - // and those that don't to be requeued. - _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, - msgToRequeue, - msgToResend - )); - - - // Process Messages to Resend - if (_logger.isDebugEnabled()) - { - if (!msgToResend.isEmpty()) - { - _logger.debug("Preparing (" + msgToResend.size() + ") message to resend."); - } - else - { - _logger.debug("No message to resend."); - } - } - - for (Map.Entry<Long, MessageInstance> entry : msgToResend.entrySet()) - { - MessageInstance message = entry.getValue(); - long deliveryTag = entry.getKey(); - - //Amend the delivery counter as the client hasn't seen these messages yet. - message.decrementDeliveryCount(); - - // Without any details from the client about what has been processed we have to mark - // all messages in the unacked map as redelivered. - message.setRedelivered(); - - if (!message.resend()) - { - msgToRequeue.put(deliveryTag, message); - } - } // for all messages - // } else !isSuspend - - if (_logger.isInfoEnabled()) - { - if (!msgToRequeue.isEmpty()) - { - _logger.info("Preparing (" + msgToRequeue.size() + ") message to requeue to."); - } - } - - // Process Messages to Requeue at the front of the queue - for (Map.Entry<Long, MessageInstance> entry : msgToRequeue.entrySet()) - { - MessageInstance message = entry.getValue(); - long deliveryTag = entry.getKey(); - - //Amend the delivery counter as the client hasn't seen these messages yet. - message.decrementDeliveryCount(); - - _unacknowledgedMessageMap.remove(deliveryTag); - - message.setRedelivered(); - message.release(); - - } - } - - - /** - * Acknowledge one or more messages. - * - * @param deliveryTag the last delivery tag - * @param multiple if true will acknowledge all messages up to an including the delivery tag. if false only - * acknowledges the single message specified by the delivery tag - * - */ - public void acknowledgeMessage(long deliveryTag, boolean multiple) - { - Collection<MessageInstance> ackedMessages = getAckedMessages(deliveryTag, multiple); - _transaction.dequeue(ackedMessages, new MessageAcknowledgeAction(ackedMessages)); - } - - private Collection<MessageInstance> getAckedMessages(long deliveryTag, boolean multiple) - { - - return _unacknowledgedMessageMap.acknowledge(deliveryTag, multiple); - - } - - /** - * Used only for testing purposes. - * - * @return the map of unacknowledged messages - */ - public UnacknowledgedMessageMap getUnacknowledgedMessageMap() - { - return _unacknowledgedMessageMap; - } - - /** - * Called from the ChannelFlowHandler to suspend this Channel - * @param suspended boolean, should this Channel be suspended - */ - public void setSuspended(boolean suspended) - { - boolean wasSuspended = _suspended.getAndSet(suspended); - if (wasSuspended != suspended) - { - // Log Flow Started before we start the subscriptions - if (!suspended) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW("Started")); - } - - - // This section takes two different approaches to perform to perform - // the same function. Ensuring that the Subscription has taken note - // of the change in Channel State - - // Here we have become unsuspended and so we ask each the queue to - // perform an Async delivery for each of the subscriptions in this - // Channel. The alternative would be to ensure that the subscription - // had received the change in suspension state. That way the logic - // behind deciding to start an async delivery was located with the - // Subscription. - if (wasSuspended) - { - // may need to deliver queued messages - for (ConsumerTarget_0_8 s : _tag2SubscriptionTargetMap.values()) - { - for(ConsumerImpl sub : s.getConsumers()) - { - sub.externalStateChange(); - } - } - } - - - // Here we have become suspended so we need to ensure that each of - // the Subscriptions has noticed this change so that we can be sure - // they are not still sending messages. Again the code here is a - // very simplistic approach to ensure that the change of suspension - // has been noticed by each of the Subscriptions. Unlike the above - // case we don't actually need to do anything else. - if (!wasSuspended) - { - // may need to deliver queued messages - for (ConsumerTarget_0_8 s : _tag2SubscriptionTargetMap.values()) - { - try - { - s.getSendLock(); - } - finally - { - s.releaseSendLock(); - } - } - } - - - // Log Suspension only after we have confirmed all suspensions are - // stopped. - if (suspended) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW("Stopped")); - } - - } - } - - public boolean isSuspended() - { - return _suspended.get() || _closing.get() || _connection.isClosing(); - } - - - public void commit(final Runnable immediateAction, boolean async) - { - - - if(async && _transaction instanceof LocalTransaction) - { - - ((LocalTransaction)_transaction).commitAsync(new Runnable() - { - @Override - public void run() - { - try - { - immediateAction.run(); - } - finally - { - _txnCommits.incrementAndGet(); - _txnStarts.incrementAndGet(); - decrementOutstandingTxnsIfNecessary(); - } - } - }); - } - else - { - _transaction.commit(immediateAction); - - _txnCommits.incrementAndGet(); - _txnStarts.incrementAndGet(); - decrementOutstandingTxnsIfNecessary(); - } - resetUncommittedMessages(); - } - - private void resetUncommittedMessages() - { - _uncommittedMessageSize = 0l; - _uncommittedMessages.clear(); - } - - public void rollback(Runnable postRollbackTask) - { - - // stop all subscriptions - _rollingBack = true; - boolean requiresSuspend = _suspended.compareAndSet(false,true); // TODO This is probably superfluous owing to the - // message assignment suspended logic in NBC. - - // ensure all subscriptions have seen the change to the channel state - for(ConsumerTarget_0_8 sub : _tag2SubscriptionTargetMap.values()) - { - sub.getSendLock(); - sub.releaseSendLock(); - } - - try - { - _transaction.rollback(); - } - finally - { - _rollingBack = false; - - _txnRejects.incrementAndGet(); - _txnStarts.incrementAndGet(); - decrementOutstandingTxnsIfNecessary(); - resetUncommittedMessages(); - } - - postRollbackTask.run(); - - for(MessageInstance entry : _resendList) - { - ConsumerImpl sub = entry.getDeliveredConsumer(); - if(sub == null || sub.isClosed()) - { - entry.release(); - } - else - { - entry.resend(); - } - } - _resendList.clear(); - - if(requiresSuspend) - { - _suspended.set(false); - for(ConsumerTarget_0_8 target : _tag2SubscriptionTargetMap.values()) - { - for(ConsumerImpl sub : target.getConsumers()) - { - sub.externalStateChange(); - } - } - - } - } - - public String toString() - { - return "("+ _suspended.get() + ", " + _closing.get() + ", " + _connection.isClosing() + ") "+"["+ _connection.toString()+":"+_channelId+"]"; - } - - public boolean isClosing() - { - return _closing.get(); - } - - public AMQProtocolEngine getConnection() - { - return _connection; - } - - public FlowCreditManager getCreditManager() - { - return _creditManager; - } - - public void setCredit(final long prefetchSize, final int prefetchCount) - { - getVirtualHost().getEventLogger().message(ChannelMessages.PREFETCH_SIZE(prefetchSize, prefetchCount)); - _creditManager.setCreditLimits(prefetchSize, prefetchCount); - } - - public MessageStore getMessageStore() - { - return _messageStore; - } - - public ClientDeliveryMethod getClientDeliveryMethod() - { - return _clientDeliveryMethod; - } - - private final RecordDeliveryMethod _recordDeliveryMethod = new RecordDeliveryMethod() - { - - public void recordMessageDelivery(final ConsumerImpl sub, final MessageInstance entry, final long deliveryTag) - { - addUnacknowledgedMessage(entry, deliveryTag, sub); - } - }; - - public RecordDeliveryMethod getRecordDeliveryMethod() - { - return _recordDeliveryMethod; - } - - - private AMQMessage createAMQMessage(StoredMessage<MessageMetaData> handle) - { - - AMQMessage message = new AMQMessage(handle, _connection.getReference()); - - return message; - } - - private boolean checkMessageUserId(ContentHeaderBody header) - { - AMQShortString userID = header.getProperties().getUserId(); - return (!_messageAuthorizationRequired || _connection.getAuthorizedPrincipal().getName().equals(userID == null? "" : userID.toString())); - - } - - @Override - public UUID getId() - { - return _id; - } - - @Override - public AMQProtocolEngine getConnectionModel() - { - return _connection; - } - - public String getClientID() - { - return String.valueOf(_connection.getContextKey()); - } - - public LogSubject getLogSubject() - { - return _logSubject; - } - - @Override - public int compareTo(AMQSessionModel o) - { - return getId().compareTo(o.getId()); - } - - @Override - public void addDeleteTask(final Action<? super AMQChannel> task) - { - _taskList.add(task); - } - - @Override - public void removeDeleteTask(final Action<? super AMQChannel> task) - { - _taskList.remove(task); - } - - public Subject getSubject() - { - return _subject; - } - - public boolean hasCurrentMessage() - { - return _currentMessage != null; - } - - public long getMaxUncommittedInMemorySize() - { - return _maxUncommittedInMemorySize; - } - - private class GetDeliveryMethod implements ClientDeliveryMethod - { - - private final FlowCreditManager _singleMessageCredit; - private final AMQQueue _queue; - private boolean _deliveredMessage; - - public GetDeliveryMethod(final FlowCreditManager singleMessageCredit, - final AMQQueue queue) - { - _singleMessageCredit = singleMessageCredit; - _queue = queue; - } - - @Override - public long deliverToClient(final ConsumerImpl sub, final ServerMessage message, - final InstanceProperties props, final long deliveryTag) - { - _singleMessageCredit.useCreditForMessage(message.getSize()); - long size = _connection.getProtocolOutputConverter().writeGetOk(message, - props, - AMQChannel.this.getChannelId(), - deliveryTag, - _queue.getQueueDepthMessages()); - - _deliveredMessage = true; - return size; - } - - public boolean hasDeliveredMessage() - { - return _deliveredMessage; - } - } - - - private class ImmediateAction implements Action<MessageInstance> - { - - public ImmediateAction() - { - } - - public void performAction(MessageInstance entry) - { - TransactionLogResource queue = entry.getOwningResource(); - - if (!entry.getDeliveredToConsumer() && entry.acquire()) - { - - ServerTransaction txn = new LocalTransaction(_messageStore); - final AMQMessage message = (AMQMessage) entry.getMessage(); - MessageReference ref = message.newReference(); - try - { - entry.delete(); - txn.dequeue(entry.getEnqueueRecord(), - new ServerTransaction.Action() - { - @Override - public void postCommit() - { - final ProtocolOutputConverter outputConverter = - _connection.getProtocolOutputConverter(); - - outputConverter.writeReturn(message.getMessagePublishInfo(), - message.getContentHeaderBody(), - message, - _channelId, - AMQConstant.NO_CONSUMERS.getCode(), - IMMEDIATE_DELIVERY_REPLY_TEXT); - - } - - @Override - public void onRollback() - { - - } - } - ); - txn.commit(); - } - finally - { - ref.release(); - } - - - } - else - { - if(queue instanceof CapacityChecker) - { - ((CapacityChecker)queue).checkCapacity(AMQChannel.this); - } - } - - } - } - - private final class CapacityCheckAction implements Action<MessageInstance> - { - @Override - public void performAction(final MessageInstance entry) - { - TransactionLogResource queue = entry.getOwningResource(); - if(queue instanceof CapacityChecker) - { - ((CapacityChecker)queue).checkCapacity(AMQChannel.this); - } - } - } - - private class MessageAcknowledgeAction implements ServerTransaction.Action - { - private final Collection<MessageInstance> _ackedMessages; - - public MessageAcknowledgeAction(Collection<MessageInstance> ackedMessages) - { - _ackedMessages = ackedMessages; - } - - public void postCommit() - { - try - { - for(MessageInstance entry : _ackedMessages) - { - entry.delete(); - } - } - finally - { - _ackedMessages.clear(); - } - - } - - public void onRollback() - { - // explicit rollbacks resend the message after the rollback-ok is sent - if(_rollingBack) - { - for(MessageInstance entry : _ackedMessages) - { - entry.unlockAcquisition(); - } - _resendList.addAll(_ackedMessages); - } - else - { - try - { - for(MessageInstance entry : _ackedMessages) - { - entry.release(); - } - } - finally - { - _ackedMessages.clear(); - } - } - - } - } - - private class WriteReturnAction implements ServerTransaction.Action - { - private final AMQConstant _errorCode; - private final String _description; - private final MessageReference<AMQMessage> _reference; - - public WriteReturnAction(AMQConstant errorCode, - String description, - AMQMessage message) - { - _errorCode = errorCode; - _description = description; - _reference = message.newReference(); - } - - public void postCommit() - { - AMQMessage message = _reference.getMessage(); - _connection.getProtocolOutputConverter().writeReturn(message.getMessagePublishInfo(), - message.getContentHeaderBody(), - message, - _channelId, - _errorCode.getCode(), - AMQShortString.validValueOf(_description)); - _reference.release(); - } - - public void onRollback() - { - _reference.release(); - } - } - - public synchronized void block() - { - if(_blockingEntities.add(this)) - { - - if(_blocking.compareAndSet(false,true)) - { - getVirtualHost().getEventLogger().message(_logSubject, - ChannelMessages.FLOW_ENFORCED("** All Queues **")); - - - getConnection().notifyWork(); - } - } - } - - public synchronized void unblock() - { - if(_blockingEntities.remove(this)) - { - if(_blockingEntities.isEmpty() && _blocking.compareAndSet(true,false)) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW_REMOVED()); - getConnection().notifyWork(); - } - } - } - - - public synchronized void block(AMQQueue queue) - { - if(_blockingEntities.add(queue)) - { - - if(_blocking.compareAndSet(false,true)) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW_ENFORCED(queue.getName())); - getConnection().notifyWork(); - - } - } - } - - public synchronized void unblock(AMQQueue queue) - { - if(_blockingEntities.remove(queue)) - { - if(_blockingEntities.isEmpty() && _blocking.compareAndSet(true,false) && !isClosing()) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW_REMOVED()); - getConnection().notifyWork(); - } - } - } - - @Override - public void transportStateChanged() - { - _creditManager.restoreCredit(0, 0); - _noAckCreditManager.restoreCredit(0, 0); - } - - @Override - public Object getConnectionReference() - { - return getConnection().getReference(); - } - - public int getUnacknowledgedMessageCount() - { - return getUnacknowledgedMessageMap().size(); - } - - private void flow(boolean flow) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createChannelFlowBody(flow); - _connection.writeFrame(responseBody.generateFrame(_channelId)); - } - - @Override - public boolean getBlocking() - { - return _blocking.get(); - } - - public VirtualHostImpl getVirtualHost() - { - return getConnection().getVirtualHost(); - } - - public void checkTransactionStatus(long openWarn, long openClose, long idleWarn, long idleClose) - { - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, openWarn, openClose, idleWarn, idleClose); - } - - /** - * Typically called from the HouseKeepingThread instead of the main receiver thread, - * therefore uses a lock to close the connection in a thread-safe manner. - */ - private void closeConnection(String reason) throws AMQException - { - _connection.closeAsync(AMQConstant.RESOURCE_ERROR, reason); - } - - public void deadLetter(long deliveryTag) - { - final UnacknowledgedMessageMap unackedMap = getUnacknowledgedMessageMap(); - final MessageInstance rejectedQueueEntry = unackedMap.remove(deliveryTag); - - if (rejectedQueueEntry == null) - { - _logger.warn("No message found, unable to DLQ delivery tag: " + deliveryTag); - } - else - { - final ServerMessage msg = rejectedQueueEntry.getMessage(); - - - int requeues = rejectedQueueEntry.routeToAlternate(new Action<MessageInstance>() - { - @Override - public void performAction(final MessageInstance requeueEntry) - { - getVirtualHost().getEventLogger().message(_logSubject, - ChannelMessages.DEADLETTERMSG(msg.getMessageNumber(), - requeueEntry.getOwningResource() - .getName())); - } - }, null); - - if(requeues == 0) - { - - final TransactionLogResource owningResource = rejectedQueueEntry.getOwningResource(); - if(owningResource instanceof AMQQueue) - { - final AMQQueue queue = (AMQQueue) owningResource; - - final Exchange altExchange = queue.getAlternateExchange(); - - if (altExchange == null) - { - _logger.debug("No alternate exchange configured for queue, must discard the message as unable to DLQ: delivery tag: " + deliveryTag); - getVirtualHost().getEventLogger().message(_logSubject, - ChannelMessages.DISCARDMSG_NOALTEXCH(msg.getMessageNumber(), - queue.getName(), - msg.getInitialRoutingAddress())); - - } - else - { - _logger.debug( - "Routing process provided no queues to enqueue the message on, must discard message as unable to DLQ: delivery tag: " - + deliveryTag); - getVirtualHost().getEventLogger().message(_logSubject, - ChannelMessages.DISCARDMSG_NOROUTE(msg.getMessageNumber(), - altExchange.getName())); - } - } - } - - } - } - - public void recordFuture(final FutureResult future, final ServerTransaction.Action action) - { - _unfinishedCommandsQueue.add(new AsyncCommand(future, action)); - } - - public void sync() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("sync() called on channel " + debugIdentity()); - } - - AsyncCommand cmd; - while((cmd = _unfinishedCommandsQueue.poll()) != null) - { - cmd.awaitReadyForCompletion(); - cmd.complete(); - } - if(_transaction instanceof LocalTransaction) - { - ((LocalTransaction)_transaction).sync(); - } - } - - private static class AsyncCommand - { - private final FutureResult _future; - private ServerTransaction.Action _action; - - public AsyncCommand(final FutureResult future, final ServerTransaction.Action action) - { - _future = future; - _action = action; - } - - void awaitReadyForCompletion() - { - _future.waitForCompletion(); - } - - void complete() - { - if(!_future.isComplete()) - { - _future.waitForCompletion(); - } - _action.postCommit(); - _action = null; - } - } - - @Override - public int getConsumerCount() - { - return _tag2SubscriptionTargetMap.size(); - } - - @Override - public Collection<Consumer<?>> getConsumers() - { - return Collections.unmodifiableCollection(_consumers); - } - - private class ConsumerClosedListener implements ConfigurationChangeListener - { - @Override - public void stateChanged(final ConfiguredObject object, final State oldState, final State newState) - { - if(newState == State.DELETED) - { - consumerRemoved((Consumer<?>)object); - } - } - - @Override - public void childAdded(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void childRemoved(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void attributeSet(final ConfiguredObject object, - final String attributeName, - final Object oldAttributeValue, - final Object newAttributeValue) - { - - } - } - - private void consumerAdded(final Consumer<?> consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerAdded(consumer); - } - } - - private void consumerRemoved(final Consumer<?> consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerRemoved(consumer); - } - } - - @Override - public void addConsumerListener(ConsumerListener listener) - { - _consumerListeners.add(listener); - } - - @Override - public void removeConsumerListener(ConsumerListener listener) - { - _consumerListeners.remove(listener); - } - - @Override - public void setModelObject(final Session<?> session) - { - _modelObject = session; - } - - @Override - public Session<?> getModelObject() - { - return _modelObject; - } - - @Override - public long getTransactionStartTime() - { - ServerTransaction serverTransaction = _transaction; - if (serverTransaction.isTransactional()) - { - return serverTransaction.getTransactionStartTime(); - } - else - { - return 0L; - } - } - - @Override - public long getTransactionUpdateTime() - { - ServerTransaction serverTransaction = _transaction; - if (serverTransaction.isTransactional()) - { - return serverTransaction.getTransactionUpdateTime(); - } - else - { - return 0L; - } - } - - @Override - public void receiveAccessRequest(final AMQShortString realm, - final boolean exclusive, - final boolean passive, - final boolean active, final boolean write, final boolean read) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] AccessRequest[" +" realm: " + realm + - " exclusive: " + exclusive + - " passive: " + passive + - " active: " + active + - " write: " + write + " read: " + read + " ]"); - } - - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - - if (ProtocolVersion.v0_91.equals(_connection.getProtocolVersion())) - { - _connection.closeConnection(AMQConstant.COMMAND_INVALID, - "AccessRequest not present in AMQP versions other than 0-8, 0-9", - _channelId); - } - else - { - // We don't implement access control class, but to keep clients happy that expect it - // always use the "0" ticket. - AccessRequestOkBody response = methodRegistry.createAccessRequestOkBody(0); - sync(); - _connection.writeFrame(response.generateFrame(_channelId)); - } - } - - @Override - public void receiveBasicAck(final long deliveryTag, final boolean multiple) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicAck[" +" deliveryTag: " + deliveryTag + " multiple: " + multiple + " ]"); - } - - acknowledgeMessage(deliveryTag, multiple); - } - - @Override - public void receiveBasicCancel(final AMQShortString consumerTag, final boolean nowait) - { - - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicCancel[" +" consumerTag: " + consumerTag + " noWait: " + nowait + " ]"); - } - - unsubscribeConsumer(consumerTag); - if (!nowait) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - BasicCancelOkBody cancelOkBody = methodRegistry.createBasicCancelOkBody(consumerTag); - sync(); - _connection.writeFrame(cancelOkBody.generateFrame(_channelId)); - } - } - - @Override - public void receiveBasicConsume(final AMQShortString queue, - final AMQShortString consumerTag, - final boolean noLocal, - final boolean noAck, - final boolean exclusive, final boolean nowait, final FieldTable arguments) - { - - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicConsume[" +" queue: " + queue + - " consumerTag: " + consumerTag + - " noLocal: " + noLocal + - " noAck: " + noAck + - " exclusive: " + exclusive + " nowait: " + nowait + " arguments: " + arguments + " ]"); - } - - AMQShortString consumerTag1 = consumerTag; - VirtualHostImpl<?, ?, ?> vHost = _connection.getVirtualHost(); - sync(); - String queueName = queue == null ? null : queue.asString(); - - MessageSource queue1 = queueName == null ? getDefaultQueue() : vHost.getQueue(queueName); - final Collection<MessageSource> sources = new HashSet<>(); - if (queue1 != null) - { - sources.add(queue1); - } - else if (vHost.getContextValue(Boolean.class, "qpid.enableMultiQueueConsumers") - && arguments != null - && arguments.get("x-multiqueue") instanceof Collection) - { - for (Object object : (Collection<Object>) arguments.get("x-multiqueue")) - { - String sourceName = String.valueOf(object); - sourceName = sourceName.trim(); - if (sourceName.length() != 0) - { - MessageSource source = vHost.getMessageSource(sourceName); - if (source == null) - { - sources.clear(); - break; - } - else - { - sources.add(source); - } - } - } - queueName = arguments.get("x-multiqueue").toString(); - } - - if (sources.isEmpty()) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("No queue for '" + queueName + "'"); - } - if (queueName != null) - { - closeChannel(AMQConstant.NOT_FOUND, "No such queue, '" + queueName + "'"); - } - else - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "No queue name provided, no default queue defined.", _channelId); - } - } - else - { - try - { - consumerTag1 = consumeFromSource(consumerTag1, - sources, - !noAck, - arguments, - exclusive, - noLocal); - if (!nowait) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createBasicConsumeOkBody(consumerTag1); - _connection.writeFrame(responseBody.generateFrame(_channelId)); - - } - } - catch (ConsumerTagInUseException cte) - { - - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Non-unique consumer tag, '" + consumerTag1 - + "'", _channelId); - } - catch (AMQInvalidArgumentException ise) - { - _connection.closeConnection(AMQConstant.ARGUMENT_INVALID, ise.getMessage(), _channelId); - - - } - catch (AMQQueue.ExistingExclusiveConsumer e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, - "Cannot subscribe to queue '" - + queue1.getName() - + "' as it already has an existing exclusive consumer", _channelId); - - } - catch (AMQQueue.ExistingConsumerPreventsExclusive e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, - "Cannot subscribe to queue '" - + queue1.getName() - + "' exclusively as it already has a consumer", _channelId); - - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, "Cannot subscribe to queue '" - + queue1.getName() - + "' permission denied", _channelId); - - } - catch (MessageSource.ConsumerAccessRefused consumerAccessRefused) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, - "Cannot subscribe to queue '" - + queue1.getName() - + "' as it already has an incompatible exclusivity policy", _channelId); - - } - - } - } - - @Override - public void receiveBasicGet(final AMQShortString queueName, final boolean noAck) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicGet[" +" queue: " + queueName + " noAck: " + noAck + " ]"); - } - - VirtualHostImpl vHost = _connection.getVirtualHost(); - sync(); - AMQQueue queue = queueName == null ? getDefaultQueue() : vHost.getQueue(queueName.toString()); - if (queue == null) - { - _logger.info("No queue for '" + queueName + "'"); - if (queueName != null) - { - _connection.closeConnection(AMQConstant.NOT_FOUND, "No such queue, '" + queueName + "'", _channelId); - - } - else - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "No queue name provided, no default queue defined.", _channelId); - - } - } - else - { - - try - { - if (!performGet(queue, !noAck)) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - - BasicGetEmptyBody responseBody = methodRegistry.createBasicGetEmptyBody(null); - - _connection.writeFrame(responseBody.generateFrame(_channelId)); - } - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), _channelId); - } - catch (MessageSource.ExistingExclusiveConsumer e) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Queue has an exclusive consumer", _channelId); - } - catch (MessageSource.ExistingConsumerPreventsExclusive e) - { - _connection.closeConnection(AMQConstant.INTERNAL_ERROR, - "The GET request has been evaluated as an exclusive consumer, " + - "this is likely due to a programming error in the Qpid broker", _channelId); - } - catch (MessageSource.ConsumerAccessRefused consumerAccessRefused) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Queue has an incompatible exclusivity policy", _channelId); - } - } - } - - @Override - public void receiveBasicPublish(final AMQShortString exchangeName, - final AMQShortString routingKey, - final boolean mandatory, - final boolean immediate) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicPublish[" +" exchange: " + exchangeName + - " routingKey: " + routingKey + - " mandatory: " + mandatory + - " immediate: " + immediate + " ]"); - } - - - - VirtualHostImpl vHost = _connection.getVirtualHost(); - - if(blockingTimeoutExceeded()) - { - getVirtualHost().getEventLogger().message(ChannelMessages.FLOW_CONTROL_IGNORED()); - closeChannel(AMQConstant.MESSAGE_TOO_LARGE, - "Channel flow control was requested, but not enforced by sender"); - } - else - { - MessageDestination destination; - - if (isDefaultExchange(exchangeName)) - { - destination = vHost.getDefaultDestination(); - } - else - { - destination = vHost.getMessageDestination(exchangeName.toString()); - } - - // if the exchange does not exist we raise a channel exception - if (destination == null) - { - closeChannel(AMQConstant.NOT_FOUND, "Unknown exchange name: '" + exchangeName + "'"); - } - else - { - - MessagePublishInfo info = new MessagePublishInfo(exchangeName, - immediate, - mandatory, - routingKey); - - try - { - setPublishFrame(info, destination); - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - - } - } - } - } - - private boolean blockingTimeoutExceeded() - { - - return _wireBlockingState && (System.currentTimeMillis() - _blockTime) > _blockingTimeout; - } - - @Override - public void receiveBasicQos(final long prefetchSize, final int prefetchCount, final boolean global) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicQos[" +" prefetchSize: " + prefetchSize + " prefetchCount: " + prefetchCount + " global: " + global + " ]"); - } - - sync(); - setCredit(prefetchSize, prefetchCount); - - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createBasicQosOkBody(); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - } - - @Override - public void receiveBasicRecover(final boolean requeue, final boolean sync) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicRecover[" + " requeue: " + requeue + " sync: " + sync + " ]"); - } - - resend(); - - if (sync) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody recoverOk = methodRegistry.createBasicRecoverSyncOkBody(); - sync(); - _connection.writeFrame(recoverOk.generateFrame(getChannelId())); - - } - - } - - @Override - public void receiveBasicReject(final long deliveryTag, final boolean requeue) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicReject[" +" deliveryTag: " + deliveryTag + " requeue: " + requeue + " ]"); - } - - MessageInstance message = getUnacknowledgedMessageMap().get(deliveryTag); - - if (message == null) - { - _logger.warn("Dropping reject request as message is null for tag:" + deliveryTag); - } - else - { - - if (message.getMessage() == null) - { - _logger.warn("Message has already been purged, unable to Reject."); - } - else - { - - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejecting: DT:" + deliveryTag - + "-" + message.getMessage() + - ": Requeue:" + requeue - + - " on channel:" + debugIdentity()); - } - - if (requeue) - { - message.decrementDeliveryCount(); - - requeue(deliveryTag); - } - else - { - // Since the Java client abuses the reject flag for requeing after rollback, we won't set reject here - // as it would prevent redelivery - // message.reject(); - - final boolean maxDeliveryCountEnabled = isMaxDeliveryCountEnabled(deliveryTag); - _logger.debug("maxDeliveryCountEnabled: " - + maxDeliveryCountEnabled - + " deliveryTag " - + deliveryTag); - if (maxDeliveryCountEnabled) - { - final boolean deliveredTooManyTimes = isDeliveredTooManyTimes(deliveryTag); - _logger.debug("deliveredTooManyTimes: " - + deliveredTooManyTimes - + " deliveryTag " - + deliveryTag); - if (deliveredTooManyTimes) - { - deadLetter(deliveryTag); - } - else - { - //this requeue represents a message rejected because of a recover/rollback that we - //are not ready to DLQ. We rely on the reject command to resend from the unacked map - //and therefore need to increment the delivery counter so we cancel out the effect - //of the AMQChannel#resend() decrement. - message.incrementDeliveryCount(); - } - } - else - { - requeue(deliveryTag); - } - } - } - } - } - - @Override - public void receiveChannelClose(final int replyCode, - final AMQShortString replyText, - final int classId, - final int methodId) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ChannelClose[" +" replyCode: " + replyCode + " replyText: " + replyText + " classId: " + classId + " methodId: " + methodId + " ]"); - } - - - sync(); - _connection.closeChannel(this); - - _connection.writeFrame(new AMQFrame(getChannelId(), - _connection.getMethodRegistry().createChannelCloseOkBody())); - } - - @Override - public void receiveChannelCloseOk() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ChannelCloseOk"); - } - - _connection.closeChannelOk(getChannelId()); - } - - @Override - public void receiveMessageContent(final byte[] data) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] MessageContent[" +" data: " + hex(data,_connection.getBinaryDataLimit()) + " ] "); - } - - if(hasCurrentMessage()) - { - publishContentBody(new ContentBody(data)); - } - else - { - _connection.closeConnection(AMQConstant.COMMAND_INVALID, - "Attempt to send a content header without first sending a publish frame", - _channelId); - } - } - - @Override - public void receiveMessageHeader(final BasicContentHeaderProperties properties, final long bodySize) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] MessageHeader[ properties: {" + properties + "} bodySize: " + bodySize + " ]"); - } - - if(hasCurrentMessage()) - { - if(bodySize > _connection.getMaxMessageSize()) - { - closeChannel(AMQConstant.MESSAGE_TOO_LARGE, - "Message size of " + bodySize + " greater than allowed maximum of " + _connection.getMaxMessageSize()); - } - publishContentHeader(new ContentHeaderBody(properties, bodySize)); - } - else - { - _connection.closeConnection(AMQConstant.COMMAND_INVALID, - "Attempt to send a content header without first sending a publish frame", - _channelId); - } - } - - @Override - public boolean ignoreAllButCloseOk() - { - return _connection.ignoreAllButCloseOk() || _connection.channelAwaitingClosure(_channelId); - } - - @Override - public void receiveBasicNack(final long deliveryTag, final boolean multiple, final boolean requeue) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicNack[" +" deliveryTag: " + deliveryTag + " multiple: " + multiple + " requeue: " + requeue + " ]"); - } - - Map<Long, MessageInstance> nackedMessageMap = new LinkedHashMap<>(); - _unacknowledgedMessageMap.collect(deliveryTag, multiple, nackedMessageMap); - - for(MessageInstance message : nackedMessageMap.values()) - { - - if (message == null) - { - _logger.warn("Ignoring nack request as message is null for tag:" + deliveryTag); - } - else - { - - if (message.getMessage() == null) - { - _logger.warn("Message has already been purged, unable to nack."); - } - else - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Nack-ing: DT:" + deliveryTag - + "-" + message.getMessage() + - ": Requeue:" + requeue - + - " on channel:" + debugIdentity()); - } - - if (requeue) - { - message.decrementDeliveryCount(); - - requeue(deliveryTag); - } - else - { - message.reject(); - - final boolean maxDeliveryCountEnabled = isMaxDeliveryCountEnabled(deliveryTag); - _logger.debug("maxDeliveryCountEnabled: " - + maxDeliveryCountEnabled - + " deliveryTag " - + deliveryTag); - if (maxDeliveryCountEnabled) - { - final boolean deliveredTooManyTimes = isDeliveredTooManyTimes(deliveryTag); - _logger.debug("deliveredTooManyTimes: " - + deliveredTooManyTimes - + " deliveryTag " - + deliveryTag); - if (deliveredTooManyTimes) - { - deadLetter(deliveryTag); - } - else - { - message.incrementDeliveryCount(); - } - } - else - { - requeue(deliveryTag); - } - } - } - } - - } - - } - - @Override - public void receiveChannelFlow(final boolean active) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ChannelFlow[" +" active: " + active + " ]"); - } - - - sync(); - setSuspended(!active); - - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createChannelFlowOkBody(active); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - } - - @Override - public void receiveChannelFlowOk(final boolean active) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ChannelFlowOk[" +" active: " + active + " ]"); - } - - // TODO - should we do anything here? - } - - @Override - public void receiveExchangeBound(final AMQShortString exchangeName, - final AMQShortString routingKey, - final AMQShortString queueName) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ExchangeBound[" +" exchange: " + exchangeName + " routingKey: " + - routingKey + " queue: " + queueName + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - - sync(); - - int replyCode; - String replyText; - - if (isDefaultExchange(exchangeName)) - { - if (routingKey == null) - { - if (queueName == null) - { - replyCode = virtualHost.getQueues().isEmpty() - ? ExchangeBoundOkBody.NO_BINDINGS - : ExchangeBoundOkBody.OK; - replyText = null; - - } - else - { - AMQQueue queue = virtualHost.getQueue(queueName.toString()); - if (queue == null) - { - replyCode = ExchangeBoundOkBody.QUEUE_NOT_FOUND; - replyText = "Queue '" + queueName + "' not found"; - } - else - { - replyCode = ExchangeBoundOkBody.OK; - replyText = null; - } - } - } - else - { - if (queueName == null) - { - replyCode = virtualHost.getQueue(routingKey.toString()) == null - ? ExchangeBoundOkBody.NO_QUEUE_BOUND_WITH_RK - : ExchangeBoundOkBody.OK; - replyText = null; - } - else - { - AMQQueue queue = virtualHost.getQueue(queueName.toString()); - if (queue == null) - { - - replyCode = ExchangeBoundOkBody.QUEUE_NOT_FOUND; - replyText = "Queue '" + queueName + "' not found"; - } - else - { - replyCode = queueName.equals(routingKey) - ? ExchangeBoundOkBody.OK - : ExchangeBoundOkBody.SPECIFIC_QUEUE_NOT_BOUND_WITH_RK; - replyText = null; - } - } - } - } - else - { - ExchangeImpl exchange = virtualHost.getExchange(exchangeName.toString()); - if (exchange == null) - { - - replyCode = ExchangeBoundOkBody.EXCHANGE_NOT_FOUND; - replyText = "Exchange '" + exchangeName + "' not found"; - } - else if (routingKey == null) - { - if (queueName == null) - { - if (exchange.hasBindings()) - { - replyCode = ExchangeBoundOkBody.OK; - replyText = null; - } - else - { - replyCode = ExchangeBoundOkBody.NO_BINDINGS; - replyText = null; - } - } - else - { - - AMQQueue queue = virtualHost.getQueue(queueName.toString()); - if (queue == null) - { - replyCode = ExchangeBoundOkBody.QUEUE_NOT_FOUND; - replyText = "Queue '" + queueName + "' not found"; - } - else - { - if (exchange.isBound(queue)) - { - replyCode = ExchangeBoundOkBody.OK; - replyText = null; - } - else - { - replyCode = ExchangeBoundOkBody.QUEUE_NOT_BOUND; - replyText = "Queue '" - + queueName - + "' not bound to exchange '" - + exchangeName - + "'"; - } - } - } - } - else if (queueName != null) - { - AMQQueue queue = virtualHost.getQueue(queueName.toString()); - if (queue == null) - { - replyCode = ExchangeBoundOkBody.QUEUE_NOT_FOUND; - replyText = "Queue '" + queueName + "' not found"; - } - else - { - String bindingKey = routingKey == null ? null : routingKey.asString(); - if (exchange.isBound(bindingKey, queue)) - { - - replyCode = ExchangeBoundOkBody.OK; - replyText = null; - } - else - { - replyCode = ExchangeBoundOkBody.SPECIFIC_QUEUE_NOT_BOUND_WITH_RK; - replyText = "Queue '" + queueName + "' not bound with routing key '" + - routingKey + "' to exchange '" + exchangeName + "'"; - - } - } - } - else - { - if (exchange.isBound(routingKey == null ? "" : routingKey.asString())) - { - - replyCode = ExchangeBoundOkBody.OK; - replyText = null; - } - else - { - replyCode = ExchangeBoundOkBody.NO_QUEUE_BOUND_WITH_RK; - replyText = - "No queue bound with routing key '" + routingKey + "' to exchange '" + exchangeName + "'"; - } - } - } - - ExchangeBoundOkBody exchangeBoundOkBody = - methodRegistry.createExchangeBoundOkBody(replyCode, AMQShortString.validValueOf(replyText)); - - _connection.writeFrame(exchangeBoundOkBody.generateFrame(getChannelId())); - - } - - @Override - public void receiveExchangeDeclare(final AMQShortString exchangeName, - final AMQShortString type, - final boolean passive, - final boolean durable, - final boolean autoDelete, - final boolean internal, - final boolean nowait, - final FieldTable arguments) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ExchangeDeclare[" +" exchange: " + exchangeName + - " type: " + type + - " passive: " + passive + - " durable: " + durable + - " autoDelete: " + autoDelete + - " internal: " + internal + " nowait: " + nowait + " arguments: " + arguments + " ]"); - } - - ExchangeImpl exchange; - VirtualHostImpl<?, ?, ?> virtualHost = _connection.getVirtualHost(); - if (isDefaultExchange(exchangeName)) - { - if (!new AMQShortString(ExchangeDefaults.DIRECT_EXCHANGE_CLASS).equals(type)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Attempt to redeclare default exchange: " - + " of type " - + ExchangeDefaults.DIRECT_EXCHANGE_CLASS - + " to " + type + ".", getChannelId()); - } - else if (!nowait) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createExchangeDeclareOkBody(); - sync(); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - } - - } - else - { - if (passive) - { - exchange = virtualHost.getExchange(exchangeName.toString()); - if (exchange == null) - { - closeChannel(AMQConstant.NOT_FOUND, "Unknown exchange: '" + exchangeName + "'"); - } - else if (!(type == null || type.length() == 0) && !exchange.getType().equals(type.asString())) - { - - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Attempt to redeclare exchange: '" - + exchangeName - + "' of type " - + exchange.getType() - + " to " - + type - + ".", getChannelId()); - } - else if (!nowait) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createExchangeDeclareOkBody(); - sync(); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - } - - } - else - { - try - { - String name = exchangeName == null ? null : exchangeName.intern().toString(); - String typeString = type == null ? null : type.intern().toString(); - - Map<String, Object> attributes = new HashMap<String, Object>(); - if (arguments != null) - { - attributes.putAll(FieldTable.convertToMap(arguments)); - } - attributes.put(Exchange.NAME, name); - attributes.put(Exchange.TYPE, typeString); - attributes.put(Exchange.DURABLE, durable); - attributes.put(Exchange.LIFETIME_POLICY, - autoDelete ? LifetimePolicy.DELETE_ON_NO_LINKS : LifetimePolicy.PERMANENT); - if (!attributes.containsKey(Exchange.ALTERNATE_EXCHANGE)) - { - attributes.put(Exchange.ALTERNATE_EXCHANGE, null); - } - exchange = virtualHost.createExchange(attributes); - - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createExchangeDeclareOkBody(); - _connection.writeFrame(responseBody.generateFrame( - getChannelId())); - } - - } - catch (ReservedExchangeNameException e) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Attempt to declare exchange: '" + exchangeName + - "' which begins with reserved prefix.", getChannelId()); - - - } - catch (ExchangeExistsException e) - { - exchange = e.getExistingExchange(); - if (!new AMQShortString(exchange.getType()).equals(type)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Attempt to redeclare exchange: '" - + exchangeName + "' of type " - + exchange.getType() - + " to " + type + ".", getChannelId()); - - } - else - { - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createExchangeDeclareOkBody(); - _connection.writeFrame(responseBody.generateFrame( - getChannelId())); - } - } - } - catch (NoFactoryForTypeException e) - { - _connection.closeConnection(AMQConstant.COMMAND_INVALID, "Unknown exchange type '" - + e.getType() - + "' for exchange '" - + exchangeName - + "'", getChannelId()); - - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - - } - catch (UnknownConfiguredObjectException e) - { - // note - since 0-8/9/9-1 can't set the alt. exchange this exception should never occur - final String message = "Unknown alternate exchange " - + (e.getName() != null - ? "name: '" + e.getName() + "'" - : "id: " + e.getId()); - _connection.closeConnection(AMQConstant.NOT_FOUND, message, getChannelId()); - - } - catch (IllegalArgumentException e) - { - _connection.closeConnection(AMQConstant.COMMAND_INVALID, "Error creating exchange '" - + exchangeName - + "': " - + e.getMessage(), getChannelId()); - - } - } - } - - } - - @Override - public void receiveExchangeDelete(final AMQShortString exchangeStr, final boolean ifUnused, final boolean nowait) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ExchangeDelete[" +" exchange: " + exchangeStr + " ifUnused: " + ifUnused + " nowait: " + nowait + " ]"); - } - - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - sync(); - try - { - - if (isDefaultExchange(exchangeStr)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Default Exchange cannot be deleted", getChannelId()); - - } - - else - { - final String exchangeName = exchangeStr.toString(); - - final ExchangeImpl exchange = virtualHost.getExchange(exchangeName); - if (exchange == null) - { - closeChannel(AMQConstant.NOT_FOUND, "No such exchange: '" + exchangeStr + "'"); - } - else - { - virtualHost.removeExchange(exchange, !ifUnused); - - ExchangeDeleteOkBody responseBody = _connection.getMethodRegistry().createExchangeDeleteOkBody(); - - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - } - } - } - catch (ExchangeIsAlternateException e) - { - closeChannel(AMQConstant.NOT_ALLOWED, "Exchange in use as an alternate exchange"); - } - catch (RequiredExchangeException e) - { - closeChannel(AMQConstant.NOT_ALLOWED, - "Exchange '" + exchangeStr + "' cannot be deleted"); - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - } - } - - @Override - public void receiveQueueBind(final AMQShortString queueName, - final AMQShortString exchange, - AMQShortString routingKey, - final boolean nowait, - final FieldTable argumentsTable) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] QueueBind[" +" queue: " + queueName + - " exchange: " + exchange + - " bindingKey: " + routingKey + - " nowait: " + nowait + " arguments: " + argumentsTable + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - AMQQueue<?> queue; - if (queueName == null) - { - - queue = getDefaultQueue(); - - if (queue != null) - { - if (routingKey == null) - { - routingKey = AMQShortString.valueOf(queue.getName()); - } - else - { - routingKey = routingKey.intern(); - } - } - } - else - { - queue = virtualHost.getQueue(queueName.toString()); - routingKey = routingKey == null ? AMQShortString.EMPTY_STRING : routingKey.intern(); - } - - if (queue == null) - { - String message = queueName == null - ? "No default queue defined on channel and queue was null" - : "Queue " + queueName + " does not exist."; - closeChannel(AMQConstant.NOT_FOUND, message); - } - else if (isDefaultExchange(exchange)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Cannot bind the queue '" + queueName + "' to the default exchange", getChannelId()); - - } - else - { - - final String exchangeName = exchange.toString(); - - final ExchangeImpl exch = virtualHost.getExchange(exchangeName); - if (exch == null) - { - closeChannel(AMQConstant.NOT_FOUND, - "Exchange '" + exchangeName + "' does not exist."); - } - else - { - - try - { - - Map<String, Object> arguments = FieldTable.convertToMap(argumentsTable); - String bindingKey = String.valueOf(routingKey); - - if (!exch.isBound(bindingKey, arguments, queue)) - { - - if (!exch.addBinding(bindingKey, queue, arguments) - && ExchangeDefaults.TOPIC_EXCHANGE_CLASS.equals( - exch.getType())) - { - exch.replaceBinding(bindingKey, queue, arguments); - } - } - - if (_logger.isInfoEnabled()) - { - _logger.info("Binding queue " - + queue - + " to exchange " - + exch - + " with routing key " - + routingKey); - } - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createQueueBindOkBody(); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - } - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - } - } - } - } - - @Override - public void receiveQueueDeclare(final AMQShortString queueStr, - final boolean passive, - final boolean durable, - final boolean exclusive, - final boolean autoDelete, - final boolean nowait, - final FieldTable arguments) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] QueueDeclare[" +" queue: " + queueStr + - " passive: " + passive + - " durable: " + durable + - " exclusive: " + exclusive + - " autoDelete: " + autoDelete + " nowait: " + nowait + " arguments: " + arguments + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - - final AMQShortString queueName; - - // if we aren't given a queue name, we create one which we return to the client - if ((queueStr == null) || (queueStr.length() == 0)) - { - queueName = new AMQShortString("tmp_" + UUID.randomUUID()); - } - else - { - queueName = queueStr.intern(); - } - - AMQQueue<?> queue; - - //TODO: do we need to check that the queue already exists with exactly the same "configuration"? - - - if (passive) - { - queue = virtualHost.getQueue(queueName.toString()); - if (queue == null) - { - closeChannel(AMQConstant.NOT_FOUND, - "Queue: '" - + queueName - + "' not found on VirtualHost '" - + virtualHost.getName() - + "'."); - } - else - { - if (!queue.verifySessionAccess(this)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Queue '" - + queue.getName() - + "' is exclusive, but not created on this Connection.", getChannelId()); - } - else - { - //set this as the default queue on the channel: - setDefaultQueue(queue); - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - QueueDeclareOkBody responseBody = - methodRegistry.createQueueDeclareOkBody(queueName, - queue.getQueueDepthMessages(), - queue.getConsumerCount()); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - _logger.info("Queue " + queueName + " declared successfully"); - } - } - } - } - else - { - - try - { - Map<String, Object> attributes = - QueueArgumentsConverter.convertWireArgsToModel(FieldTable.convertToMap(arguments)); - final String queueNameString = AMQShortString.toString(queueName); - attributes.put(Queue.NAME, queueNameString); - attributes.put(Queue.DURABLE, durable); - - LifetimePolicy lifetimePolicy; - ExclusivityPolicy exclusivityPolicy; - - if (exclusive) - { - lifetimePolicy = autoDelete - ? LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS - : durable ? LifetimePolicy.PERMANENT : LifetimePolicy.DELETE_ON_CONNECTION_CLOSE; - exclusivityPolicy = durable ? ExclusivityPolicy.CONTAINER : ExclusivityPolicy.CONNECTION; - } - else - { - lifetimePolicy = autoDelete ? LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS : LifetimePolicy.PERMANENT; - exclusivityPolicy = ExclusivityPolicy.NONE; - } - - attributes.put(Queue.EXCLUSIVE, exclusivityPolicy); - attributes.put(Queue.LIFETIME_POLICY, lifetimePolicy); - - - queue = virtualHost.createQueue(attributes); - - setDefaultQueue(queue); - - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - QueueDeclareOkBody responseBody = - methodRegistry.createQueueDeclareOkBody(queueName, - queue.getQueueDepthMessages(), - queue.getConsumerCount()); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - _logger.info("Queue " + queueName + " declared successfully"); - } - } - catch (QueueExistsException qe) - { - - queue = qe.getExistingQueue(); - - if (!queue.verifySessionAccess(this)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Queue '" - + queue.getName() - + "' is exclusive, but not created on this Connection.", getChannelId()); - - } - else if (queue.isExclusive() != exclusive) - { - - closeChannel(AMQConstant.ALREADY_EXISTS, - "Cannot re-declare queue '" - + queue.getName() - + "' with different exclusivity (was: " - + queue.isExclusive() - + " requested " - + exclusive - + ")"); - } - else if ((autoDelete - && queue.getLifetimePolicy() != LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS) - || (!autoDelete && queue.getLifetimePolicy() != ((exclusive - && !durable) - ? LifetimePolicy.DELETE_ON_CONNECTION_CLOSE - : LifetimePolicy.PERMANENT))) - { - closeChannel(AMQConstant.ALREADY_EXISTS, - "Cannot re-declare queue '" - + queue.getName() - + "' with different lifetime policy (was: " - + queue.getLifetimePolicy() - + " requested autodelete: " - + autoDelete - + ")"); - } - else - { - setDefaultQueue(queue); - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - QueueDeclareOkBody responseBody = - methodRegistry.createQueueDeclareOkBody(queueName, - queue.getQueueDepthMessages(), - queue.getConsumerCount()); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - _logger.info("Queue " + queueName + " declared successfully"); - } - } - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - } - - } - } - - @Override - public void receiveQueueDelete(final AMQShortString queueName, - final boolean ifUnused, - final boolean ifEmpty, - final boolean nowait) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] QueueDelete[" +" queue: " + queueName + " ifUnused: " + ifUnused + " ifEmpty: " + ifEmpty + " nowait: " + nowait + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - sync(); - AMQQueue queue; - if (queueName == null) - { - - //get the default queue on the channel: - queue = getDefaultQueue(); - } - else - { - queue = virtualHost.getQueue(queueName.toString()); - } - - if (queue == null) - { - closeChannel(AMQConstant.NOT_FOUND, "Queue '" + queueName + "' does not exist."); - - } - else - { - if (ifEmpty && !queue.isEmpty()) - { - closeChannel(AMQConstant.IN_USE, "Queue: '" + queueName + "' is not empty."); - } - else if (ifUnused && !queue.isUnused()) - { - // TODO - Error code - closeChannel(AMQConstant.IN_USE, "Queue: '" + queueName + "' is still used."); - } - else - { - if (!queue.verifySessionAccess(this)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Queue '" - + queue.getName() - + "' is exclusive, but not created on this Connection.", getChannelId()); - - } - else - { - try - { - int purged = virtualHost.removeQueue(queue); - - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - QueueDeleteOkBody responseBody = methodRegistry.createQueueDeleteOkBody(purged); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - - } - } - } - } - } - - @Override - public void receiveQueuePurge(final AMQShortString queueName, final boolean nowait) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] QueuePurge[" +" queue: " + queueName + " nowait: " + nowait + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - AMQQueue queue = null; - if (queueName == null && (queue = getDefaultQueue()) == null) - { - - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "No queue specified.", getChannelId()); - } - else if ((queueName != null) && (queue = virtualHost.getQueue(queueName.toString())) == null) - { - closeChannel(AMQConstant.NOT_FOUND, "Queue '" + queueName + "' does not exist."); - } - else if (!queue.verifySessionAccess(this)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Queue is exclusive, but not created on this Connection.", getChannelId()); - } - else - { - try - { - long purged = queue.clearQueue(); - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createQueuePurgeOkBody(purged); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - } - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - - } - - } - } - - @Override - public void receiveQueueUnbind(final AMQShortString queueName, - final AMQShortString exchange, - final AMQShortString bindingKey, - final FieldTable arguments) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] QueueUnbind[" +" queue: " + queueName + - " exchange: " + exchange + - " bindingKey: " + bindingKey + - " arguments: " + arguments + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - - - final boolean useDefaultQueue = queueName == null; - final AMQQueue queue = useDefaultQueue - ? getDefaultQueue() - : virtualHost.getQueue(queueName.toString()); - - - if (queue == null) - { - String message = useDefaultQueue - ? "No default queue defined on channel and queue was null" - : "Queue '" + queueName + "' does not exist."; - closeChannel(AMQConstant.NOT_FOUND, message); - } - else if (isDefaultExchange(exchange)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Cannot unbind the queue '" - + queue.getName() - + "' from the default exchange", getChannelId()); - - } - else - { - - final ExchangeImpl exch = virtualHost.getExchange(exchange.toString()); - - if (exch == null) - { - closeChannel(AMQConstant.NOT_FOUND, "Exchange '" + exchange + "' does not exist."); - } - else if (!exch.hasBinding(String.valueOf(bindingKey), queue)) - { - closeChannel(AMQConstant.NOT_FOUND, "No such binding"); - } - else - { - try - { - exch.deleteBinding(String.valueOf(bindingKey), queue); - - final AMQMethodBody responseBody = _connection.getMethodRegistry().createQueueUnbindOkBody(); - sync(); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - - } - } - - } - } - - @Override - public void receiveTxSelect() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] TxSelect"); - } - - setLocalTransactional(); - - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - TxSelectOkBody responseBody = methodRegistry.createTxSelectOkBody(); - _connection.writeFrame(responseBody.generateFrame(_channelId)); - - } - - @Override - public void receiveTxCommit() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] TxCommit"); - } - - - if (!isTransactional()) - { - closeChannel(AMQConstant.COMMAND_INVALID, - "Fatal error: commit called on non-transactional channel"); - } - commit(new Runnable() - { - - @Override - public void run() - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createTxCommitOkBody(); - _connection.writeFrame(responseBody.generateFrame(_channelId)); - } - }, true); - - } - - @Override - public void receiveTxRollback() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] TxRollback"); - } - - if (!isTransactional()) - { - closeChannel(AMQConstant.COMMAND_INVALID, - "Fatal error: rollback called on non-transactional channel"); - } - - final MethodRegistry methodRegistry = _connection.getMethodRegistry(); - final AMQMethodBody responseBody = methodRegistry.createTxRollbackOkBody(); - - Runnable task = new Runnable() - { - - public void run() - { - _connection.writeFrame(responseBody.generateFrame(_channelId)); - } - }; - - rollback(task); - - //Now resend all the unacknowledged messages back to the original subscribers. - //(Must be done after the TxnRollback-ok response). - // Why, are we not allowed to send messages back to client before the ok method? - resend(); - } - - @Override - public void receiveConfirmSelect(final boolean nowait) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ConfirmSelect [ nowait: " + nowait + " ]"); - } - _confirmOnPublish = true; - - if(!nowait) - { - _connection.writeFrame(new AMQFrame(_channelId, ConfirmSelectOkBody.INSTANCE)); - } - } - - - private void closeChannel(final AMQConstant cause, final String message) - { - _connection.closeChannelAndWriteFrame(this, cause, message); - } - - - private boolean isDefaultExchange(final AMQShortString exchangeName) - { - return exchangeName == null || AMQShortString.EMPTY_STRING.equals(exchangeName); - } - - private void setDefaultQueue(AMQQueue<?> queue) - { - AMQQueue<?> currentDefaultQueue = _defaultQueue; - if (queue != currentDefaultQueue) - { - if (currentDefaultQueue != null) - { - currentDefaultQueue.removeDeleteTask(_defaultQueueAssociationClearingTask); - } - if (queue != null) - { - queue.addDeleteTask(_defaultQueueAssociationClearingTask); - } - } - _defaultQueue = queue; - } - - private AMQQueue getDefaultQueue() - { - return _defaultQueue; - } - - private class DefaultQueueAssociationClearingTask implements Action<AMQQueue> - { - @Override - public void performAction(final AMQQueue queue) - { - if ( queue == _defaultQueue) - { - _defaultQueue = null; - } - } - } - - @Override - public void processPending() - { - - boolean desiredBlockingState = _blocking.get(); - if (desiredBlockingState != _wireBlockingState) - { - _wireBlockingState = desiredBlockingState; - flow(!desiredBlockingState); - _blockTime = desiredBlockingState ? System.currentTimeMillis() : 0; - } - - for(ConsumerTarget target : _tag2SubscriptionTargetMap.values()) - { - target.processPending(); - } - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQMessage.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQMessage.java deleted file mode 100644 index faa3831d70..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQMessage.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.AbstractServerMessageImpl; -import org.apache.qpid.server.store.StoredMessage; - -/** - * A deliverable message. - */ -public class AMQMessage extends AbstractServerMessageImpl<AMQMessage, MessageMetaData> -{ - private final long _size; - - public AMQMessage(StoredMessage<MessageMetaData> handle) - { - this(handle, null); - } - - public AMQMessage(StoredMessage<MessageMetaData> handle, Object connectionReference) - { - super(handle, connectionReference); - _size = handle.getMetaData().getContentSize(); - } - - public MessageMetaData getMessageMetaData() - { - return getStoredMessage().getMetaData(); - } - - public ContentHeaderBody getContentHeaderBody() - { - return getMessageMetaData().getContentHeaderBody(); - } - - public String getInitialRoutingAddress() - { - MessageMetaData messageMetaData = getMessageMetaData(); - if (messageMetaData != null) - { - AMQShortString routingKey = messageMetaData.getMessagePublishInfo().getRoutingKey(); - if (routingKey != null) - { - return routingKey.asString(); - } - } - return null; - } - - public AMQMessageHeader getMessageHeader() - { - return getMessageMetaData().getMessageHeader(); - } - - public MessagePublishInfo getMessagePublishInfo() - { - return getMessageMetaData().getMessagePublishInfo(); - } - - public long getArrivalTime() - { - return getMessageMetaData().getArrivalTime(); - } - - public long getSize() - { - return _size; - } - - public boolean isImmediate() - { - return getMessagePublishInfo().isImmediate(); - } - - public boolean isMandatory() - { - return getMessagePublishInfo().isMandatory(); - } - - public long getExpiration() - { - return getMessageHeader().getExpiration(); - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQNoMethodHandlerException.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQNoMethodHandlerException.java deleted file mode 100644 index 42250190b4..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQNoMethodHandlerException.java +++ /dev/null @@ -1,42 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.protocol.v0_8;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
-
-/**
- * AMQNoMethodHandlerException represents the case where no method handler exists to handle an AQMP method.
- *
- * <p>
- * TODO Not an AMQP exception as no status code.
- * <p>
- * TODO Missing method handler. Unlikely to ever happen, and if it does its a coding error. Consider replacing with a
- * Runtime.
- */
-public class AMQNoMethodHandlerException extends AMQException
-{
- public AMQNoMethodHandlerException(AMQMethodEvent<AMQMethodBody> evt)
- {
- super("AMQMethodEvent " + evt + " was not processed by any listener on Broker.");
- }
-}
diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngine.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngine.java deleted file mode 100644 index b1f2a6e841..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngine.java +++ /dev/null @@ -1,2033 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.io.IOException; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.security.AccessControlException; -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import javax.security.auth.Subject; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQConnectionException; -import org.apache.qpid.AMQException; -import org.apache.qpid.codec.AMQDecoder; -import org.apache.qpid.common.QpidProperties; -import org.apache.qpid.common.ServerPropertyNames; -import org.apache.qpid.framing.*; -import org.apache.qpid.properties.ConnectionStartProperties; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.logging.messages.ConnectionMessages; -import org.apache.qpid.server.logging.subjects.ConnectionLogSubject; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.SessionModelListener; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.security.auth.SubjectAuthenticationResult; -import org.apache.qpid.server.stats.StatisticsCounter; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.SenderClosedException; -import org.apache.qpid.transport.SenderException; -import org.apache.qpid.transport.TransportException; -import org.apache.qpid.transport.network.NetworkConnection; - -public class AMQProtocolEngine implements ServerProtocolEngine, - AMQConnectionModel<AMQProtocolEngine, AMQChannel>, - ServerMethodProcessor<ServerChannelMethodProcessor> -{ - - - - enum ConnectionState - { - INIT, - AWAIT_START_OK, - AWAIT_SECURE_OK, - AWAIT_TUNE_OK, - AWAIT_OPEN, - OPEN - } - - private static final Logger _logger = LoggerFactory.getLogger(AMQProtocolEngine.class); - - // to save boxing the channelId and looking up in a map... cache in an array the low numbered - // channels. This value must be of the form 2^x - 1. - private static final int CHANNEL_CACHE_SIZE = 0xff; - private static final String BROKER_DEBUG_BINARY_DATA_LENGTH = "broker.debug.binaryDataLength"; - private static final int DEFAULT_DEBUG_BINARY_DATA_LENGTH = 80; - private static final long AWAIT_CLOSED_TIMEOUT = 60000; - private final AmqpPort<?> _port; - private final long _creationTime; - private final AtomicBoolean _stateChanged = new AtomicBoolean(); - private final AtomicReference<Action<ServerProtocolEngine>> _workListener = new AtomicReference<>(); - - private AMQShortString _contextKey; - - private String _clientVersion = null; - private String _clientProduct = null; - private String _remoteProcessPid = null; - - private volatile VirtualHostImpl<?,?,?> _virtualHost; - - private final Map<Integer, AMQChannel> _channelMap = - new HashMap<>(); - private final CopyOnWriteArrayList<SessionModelListener> _sessionListeners = - new CopyOnWriteArrayList<>(); - - private final AMQChannel[] _cachedChannels = new AMQChannel[CHANNEL_CACHE_SIZE + 1]; - - private ConnectionState _state = ConnectionState.INIT; - - /** - * The channels that the latest call to {@link #received(ByteBuffer)} applied to. - * Used so we know which channels we need to call {@link AMQChannel#receivedComplete()} - * on after handling the frames. - */ - private final Set<AMQChannel> _channelsForCurrentMessage = new HashSet<>(); - - private AMQDecoder _decoder; - - private SaslServer _saslServer; - - private volatile boolean _closed; - - private long _maxNoOfChannels; - - private ProtocolVersion _protocolVersion = ProtocolVersion.getLatestSupportedVersion(); - private final MethodRegistry _methodRegistry = new MethodRegistry(_protocolVersion); - private final List<Action<? super AMQProtocolEngine>> _connectionCloseTaskList = - new CopyOnWriteArrayList<>(); - - private final Queue<Action<? super AMQProtocolEngine>> _asyncTaskList = - new ConcurrentLinkedQueue<>(); - - private Map<Integer, Long> _closingChannelsList = new ConcurrentHashMap<>(); - private ProtocolOutputConverter _protocolOutputConverter; - private final Subject _authorizedSubject = new Subject(); - - private final long _connectionId; - private Object _reference = new Object(); - - private LogSubject _logSubject; - - private volatile long _lastIoTime; - - private long _writtenBytes; - - private int _maxFrameSize; - private final AtomicBoolean _closing = new AtomicBoolean(false); - - private final StatisticsCounter _messagesDelivered, _dataDelivered, _messagesReceived, _dataReceived; - - private NetworkConnection _network; - private ByteBufferSender _sender; - - private volatile boolean _deferFlush; - private volatile long _lastReceivedTime = System.currentTimeMillis(); - private volatile long _lastWriteTime = System.currentTimeMillis(); - private boolean _blocking; - - private final Broker<?> _broker; - private final Transport _transport; - - private volatile boolean _closeWhenNoRoute; - private volatile boolean _stopped; - private long _readBytes; - private boolean _authenticated; - private boolean _compressionSupported; - private int _messageCompressionThreshold; - private int _currentClassId; - private int _currentMethodId; - private int _binaryDataLimit; - private long _maxMessageSize; - private volatile boolean _transportBlockedForWriting; - - private final AtomicReference<Thread> _messageAssignmentSuspended = new AtomicReference<>(); - - - @Override - public boolean isMessageAssignmentSuspended() - { - Thread lock = _messageAssignmentSuspended.get(); - return lock != null && _messageAssignmentSuspended.get() != Thread.currentThread(); - } - - @Override - public void setMessageAssignmentSuspended(final boolean messageAssignmentSuspended) - { - _messageAssignmentSuspended.set(messageAssignmentSuspended ? Thread.currentThread() : null); - for(AMQSessionModel<?,?> session : getSessionModels()) - { - for (Consumer<?> consumer : session.getConsumers()) - { - ConsumerImpl consumerImpl = (ConsumerImpl) consumer; - if (!messageAssignmentSuspended) - { - consumerImpl.getTarget().notifyCurrentState(); - } - else - { - // ensure that by the time the method returns, no consumer can be in the process of - // delivering a message. - consumerImpl.getSendLock(); - consumerImpl.releaseSendLock(); - } - } - } - } - - - public AMQProtocolEngine(Broker<?> broker, - final NetworkConnection network, - final long connectionId, - AmqpPort<?> port, - Transport transport) - { - _broker = broker; - _port = port; - _transport = transport; - _maxNoOfChannels = broker.getConnection_sessionCountLimit(); - _decoder = new BrokerDecoder(this); - _connectionId = connectionId; - _logSubject = new ConnectionLogSubject(this); - _binaryDataLimit = _broker.getContextKeys(false).contains(BROKER_DEBUG_BINARY_DATA_LENGTH) - ? _broker.getContextValue(Integer.class, BROKER_DEBUG_BINARY_DATA_LENGTH) - : DEFAULT_DEBUG_BINARY_DATA_LENGTH; - - int maxMessageSize = port.getContextValue(Integer.class, AmqpPort.PORT_MAX_MESSAGE_SIZE); - _maxMessageSize = (maxMessageSize > 0) ? (long) maxMessageSize : Long.MAX_VALUE; - - _authorizedSubject.getPrincipals().add(new ConnectionPrincipal(this)); - runAsSubject(new PrivilegedAction<Void>() - { - - @Override - public Void run() - { - setNetworkConnection(network); - - getEventLogger().message(ConnectionMessages.OPEN(null, null, null, null, false, false, false, false)); - - _closeWhenNoRoute = _broker.getConnection_closeWhenNoRoute(); - - return null; - } - }); - - _messagesDelivered = new StatisticsCounter("messages-delivered-" + _connectionId); - _dataDelivered = new StatisticsCounter("data-delivered-" + _connectionId); - _messagesReceived = new StatisticsCounter("messages-received-" + _connectionId); - _dataReceived = new StatisticsCounter("data-received-" + _connectionId); - _creationTime = System.currentTimeMillis(); - } - - private <T> T runAsSubject(PrivilegedAction<T> action) - { - return Subject.doAs(getAuthorizedSubject(), action); - } - - private boolean runningAsSubject() - { - return getAuthorizedSubject().equals(Subject.getSubject(AccessController.getContext())); - } - - @Override - public Subject getSubject() - { - return _authorizedSubject; - } - - @Override - public boolean isTransportBlockedForWriting() - { - return _transportBlockedForWriting; - } - - @Override - public void setTransportBlockedForWriting(final boolean blocked) - { - _transportBlockedForWriting = blocked; - for(AMQChannel channel : _channelMap.values()) - { - channel.transportStateChanged(); - } - } - - public void setNetworkConnection(NetworkConnection network) - { - setNetworkConnection(network, network.getSender()); - } - - public void setNetworkConnection(NetworkConnection network, ByteBufferSender sender) - { - _network = network; - _sender = sender; - } - - public void setMaxFrameSize(int frameMax) - { - _maxFrameSize = frameMax; - _decoder.setMaxFrameSize(frameMax); - } - - public long getMaxFrameSize() - { - return _maxFrameSize; - } - - public boolean isClosing() - { - return _closing.get(); - } - - - - public ClientDeliveryMethod createDeliveryMethod(int channelId) - { - return new WriteDeliverMethod(channelId); - } - - public void received(final ByteBuffer msg) - { - Subject.doAs(_authorizedSubject, new PrivilegedAction<Void>() - { - @Override - public Void run() - { - - final long arrivalTime = System.currentTimeMillis(); - if (!_authenticated && - (arrivalTime - _creationTime) > _port.getContextValue(Long.class, - Port.CONNECTION_MAXIMUM_AUTHENTICATION_DELAY)) - { - _logger.warn("Connection has taken more than " - + _port.getContextValue(Long.class, Port.CONNECTION_MAXIMUM_AUTHENTICATION_DELAY) - + "ms to establish identity. Closing as possible DoS."); - getEventLogger().message(ConnectionMessages.IDLE_CLOSE()); - closeNetworkConnection(); - } - _lastReceivedTime = arrivalTime; - _lastIoTime = arrivalTime; - _readBytes += msg.remaining(); - - try - { - _decoder.decodeBuffer(msg); - receivedComplete(); - } - catch (ConnectionScopedRuntimeException e) - { - _logger.error("Unexpected exception", e); - closeNetworkConnection(); - } - catch (AMQProtocolVersionException e) - { - _logger.error("Unexpected protocol version", e); - closeNetworkConnection(); - } - catch (SenderClosedException e) - { - _logger.debug("Sender was closed abruptly, closing network.", e); - closeNetworkConnection(); - } - catch (SenderException e) - { - _logger.info("Unexpected exception on send, closing network.", e); - closeNetworkConnection(); - } - catch (TransportException e) - { - _logger.error("Unexpected transport exception", e); - closeNetworkConnection(); - } - catch (AMQFrameDecodingException e) - { - _logger.error("Frame decoding", e); - closeNetworkConnection(); - } - catch (IOException e) - { - _logger.error("I/O Exception", e); - closeNetworkConnection(); - } - catch (StoreException e) - { - if (_virtualHost.getState() == State.ACTIVE) - { - throw e; - } - else - { - _logger.error("Store Exception ignored as virtual host no longer active", e); - } - } - return null; - } - }); - - } - - private void receivedComplete() - { - RuntimeException exception = null; - - for (AMQChannel channel : _channelsForCurrentMessage) - { - try - { - channel.receivedComplete(); - } - catch(RuntimeException exceptionForThisChannel) - { - if(exception == null) - { - exception = exceptionForThisChannel; - } - _logger.error("Error informing channel that receiving is complete. Channel: " + channel, - exceptionForThisChannel); - } - } - - _channelsForCurrentMessage.clear(); - - if(exception != null) - { - throw exception; - } - } - - - void channelRequiresSync(final AMQChannel amqChannel) - { - _channelsForCurrentMessage.add(amqChannel); - } - - private synchronized void protocolInitiationReceived(ProtocolInitiation pi) - { - // this ensures the codec never checks for a PI message again - _decoder.setExpectProtocolInitiation(false); - try - { - // Log incoming protocol negotiation request - getEventLogger().message(ConnectionMessages.OPEN(null, - pi.getProtocolMajor() + "-" + pi.getProtocolMinor(), - null, - null, - false, - true, - false, - false)); - - ProtocolVersion pv = pi.checkVersion(); // Fails if not correct - - setProtocolVersion(pv); - - StringBuilder mechanismBuilder = new StringBuilder(); - SubjectCreator subjectCreator = _port.getAuthenticationProvider().getSubjectCreator(_transport.isSecure()); - for(String mechanismName : subjectCreator.getMechanisms()) - { - if(mechanismBuilder.length() != 0) - { - mechanismBuilder.append(' '); - } - mechanismBuilder.append(mechanismName); - } - String mechanisms = mechanismBuilder.toString(); - - String locales = "en_US"; - - - FieldTable serverProperties = FieldTableFactory.newFieldTable(); - - serverProperties.setString(ServerPropertyNames.PRODUCT, - QpidProperties.getProductName()); - serverProperties.setString(ServerPropertyNames.VERSION, - QpidProperties.getReleaseVersion()); - serverProperties.setString(ServerPropertyNames.QPID_BUILD, - QpidProperties.getBuildVersion()); - serverProperties.setString(ServerPropertyNames.QPID_INSTANCE_NAME, - _broker.getName()); - serverProperties.setString(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE, - String.valueOf(_closeWhenNoRoute)); - serverProperties.setString(ConnectionStartProperties.QPID_MESSAGE_COMPRESSION_SUPPORTED, - String.valueOf(_broker.isMessageCompressionEnabled())); - serverProperties.setString(ConnectionStartProperties.QPID_CONFIRMED_PUBLISH_SUPPORTED, Boolean.TRUE.toString()); - - AMQMethodBody responseBody = getMethodRegistry().createConnectionStartBody((short) getProtocolMajorVersion(), - (short) pv.getActualMinorVersion(), - serverProperties, - mechanisms.getBytes(), - locales.getBytes()); - writeFrame(responseBody.generateFrame(0)); - _state = ConnectionState.AWAIT_START_OK; - - _sender.flush(); - - } - catch (AMQException e) - { - _logger.info("Received unsupported protocol initiation for protocol version: " + getProtocolVersion()); - - writeFrame(new ProtocolInitiation(ProtocolVersion.getLatestSupportedVersion())); - _sender.flush(); - } - } - - - - - public synchronized void writeFrame(AMQDataBlock frame) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("SEND: " + frame); - } - - try - { - _writtenBytes += frame.writePayload(_sender); - } - catch (IOException e) - { - throw new ServerScopedRuntimeException(e); - } - - - final long time = System.currentTimeMillis(); - _lastIoTime = time; - _lastWriteTime = time; - - if(!_deferFlush) - { - _sender.flush(); - } - } - - public AMQShortString getContextKey() - { - return _contextKey; - } - - public void setContextKey(AMQShortString contextKey) - { - _contextKey = contextKey; - } - - public List<AMQChannel> getChannels() - { - synchronized (_channelMap) - { - return new ArrayList<>(_channelMap.values()); - } - } - - public AMQChannel getChannel(int channelId) - { - final AMQChannel channel = - ((channelId & CHANNEL_CACHE_SIZE) == channelId) ? _cachedChannels[channelId] : _channelMap.get(channelId); - if ((channel == null) || channel.isClosing()) - { - return null; - } - else - { - return channel; - } - } - - public boolean channelAwaitingClosure(int channelId) - { - return !_closingChannelsList.isEmpty() && _closingChannelsList.containsKey(channelId); - } - - public void addChannel(AMQChannel channel) - { - final int channelId = channel.getChannelId(); - - synchronized (_channelMap) - { - _channelMap.put(channel.getChannelId(), channel); - sessionAdded(channel); - if(_blocking) - { - channel.block(); - } - } - - if (((channelId & CHANNEL_CACHE_SIZE) == channelId)) - { - _cachedChannels[channelId] = channel; - } - } - - private void sessionAdded(final AMQSessionModel<?,?> session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionAdded(session); - } - } - - private void sessionRemoved(final AMQSessionModel<?,?> session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionRemoved(session); - } - } - - public long getMaximumNumberOfChannels() - { - return _maxNoOfChannels; - } - - public void setMaximumNumberOfChannels(Long value) - { - _maxNoOfChannels = value; - } - - - void closeChannel(AMQChannel channel) - { - closeChannel(channel, null, null, false); - } - - public void closeChannelAndWriteFrame(AMQChannel channel, AMQConstant cause, String message) - { - writeFrame(new AMQFrame(channel.getChannelId(), - getMethodRegistry().createChannelCloseBody(cause.getCode(), - AMQShortString.validValueOf(message), - _currentClassId, - _currentMethodId))); - closeChannel(channel, cause, message, true); - } - - public void closeChannel(int channelId, AMQConstant cause, String message) - { - final AMQChannel channel = getChannel(channelId); - if (channel == null) - { - throw new IllegalArgumentException("Unknown channel id"); - } - closeChannel(channel, cause, message, true); - } - - void closeChannel(AMQChannel channel, AMQConstant cause, String message, boolean mark) - { - int channelId = channel.getChannelId(); - try - { - channel.close(cause, message); - if(mark) - { - markChannelAwaitingCloseOk(channelId); - } - } - finally - { - removeChannel(channelId); - } - } - - - public void closeChannelOk(int channelId) - { - _closingChannelsList.remove(channelId); - } - - private void markChannelAwaitingCloseOk(int channelId) - { - _closingChannelsList.put(channelId, System.currentTimeMillis()); - } - - /** - * In our current implementation this is used by the clustering code. - * - * @param channelId The channel to remove - */ - public void removeChannel(int channelId) - { - AMQChannel session; - synchronized (_channelMap) - { - session = _channelMap.remove(channelId); - if ((channelId & CHANNEL_CACHE_SIZE) == channelId) - { - _cachedChannels[channelId] = null; - } - } - sessionRemoved(session); - } - - private void initHeartbeats(int delay) - { - if (delay > 0) - { - _network.setMaxWriteIdle(delay); - _network.setMaxReadIdle(BrokerProperties.HEARTBEAT_TIMEOUT_FACTOR * delay); - } - else - { - _network.setMaxWriteIdle(0); - _network.setMaxReadIdle(0); - } - } - - private void closeAllChannels() - { - try - { - RuntimeException firstException = null; - for (AMQChannel channel : getChannels()) - { - try - { - channel.close(); - } - catch (RuntimeException re) - { - if (!(re instanceof ConnectionScopedRuntimeException)) - { - _logger.error("Unexpected exception closing channel", re); - } - firstException = re; - } - } - - if (firstException != null) - { - throw firstException; - } - } - finally - { - synchronized (_channelMap) - { - _channelMap.clear(); - } - for (int i = 0; i <= CHANNEL_CACHE_SIZE; i++) - { - _cachedChannels[i] = null; - } - - } - } - - private void closeConnectionInternal(final boolean connectionDropped) - { - - if(runningAsSubject()) - { - if(_closing.compareAndSet(false,true)) - { - // force sync of outstanding async work - try - { - receivedComplete(); - } - finally - { - - finishClose(connectionDropped); - } - - } - else - { - awaitClosed(); - } - } - else - { - runAsSubject(new PrivilegedAction<Object>() - { - @Override - public Object run() - { - closeConnectionInternal(connectionDropped); - return null; - } - }); - - } - } - - private void finishClose(boolean connectionDropped) - { - if (!_closed) - { - - try - { - if (_virtualHost != null) - { - _virtualHost.getConnectionRegistry().deregisterConnection(this); - } - closeAllChannels(); - } - finally - { - try - { - for (Action<? super AMQProtocolEngine> task : _connectionCloseTaskList) - { - task.performAction(this); - } - } - finally - { - synchronized (this) - { - _closed = true; - notifyAll(); - } - getEventLogger().message(_logSubject, connectionDropped ? ConnectionMessages.DROPPED_CONNECTION() : ConnectionMessages.CLOSE()); - } - } - } - } - - private void awaitClosed() - { - synchronized(this) - { - final long endTime = System.currentTimeMillis() + AWAIT_CLOSED_TIMEOUT; - - while(!_closed && endTime > System.currentTimeMillis()) - { - try - { - wait(1000); - } - catch (InterruptedException e) - { - Thread.currentThread().interrupt(); - break; - } - } - - if (!_closed) - { - throw new ConnectionScopedRuntimeException("Connection " + this + " failed to become closed within " + AWAIT_CLOSED_TIMEOUT + "ms."); - } - } - } - - private void closeConnection(int channelId, AMQConnectionException e) - { - - if (_logger.isInfoEnabled()) - { - _logger.info("Closing connection due to: " + e); - } - closeConnection(channelId, e.getCloseFrame()); - } - - - void closeConnection(AMQConstant errorCode, - String message, int channelId) - { - - if (_logger.isInfoEnabled()) - { - _logger.info("Closing connection due to: " + message); - } - closeConnection(channelId, new AMQFrame(0, new ConnectionCloseBody(getProtocolVersion(), errorCode.getCode(), AMQShortString.validValueOf(message), _currentClassId, _currentMethodId))); - } - - private void closeConnection(int channelId, AMQFrame frame) - { - if(!_closing.get()) - { - try - { - markChannelAwaitingCloseOk(channelId); - closeConnectionInternal(false); - } - finally - { - try - { - writeFrame(frame); - } - finally - { - closeNetworkConnection(); - } - } - } - else - { - awaitClosed(); - } - } - - public void closeNetworkConnection() - { - _network.close(); - } - - public String toString() - { - return getRemoteAddress() + "(" + (getAuthorizedPrincipal() == null ? "?" : getAuthorizedPrincipal().getName() + ")"); - } - - private String getLocalFQDN() - { - SocketAddress address = _network.getLocalAddress(); - if (address instanceof InetSocketAddress) - { - return ((InetSocketAddress) address).getHostName(); - } - else - { - throw new IllegalArgumentException("Unsupported socket address class: " + address); - } - } - - public SaslServer getSaslServer() - { - return _saslServer; - } - - public void setSaslServer(SaslServer saslServer) - { - _saslServer = saslServer; - } - - public void setClientProperties(FieldTable clientProperties) - { - if (clientProperties != null) - { - String closeWhenNoRoute = clientProperties.getString(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE); - if (closeWhenNoRoute != null) - { - _closeWhenNoRoute = Boolean.parseBoolean(closeWhenNoRoute); - if(_logger.isDebugEnabled()) - { - _logger.debug("Client set closeWhenNoRoute=" + _closeWhenNoRoute + " for protocol engine " + this); - } - } - String compressionSupported = clientProperties.getString(ConnectionStartProperties.QPID_MESSAGE_COMPRESSION_SUPPORTED); - if (compressionSupported != null) - { - _compressionSupported = Boolean.parseBoolean(compressionSupported); - if(_logger.isDebugEnabled()) - { - _logger.debug("Client set compressionSupported=" + _compressionSupported + " for protocol engine " + this); - } - } - - _clientVersion = clientProperties.getString(ConnectionStartProperties.VERSION_0_8); - _clientProduct = clientProperties.getString(ConnectionStartProperties.PRODUCT); - _remoteProcessPid = clientProperties.getString(ConnectionStartProperties.PID); - - String clientId = clientProperties.getString(ConnectionStartProperties.CLIENT_ID_0_8); - if (clientId != null) - { - setContextKey(new AMQShortString(clientId)); - } - - getEventLogger().message(ConnectionMessages.OPEN(clientId, - _protocolVersion.toString(), - _clientVersion, - _clientProduct, - true, - true, - true, - true)); - } - } - - private void setProtocolVersion(ProtocolVersion pv) - { - _protocolVersion = pv; - _methodRegistry.setProtocolVersion(_protocolVersion); - _protocolOutputConverter = new ProtocolOutputConverterImpl(this); - } - - public byte getProtocolMajorVersion() - { - return _protocolVersion.getMajorVersion(); - } - - public ProtocolVersion getProtocolVersion() - { - return _protocolVersion; - } - - public byte getProtocolMinorVersion() - { - return _protocolVersion.getMinorVersion(); - } - - public MethodRegistry getRegistry() - { - return getMethodRegistry(); - } - - public VirtualHostImpl<?,?,?> getVirtualHost() - { - return _virtualHost; - } - - public void setVirtualHost(VirtualHostImpl<?,?,?> virtualHost) - { - _virtualHost = virtualHost; - - _virtualHost.getConnectionRegistry().registerConnection(this); - - - _messageCompressionThreshold = virtualHost.getContextValue(Integer.class, - Broker.MESSAGE_COMPRESSION_THRESHOLD_SIZE); - if(_messageCompressionThreshold <= 0) - { - _messageCompressionThreshold = Integer.MAX_VALUE; - } - } - - public void addDeleteTask(Action<? super AMQProtocolEngine> task) - { - _connectionCloseTaskList.add(task); - } - - public void removeDeleteTask(Action<? super AMQProtocolEngine> task) - { - _connectionCloseTaskList.remove(task); - } - - public ProtocolOutputConverter getProtocolOutputConverter() - { - return _protocolOutputConverter; - } - - public void setAuthorizedSubject(final Subject authorizedSubject) - { - if (authorizedSubject == null) - { - throw new IllegalArgumentException("authorizedSubject cannot be null"); - } - - _authenticated = true; - _authorizedSubject.getPrincipals().addAll(authorizedSubject.getPrincipals()); - _authorizedSubject.getPrivateCredentials().addAll(authorizedSubject.getPrivateCredentials()); - _authorizedSubject.getPublicCredentials().addAll(authorizedSubject.getPublicCredentials()); - - } - - public Subject getAuthorizedSubject() - { - return _authorizedSubject; - } - - public Principal getAuthorizedPrincipal() - { - - return _authorizedSubject.getPrincipals(AuthenticatedPrincipal.class).size() == 0 ? null : AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(_authorizedSubject); - } - - public SocketAddress getRemoteAddress() - { - return _network.getRemoteAddress(); - } - - @Override - public String getRemoteProcessPid() - { - return _remoteProcessPid; - } - - public SocketAddress getLocalAddress() - { - return _network.getLocalAddress(); - } - - public Principal getPeerPrincipal() - { - return _network.getPeerPrincipal(); - } - - public MethodRegistry getMethodRegistry() - { - return _methodRegistry; - } - - public void closed() - { - try - { - try - { - closeConnectionInternal(true); - } - finally - { - closeNetworkConnection(); - } - } - catch (ConnectionScopedRuntimeException | TransportException e) - { - _logger.error("Could not close protocol engine", e); - } - } - - @Override - public void encryptedTransport() - { - } - - public void readerIdle() - { - Subject.doAs(_authorizedSubject, new PrivilegedAction<Object>() - { - @Override - public Object run() - { - getEventLogger().message(ConnectionMessages.IDLE_CLOSE()); - _network.close(); - return null; - } - }); - } - - public synchronized void writerIdle() - { - writeFrame(HeartbeatBody.FRAME); - } - - public void exception(Throwable throwable) - { - // noop - exception method is not used by new i/o layer - } - - public long getReadBytes() - { - return _readBytes; - } - - public long getWrittenBytes() - { - return _writtenBytes; - } - - public long getLastIoTime() - { - return _lastIoTime; - } - - @Override - public AmqpPort<?> getPort() - { - return _port; - } - - @Override - public Transport getTransport() - { - return _transport; - } - - @Override - public void stop() - { - _stopped = true; - } - - @Override - public boolean isStopped() - { - return _stopped; - } - - @Override - public String getVirtualHostName() - { - return _virtualHost == null ? null : _virtualHost.getName(); - } - - public long getLastReceivedTime() - { - return _lastReceivedTime; - } - - public String getClientVersion() - { - return _clientVersion; - } - - @Override - public String getClientProduct() - { - return _clientProduct; - } - - public long getSessionCountLimit() - { - return getMaximumNumberOfChannels(); - } - - public boolean isDurable() - { - return false; - } - - public long getConnectionId() - { - return _connectionId; - } - - public String getAddress() - { - return String.valueOf(getRemoteAddress()); - } - - public void closeSessionAsync(final AMQChannel session, final AMQConstant cause, final String message) - { - addAsyncTask(new Action<AMQProtocolEngine>() - { - - @Override - public void performAction(final AMQProtocolEngine object) - { - int channelId = session.getChannelId(); - closeChannel(channelId, cause, message); - - MethodRegistry methodRegistry = getMethodRegistry(); - ChannelCloseBody responseBody = - methodRegistry.createChannelCloseBody( - cause.getCode(), - AMQShortString.validValueOf(message), - 0, 0); - - writeFrame(responseBody.generateFrame(channelId)); - } - }); - - } - - public void closeAsync(final AMQConstant cause, final String message) - { - Action<AMQProtocolEngine> action = new Action<AMQProtocolEngine>() - { - @Override - public void performAction(final AMQProtocolEngine object) - { - closeConnection(0, new AMQConnectionException(cause, message, 0, 0, - getMethodRegistry(), - null)); - - } - }; - addAsyncTask(action); - } - - private void addAsyncTask(final Action<AMQProtocolEngine> action) - { - _asyncTaskList.add(action); - notifyWork(); - } - - public void block() - { - synchronized (_channelMap) - { - if(!_blocking) - { - _blocking = true; - for(AMQChannel channel : _channelMap.values()) - { - channel.block(); - } - } - } - } - - public void unblock() - { - synchronized (_channelMap) - { - if(_blocking) - { - _blocking = false; - for(AMQChannel channel : _channelMap.values()) - { - channel.unblock(); - } - } - } - } - - public boolean isClosed() - { - return _closed; - } - - public List<AMQChannel> getSessionModels() - { - return new ArrayList<>(getChannels()); - } - - public LogSubject getLogSubject() - { - return _logSubject; - } - - public void registerMessageDelivered(long messageSize) - { - _messagesDelivered.registerEvent(1L); - _dataDelivered.registerEvent(messageSize); - _virtualHost.registerMessageDelivered(messageSize); - } - - public void registerMessageReceived(long messageSize, long timestamp) - { - _messagesReceived.registerEvent(1L, timestamp); - _dataReceived.registerEvent(messageSize, timestamp); - _virtualHost.registerMessageReceived(messageSize, timestamp); - } - - public StatisticsCounter getMessageReceiptStatistics() - { - return _messagesReceived; - } - - public StatisticsCounter getDataReceiptStatistics() - { - return _dataReceived; - } - - public StatisticsCounter getMessageDeliveryStatistics() - { - return _messagesDelivered; - } - - public StatisticsCounter getDataDeliveryStatistics() - { - return _dataDelivered; - } - - public void resetStatistics() - { - _messagesDelivered.reset(); - _dataDelivered.reset(); - _messagesReceived.reset(); - _dataReceived.reset(); - } - - public String getRemoteAddressString() - { - return String.valueOf(getRemoteAddress()); - } - - public String getClientId() - { - return String.valueOf(getContextKey()); - } - - @Override - public String getRemoteContainerName() - { - return String.valueOf(getContextKey()); - } - - @Override - public void addSessionListener(final SessionModelListener listener) - { - _sessionListeners.add(listener); - } - - @Override - public void removeSessionListener(final SessionModelListener listener) - { - _sessionListeners.remove(listener); - } - - public void setDeferFlush(boolean deferFlush) - { - _deferFlush = deferFlush; - } - - @Override - public void receiveChannelOpen(final int channelId) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + channelId + "] ChannelOpen"); - } - assertState(ConnectionState.OPEN); - - // Protect the broker against out of order frame request. - if (_virtualHost == null) - { - closeConnection(AMQConstant.COMMAND_INVALID, - "Virtualhost has not yet been set. ConnectionOpen has not been called.", channelId); - } - else if(getChannel(channelId) != null || channelAwaitingClosure(channelId)) - { - closeConnection(AMQConstant.CHANNEL_ERROR, "Channel " + channelId + " already exists", channelId); - } - else if(channelId > getMaximumNumberOfChannels()) - { - closeConnection(AMQConstant.CHANNEL_ERROR, - "Channel " + channelId + " cannot be created as the max allowed channel id is " - + getMaximumNumberOfChannels(), - channelId); - } - else - { - _logger.info("Connecting to: " + _virtualHost.getName()); - - final AMQChannel channel = new AMQChannel(this, channelId, _virtualHost.getMessageStore()); - - addChannel(channel); - - ChannelOpenOkBody response; - - - response = getMethodRegistry().createChannelOpenOkBody(); - - - writeFrame(response.generateFrame(channelId)); - } - } - - void assertState(final ConnectionState requiredState) - { - if(_state != requiredState) - { - closeConnection(AMQConstant.COMMAND_INVALID, "Command Invalid", 0); - - } - } - - @Override - public void receiveConnectionOpen(AMQShortString virtualHostName, - AMQShortString capabilities, - boolean insist) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionOpen[" +" virtualHost: " + virtualHostName + " capabilities: " + capabilities + " insist: " + insist + " ]"); - } - - String virtualHostStr; - if ((virtualHostName != null) && virtualHostName.charAt(0) == '/') - { - virtualHostStr = virtualHostName.toString().substring(1); - } - else - { - virtualHostStr = virtualHostName == null ? null : virtualHostName.toString(); - } - - VirtualHostImpl<?,?,?> virtualHost = ((AmqpPort)getPort()).getVirtualHost(virtualHostStr); - - if (virtualHost == null) - { - closeConnection(AMQConstant.NOT_FOUND, - "Unknown virtual host: '" + virtualHostName + "'",0); - - } - else - { - // Check virtualhost access - if (virtualHost.getState() != State.ACTIVE) - { - String redirectHost = virtualHost.getRedirectHost(getPort()); - if(redirectHost != null) - { - closeConnection(0, new AMQFrame(0,new ConnectionRedirectBody(getProtocolVersion(),AMQShortString.valueOf(redirectHost), null))); - } - else - { - closeConnection(AMQConstant.CONNECTION_FORCED, - "Virtual host '" + virtualHost.getName() + "' is not active", 0); - } - - } - else - { - setVirtualHost(virtualHost); - try - { - - if(virtualHost.authoriseCreateConnection(this)) - { - if (getContextKey() == null) - { - setContextKey(new AMQShortString(Long.toString(System.currentTimeMillis()))); - } - - MethodRegistry methodRegistry = getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createConnectionOpenOkBody(virtualHostName); - - writeFrame(responseBody.generateFrame(0)); - _state = ConnectionState.OPEN; - - } - else - { - closeConnection(AMQConstant.ACCESS_REFUSED, "Connection refused",0); - } - } - catch (AccessControlException e) - { - closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), 0); - } - } - } - } - - @Override - public void receiveConnectionClose(final int replyCode, - final AMQShortString replyText, - final int classId, - final int methodId) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionClose[" +" replyCode: " + replyCode + " replyText: " + replyText + " classId: " + classId + " methodId: " + methodId + " ]"); - } - - if (_logger.isInfoEnabled()) - { - _logger.info("ConnectionClose received with reply code/reply text " + replyCode + "/" + - replyText + " for " + this); - } - try - { - closeConnectionInternal(false); - - MethodRegistry methodRegistry = getMethodRegistry(); - ConnectionCloseOkBody responseBody = methodRegistry.createConnectionCloseOkBody(); - writeFrame(responseBody.generateFrame(0)); - } - catch (Exception e) - { - _logger.error("Error closing connection for " + getRemoteAddressString(), e); - } - finally - { - closeNetworkConnection(); - } - } - - @Override - public void receiveConnectionCloseOk() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionCloseOk"); - } - - _logger.info("Received Connection-close-ok"); - - try - { - closeConnectionInternal(false); - } - catch (Exception e) - { - _logger.error("Error closing connection: " + getRemoteAddressString(), e); - } - finally - { - closeNetworkConnection(); - } - - } - - @Override - public void receiveConnectionSecureOk(final byte[] response) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionSecureOk[ response: ******** ] "); - } - - assertState(ConnectionState.AWAIT_SECURE_OK); - - Broker<?> broker = getBroker(); - - SubjectCreator subjectCreator = getSubjectCreator(); - - SaslServer ss = getSaslServer(); - if (ss == null) - { - closeConnection(AMQConstant.INTERNAL_ERROR, "No SASL context set up in connection",0 ); - } - MethodRegistry methodRegistry = getMethodRegistry(); - SubjectAuthenticationResult authResult = subjectCreator.authenticate(ss, response); - switch (authResult.getStatus()) - { - case ERROR: - Exception cause = authResult.getCause(); - - _logger.info("Authentication failed:" + (cause == null ? "" : cause.getMessage())); - - closeConnection(AMQConstant.NOT_ALLOWED, "Authentication failed",0); - - disposeSaslServer(); - break; - case SUCCESS: - if (_logger.isInfoEnabled()) - { - _logger.info("Connected as: " + authResult.getSubject()); - } - - int frameMax = broker.getContextValue(Integer.class, Broker.BROKER_FRAME_SIZE); - - if (frameMax <= 0) - { - frameMax = Integer.MAX_VALUE; - } - - ConnectionTuneBody tuneBody = - methodRegistry.createConnectionTuneBody(broker.getConnection_sessionCountLimit(), - frameMax, - broker.getConnection_heartBeatDelay()); - writeFrame(tuneBody.generateFrame(0)); - _state = ConnectionState.AWAIT_TUNE_OK; - setAuthorizedSubject(authResult.getSubject()); - disposeSaslServer(); - break; - case CONTINUE: - - ConnectionSecureBody - secureBody = methodRegistry.createConnectionSecureBody(authResult.getChallenge()); - writeFrame(secureBody.generateFrame(0)); - } - } - - - private void disposeSaslServer() - { - SaslServer ss = getSaslServer(); - if (ss != null) - { - setSaslServer(null); - try - { - ss.dispose(); - } - catch (SaslException e) - { - _logger.error("Error disposing of Sasl server: " + e); - } - } - } - - @Override - public void receiveConnectionStartOk(final FieldTable clientProperties, - final AMQShortString mechanism, - final byte[] response, - final AMQShortString locale) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionStartOk[" - + " clientProperties: " - + clientProperties - + " mechanism: " - + mechanism - + " response: ********" - + " locale: " - + locale - + " ]"); - } - - assertState(ConnectionState.AWAIT_START_OK); - - Broker<?> broker = getBroker(); - - _logger.info("SASL Mechanism selected: " + mechanism); - _logger.info("Locale selected: " + locale); - - SubjectCreator subjectCreator = getSubjectCreator(); - SaslServer ss; - try - { - ss = subjectCreator.createSaslServer(String.valueOf(mechanism), - getLocalFQDN(), - getPeerPrincipal()); - - if (ss == null) - { - closeConnection(AMQConstant.RESOURCE_ERROR, "Unable to create SASL Server:" + mechanism, 0); - - } - else - { - //save clientProperties - setClientProperties(clientProperties); - - setSaslServer(ss); - - final SubjectAuthenticationResult authResult = subjectCreator.authenticate(ss, response); - - MethodRegistry methodRegistry = getMethodRegistry(); - - switch (authResult.getStatus()) - { - case ERROR: - Exception cause = authResult.getCause(); - - _logger.info("Authentication failed:" + (cause == null ? "" : cause.getMessage())); - - closeConnection(AMQConstant.NOT_ALLOWED, "Authentication failed", 0); - - disposeSaslServer(); - break; - - case SUCCESS: - if (_logger.isInfoEnabled()) - { - _logger.info("Connected as: " + authResult.getSubject()); - } - setAuthorizedSubject(authResult.getSubject()); - - int frameMax = broker.getContextValue(Integer.class, Broker.BROKER_FRAME_SIZE); - - if (frameMax <= 0) - { - frameMax = Integer.MAX_VALUE; - } - - ConnectionTuneBody - tuneBody = - methodRegistry.createConnectionTuneBody(broker.getConnection_sessionCountLimit(), - frameMax, - broker.getConnection_heartBeatDelay()); - writeFrame(tuneBody.generateFrame(0)); - _state = ConnectionState.AWAIT_TUNE_OK; - break; - case CONTINUE: - ConnectionSecureBody - secureBody = methodRegistry.createConnectionSecureBody(authResult.getChallenge()); - writeFrame(secureBody.generateFrame(0)); - - _state = ConnectionState.AWAIT_SECURE_OK; - } - } - } - catch (SaslException e) - { - disposeSaslServer(); - closeConnection(AMQConstant.INTERNAL_ERROR, "SASL error: " + e, 0); - } - } - - @Override - public void receiveConnectionTuneOk(final int channelMax, final long frameMax, final int heartbeat) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionTuneOk[" +" channelMax: " + channelMax + " frameMax: " + frameMax + " heartbeat: " + heartbeat + " ]"); - } - - assertState(ConnectionState.AWAIT_TUNE_OK); - - initHeartbeats(heartbeat); - - int brokerFrameMax = getBroker().getContextValue(Integer.class, Broker.BROKER_FRAME_SIZE); - if (brokerFrameMax <= 0) - { - brokerFrameMax = Integer.MAX_VALUE; - } - - if (frameMax > (long) brokerFrameMax) - { - closeConnection(AMQConstant.SYNTAX_ERROR, - "Attempt to set max frame size to " + frameMax - + " greater than the broker will allow: " - + brokerFrameMax, 0); - } - else if (frameMax > 0 && frameMax < AMQConstant.FRAME_MIN_SIZE.getCode()) - { - closeConnection(AMQConstant.SYNTAX_ERROR, - "Attempt to set max frame size to " + frameMax - + " which is smaller than the specification defined minimum: " - + AMQConstant.FRAME_MIN_SIZE.getCode(), 0); - } - else - { - int calculatedFrameMax = frameMax == 0 ? brokerFrameMax : (int) frameMax; - setMaxFrameSize(calculatedFrameMax); - - //0 means no implied limit, except that forced by protocol limitations (0xFFFF) - setMaximumNumberOfChannels( ((channelMax == 0l) || (channelMax > 0xFFFFL)) - ? 0xFFFFL - : channelMax); - - } - _state = ConnectionState.AWAIT_OPEN; - - } - - public int getBinaryDataLimit() - { - return _binaryDataLimit; - } - - public long getMaxMessageSize() - { - return _maxMessageSize; - } - - public final class WriteDeliverMethod - implements ClientDeliveryMethod - { - private final int _channelId; - - public WriteDeliverMethod(int channelId) - { - _channelId = channelId; - } - - @Override - public long deliverToClient(final ConsumerImpl sub, final ServerMessage message, - final InstanceProperties props, final long deliveryTag) - { - long size = _protocolOutputConverter.writeDeliver(message, - props, - _channelId, - deliveryTag, - new AMQShortString(sub.getName())); - registerMessageDelivered(size); - return size; - } - - } - - public Object getReference() - { - return _reference; - } - - @Override - public long getLastReadTime() - { - return _lastReceivedTime; - } - - @Override - public long getLastWriteTime() - { - return _lastWriteTime; - } - - public boolean isCloseWhenNoRoute() - { - return _closeWhenNoRoute; - } - - public boolean isCompressionSupported() - { - return _compressionSupported && _broker.isMessageCompressionEnabled(); - } - - public int getMessageCompressionThreshold() - { - return _messageCompressionThreshold; - } - - public Broker<?> getBroker() - { - return _broker; - } - - public SubjectCreator getSubjectCreator() - { - return _port.getAuthenticationProvider().getSubjectCreator(getTransport().isSecure()); - } - - public EventLogger getEventLogger() - { - if(_virtualHost != null) - { - return _virtualHost.getEventLogger(); - } - else - { - return _broker.getEventLogger(); - } - } - - @Override - public ServerChannelMethodProcessor getChannelMethodProcessor(final int channelId) - { - assertState(ConnectionState.OPEN); - - ServerChannelMethodProcessor channelMethodProcessor = getChannel(channelId); - if(channelMethodProcessor == null) - { - channelMethodProcessor = (ServerChannelMethodProcessor) Proxy.newProxyInstance(ServerMethodDispatcher.class.getClassLoader(), - new Class[] { ServerChannelMethodProcessor.class }, new InvocationHandler() - { - @Override - public Object invoke(final Object proxy, final Method method, final Object[] args) - throws Throwable - { - if(method.getName().startsWith("receive")) - { - closeConnection(AMQConstant.CHANNEL_ERROR, - "Unknown channel id: " + channelId, - channelId); - return null; - } - else if(method.getName().equals("ignoreAllButCloseOk")) - { - return false; - } - return null; - } - }); - } - return channelMethodProcessor; - } - - @Override - public void receiveHeartbeat() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV Heartbeat"); - } - - // No op - } - - @Override - public void receiveProtocolHeader(final ProtocolInitiation protocolInitiation) - { - - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ProtocolHeader [" + protocolInitiation + " ]"); - } - - protocolInitiationReceived(protocolInitiation); - } - - @Override - public void setCurrentMethod(final int classId, final int methodId) - { - _currentClassId = classId; - _currentMethodId = methodId; - } - - @Override - public boolean ignoreAllButCloseOk() - { - return _closing.get(); - } - - @Override - public void processPending() - { - for (AMQSessionModel session : getSessionModels()) - { - session.processPending(); - } - - while(_asyncTaskList.peek() != null) - { - Action<? super AMQProtocolEngine> asyncAction = _asyncTaskList.poll(); - asyncAction.performAction(this); - } - - } - - @Override - public boolean hasWork() - { - return _stateChanged.get(); - } - - @Override - public void notifyWork() - { - _stateChanged.set(true); - - final Action<ServerProtocolEngine> listener = _workListener.get(); - if(listener != null) - { - - listener.performAction(this); - } - } - - @Override - public void clearWork() - { - _stateChanged.set(false); - } - - @Override - public void setWorkListener(final Action<ServerProtocolEngine> listener) - { - _workListener.set(listener); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/BrokerDecoder.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/BrokerDecoder.java deleted file mode 100644 index 81e0b1b736..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/BrokerDecoder.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.io.IOException; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.codec.MarkableDataInput; -import org.apache.qpid.codec.ServerDecoder; -import org.apache.qpid.framing.AMQFrameDecodingException; -import org.apache.qpid.server.util.ServerScopedRuntimeException; - -public class BrokerDecoder extends ServerDecoder -{ - private static final Logger _logger = LoggerFactory.getLogger(BrokerDecoder.class); - private final AMQProtocolEngine _connection; - /** - * Creates a new AMQP decoder. - * - * @param connection - */ - public BrokerDecoder(final AMQProtocolEngine connection) - { - super(connection); - _connection = connection; - } - - @Override - protected void processFrame(final int channelId, final byte type, final long bodySize, final MarkableDataInput in) - throws AMQFrameDecodingException, IOException - { - long startTime = 0; - if (_logger.isDebugEnabled()) - { - startTime = System.currentTimeMillis(); - } - Subject subject; - AMQChannel channel = _connection.getChannel(channelId); - if(channel == null) - { - subject = _connection.getSubject(); - } - else - { - _connection.channelRequiresSync(channel); - - subject = channel.getSubject(); - } - try - { - Subject.doAs(subject, new PrivilegedExceptionAction<Object>() - { - @Override - public Void run() throws IOException, AMQFrameDecodingException - { - doProcessFrame(channelId, type, bodySize, in); - return null; - } - }); - if(_logger.isDebugEnabled()) - { - _logger.debug("Frame handled in " + (System.currentTimeMillis() - startTime) + " ms."); - } - - } - catch (PrivilegedActionException e) - { - Throwable cause = e.getCause(); - if(cause instanceof IOException) - { - throw (IOException) cause; - } - else if(cause instanceof AMQFrameDecodingException) - { - throw (AMQFrameDecodingException) cause; - } - else if(cause instanceof RuntimeException) - { - throw (RuntimeException) cause; - } - else throw new ServerScopedRuntimeException(cause); - } - - } - - - private void doProcessFrame(final int channelId, final byte type, final long bodySize, final MarkableDataInput in) - throws AMQFrameDecodingException, IOException - { - super.processFrame(channelId, type, bodySize, in); - - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ClientDeliveryMethod.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ClientDeliveryMethod.java deleted file mode 100644 index c7871e8b9a..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ClientDeliveryMethod.java +++ /dev/null @@ -1,31 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.protocol.v0_8; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.ServerMessage; - -public interface ClientDeliveryMethod -{ - long deliverToClient(final ConsumerImpl sub, final ServerMessage message, final InstanceProperties props, - final long deliveryTag); -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTagInUseException.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTagInUseException.java deleted file mode 100644 index 25c1462060..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTagInUseException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -public class ConsumerTagInUseException extends Exception -{ - public ConsumerTagInUseException(final String message) - { - super(message); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTarget_0_8.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTarget_0_8.java deleted file mode 100644 index d46ed719b2..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTarget_0_8.java +++ /dev/null @@ -1,565 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.qpid.AMQException; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.consumer.AbstractConsumerTarget; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.flow.FlowCreditManager; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.StateChangeListener; - -/** - * Encapsulation of a subscription to a queue. - * <p> - * Ties together the protocol session of a subscriber, the consumer tag - * that was given out by the broker and the channel id. - */ -public abstract class ConsumerTarget_0_8 extends AbstractConsumerTarget implements FlowCreditManager.FlowCreditManagerListener -{ - - private final StateChangeListener<MessageInstance, MessageInstance.State> _entryReleaseListener = - new StateChangeListener<MessageInstance, MessageInstance.State>() - { - @Override - public void stateChanged(final MessageInstance entry, - final MessageInstance.State oldSate, - final MessageInstance.State newState) - { - if (oldSate == QueueEntry.State.ACQUIRED && newState != QueueEntry.State.ACQUIRED) - { - restoreCredit(entry.getMessage()); - } - entry.removeStateChangeListener(this); - } - }; - - private final ClientDeliveryMethod _deliveryMethod; - private final RecordDeliveryMethod _recordMethod; - - private final AtomicLong _unacknowledgedCount = new AtomicLong(0); - private final AtomicLong _unacknowledgedBytes = new AtomicLong(0); - private final List<ConsumerImpl> _consumers = new CopyOnWriteArrayList<>(); - private final AtomicBoolean _needToClose = new AtomicBoolean(); - - - public static ConsumerTarget_0_8 createBrowserTarget(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager) - { - return new BrowserConsumer(channel, consumerTag, filters, creditManager, channel.getClientDeliveryMethod(), channel.getRecordDeliveryMethod()); - } - - public static ConsumerTarget_0_8 createGetNoAckTarget(final AMQChannel channel, - final AMQShortString consumerTag, - final FieldTable filters, - final FlowCreditManager creditManager, - final ClientDeliveryMethod deliveryMethod, - final RecordDeliveryMethod recordMethod) - { - return new GetNoAckConsumer(channel, consumerTag, filters, creditManager, deliveryMethod, recordMethod); - } - - public List<ConsumerImpl> getConsumers() - { - return _consumers; - } - - - static final class BrowserConsumer extends ConsumerTarget_0_8 - { - public BrowserConsumer(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - super(channel, consumerTag, - filters, creditManager, deliveryMethod, recordMethod); - } - - /** - * This method can be called by each of the publisher threads. As a result all changes to the channel object must be - * thread safe. - * - * - * - * @param consumer - * @param entry - * @param batch - * @throws org.apache.qpid.AMQException - */ - @Override - public void doSend(final ConsumerImpl consumer, MessageInstance entry, boolean batch) - { - // We don't decrement the reference here as we don't want to consume the message - // but we do want to send it to the client. - - synchronized (getChannel()) - { - long deliveryTag = getChannel().getNextDeliveryTag(); - sendToClient(consumer, entry.getMessage(), entry.getInstanceProperties(), deliveryTag); - } - - } - - } - - public static ConsumerTarget_0_8 createNoAckTarget(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager) - { - return new NoAckConsumer(channel, consumerTag, filters, creditManager, channel.getClientDeliveryMethod(), channel.getRecordDeliveryMethod()); - } - - public static ConsumerTarget_0_8 createNoAckTarget(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) throws AMQException - { - return new NoAckConsumer(channel, consumerTag, filters, creditManager, deliveryMethod, recordMethod); - } - - public static class NoAckConsumer extends ConsumerTarget_0_8 - { - private final AutoCommitTransaction _txn; - - public NoAckConsumer(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - super(channel, consumerTag, filters, creditManager, deliveryMethod, recordMethod); - - _txn = new AutoCommitTransaction(channel.getVirtualHost().getMessageStore()); - } - - /** - * This method can be called by each of the publisher threads. As a result all changes to the channel object must be - * thread safe. - * - * @param consumer - * @param entry The message to send - * @param batch - */ - @Override - public void doSend(final ConsumerImpl consumer, MessageInstance entry, boolean batch) - { - // if we do not need to wait for client acknowledgements - // we can decrement the reference count immediately. - - // By doing this _before_ the send we ensure that it - // doesn't get sent if it can't be dequeued, preventing - // duplicate delivery on recovery. - - // The send may of course still fail, in which case, as - // the message is unacked, it will be lost. - _txn.dequeue(entry.getEnqueueRecord(), NOOP); - - ServerMessage message = entry.getMessage(); - MessageReference ref = message.newReference(); - InstanceProperties props = entry.getInstanceProperties(); - entry.delete(); - long size; - synchronized (getChannel()) - { - getChannel().getConnection().setDeferFlush(batch); - long deliveryTag = getChannel().getNextDeliveryTag(); - - size = sendToClient(consumer, message, props, deliveryTag); - - } - ref.release(); - - } - - private static final ServerTransaction.Action NOOP = - new ServerTransaction.Action() - { - @Override - public void postCommit() - { - } - - @Override - public void onRollback() - { - } - }; - } - - /** - * NoAck Subscription for use with BasicGet method. - */ - public static final class GetNoAckConsumer extends NoAckConsumer - { - public GetNoAckConsumer(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - super(channel, consumerTag, filters, creditManager, deliveryMethod, recordMethod); - } - - } - - - public static ConsumerTarget_0_8 createAckTarget(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager) - { - return new AckConsumer(channel,consumerTag,filters,creditManager, channel.getClientDeliveryMethod(), channel.getRecordDeliveryMethod()); - } - - - public static ConsumerTarget_0_8 createAckTarget(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - return new AckConsumer(channel,consumerTag,filters,creditManager, deliveryMethod, recordMethod); - } - - static final class AckConsumer extends ConsumerTarget_0_8 - { - public AckConsumer(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - super(channel, consumerTag, filters, creditManager, deliveryMethod, recordMethod); - } - - /** - * This method can be called by each of the publisher threads. As a result all changes to the channel object must be - * thread safe. - * - * @param consumer - * @param entry The message to send - * @param batch - */ - @Override - public void doSend(final ConsumerImpl consumer, MessageInstance entry, boolean batch) - { - - // put queue entry on a list and then notify the connection to read list. - - synchronized (getChannel()) - { - getChannel().getConnection().setDeferFlush(batch); - long deliveryTag = getChannel().getNextDeliveryTag(); - - addUnacknowledgedMessage(entry); - recordMessageDelivery(consumer, entry, deliveryTag); - entry.addStateChangeListener(getReleasedStateChangeListener()); - long size = sendToClient(consumer, entry.getMessage(), entry.getInstanceProperties(), deliveryTag); - entry.incrementDeliveryCount(); - } - - - } - - - - - - } - - private final AMQChannel _channel; - - private final AMQShortString _consumerTag; - - private final FlowCreditManager _creditManager; - - private final Boolean _autoClose; - - private final AtomicBoolean _deleted = new AtomicBoolean(false); - - - - - public ConsumerTarget_0_8(AMQChannel channel, - AMQShortString consumerTag, - FieldTable arguments, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - super(State.ACTIVE); - - _channel = channel; - _consumerTag = consumerTag; - - _creditManager = creditManager; - creditManager.addStateListener(this); - - _deliveryMethod = deliveryMethod; - _recordMethod = recordMethod; - - if (arguments != null) - { - Object autoClose = arguments.get(AMQPFilterTypes.AUTO_CLOSE.getValue()); - if (autoClose != null) - { - _autoClose = (Boolean) autoClose; - } - else - { - _autoClose = false; - } - } - else - { - _autoClose = false; - } - } - - @Override - public void consumerRemoved(final ConsumerImpl sub) - { - _consumers.remove(sub); - if(_consumers.isEmpty()) - { - close(); - } - } - - @Override - public void consumerAdded(final ConsumerImpl sub) - { - _consumers.add( sub ); - } - - public AMQSessionModel getSessionModel() - { - return _channel; - } - - public String toString() - { - String subscriber = "[channel=" + _channel + - ", consumerTag=" + _consumerTag + - ", session=" + getConnection().getRemoteAddressString(); - - return subscriber + "]"; - } - - @Override - public boolean doIsSuspended() - { - return getState()!=State.ACTIVE || _channel.isSuspended() || _deleted.get() || _channel.getConnectionModel().isStopped(); - } - - /** - * Callback indicating that a queue has been deleted. - * - */ - public void queueDeleted() - { - _deleted.set(true); - } - - public boolean isAutoClose() - { - return _autoClose; - } - - public FlowCreditManager getCreditManager() - { - return _creditManager; - } - - - public boolean close() - { - boolean closed = false; - State state = getState(); - - getSendLock(); - - try - { - while(!closed && state != State.CLOSED) - { - closed = updateState(state, State.CLOSED); - if(!closed) - { - state = getState(); - } - } - _creditManager.removeListener(this); - return closed; - } - finally - { - releaseSendLock(); - } - } - - - public boolean allocateCredit(ServerMessage msg) - { - return _creditManager.useCreditForMessage(msg.getSize()); - } - - public AMQChannel getChannel() - { - return _channel; - } - - public AMQShortString getConsumerTag() - { - return _consumerTag; - } - - private AMQProtocolEngine getConnection() - { - return _channel.getConnection(); - } - - public void restoreCredit(final ServerMessage message) - { - _creditManager.restoreCredit(1, message.getSize()); - } - - protected final StateChangeListener<MessageInstance, MessageInstance.State> getReleasedStateChangeListener() - { - return _entryReleaseListener; - } - - public void creditStateChanged(boolean hasCredit) - { - - if(hasCredit) - { - if(!updateState(State.SUSPENDED, State.ACTIVE)) - { - // this is a hack to get round the issue of increasing bytes credit - notifyCurrentState(); - } - } - else - { - updateState(State.ACTIVE, State.SUSPENDED); - } - } - - protected long sendToClient(final ConsumerImpl consumer, final ServerMessage message, - final InstanceProperties props, - final long deliveryTag) - { - return _deliveryMethod.deliverToClient(consumer, message, props, deliveryTag); - - } - - - protected void recordMessageDelivery(final ConsumerImpl consumer, - final MessageInstance entry, - final long deliveryTag) - { - _recordMethod.recordMessageDelivery(consumer, entry, deliveryTag); - } - - - public void confirmAutoClose() - { - ProtocolOutputConverter converter = getChannel().getConnection().getProtocolOutputConverter(); - converter.confirmConsumerAutoClose(getChannel().getChannelId(), getConsumerTag()); - } - - public void queueEmpty() - { - if (isAutoClose()) - { - _needToClose.set(true); - getChannel().getConnection().notifyWork(); - } - } - - @Override - protected void processClosed() - { - if (_needToClose.get() && getState() != State.CLOSED) - { - close(); - confirmAutoClose(); - } - } - - public void flushBatched() - { - _channel.getConnection().setDeferFlush(false); - } - - protected void addUnacknowledgedMessage(MessageInstance entry) - { - final long size = entry.getMessage().getSize(); - _unacknowledgedBytes.addAndGet(size); - _unacknowledgedCount.incrementAndGet(); - entry.addStateChangeListener(new StateChangeListener<MessageInstance, MessageInstance.State>() - { - public void stateChanged(MessageInstance entry, MessageInstance.State oldState, MessageInstance.State newState) - { - if(oldState.equals(MessageInstance.State.ACQUIRED) && !newState.equals(MessageInstance.State.ACQUIRED)) - { - _unacknowledgedBytes.addAndGet(-size); - _unacknowledgedCount.decrementAndGet(); - entry.removeStateChangeListener(this); - } - } - }); - } - - @Override - public void acquisitionRemoved(final MessageInstance node) - { - } - - public long getUnacknowledgedBytes() - { - return _unacknowledgedBytes.longValue(); - } - - public long getUnacknowledgedMessages() - { - return _unacknowledgedCount.longValue(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeue.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeue.java deleted file mode 100644 index 45ab62ee05..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeue.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; - -public class ExtractResendAndRequeue implements UnacknowledgedMessageMap.Visitor -{ - private static final Logger _log = LoggerFactory.getLogger(ExtractResendAndRequeue.class); - - private final Map<Long, MessageInstance> _msgToRequeue; - private final Map<Long, MessageInstance> _msgToResend; - private final UnacknowledgedMessageMap _unacknowledgedMessageMap; - - public ExtractResendAndRequeue(UnacknowledgedMessageMap unacknowledgedMessageMap, - Map<Long, MessageInstance> msgToRequeue, - Map<Long, MessageInstance> msgToResend) - { - _unacknowledgedMessageMap = unacknowledgedMessageMap; - _msgToRequeue = msgToRequeue; - _msgToResend = msgToResend; - } - - public boolean callback(final long deliveryTag, MessageInstance message) - { - - message.setRedelivered(); - final ConsumerImpl consumer = message.getDeliveredConsumer(); - if (consumer != null) - { - // Consumer exists - if (!consumer.isClosed()) - { - _msgToResend.put(deliveryTag, message); - } - else // consumer has gone - { - _msgToRequeue.put(deliveryTag, message); - } - } - else - { - _log.info("No DeadLetter Queue and requeue not requested so dropping message:" + message); - } - - // false means continue processing - return false; - } - - public void visitComplete() - { - _unacknowledgedMessageMap.clear(); - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/IncomingMessage.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/IncomingMessage.java deleted file mode 100644 index 6e622fb59a..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/IncomingMessage.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentBody; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.MessageDestination; - -public class IncomingMessage -{ - - private final MessagePublishInfo _messagePublishInfo; - private ContentHeaderBody _contentHeaderBody; - private MessageDestination _messageDestination; - - /** - * Keeps a track of how many bytes we have received in body frames - */ - private long _bodyLengthReceived = 0; - private List<ContentBody> _contentChunks = new ArrayList<ContentBody>(); - - public IncomingMessage(MessagePublishInfo info) - { - _messagePublishInfo = info; - } - - public void setContentHeaderBody(final ContentHeaderBody contentHeaderBody) - { - _contentHeaderBody = contentHeaderBody; - } - - public MessagePublishInfo getMessagePublishInfo() - { - return _messagePublishInfo; - } - - public long addContentBodyFrame(final ContentBody contentChunk) - { - _bodyLengthReceived += contentChunk.getSize(); - _contentChunks.add(contentChunk); - return _bodyLengthReceived; - } - - public boolean allContentReceived() - { - return (_bodyLengthReceived == getContentHeader().getBodySize()); - } - - public AMQShortString getExchangeName() - { - return _messagePublishInfo.getExchange(); - } - - public MessageDestination getDestination() - { - return _messageDestination; - } - - public ContentHeaderBody getContentHeader() - { - return _contentHeaderBody; - } - - public long getSize() - { - return getContentHeader().getBodySize(); - } - - public void setMessageDestination(final MessageDestination e) - { - _messageDestination = e; - } - - public int getBodyCount() - { - return _contentChunks.size(); - } - - public ContentBody getContentChunk(int index) - { - return _contentChunks.get(index); - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.java deleted file mode 100644 index ef42a1311f..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.codec.BBEncoder; - -@PluggableService -public class MessageConverter_Internal_to_v0_8 implements MessageConverter<InternalMessage, AMQMessage> -{ - private static final int BASIC_CLASS_ID = 60; - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - - public Class<InternalMessage> getInputClass() - { - return InternalMessage.class; - } - - @Override - public Class<AMQMessage> getOutputClass() - { - return AMQMessage.class; - } - - @Override - public AMQMessage convert(InternalMessage serverMsg, VirtualHostImpl vhost) - { - return new AMQMessage(convertToStoredMessage(serverMsg), null); - } - - private StoredMessage<MessageMetaData> convertToStoredMessage(final InternalMessage serverMsg) - { - final byte[] messageContent = convertToBody(serverMsg.getMessageBody()); - final MessageMetaData messageMetaData_0_8 = convertMetaData(serverMsg, - getBodyMimeType(serverMsg.getMessageBody()), - messageContent.length); - - return new StoredMessage<MessageMetaData>() - { - @Override - public MessageMetaData getMetaData() - { - return messageMetaData_0_8; - } - - @Override - public long getMessageNumber() - { - return serverMsg.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - int size = messageContent.length - offsetInMessage; - if(dst.remaining() < size) - { - size = dst.remaining(); - } - ByteBuffer buf = ByteBuffer.wrap(messageContent, offsetInMessage, size); - dst.put(buf); - return size; - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return ByteBuffer.wrap(messageContent, offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData convertMetaData(final InternalMessage serverMsg, final String bodyMimeType, final int size) - { - - MessagePublishInfo publishInfo = new MessagePublishInfo(AMQShortString.EMPTY_STRING, - false, - false, - AMQShortString.valueOf(serverMsg.getInitialRoutingAddress())); - - - final BasicContentHeaderProperties props = new BasicContentHeaderProperties(); - props.setAppId(serverMsg.getMessageHeader().getAppId()); - props.setContentType(bodyMimeType); - props.setCorrelationId(serverMsg.getMessageHeader().getCorrelationId()); - props.setDeliveryMode(serverMsg.isPersistent() ? BasicContentHeaderProperties.PERSISTENT : BasicContentHeaderProperties.NON_PERSISTENT); - props.setExpiration(serverMsg.getExpiration()); - props.setMessageId(serverMsg.getMessageHeader().getMessageId()); - props.setPriority(serverMsg.getMessageHeader().getPriority()); - props.setReplyTo(serverMsg.getMessageHeader().getReplyTo()); - props.setTimestamp(serverMsg.getMessageHeader().getTimestamp()); - props.setUserId(serverMsg.getMessageHeader().getUserId()); - - - Map<String,Object> headerProps = new LinkedHashMap<String, Object>(); - - for(String headerName : serverMsg.getMessageHeader().getHeaderNames()) - { - headerProps.put(headerName, serverMsg.getMessageHeader().getHeader(headerName)); - } - - props.setHeaders(FieldTable.convertToFieldTable(headerProps)); - - final ContentHeaderBody chb = new ContentHeaderBody(props); - chb.setBodySize(size); - return new MessageMetaData(publishInfo, chb, serverMsg.getArrivalTime()); - } - - - @Override - public String getType() - { - return "Internal to v0-8"; - } - - - public static byte[] convertToBody(Object object) - { - if(object instanceof String) - { - return ((String)object).getBytes(UTF_8); - } - else if(object instanceof byte[]) - { - return (byte[]) object; - } - else if(object instanceof Map) - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeMap((Map)object); - ByteBuffer buf = encoder.segment(); - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - - } - else if(object instanceof List) - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeList((List) object); - ByteBuffer buf = encoder.segment(); - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - } - else - { - ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - try - { - ObjectOutputStream os = new ObjectOutputStream(bytesOut); - os.writeObject(object); - return bytesOut.toByteArray(); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - } - - public static String getBodyMimeType(Object object) - { - if(object instanceof String) - { - return "text/plain"; - } - else if(object instanceof byte[]) - { - return "application/octet-stream"; - } - else if(object instanceof Map) - { - return "amqp/map"; - } - else if(object instanceof List) - { - return "amqp/list"; - } - else - { - return "application/java-object-stream"; - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java deleted file mode 100644 index 0b98699b4a..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java +++ /dev/null @@ -1,358 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.io.EOFException; -import java.net.URISyntaxException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.typedmessage.TypedBytesContentReader; -import org.apache.qpid.typedmessage.TypedBytesFormatException; -import org.apache.qpid.url.AMQBindingURL; - -@PluggableService -public class MessageConverter_v0_8_to_Internal implements MessageConverter<AMQMessage, InternalMessage> -{ - @Override - public Class<AMQMessage> getInputClass() - { - return AMQMessage.class; - } - - @Override - public Class<InternalMessage> getOutputClass() - { - return InternalMessage.class; - } - - @Override - public InternalMessage convert(AMQMessage serverMessage, VirtualHostImpl vhost) - { - final String mimeType = serverMessage.getMessageHeader().getMimeType(); - byte[] data = new byte[(int) serverMessage.getSize()]; - serverMessage.getContent(ByteBuffer.wrap(data), 0); - - Object body = convertMessageBody(mimeType, data); - - return InternalMessage.convert(serverMessage.getMessageNumber(), serverMessage.isPersistent(), - new DelegatingMessageHeader(serverMessage.getMessageHeader()), body); - } - - private static class ReplyToComponents - { - private String _exchange; - private String _queue; - private String _routingKey; - - public void setExchange(final String exchange) - { - _exchange = exchange; - } - - public void setQueue(final String queue) - { - _queue = queue; - } - - public void setRoutingKey(final String routingKey) - { - _routingKey = routingKey; - } - - public String getExchange() - { - return _exchange; - } - - public String getQueue() - { - return _queue; - } - - public String getRoutingKey() - { - return _routingKey; - } - - public boolean hasExchange() - { - return _exchange != null; - } - - public boolean hasQueue() - { - return _queue != null; - } - - public boolean hasRoutingKey() - { - return _routingKey != null; - } - } - - private static class DelegatingMessageHeader implements AMQMessageHeader - { - private final AMQMessageHeader _delegate; - - private DelegatingMessageHeader(final AMQMessageHeader delegate) - { - _delegate = delegate; - } - - @Override - public String getCorrelationId() - { - return _delegate.getCorrelationId(); - } - - @Override - public long getExpiration() - { - return _delegate.getExpiration(); - } - - @Override - public String getUserId() - { - return _delegate.getUserId(); - } - - @Override - public String getAppId() - { - return _delegate.getAppId(); - } - - @Override - public String getMessageId() - { - return _delegate.getMessageId(); - } - - @Override - public String getMimeType() - { - return _delegate.getMimeType(); - } - - @Override - public String getEncoding() - { - return _delegate.getEncoding(); - } - - @Override - public byte getPriority() - { - return _delegate.getPriority(); - } - - @Override - public long getTimestamp() - { - return _delegate.getTimestamp(); - } - - @Override - public String getType() - { - return _delegate.getType(); - } - - @Override - public String getReplyTo() - { - String originalReplyTo = _delegate.getReplyTo(); - ReplyToComponents replyTo = convertReplyTo(originalReplyTo); - if(replyTo != null) - { - if(replyTo.hasExchange()) - { - return replyTo.getExchange() + (replyTo.hasRoutingKey() ? "/" + replyTo.getRoutingKey() : ""); - } - else - { - return replyTo.hasQueue() ? replyTo.getQueue() : replyTo.getRoutingKey(); - } - } - else - { - return originalReplyTo; - } - } - - private ReplyToComponents convertReplyTo(final String origReplyToString) - { - try - { - AMQBindingURL burl = new AMQBindingURL(origReplyToString); - ReplyToComponents replyTo = new ReplyToComponents(); - AMQShortString routingKey = burl.getRoutingKey(); - if(routingKey != null) - { - replyTo.setRoutingKey(routingKey.asString()); - } - - AMQShortString exchangeName = burl.getExchangeName(); - if(exchangeName != null) - { - replyTo.setExchange(exchangeName.asString()); - } - - AMQShortString queueName = burl.getQueueName(); - if(queueName != null) - { - replyTo.setQueue(queueName.asString()); - } - return replyTo; - } - catch (URISyntaxException e) - { - return null; - } - } - - @Override - public Object getHeader(final String name) - { - return _delegate.getHeader(name); - } - - @Override - public boolean containsHeaders(final Set<String> names) - { - return _delegate.containsHeaders(names); - } - - @Override - public boolean containsHeader(final String name) - { - return _delegate.containsHeader(name); - } - - @Override - public Collection<String> getHeaderNames() - { - return _delegate.getHeaderNames(); - } - } - - - private static Object convertMessageBody(String mimeType, byte[] data) - { - if("text/plain".equals(mimeType) || "text/xml".equals(mimeType)) - { - String text = new String(data); - return text; - } - else if("jms/map-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - LinkedHashMap map = new LinkedHashMap(); - final int entries = reader.readIntImpl(); - for (int i = 0; i < entries; i++) - { - try - { - String propName = reader.readStringImpl(); - Object value = reader.readObject(); - - map.put(propName, value); - } - catch (EOFException e) - { - throw new IllegalArgumentException(e); - } - catch (TypedBytesFormatException e) - { - throw new IllegalArgumentException(e); - } - - } - - return map; - - } - else if("amqp/map".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - final Map<String,Object> map = decoder.readMap(); - - return map; - - } - else if("amqp/list".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - return decoder.readList(); - } - else if("jms/stream-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - List list = new ArrayList(); - while (reader.remaining() != 0) - { - try - { - list.add(reader.readObject()); - } - catch (TypedBytesFormatException e) - { - throw new ConnectionScopedRuntimeException(e); - } - catch (EOFException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - return list; - } - else - { - return data; - - } - } - - @Override - public String getType() - { - return "v0-8 to Internal"; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java deleted file mode 100644 index 6b2902d0fa..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.Collection; -import java.util.Set; - -import org.apache.qpid.framing.AMQFrameDecodingException; -import org.apache.qpid.framing.AMQProtocolVersionException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.EncodingUtils; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.store.StorableMessageMetaData; -import org.apache.qpid.server.util.ByteBufferOutputStream; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.util.ByteBufferInputStream; - -/** - * Encapsulates a publish body and a content header. In the context of the message store these are treated as a - * single unit. - */ -public class MessageMetaData implements StorableMessageMetaData -{ - private final MessagePublishInfo _messagePublishInfo; - - private final ContentHeaderBody _contentHeaderBody; - - - private long _arrivalTime; - private static final byte MANDATORY_FLAG = 1; - private static final byte IMMEDIATE_FLAG = 2; - public static final MessageMetaDataType.Factory<MessageMetaData> FACTORY = new MetaDataFactory(); - private static final MessageMetaDataType_0_8 TYPE = new MessageMetaDataType_0_8(); - - public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody) - { - this(publishBody,contentHeaderBody, System.currentTimeMillis()); - } - - public MessageMetaData(MessagePublishInfo publishBody, - ContentHeaderBody contentHeaderBody, - long arrivalTime) - { - _contentHeaderBody = contentHeaderBody; - _messagePublishInfo = publishBody; - _arrivalTime = arrivalTime; - } - - - public ContentHeaderBody getContentHeaderBody() - { - return _contentHeaderBody; - } - - public MessagePublishInfo getMessagePublishInfo() - { - return _messagePublishInfo; - } - - public long getArrivalTime() - { - return _arrivalTime; - } - - public MessageMetaDataType getType() - { - return TYPE; - } - - public int getStorableSize() - { - int size = _contentHeaderBody.getSize(); - size += 4; - size += EncodingUtils.encodedShortStringLength(_messagePublishInfo.getExchange()); - size += EncodingUtils.encodedShortStringLength(_messagePublishInfo.getRoutingKey()); - size += 1; // flags for immediate/mandatory - size += EncodingUtils.encodedLongLength(); - - return size; - } - - - public int writeToBuffer(ByteBuffer dest) - { - int oldPosition = dest.position(); - try - { - - DataOutputStream dataOutputStream = new DataOutputStream(new ByteBufferOutputStream(dest)); - EncodingUtils.writeInteger(dataOutputStream, _contentHeaderBody.getSize()); - _contentHeaderBody.writePayload(dataOutputStream); - EncodingUtils.writeShortStringBytes(dataOutputStream, _messagePublishInfo.getExchange()); - EncodingUtils.writeShortStringBytes(dataOutputStream, _messagePublishInfo.getRoutingKey()); - byte flags = 0; - if(_messagePublishInfo.isMandatory()) - { - flags |= MANDATORY_FLAG; - } - if(_messagePublishInfo.isImmediate()) - { - flags |= IMMEDIATE_FLAG; - } - dest.put(flags); - dest.putLong(_arrivalTime); - - } - catch (IOException e) - { - // This shouldn't happen as we are not actually using anything that can throw an IO Exception - throw new ConnectionScopedRuntimeException(e); - } - - return dest.position()-oldPosition; - } - - public int getContentSize() - { - return (int) _contentHeaderBody.getBodySize(); - } - - public boolean isPersistent() - { - return _contentHeaderBody.getProperties().getDeliveryMode() == BasicContentHeaderProperties.PERSISTENT; - } - - private static class MetaDataFactory implements MessageMetaDataType.Factory - { - - - public MessageMetaData createMetaData(ByteBuffer buf) - { - try - { - ByteBufferInputStream bbis = new ByteBufferInputStream(buf); - DataInputStream dais = new DataInputStream(bbis); - int size = EncodingUtils.readInteger(dais); - ContentHeaderBody chb = ContentHeaderBody.createFromBuffer(dais, size); - final AMQShortString exchange = EncodingUtils.readAMQShortString(dais); - final AMQShortString routingKey = EncodingUtils.readAMQShortString(dais); - - final byte flags = EncodingUtils.readByte(dais); - long arrivalTime = EncodingUtils.readLong(dais); - - MessagePublishInfo publishBody = - new MessagePublishInfo(exchange, - (flags & IMMEDIATE_FLAG) != 0, - (flags & MANDATORY_FLAG) != 0, - routingKey); - - return new MessageMetaData(publishBody, chb, arrivalTime); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException(e); - } - catch (AMQProtocolVersionException e) - { - throw new ConnectionScopedRuntimeException(e); - } - catch (AMQFrameDecodingException e) - { - throw new ConnectionScopedRuntimeException(e); - } - - } - } - - public AMQMessageHeader getMessageHeader() - { - return new MessageHeaderAdapter(); - } - - private final class MessageHeaderAdapter implements AMQMessageHeader - { - private BasicContentHeaderProperties getProperties() - { - return getContentHeaderBody().getProperties(); - } - - public String getUserId() - { - return getProperties().getUserIdAsString(); - } - - public String getAppId() - { - return getProperties().getAppIdAsString(); - } - - public String getCorrelationId() - { - return getProperties().getCorrelationIdAsString(); - } - - public long getExpiration() - { - return getProperties().getExpiration(); - } - - public String getMessageId() - { - return getProperties().getMessageIdAsString(); - } - - public String getMimeType() - { - return getProperties().getContentTypeAsString(); - } - - public String getEncoding() - { - return getProperties().getEncodingAsString(); - } - - public byte getPriority() - { - return getProperties().getPriority(); - } - - public long getTimestamp() - { - return getProperties().getTimestamp(); - } - - public String getType() - { - return getProperties().getTypeAsString(); - } - - public String getReplyTo() - { - return getProperties().getReplyToAsString(); - } - - public Object getHeader(String name) - { - FieldTable ft = getProperties().getHeaders(); - return ft.get(name); - } - - public boolean containsHeaders(Set<String> names) - { - FieldTable ft = getProperties().getHeaders(); - for(String name : names) - { - if(!ft.containsKey(name)) - { - return false; - } - } - return true; - } - - @Override - public Collection<String> getHeaderNames() - { - return getProperties().getHeaders().keys(); - } - - public boolean containsHeader(String name) - { - FieldTable ft = getProperties().getHeaders(); - return ft.containsKey(name); - } - - - - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.java deleted file mode 100644 index 5e263cd3b0..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.nio.ByteBuffer; - -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; - -@PluggableService -public class MessageMetaDataType_0_8 implements MessageMetaDataType<MessageMetaData> -{ - - public static final int TYPE = 0; - public static final String V0_8 = "v0_8"; - - @Override - public int ordinal() - { - return TYPE; - } - - @Override - public MessageMetaData createMetaData(ByteBuffer buf) - { - return MessageMetaData.FACTORY.createMetaData(buf); - } - - @Override - public ServerMessage<MessageMetaData> createMessage(StoredMessage<MessageMetaData> msg) - { - return new AMQMessage(msg); - } - - public int hashCode() - { - return ordinal(); - } - - public boolean equals(Object o) - { - return o != null && o.getClass() == getClass(); - } - - @Override - public String getType() - { - return V0_8; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageOnlyCreditManager.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageOnlyCreditManager.java deleted file mode 100644 index af54c911dc..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageOnlyCreditManager.java +++ /dev/null @@ -1,73 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.protocol.v0_8; - -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.qpid.server.flow.AbstractFlowCreditManager; -import org.apache.qpid.server.flow.FlowCreditManager; - -public class MessageOnlyCreditManager extends AbstractFlowCreditManager implements FlowCreditManager -{ - private final AtomicLong _messageCredit; - - public MessageOnlyCreditManager(final long initialCredit) - { - _messageCredit = new AtomicLong(initialCredit); - } - - public void restoreCredit(long messageCredit, long bytesCredit) - { - _messageCredit.addAndGet(messageCredit); - setSuspended(false); - - } - - public boolean hasCredit() - { - return _messageCredit.get() > 0L; - } - - public boolean useCreditForMessage(long msgSize) - { - if(hasCredit()) - { - if(_messageCredit.addAndGet(-1L) >= 0) - { - setSuspended(false); - return true; - } - else - { - _messageCredit.addAndGet(1L); - setSuspended(true); - return false; - } - } - else - { - setSuspended(true); - return false; - } - - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/NoAckCreditManager.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/NoAckCreditManager.java deleted file mode 100644 index 6e5aab2dd5..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/NoAckCreditManager.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.qpid.server.protocol.v0_8; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.flow.AbstractFlowCreditManager; - -public class NoAckCreditManager extends AbstractFlowCreditManager -{ - private final ServerProtocolEngine _serverProtocolEngine; - - public NoAckCreditManager(ServerProtocolEngine serverProtocolEngine) - { - _serverProtocolEngine = serverProtocolEngine; - } - - @Override - public void restoreCredit(final long messageCredit, final long bytesCredit) - { - setSuspended(!hasCredit()); - } - - @Override - public boolean hasCredit() - { - return !_serverProtocolEngine.isTransportBlockedForWriting(); - } - - @Override - public boolean useCreditForMessage(final long msgSize) - { - if (!hasCredit()) - { - setSuspended(true); - return false; - } - return true; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/Pre0_10CreditManager.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/Pre0_10CreditManager.java deleted file mode 100644 index a869a707e1..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/Pre0_10CreditManager.java +++ /dev/null @@ -1,190 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.protocol.v0_8; - - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.flow.AbstractFlowCreditManager; -import org.apache.qpid.server.flow.FlowCreditManager; - -public class Pre0_10CreditManager extends AbstractFlowCreditManager implements FlowCreditManager -{ - - private final ServerProtocolEngine _protocolEngine; - private volatile long _bytesCreditLimit; - private volatile long _messageCreditLimit; - - private volatile long _bytesCredit; - private volatile long _messageCredit; - - public Pre0_10CreditManager(long bytesCreditLimit, - long messageCreditLimit, - ServerProtocolEngine protocolEngine) - { - _protocolEngine = protocolEngine; - _bytesCreditLimit = bytesCreditLimit; - _messageCreditLimit = messageCreditLimit; - _bytesCredit = bytesCreditLimit; - _messageCredit = messageCreditLimit; - } - - - - public synchronized void setCreditLimits(final long bytesCreditLimit, final long messageCreditLimit) - { - long bytesCreditChange = bytesCreditLimit - _bytesCreditLimit; - long messageCreditChange = messageCreditLimit - _messageCreditLimit; - - - - if(bytesCreditChange != 0L) - { - if(bytesCreditLimit == 0L) - { - _bytesCredit = 0; - } - else - { - _bytesCredit += bytesCreditChange; - } - } - - - if(messageCreditChange != 0L) - { - if(messageCreditLimit == 0L) - { - _messageCredit = 0; - } - else - { - _messageCredit += messageCreditChange; - } - } - - - _bytesCreditLimit = bytesCreditLimit; - _messageCreditLimit = messageCreditLimit; - - setSuspended(!hasCredit()); - - } - - - public synchronized void restoreCredit(final long messageCredit, final long bytesCredit) - { - final long messageCreditLimit = _messageCreditLimit; - boolean notifyIncrease = true; - if(messageCreditLimit != 0L) - { - notifyIncrease = (_messageCredit != 0); - long newCredit = _messageCredit + messageCredit; - _messageCredit = newCredit > messageCreditLimit ? messageCreditLimit : newCredit; - } - - - final long bytesCreditLimit = _bytesCreditLimit; - if(bytesCreditLimit != 0L) - { - long newCredit = _bytesCredit + bytesCredit; - _bytesCredit = newCredit > bytesCreditLimit ? bytesCreditLimit : newCredit; - if(notifyIncrease && bytesCredit>0) - { - notifyIncreaseBytesCredit(); - } - } - - - - setSuspended(!hasCredit()); - - } - - public synchronized boolean hasCredit() - { - return (_bytesCreditLimit == 0L || _bytesCredit > 0) - && (_messageCreditLimit == 0L || _messageCredit > 0) - && !_protocolEngine.isTransportBlockedForWriting(); - } - - public synchronized boolean useCreditForMessage(final long msgSize) - { - if (_protocolEngine.isTransportBlockedForWriting()) - { - setSuspended(true); - return false; - } - else if(_messageCreditLimit != 0L) - { - if(_messageCredit != 0L) - { - if(_bytesCreditLimit == 0L) - { - _messageCredit--; - - return true; - } - else - { - if((_bytesCredit >= msgSize) || (_bytesCredit == _bytesCreditLimit)) - { - _messageCredit--; - _bytesCredit -= msgSize; - - return true; - } - else - { - return false; - } - } - } - else - { - setSuspended(true); - return false; - } - } - else - { - if(_bytesCreditLimit == 0L) - { - - return true; - } - else - { - if((_bytesCredit >= msgSize) || (_bytesCredit == _bytesCreditLimit)) - { - _bytesCredit -= msgSize; - - return true; - } - else - { - return false; - } - } - - } - - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_8.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_8.java deleted file mode 100644 index e8cf028069..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_8.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.ProtocolEngineCreator; -import org.apache.qpid.transport.network.NetworkConnection; - -@PluggableService -public class ProtocolEngineCreator_0_8 implements ProtocolEngineCreator -{ - private static final byte[] AMQP_0_8_HEADER = - new byte[] { (byte) 'A', - (byte) 'M', - (byte) 'Q', - (byte) 'P', - (byte) 1, - (byte) 1, - (byte) 8, - (byte) 0 - }; - - - public ProtocolEngineCreator_0_8() - { - } - - public Protocol getVersion() - { - return Protocol.AMQP_0_8; - } - - public byte[] getHeaderIdentifier() - { - return AMQP_0_8_HEADER; - } - - public ServerProtocolEngine newProtocolEngine(Broker<?> broker, - NetworkConnection network, - AmqpPort<?> port, - Transport transport, - long id) - { - return new AMQProtocolEngine(broker, network, id, port, transport); - } - - private static ProtocolEngineCreator INSTANCE = new ProtocolEngineCreator_0_8(); - - public static ProtocolEngineCreator getInstance() - { - return INSTANCE; - } - - @Override - public String getType() - { - return getVersion().toString(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9.java deleted file mode 100644 index 8817e79aff..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.ProtocolEngineCreator; -import org.apache.qpid.transport.network.NetworkConnection; - -@PluggableService -public class ProtocolEngineCreator_0_9 implements ProtocolEngineCreator -{ - private static final byte[] AMQP_0_9_HEADER = - new byte[] { (byte) 'A', - (byte) 'M', - (byte) 'Q', - (byte) 'P', - (byte) 1, - (byte) 1, - (byte) 0, - (byte) 9 - }; - - public ProtocolEngineCreator_0_9() - { - } - - public Protocol getVersion() - { - return Protocol.AMQP_0_9; - } - - - public byte[] getHeaderIdentifier() - { - return AMQP_0_9_HEADER; - } - - public ServerProtocolEngine newProtocolEngine(Broker<?> broker, - NetworkConnection network, - AmqpPort<?> port, - Transport transport, - long id) - { - return new AMQProtocolEngine(broker, network, id, port, transport); - } - - private static ProtocolEngineCreator INSTANCE = new ProtocolEngineCreator_0_9(); - - public static ProtocolEngineCreator getInstance() - { - return INSTANCE; - } - - @Override - public String getType() - { - return getVersion().toString(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9_1.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9_1.java deleted file mode 100644 index af37b17d85..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9_1.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.ProtocolEngineCreator; -import org.apache.qpid.transport.network.NetworkConnection; - -@PluggableService -public class ProtocolEngineCreator_0_9_1 implements ProtocolEngineCreator -{ - - private static final byte[] AMQP_0_9_1_HEADER = - new byte[] { (byte) 'A', - (byte) 'M', - (byte) 'Q', - (byte) 'P', - (byte) 0, - (byte) 0, - (byte) 9, - (byte) 1 - }; - - public ProtocolEngineCreator_0_9_1() - { - } - - public Protocol getVersion() - { - return Protocol.AMQP_0_9_1; - } - - - public byte[] getHeaderIdentifier() - { - return AMQP_0_9_1_HEADER; - } - - public ServerProtocolEngine newProtocolEngine(Broker<?> broker, - NetworkConnection network, - AmqpPort<?> port, - Transport transport, - long id) - { - return new AMQProtocolEngine(broker, network, id, port, transport); - } - - - private static ProtocolEngineCreator INSTANCE = new ProtocolEngineCreator_0_9_1(); - - public static ProtocolEngineCreator getInstance() - { - return INSTANCE; - } - - @Override - public String getType() - { - return getVersion().toString(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverter.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverter.java deleted file mode 100644 index 69f71f14a9..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverter.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -/* - * This file is auto-generated by Qpid Gentools v.0.1 - do not modify. - * Supported AMQP versions: - * 8-0 - */ -package org.apache.qpid.server.protocol.v0_8; - -import org.apache.qpid.framing.AMQDataBlock; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.server.message.ServerMessage; - -public interface ProtocolOutputConverter -{ - void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag); - - long writeDeliver(final ServerMessage msg, - final InstanceProperties props, int channelId, - long deliveryTag, - AMQShortString consumerTag); - - long writeGetOk(final ServerMessage msg, - final InstanceProperties props, - int channelId, - long deliveryTag, - int queueSize); - - void writeReturn(MessagePublishInfo messagePublishInfo, ContentHeaderBody header, MessageContentSource msgContent, int channelId, int replyCode, AMQShortString replyText); - - void writeFrame(AMQDataBlock block); -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.java deleted file mode 100644 index 15ce9262fc..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.java +++ /dev/null @@ -1,543 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.io.DataOutput; -import java.io.IOException; -import java.nio.ByteBuffer; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQBody; -import org.apache.qpid.framing.AMQDataBlock; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQMethodBody; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicCancelOkBody; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.BasicGetOkBody; -import org.apache.qpid.framing.BasicReturnBody; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.protocol.MessageConverterRegistry; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.util.GZIPUtils; - -public class ProtocolOutputConverterImpl implements ProtocolOutputConverter -{ - private static final int BASIC_CLASS_ID = 60; - - private final AMQProtocolEngine _connection; - private static final AMQShortString GZIP_ENCODING = AMQShortString.valueOf(GZIPUtils.GZIP_CONTENT_ENCODING); - - public ProtocolOutputConverterImpl(AMQProtocolEngine connection) - { - _connection = connection; - } - - - public long writeDeliver(final ServerMessage m, - final InstanceProperties props, int channelId, - long deliveryTag, - AMQShortString consumerTag) - { - final AMQMessage msg = convertToAMQMessage(m); - final boolean isRedelivered = Boolean.TRUE.equals(props.getProperty(InstanceProperties.Property.REDELIVERED)); - AMQBody deliverBody = createEncodedDeliverBody(msg, isRedelivered, deliveryTag, consumerTag); - return writeMessageDelivery(msg, channelId, deliverBody); - } - - private AMQMessage convertToAMQMessage(ServerMessage serverMessage) - { - if(serverMessage instanceof AMQMessage) - { - return (AMQMessage) serverMessage; - } - else - { - return getMessageConverter(serverMessage).convert(serverMessage, _connection.getVirtualHost()); - } - } - - private <M extends ServerMessage> MessageConverter<M, AMQMessage> getMessageConverter(M message) - { - Class<M> clazz = (Class<M>) message.getClass(); - return MessageConverterRegistry.getConverter(clazz, AMQMessage.class); - } - - private long writeMessageDelivery(AMQMessage message, int channelId, AMQBody deliverBody) - { - return writeMessageDelivery(message, message.getContentHeaderBody(), channelId, deliverBody); - } - - private long writeMessageDelivery(MessageContentSource message, ContentHeaderBody contentHeaderBody, int channelId, AMQBody deliverBody) - { - - int bodySize = (int) message.getSize(); - boolean msgCompressed = isCompressed(contentHeaderBody); - byte[] modifiedContent; - - // straight through case - boolean compressionSupported = _connection.isCompressionSupported(); - - if(msgCompressed && !compressionSupported && - (modifiedContent = GZIPUtils.uncompressBufferToArray(message.getContent(0,bodySize))) != null) - { - BasicContentHeaderProperties modifiedProps = - new BasicContentHeaderProperties(contentHeaderBody.getProperties()); - modifiedProps.setEncoding((String)null); - - writeMessageDeliveryModified(channelId, deliverBody, modifiedProps, modifiedContent); - - return modifiedContent.length; - } - else if(!msgCompressed - && compressionSupported - && contentHeaderBody.getProperties().getEncoding()==null - && bodySize > _connection.getMessageCompressionThreshold() - && (modifiedContent = GZIPUtils.compressBufferToArray(message.getContent(0, bodySize))) != null) - { - BasicContentHeaderProperties modifiedProps = - new BasicContentHeaderProperties(contentHeaderBody.getProperties()); - modifiedProps.setEncoding(GZIP_ENCODING); - - writeMessageDeliveryModified(channelId, deliverBody, modifiedProps, modifiedContent); - - return modifiedContent.length; - } - else - { - writeMessageDeliveryUnchanged(message, contentHeaderBody, channelId, deliverBody, bodySize); - - return bodySize; - } - } - - private int writeMessageDeliveryModified(final int channelId, - final AMQBody deliverBody, - final BasicContentHeaderProperties modifiedProps, - final byte[] content) - { - final int bodySize; - bodySize = content.length; - ContentHeaderBody modifiedHeaderBody = - new ContentHeaderBody(modifiedProps, bodySize); - final MessageContentSource wrappedSource = new MessageContentSource() - { - @Override - public int getContent(final ByteBuffer buf, final int offset) - { - int size = Math.min(buf.remaining(), content.length - offset); - buf.put(content, offset, size); - return size; - } - - @Override - public ByteBuffer getContent(final int offset, final int size) - { - return ByteBuffer.wrap(content, offset, size); - } - - @Override - public long getSize() - { - return content.length; - } - }; - writeMessageDeliveryUnchanged(wrappedSource, modifiedHeaderBody, channelId, deliverBody, bodySize); - return bodySize; - } - - private void writeMessageDeliveryUnchanged(final MessageContentSource message, - final ContentHeaderBody contentHeaderBody, - final int channelId, final AMQBody deliverBody, final int bodySize) - { - if (bodySize == 0) - { - SmallCompositeAMQBodyBlock compositeBlock = new SmallCompositeAMQBodyBlock(channelId, deliverBody, - contentHeaderBody); - - writeFrame(compositeBlock); - } - else - { - int maxBodySize = (int) _connection.getMaxFrameSize() - AMQFrame.getFrameOverhead(); - - - int capacity = bodySize > maxBodySize ? maxBodySize : bodySize; - - int writtenSize = capacity; - - AMQBody firstContentBody = new MessageContentSourceBody(message, 0, capacity); - - CompositeAMQBodyBlock - compositeBlock = - new CompositeAMQBodyBlock(channelId, deliverBody, contentHeaderBody, firstContentBody); - writeFrame(compositeBlock); - - while (writtenSize < bodySize) - { - capacity = bodySize - writtenSize > maxBodySize ? maxBodySize : bodySize - writtenSize; - MessageContentSourceBody body = new MessageContentSourceBody(message, writtenSize, capacity); - writtenSize += capacity; - - writeFrame(new AMQFrame(channelId, body)); - } - } - } - - private boolean isCompressed(final ContentHeaderBody contentHeaderBody) - { - return GZIP_ENCODING.equals(contentHeaderBody.getProperties().getEncoding()); - } - - private class MessageContentSourceBody implements AMQBody - { - public static final byte TYPE = 3; - private final int _length; - private final MessageContentSource _message; - private final int _offset; - - public MessageContentSourceBody(MessageContentSource message, int offset, int length) - { - _message = message; - _offset = offset; - _length = length; - } - - public byte getFrameType() - { - return TYPE; - } - - public int getSize() - { - return _length; - } - - public void writePayload(DataOutput buffer) throws IOException - { - ByteBuffer buf = _message.getContent(_offset, _length); - - if(buf.hasArray()) - { - buffer.write(buf.array(), buf.arrayOffset()+buf.position(), buf.remaining()); - } - else - { - - byte[] data = new byte[_length]; - - buf.get(data); - - buffer.write(data); - } - } - - @Override - public long writePayload(final ByteBufferSender sender) throws IOException - { - ByteBuffer buf = _message.getContent(_offset, _length); - long size = buf.remaining(); - sender.send(buf.duplicate()); - return size; - } - - public void handle(int channelId, AMQVersionAwareProtocolSession amqProtocolSession) throws AMQException - { - throw new UnsupportedOperationException(); - } - - @Override - public String toString() - { - return "[" + getClass().getSimpleName() + " offset: " + _offset + ", length: " + _length + "]"; - } - - } - - public long writeGetOk(final ServerMessage msg, - final InstanceProperties props, - int channelId, - long deliveryTag, - int queueSize) - { - AMQBody deliver = createEncodedGetOkBody(msg, props, deliveryTag, queueSize); - return writeMessageDelivery(convertToAMQMessage(msg), channelId, deliver); - } - - - private AMQBody createEncodedDeliverBody(AMQMessage message, - boolean isRedelivered, - final long deliveryTag, - final AMQShortString consumerTag) - { - - final AMQShortString exchangeName; - final AMQShortString routingKey; - - final MessagePublishInfo pb = message.getMessagePublishInfo(); - exchangeName = pb.getExchange(); - routingKey = pb.getRoutingKey(); - - final AMQBody returnBlock = new EncodedDeliveryBody(deliveryTag, routingKey, exchangeName, consumerTag, isRedelivered); - return returnBlock; - } - - private class EncodedDeliveryBody implements AMQBody - { - private final long _deliveryTag; - private final AMQShortString _routingKey; - private final AMQShortString _exchangeName; - private final AMQShortString _consumerTag; - private final boolean _isRedelivered; - private AMQBody _underlyingBody; - - private EncodedDeliveryBody(long deliveryTag, AMQShortString routingKey, AMQShortString exchangeName, AMQShortString consumerTag, boolean isRedelivered) - { - _deliveryTag = deliveryTag; - _routingKey = routingKey; - _exchangeName = exchangeName; - _consumerTag = consumerTag; - _isRedelivered = isRedelivered; - } - - public AMQBody createAMQBody() - { - return _connection.getMethodRegistry().createBasicDeliverBody(_consumerTag, - _deliveryTag, - _isRedelivered, - _exchangeName, - _routingKey); - } - - public byte getFrameType() - { - return AMQMethodBody.TYPE; - } - - public int getSize() - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - return _underlyingBody.getSize(); - } - - public void writePayload(DataOutput buffer) throws IOException - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - _underlyingBody.writePayload(buffer); - } - - public long writePayload(ByteBufferSender sender) throws IOException - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - return _underlyingBody.writePayload(sender); - } - - public void handle(final int channelId, final AMQVersionAwareProtocolSession amqProtocolSession) - throws AMQException - { - throw new AMQException("This block should never be dispatched!"); - } - - @Override - public String toString() - { - return "[" + getClass().getSimpleName() + " underlyingBody: " + String.valueOf(_underlyingBody) + "]"; - } - } - - private AMQBody createEncodedGetOkBody(ServerMessage msg, InstanceProperties props, long deliveryTag, int queueSize) - { - final AMQShortString exchangeName; - final AMQShortString routingKey; - - final AMQMessage message = convertToAMQMessage(msg); - final MessagePublishInfo pb = message.getMessagePublishInfo(); - exchangeName = pb.getExchange(); - routingKey = pb.getRoutingKey(); - - final boolean isRedelivered = Boolean.TRUE.equals(props.getProperty(InstanceProperties.Property.REDELIVERED)); - - BasicGetOkBody getOkBody = - _connection.getMethodRegistry().createBasicGetOkBody(deliveryTag, - isRedelivered, - exchangeName, - routingKey, - queueSize); - - return getOkBody; - } - - private AMQBody createEncodedReturnFrame(MessagePublishInfo messagePublishInfo, - int replyCode, - AMQShortString replyText) - { - - BasicReturnBody basicReturnBody = - _connection.getMethodRegistry().createBasicReturnBody(replyCode, - replyText, - messagePublishInfo.getExchange(), - messagePublishInfo.getRoutingKey()); - - - return basicReturnBody; - } - - public void writeReturn(MessagePublishInfo messagePublishInfo, ContentHeaderBody header, MessageContentSource message, int channelId, int replyCode, AMQShortString replyText) - { - - AMQBody returnFrame = createEncodedReturnFrame(messagePublishInfo, replyCode, replyText); - - writeMessageDelivery(message, header, channelId, returnFrame); - } - - - public void writeFrame(AMQDataBlock block) - { - _connection.writeFrame(block); - } - - - public void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag) - { - - BasicCancelOkBody basicCancelOkBody = _connection.getMethodRegistry().createBasicCancelOkBody(consumerTag); - writeFrame(basicCancelOkBody.generateFrame(channelId)); - - } - - - public static final class CompositeAMQBodyBlock extends AMQDataBlock - { - public static final int OVERHEAD = 3 * AMQFrame.getFrameOverhead(); - - private final AMQBody _methodBody; - private final AMQBody _headerBody; - private final AMQBody _contentBody; - private final int _channel; - - - public CompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody, AMQBody contentBody) - { - _channel = channel; - _methodBody = methodBody; - _headerBody = headerBody; - _contentBody = contentBody; - } - - public long getSize() - { - return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() + _contentBody.getSize(); - } - - public void writePayload(DataOutput buffer) throws IOException - { - AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody, _contentBody); - } - - @Override - public long writePayload(final ByteBufferSender sender) throws IOException - { - long size = (new AMQFrame(_channel, _methodBody)).writePayload(sender); - - size += (new AMQFrame(_channel, _headerBody)).writePayload(sender); - - size += (new AMQFrame(_channel, _contentBody)).writePayload(sender); - - return size; - } - - @Override - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[").append(getClass().getSimpleName()) - .append(" methodBody=").append(_methodBody) - .append(", headerBody=").append(_headerBody) - .append(", contentBody=").append(_contentBody) - .append(", channel=").append(_channel).append("]"); - return builder.toString(); - } - - } - - public static final class SmallCompositeAMQBodyBlock extends AMQDataBlock - { - public static final int OVERHEAD = 2 * AMQFrame.getFrameOverhead(); - - private final AMQBody _methodBody; - private final AMQBody _headerBody; - private final int _channel; - - - public SmallCompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody) - { - _channel = channel; - _methodBody = methodBody; - _headerBody = headerBody; - - } - - public long getSize() - { - return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() ; - } - - public void writePayload(DataOutput buffer) throws IOException - { - AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody); - } - - @Override - public long writePayload(final ByteBufferSender sender) throws IOException - { - long size = (new AMQFrame(_channel, _methodBody)).writePayload(sender); - size += (new AMQFrame(_channel, _headerBody)).writePayload(sender); - return size; - } - - @Override - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append(getClass().getSimpleName()) - .append("methodBody=").append(_methodBody) - .append(", headerBody=").append(_headerBody) - .append(", channel=").append(_channel).append("]"); - return builder.toString(); - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/RecordDeliveryMethod.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/RecordDeliveryMethod.java deleted file mode 100644 index c13ff17f67..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/RecordDeliveryMethod.java +++ /dev/null @@ -1,29 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.protocol.v0_8; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; - -public interface RecordDeliveryMethod -{ - void recordMessageDelivery(final ConsumerImpl sub, final MessageInstance entry, final long deliveryTag); -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMap.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMap.java deleted file mode 100644 index 198b7fe21b..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMap.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.message.MessageInstance; - - -public interface UnacknowledgedMessageMap -{ - public interface Visitor - { - /** - * @param deliveryTag - *@param message the message being iterated over @return true to stop iteration, false to continue - * @throws AMQException - */ - boolean callback(final long deliveryTag, MessageInstance message); - - void visitComplete(); - } - - void visit(Visitor visitor); - - void add(long deliveryTag, MessageInstance message); - - MessageInstance remove(long deliveryTag); - - Collection<MessageInstance> cancelAllMessages(); - - int size(); - - void clear(); - - MessageInstance get(long deliveryTag); - - /** - * Get the set of delivery tags that are outstanding. - * - * @return a set of delivery tags - */ - Set<Long> getDeliveryTags(); - - Collection<MessageInstance> acknowledge(long deliveryTag, boolean multiple); - void collect(long key, boolean multiple, Map<Long, MessageInstance> msgs); -} - - diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapImpl.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapImpl.java deleted file mode 100644 index 2d39daed1c..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapImpl.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.qpid.server.message.MessageInstance; - -public class UnacknowledgedMessageMapImpl implements UnacknowledgedMessageMap -{ - private final Object _lock = new Object(); - - private Map<Long, MessageInstance> _map; - - private final int _prefetchLimit; - - public UnacknowledgedMessageMapImpl(int prefetchLimit) - { - _prefetchLimit = prefetchLimit; - _map = new LinkedHashMap<>(prefetchLimit); - } - - public void collect(long deliveryTag, boolean multiple, Map<Long, MessageInstance> msgs) - { - if (multiple) - { - collect(deliveryTag, msgs); - } - else - { - final MessageInstance entry = get(deliveryTag); - if(entry != null) - { - msgs.put(deliveryTag, entry); - } - } - - } - - public void remove(Map<Long,MessageInstance> msgs) - { - synchronized (_lock) - { - for (Long deliveryTag : msgs.keySet()) - { - remove(deliveryTag); - } - } - } - - public MessageInstance remove(long deliveryTag) - { - synchronized (_lock) - { - - MessageInstance message = _map.remove(deliveryTag); - return message; - } - } - - public void visit(Visitor visitor) - { - synchronized (_lock) - { - Set<Map.Entry<Long, MessageInstance>> currentEntries = _map.entrySet(); - for (Map.Entry<Long, MessageInstance> entry : currentEntries) - { - visitor.callback(entry.getKey().longValue(), entry.getValue()); - } - visitor.visitComplete(); - } - } - - public void add(long deliveryTag, MessageInstance message) - { - synchronized (_lock) - { - _map.put(deliveryTag, message); - } - } - - public Collection<MessageInstance> cancelAllMessages() - { - synchronized (_lock) - { - Collection<MessageInstance> currentEntries = _map.values(); - _map = new LinkedHashMap<>(_prefetchLimit); - return currentEntries; - } - } - - public int size() - { - synchronized (_lock) - { - return _map.size(); - } - } - - public void clear() - { - synchronized (_lock) - { - _map.clear(); - } - } - - public MessageInstance get(long key) - { - synchronized (_lock) - { - return _map.get(key); - } - } - - public Set<Long> getDeliveryTags() - { - synchronized (_lock) - { - return _map.keySet(); - } - } - - public Collection<MessageInstance> acknowledge(long deliveryTag, boolean multiple) - { - Map<Long, MessageInstance> ackedMessageMap = new LinkedHashMap<Long,MessageInstance>(); - collect(deliveryTag, multiple, ackedMessageMap); - remove(ackedMessageMap); - List<MessageInstance> acknowledged = new ArrayList<>(); - for(MessageInstance instance : ackedMessageMap.values()) - { - if(instance.lockAcquisition()) - { - acknowledged.add(instance); - } - } - return acknowledged; - } - - private void collect(long key, Map<Long, MessageInstance> msgs) - { - synchronized (_lock) - { - for (Map.Entry<Long, MessageInstance> entry : _map.entrySet()) - { - msgs.put(entry.getKey(),entry.getValue()); - if (entry.getKey() == key) - { - break; - } - } - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnexpectedMethodException.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnexpectedMethodException.java deleted file mode 100644 index 432a725c86..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnexpectedMethodException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.protocol.v0_8;
-
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQMethodBody;
-
-public class UnexpectedMethodException extends AMQException
-{
-
- private static final long serialVersionUID = -255921574946294892L;
-
- public UnexpectedMethodException(AMQMethodBody body)
- {
- super("Unexpected method received: " + body.getClass().getName());
- }
-}
diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQChannelTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQChannelTest.java deleted file mode 100644 index a6725a6d58..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQChannelTest.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.framing.AMQDataBlock; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ChannelCloseBody; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.test.utils.QpidTestCase; - -public class AMQChannelTest extends QpidTestCase -{ - private VirtualHostImpl _virtualHost; - private AMQProtocolEngine _protocolSession; - private Map<Integer,String> _replies; - private Broker _broker; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _virtualHost = BrokerTestHelper.createVirtualHost(getTestName()); - _broker = BrokerTestHelper.createBrokerMock(); - AmqpPort port = mock(AmqpPort.class); - when(port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(AmqpPort.DEFAULT_MAX_MESSAGE_SIZE); - - _protocolSession = new InternalTestProtocolSession(_virtualHost, _broker, port) - { - @Override - public void writeReturn(MessagePublishInfo messagePublishInfo, - ContentHeaderBody header, - MessageContentSource msgContent, - int channelId, - int replyCode, - AMQShortString replyText) - { - _replies.put(replyCode, replyText.asString()); - } - }; - _replies = new HashMap<Integer, String>(); - } - - @Override - public void tearDown() throws Exception - { - try - { - _virtualHost.close(); - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - public void testCompareTo() throws Exception - { - AMQChannel channel1 = new AMQChannel(_protocolSession, 1, _virtualHost.getMessageStore()); - - AmqpPort port = mock(AmqpPort.class); - when(port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(AmqpPort.DEFAULT_MAX_MESSAGE_SIZE); - // create a channel with the same channelId but on a different session - AMQChannel channel2 = new AMQChannel(new InternalTestProtocolSession(_virtualHost, _broker, port), 1, _virtualHost.getMessageStore()); - assertFalse("Unexpected compare result", channel1.compareTo(channel2) == 0); - assertEquals("Unexpected compare result", 0, channel1.compareTo(channel1)); - } - - public void testPublishContentHeaderWhenMessageAuthorizationFails() throws Exception - { - setTestSystemProperty(BrokerProperties.PROPERTY_MSG_AUTH, "true"); - AMQChannel channel = new AMQChannel(_protocolSession, 1, _virtualHost.getMessageStore()); - channel.setLocalTransactional(); - - MessagePublishInfo info = new MessagePublishInfo(new AMQShortString("test"), false, false, null); - ExchangeImpl e = mock(ExchangeImpl.class); - ContentHeaderBody contentHeaderBody= mock(ContentHeaderBody.class); - BasicContentHeaderProperties properties = mock(BasicContentHeaderProperties.class); - - when(contentHeaderBody.getProperties()).thenReturn(properties); - when(properties.getUserId()).thenReturn(new AMQShortString(_protocolSession.getAuthorizedPrincipal().getName() + "_incorrect")); - - channel.setPublishFrame(info, e); - channel.publishContentHeader(contentHeaderBody); - channel.commit(null, false); - - assertEquals("Unexpected number of replies", 1, _replies.size()); - assertEquals("Message authorization passed", "Access Refused", _replies.get(403)); - } - - public void testPublishContentHeaderWhenMessageAuthorizationPasses() throws Exception - { - setTestSystemProperty(BrokerProperties.PROPERTY_MSG_AUTH, "true"); - AMQChannel channel = new AMQChannel(_protocolSession, 1, _virtualHost.getMessageStore()); - channel.setLocalTransactional(); - - MessagePublishInfo info = new MessagePublishInfo(new AMQShortString("test"), false, false, null); - ExchangeImpl e = mock(ExchangeImpl.class); - ContentHeaderBody contentHeaderBody= mock(ContentHeaderBody.class); - BasicContentHeaderProperties properties = mock(BasicContentHeaderProperties.class); - - when(contentHeaderBody.getProperties()).thenReturn(properties); - when(properties.getUserId()).thenReturn(new AMQShortString(_protocolSession.getAuthorizedPrincipal().getName())); - - channel.setPublishFrame(info, e); - channel.publishContentHeader(contentHeaderBody); - channel.commit(null, false); - - assertEquals("Unexpected number of replies", 0, _replies.size()); - } - - public void testOverlargeMessage() throws Exception - { - - AmqpPort port = mock(AmqpPort.class); - when(port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(1024); - final List<AMQDataBlock> frames = new ArrayList<>(); - _protocolSession = new InternalTestProtocolSession(_virtualHost, _broker, port) - { - @Override - public synchronized void writeFrame(final AMQDataBlock frame) - { - frames.add(frame); - } - }; - - AMQChannel channel = new AMQChannel(_protocolSession, 1, _virtualHost.getMessageStore()); - - channel.receiveBasicPublish(AMQShortString.EMPTY_STRING, AMQShortString.EMPTY_STRING, false, false); - - final BasicContentHeaderProperties properties = new BasicContentHeaderProperties(); - channel.receiveMessageHeader(properties, 2048l); - - frames.toString(); - - assertEquals(1, frames.size()); - assertEquals(ChannelCloseBody.class, ((AMQFrame) frames.get(0)).getBodyFrame().getClass()); - assertEquals(AMQConstant.MESSAGE_TOO_LARGE.getCode(), ((ChannelCloseBody)((AMQFrame)frames.get(0)).getBodyFrame()).getReplyCode()); - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngineTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngineTest.java deleted file mode 100644 index cc5da731b8..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngineTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrameDecodingException; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.properties.ConnectionStartProperties; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.SenderException; -import org.apache.qpid.transport.network.NetworkConnection; - -public class AMQProtocolEngineTest extends QpidTestCase -{ - private Broker<?> _broker; - private AmqpPort<?> _port; - private NetworkConnection _network; - private Transport _transport; - - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _broker = BrokerTestHelper.createBrokerMock(); - when(_broker.getConnection_closeWhenNoRoute()).thenReturn(true); - - _port = mock(AmqpPort.class); - when(_port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(AmqpPort.DEFAULT_MAX_MESSAGE_SIZE); - - _network = mock(NetworkConnection.class); - _transport = Transport.TCP; - } - - public void tearDown() throws Exception - { - try - { - super.tearDown(); - } - finally - { - BrokerTestHelper.tearDown(); - } - } - - public void testSetClientPropertiesForNoRouteProvidedAsString() - { - AMQProtocolEngine engine = new AMQProtocolEngine(_broker, _network, 0, _port, _transport); - assertTrue("Unexpected closeWhenNoRoute before client properties set", engine.isCloseWhenNoRoute()); - - Map<String, Object> clientProperties = new HashMap<String, Object>(); - clientProperties.put(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE, Boolean.FALSE.toString()); - engine.setClientProperties(FieldTable.convertToFieldTable(clientProperties)); - - assertFalse("Unexpected closeWhenNoRoute after client properties set", engine.isCloseWhenNoRoute()); - } - - public void testSetClientPropertiesForNoRouteProvidedAsBoolean() - { - AMQProtocolEngine engine = new AMQProtocolEngine(_broker, _network, 0, _port, _transport); - assertTrue("Unexpected closeWhenNoRoute before client properties set", engine.isCloseWhenNoRoute()); - - Map<String, Object> clientProperties = new HashMap<String, Object>(); - clientProperties.put(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE, Boolean.FALSE); - engine.setClientProperties(FieldTable.convertToFieldTable(clientProperties)); - - assertFalse("Unexpected closeWhenNoRoute after client properties set", engine.isCloseWhenNoRoute()); - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AckTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AckTest.java deleted file mode 100644 index 406566cd4c..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AckTest.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - - -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.Set; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.MessageEnqueueRecord; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.store.TestMemoryMessageStore; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.test.utils.QpidTestCase; - -/** - * Tests that acknowledgements are handled correctly. - */ -public class AckTest extends QpidTestCase -{ - private ConsumerTarget_0_8 _subscriptionTarget; - private ConsumerImpl _consumer; - - private AMQProtocolEngine _protocolEngine; - - private TestMemoryMessageStore _messageStore; - - private AMQChannel _channel; - - private AMQQueue _queue; - - private static final AMQShortString DEFAULT_CONSUMER_TAG = new AMQShortString("conTag"); - private VirtualHostImpl _virtualHost; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _channel = BrokerTestHelper_0_8.createChannel(5); - _protocolEngine = _channel.getConnection(); - _virtualHost = _protocolEngine.getVirtualHost(); - _queue = BrokerTestHelper.createQueue(getTestName(), _virtualHost); - _messageStore = (TestMemoryMessageStore)_virtualHost.getMessageStore(); - } - - @Override - protected void tearDown() throws Exception - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - - private void publishMessages(int count) throws AMQException - { - publishMessages(count, false); - } - - private void publishMessages(int count, boolean persistent) throws AMQException - { - for (int i = 1; i <= count; i++) - { - MessagePublishInfo publishBody = new MessagePublishInfo(new AMQShortString("someExchange"), false, false, - new AMQShortString("rk")); - BasicContentHeaderProperties b = new BasicContentHeaderProperties(); - ContentHeaderBody cb = new ContentHeaderBody(b); - - if (persistent) - { - //This is DeliveryMode.PERSISTENT - b.setDeliveryMode((byte) 2); - } - - // The test is easier to construct if we have direct access to the subscription - ArrayList<AMQQueue> qs = new ArrayList<AMQQueue>(); - qs.add(_queue); - - final MessageMetaData mmd = new MessageMetaData(publishBody,cb, System.currentTimeMillis()); - - final StoredMessage<MessageMetaData> result =_messageStore.addMessage(mmd).allContentAdded(); - - final StoredMessage storedMessage = result; - final AMQMessage message = new AMQMessage(storedMessage); - ServerTransaction txn = new AutoCommitTransaction(_messageStore); - txn.enqueue(_queue, message, - new ServerTransaction.EnqueueAction() - { - public void postCommit(MessageEnqueueRecord... records) - { - _queue.enqueue(message,null, null); - } - - public void onRollback() - { - } - }); - - } - try - { - Thread.sleep(2000L); - } - catch (InterruptedException e) - { - Thread.currentThread().interrupt(); - } - - } - - /** - * Tests that the acknowledgements are correctly associated with a channel and - * order is preserved when acks are enabled - */ - public void testAckChannelAssociationTest() throws Exception - { - _subscriptionTarget = ConsumerTarget_0_8.createAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - final int msgCount = 10; - publishMessages(msgCount, true); - UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap(); - assertEquals("Unexpected size for unacknowledged message map",msgCount,map.size()); - - Set<Long> deliveryTagSet = map.getDeliveryTags(); - int i = 1; - for (long deliveryTag : deliveryTagSet) - { - assertTrue(deliveryTag == i); - i++; - MessageInstance unackedMsg = map.get(deliveryTag); - assertTrue(unackedMsg.getOwningResource() == _queue); - } - - } - - /** - * Tests that in no-ack mode no messages are retained - */ - public void testNoAckMode() throws Exception - { - // false arg means no acks expected - _subscriptionTarget = ConsumerTarget_0_8.createNoAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, - null, - AMQMessage.class, - DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - final int msgCount = 10; - publishMessages(msgCount); - UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap(); - assertTrue(map.size() == 0); - assertTrue(_messageStore.getMessageCount() == 0); - - - } - - /** - * Tests that in no-ack mode no messages are retained - */ - public void testPersistentNoAckMode() throws Exception - { - // false arg means no acks expected - - _subscriptionTarget = ConsumerTarget_0_8.createNoAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, ConsumerImpl.Option.ACQUIRES)); - final int msgCount = 10; - publishMessages(msgCount, true); - - UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap(); - assertTrue(map.size() == 0); - assertTrue(_messageStore.getMessageCount() == 0); - - - } - - /** - * Tests that a single acknowledgement is handled correctly (i.e multiple flag not - * set case) - */ - public void testSingleAckReceivedTest() throws Exception - { - - _subscriptionTarget = ConsumerTarget_0_8.createAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - - final int msgCount = 10; - publishMessages(msgCount); - - _channel.acknowledgeMessage(5, false); - UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap(); - assertEquals("Map not expected size",msgCount - 1,map.size()); - - Set<Long> deliveryTagSet = map.getDeliveryTags(); - int i = 1; - for (long deliveryTag : deliveryTagSet) - { - assertTrue(deliveryTag == i); - MessageInstance unackedMsg = map.get(deliveryTag); - assertTrue(unackedMsg.getOwningResource() == _queue); - // 5 is the delivery tag of the message that *should* be removed - if (++i == 5) - { - ++i; - } - } - } - - /** - * Tests that a single acknowledgement is handled correctly (i.e multiple flag not - * set case) - */ - public void testMultiAckReceivedTest() throws Exception - { - - _subscriptionTarget = ConsumerTarget_0_8.createAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - - final int msgCount = 10; - publishMessages(msgCount); - - - - _channel.acknowledgeMessage(5, true); - UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap(); - assertTrue(map.size() == 5); - - Set<Long> deliveryTagSet = map.getDeliveryTags(); - int i = 1; - for (long deliveryTag : deliveryTagSet) - { - assertTrue(deliveryTag == i + 5); - MessageInstance unackedMsg = map.get(deliveryTag); - assertTrue(unackedMsg.getOwningResource() == _queue); - ++i; - } - } - - /** - * Tests that a multiple acknowledgement is handled correctly. When ack'ing all pending msgs. - */ - public void testMultiAckAllReceivedTest() throws Exception - { - - _subscriptionTarget = ConsumerTarget_0_8.createAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - - final int msgCount = 10; - publishMessages(msgCount); - - _channel.acknowledgeMessage(0, true); - UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap(); - assertTrue(map.size() == 0); - - Set<Long> deliveryTagSet = map.getDeliveryTags(); - int i = 1; - for (long deliveryTag : deliveryTagSet) - { - assertTrue(deliveryTag == i + 5); - MessageInstance unackedMsg = map.get(deliveryTag); - assertTrue(unackedMsg.getOwningResource() == _queue); - ++i; - } - } - - /** - * A regression fixing QPID-1136 showed this up - * - * @throws Exception - */ - public void testMessageDequeueRestoresCreditTest() throws Exception - { - // Send 10 messages - Pre0_10CreditManager creditManager = new Pre0_10CreditManager(0l, 1, _protocolEngine); - - - _subscriptionTarget = ConsumerTarget_0_8.createAckTarget(_channel, DEFAULT_CONSUMER_TAG, null, creditManager); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - - final int msgCount = 1; - publishMessages(msgCount); - - _consumer.externalStateChange(); - - _channel.acknowledgeMessage(1, false); - - // Check credit available - assertTrue("No credit available", creditManager.hasCredit()); - - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(AckTest.class); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AcknowledgeTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AcknowledgeTest.java deleted file mode 100644 index 7dd4734e6b..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AcknowledgeTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.util.Collections; -import java.util.List; - -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.MessageCounter; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.test.utils.QpidTestCase; - -public class AcknowledgeTest extends QpidTestCase -{ - private AMQChannel _channel; - private AMQQueue _queue; - private MessageStore _messageStore; - private String _queueName; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _channel = BrokerTestHelper_0_8.createChannel(); - VirtualHostImpl virtualHost = _channel.getVirtualHost(); - _queueName = getTestName(); - _queue = BrokerTestHelper.createQueue(_queueName, virtualHost); - _messageStore = virtualHost.getMessageStore(); - } - - @Override - public void tearDown() throws Exception - { - try - { - if (_channel != null) - { - _channel.getVirtualHost().close(); - } - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - private AMQChannel getChannel() - { - return _channel; - } - - private InternalTestProtocolSession getSession() - { - return (InternalTestProtocolSession)_channel.getConnection(); - } - - private AMQQueue getQueue() - { - return _queue; - } - - public void testTransactionalSingleAck() throws Exception - { - getChannel().setLocalTransactional(); - runMessageAck(1, 1, 1, false, 0); - } - - public void testTransactionalMultiAck() throws Exception - { - getChannel().setLocalTransactional(); - runMessageAck(10, 1, 5, true, 5); - } - - public void testTransactionalAckAll() throws Exception - { - getChannel().setLocalTransactional(); - runMessageAck(10, 1, 0, true, 0); - } - - public void testNonTransactionalSingleAck() throws Exception - { - runMessageAck(1, 1, 1, false, 0); - } - - public void testNonTransactionalMultiAck() throws Exception - { - runMessageAck(10, 1, 5, true, 5); - } - - public void testNonTransactionalAckAll() throws Exception - { - runMessageAck(10, 1, 0, true, 0); - } - - protected void runMessageAck(int sendMessageCount, long firstDeliveryTag, long acknowledgeDeliveryTag, boolean acknowledgeMultiple, int remainingUnackedMessages) throws Exception - { - //Check store is empty - checkStoreContents(0); - - //Send required messages to the queue - BrokerTestHelper_0_8.publishMessages(getChannel(), - sendMessageCount, - _queueName, - ExchangeDefaults.DEFAULT_EXCHANGE_NAME); - - if (getChannel().isTransactional()) - { - getChannel().commit(null, false); - } - - //Ensure they are stored - checkStoreContents(sendMessageCount); - - //Check that there are no unacked messages - assertEquals("Channel should have no unacked msgs ", 0, getChannel().getUnacknowledgedMessageMap().size()); - - //Subscribe to the queue - AMQShortString subscriber = _channel.consumeFromSource(null, - Collections.<MessageSource>singleton(_queue), - true, null, true, false); - - getQueue().deliverAsync(); - - //Wait for the messages to be delivered - getSession().awaitDelivery(sendMessageCount); - - //Check that they are all waiting to be acknowledged - assertEquals("Channel should have unacked msgs", sendMessageCount, getChannel().getUnacknowledgedMessageMap().size()); - - List<InternalTestProtocolSession.DeliveryPair> messages = getSession().getDelivers(getChannel().getChannelId(), subscriber, sendMessageCount); - - //Double check we received the right number of messages - assertEquals(sendMessageCount, messages.size()); - - //Check that the first message has the expected deliveryTag - assertEquals("First message does not have expected deliveryTag", firstDeliveryTag, messages.get(0).getDeliveryTag()); - - //Send required Acknowledgement - getChannel().acknowledgeMessage(acknowledgeDeliveryTag, acknowledgeMultiple); - - if (getChannel().isTransactional()) - { - getChannel().commit(null, false); - } - - // Check Remaining Acknowledgements - assertEquals("Channel unacked msgs count incorrect", remainingUnackedMessages, getChannel().getUnacknowledgedMessageMap().size()); - - //Check store contents are also correct. - checkStoreContents(remainingUnackedMessages); - } - - private void checkStoreContents(int messageCount) - { - MessageCounter counter = new MessageCounter(); - _messageStore.newMessageStoreReader().visitMessages(counter); - assertEquals("Message header count incorrect in the MetaDataMap", messageCount, counter.getCount()); - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/BrokerTestHelper_0_8.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/BrokerTestHelper_0_8.java deleted file mode 100644 index a0a3d60458..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/BrokerTestHelper_0_8.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class BrokerTestHelper_0_8 extends BrokerTestHelper -{ - - public static AMQChannel createChannel(int channelId, AMQProtocolEngine session) throws AMQException - { - AMQChannel channel = new AMQChannel(session, channelId, session.getVirtualHost().getMessageStore()); - session.addChannel(channel); - return channel; - } - - public static AMQChannel createChannel(int channelId) throws Exception - { - InternalTestProtocolSession session = createProtocolSession(); - return createChannel(channelId, session); - } - - public static AMQChannel createChannel() throws Exception - { - return createChannel(1); - } - - public static InternalTestProtocolSession createProtocolSession() throws Exception - { - return createProtocolSession("test"); - } - - public static InternalTestProtocolSession createProtocolSession(String hostName) throws Exception - { - VirtualHostImpl virtualHost = createVirtualHost(hostName); - - AmqpPort port = mock(AmqpPort.class); - when(port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(AmqpPort.DEFAULT_MAX_MESSAGE_SIZE); - return new InternalTestProtocolSession(virtualHost, createBrokerMock(), port); - } - - public static void publishMessages(AMQChannel channel, int numberOfMessages, String queueName, String exchangeName) - throws AMQException - { - AMQShortString routingKey = new AMQShortString(queueName); - AMQShortString exchangeNameAsShortString = new AMQShortString(exchangeName); - MessagePublishInfo info = new MessagePublishInfo(exchangeNameAsShortString, false, false, routingKey); - - MessageDestination destination; - if(exchangeName == null || "".equals(exchangeName)) - { - destination = channel.getVirtualHost().getDefaultDestination(); - } - else - { - destination = channel.getVirtualHost().getExchange(exchangeName); - } - for (int count = 0; count < numberOfMessages; count++) - { - channel.setPublishFrame(info, destination); - - - // Set Minimum properties - BasicContentHeaderProperties properties = new BasicContentHeaderProperties(); - - - properties.setExpiration(0L); - properties.setTimestamp(System.currentTimeMillis()); - - // Make Message Persistent - properties.setDeliveryMode((byte) 2); - - ContentHeaderBody headerBody = new ContentHeaderBody(properties, 0); - - channel.publishContentHeader(headerBody); - } - channel.sync(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeueTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeueTest.java deleted file mode 100644 index 6d3e648369..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeueTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import junit.framework.TestCase; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueEntry; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.Map; - -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * QPID-1385 : Race condition between added to unacked map and resending due to a rollback. - * - * In AMQChannel _unackedMap.clear() was done after the visit. This meant that the clear was not in the same - * synchronized block as as the preparation to resend. - * - * This clearing/prep for resend was done as a result of the rollback call. HOWEVER, the delivery thread was still - * in the process of sending messages to the client. It is therefore possible that a message could block on the - * _unackedMap lock waiting for the visit to complete so that it can add the new message to the unackedMap.... - * which is then cleared by the resend/rollback thread. - * - * This problem was encountered by the testSend2ThenRollback test. - * - * To try and increase the chance of the race condition occurring this test will send multiple messages so that the - * delivery thread will be in progress while the rollback method is called. Hopefully this will cause the - * deliveryTag to be lost - */ -public class ExtractResendAndRequeueTest extends TestCase -{ - - private UnacknowledgedMessageMapImpl _unacknowledgedMessageMap; - private static final int INITIAL_MSG_COUNT = 10; - private AMQQueue _queue; - private LinkedList<MessageInstance> _referenceList = new LinkedList<MessageInstance>(); - private ConsumerImpl _consumer; - private boolean _queueDeleted; - - @Override - public void setUp() throws AMQException - { - _queueDeleted = false; - _unacknowledgedMessageMap = new UnacknowledgedMessageMapImpl(100); - _queue = mock(AMQQueue.class); - when(_queue.getName()).thenReturn(getName()); - when(_queue.isDeleted()).thenReturn(_queueDeleted); - _consumer = mock(ConsumerImpl.class); - when(_consumer.getConsumerNumber()).thenReturn(ConsumerImpl.CONSUMER_NUMBER_GENERATOR.getAndIncrement()); - - - long id = 0; - - // Add initial messages to QueueEntryList - for (int count = 0; count < INITIAL_MSG_COUNT; count++) - { - ServerMessage msg = mock(ServerMessage.class); - when(msg.getMessageNumber()).thenReturn(id); - final QueueEntry entry = mock(QueueEntry.class); - when(entry.getMessage()).thenReturn(msg); - when(entry.getQueue()).thenReturn(_queue); - when(entry.isQueueDeleted()).thenReturn(_queueDeleted); - doAnswer(new Answer() - { - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable - { - when(entry.isDeleted()).thenReturn(true); - return null; - } - }).when(entry).delete(); - - _unacknowledgedMessageMap.add(id, entry); - _referenceList.add(entry); - //Increment ID; - id++; - } - - assertEquals("Map does not contain correct setup data", INITIAL_MSG_COUNT, _unacknowledgedMessageMap.size()); - } - - /** - * Helper method to create a new subscription and acquire the given messages. - * - * @param messageList The messages to acquire - * - * @return Subscription that performed the acquire - */ - private void acquireMessages(LinkedList<MessageInstance> messageList) - { - - // Acquire messages in subscription - for(MessageInstance entry : messageList) - { - when(entry.getDeliveredConsumer()).thenReturn(_consumer); - } - } - - /** - * This is the normal consumer rollback method. - * - * An active consumer that has acquired messages expects those messages to be reset when rollback is requested. - * - * This test validates that the msgToResend map includes all the messages and none are left behind. - * - * @throws AMQException the visit interface throws this - */ - public void testResend() throws AMQException - { - //We don't need the subscription object here. - acquireMessages(_referenceList); - - final Map<Long, MessageInstance> msgToRequeue = new LinkedHashMap<Long, MessageInstance>(); - final Map<Long, MessageInstance> msgToResend = new LinkedHashMap<Long, MessageInstance>(); - - // requeueIfUnableToResend doesn't matter here. - _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue, - msgToResend)); - - assertEquals("Message count for resend not correct.", INITIAL_MSG_COUNT, msgToResend.size()); - assertEquals("Message count for requeue not correct.", 0, msgToRequeue.size()); - assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size()); - } - - /** - * This is the normal consumer close method. - * - * When a consumer that has acquired messages expects closes the messages that it has acquired should be removed from - * the unacknowledgedMap and placed in msgToRequeue - * - * This test validates that the msgToRequeue map includes all the messages and none are left behind. - * - * @throws AMQException the visit interface throws this - */ - public void testRequeueDueToSubscriptionClosure() throws AMQException - { - acquireMessages(_referenceList); - - // Close subscription - when(_consumer.isClosed()).thenReturn(true); - - final Map<Long, MessageInstance> msgToRequeue = new LinkedHashMap<Long, MessageInstance>(); - final Map<Long, MessageInstance> msgToResend = new LinkedHashMap<Long, MessageInstance>(); - - // requeueIfUnableToResend doesn't matter here. - _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue, - msgToResend)); - - assertEquals("Message count for resend not correct.", 0, msgToResend.size()); - assertEquals("Message count for requeue not correct.", INITIAL_MSG_COUNT, msgToRequeue.size()); - assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size()); - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/InternalTestProtocolSession.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/InternalTestProtocolSession.java deleted file mode 100644 index 7e68bee661..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/InternalTestProtocolSession.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.security.auth.UsernamePrincipal; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.network.NetworkConnection; - -public class InternalTestProtocolSession extends AMQProtocolEngine implements ProtocolOutputConverter -{ - private static final Logger _logger = LoggerFactory.getLogger(InternalTestProtocolSession.class); - // ChannelID(LIST) -> LinkedList<Pair> - private final Map<Integer, Map<String, LinkedList<DeliveryPair>>> _channelDelivers; - private AtomicInteger _deliveryCount = new AtomicInteger(0); - private static final AtomicLong ID_GENERATOR = new AtomicLong(0); - - public InternalTestProtocolSession(VirtualHostImpl virtualHost, Broker<?> broker, final AmqpPort<?> port) throws AMQException - { - super(broker, new TestNetworkConnection(), ID_GENERATOR.getAndIncrement(), port, null); - - _channelDelivers = new HashMap<Integer, Map<String, LinkedList<DeliveryPair>>>(); - - setTestAuthorizedSubject(); - setVirtualHost(virtualHost); - } - - private void setTestAuthorizedSubject() - { - Principal principal = new AuthenticatedPrincipal(new UsernamePrincipal("InternalTestProtocolSession")); - Subject authorizedSubject = new Subject( - true, - Collections.singleton(principal), - Collections.emptySet(), - Collections.emptySet()); - - setAuthorizedSubject(authorizedSubject); - } - - public ProtocolOutputConverter getProtocolOutputConverter() - { - return this; - } - - public byte getProtocolMajorVersion() - { - return (byte) 8; - } - - public void writeReturn(MessagePublishInfo messagePublishInfo, - ContentHeaderBody header, - MessageContentSource msgContent, - int channelId, - int replyCode, - AMQShortString replyText) - { - //To change body of implemented methods use File | Settings | File Templates. - } - - public byte getProtocolMinorVersion() - { - return (byte) 0; - } - - // *** - - public List<DeliveryPair> getDelivers(int channelId, AMQShortString consumerTag, int count) - { - synchronized (_channelDelivers) - { - List<DeliveryPair> all =_channelDelivers.get(channelId).get(AMQShortString.toString(consumerTag)); - - if (all == null) - { - return new ArrayList<DeliveryPair>(0); - } - - List<DeliveryPair> msgs = all.subList(0, count); - - List<DeliveryPair> response = new ArrayList<DeliveryPair>(msgs); - - //Remove the msgs from the receivedList. - msgs.clear(); - - return response; - } - } - - public ClientDeliveryMethod createDeliveryMethod(int channelId) - { - return new InternalWriteDeliverMethod(channelId); - } - - public void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag) - { - } - - public long writeDeliver(final ServerMessage msg, - final InstanceProperties props, int channelId, - long deliveryTag, - AMQShortString consumerTag) - { - _deliveryCount.incrementAndGet(); - long size = msg.getSize(); - synchronized (_channelDelivers) - { - Map<String, LinkedList<DeliveryPair>> consumers = _channelDelivers.get(channelId); - - if (consumers == null) - { - consumers = new HashMap<String, LinkedList<DeliveryPair>>(); - _channelDelivers.put(channelId, consumers); - } - - LinkedList<DeliveryPair> consumerDelivers = consumers.get(AMQShortString.toString(consumerTag)); - - if (consumerDelivers == null) - { - consumerDelivers = new LinkedList<DeliveryPair>(); - consumers.put(consumerTag.toString(), consumerDelivers); - } - - consumerDelivers.add(new DeliveryPair(deliveryTag, msg)); - } - return size; - } - - public long writeGetOk(final ServerMessage msg, - final InstanceProperties props, - int channelId, - long deliveryTag, - int queueSize) - { - return msg.getSize(); - } - - public void awaitDelivery(int msgs) - { - while (msgs > _deliveryCount.get()) - { - try - { - Thread.sleep(100); - } - catch (InterruptedException e) - { - _logger.error("Thread interrupted", e); - } - } - } - - public class DeliveryPair - { - private long _deliveryTag; - private ServerMessage _message; - - public DeliveryPair(long deliveryTag, ServerMessage message) - { - _deliveryTag = deliveryTag; - _message = message; - } - - public ServerMessage getMessage() - { - return _message; - } - - public long getDeliveryTag() - { - return _deliveryTag; - } - } - - public void closeNetworkConnection() - { - // Override as we don't have a real IOSession to close. - // The alternative is to fully implement the TestIOSession to return a CloseFuture from close(); - // Then the AMQMinaProtocolSession can join on the returning future without a NPE. - } - - private class InternalWriteDeliverMethod implements ClientDeliveryMethod - { - private int _channelId; - - public InternalWriteDeliverMethod(int channelId) - { - _channelId = channelId; - } - - - @Override - public long deliverToClient(ConsumerImpl sub, ServerMessage message, - InstanceProperties props, long deliveryTag) - { - _deliveryCount.incrementAndGet(); - long size = message.getSize(); - synchronized (_channelDelivers) - { - Map<String, LinkedList<DeliveryPair>> consumers = _channelDelivers.get(_channelId); - - if (consumers == null) - { - consumers = new HashMap<String, LinkedList<DeliveryPair>>(); - _channelDelivers.put(_channelId, consumers); - } - - LinkedList<DeliveryPair> consumerDelivers = consumers.get(sub.getName()); - - if (consumerDelivers == null) - { - consumerDelivers = new LinkedList<DeliveryPair>(); - consumers.put(sub.getName(), consumerDelivers); - } - - consumerDelivers.add(new DeliveryPair(deliveryTag, message)); - } - return size; - } - } - - void assertState(final ConnectionState requiredState) - { - // no-op - } - - - private static final AtomicInteger portNumber = new AtomicInteger(0); - - private static class TestNetworkConnection implements NetworkConnection - { - private String _remoteHost = "127.0.0.1"; - private String _localHost = "127.0.0.1"; - private int _port = portNumber.incrementAndGet(); - private final ByteBufferSender _sender; - - public TestNetworkConnection() - { - _sender = new ByteBufferSender() - { - public void send(ByteBuffer msg) - { - } - - public void flush() - { - } - - public void close() - { - } - }; - } - - @Override - public SocketAddress getLocalAddress() - { - return new InetSocketAddress(_localHost, _port); - } - - @Override - public SocketAddress getRemoteAddress() - { - return new InetSocketAddress(_remoteHost, _port); - } - - @Override - public void setMaxReadIdle(int idleTime) - { - } - - @Override - public Principal getPeerPrincipal() - { - return null; - } - - @Override - public int getMaxReadIdle() - { - return 0; - } - - @Override - public int getMaxWriteIdle() - { - return 0; - } - - @Override - public void setMaxWriteIdle(int idleTime) - { - } - - @Override - public void close() - { - } - - @Override - public ByteBufferSender getSender() - { - return _sender; - } - - @Override - public void start() - { - } - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/LimitlessCreditManager.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/LimitlessCreditManager.java deleted file mode 100644 index c4c89ac24a..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/LimitlessCreditManager.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.protocol.v0_8; - - -import org.apache.qpid.server.flow.AbstractFlowCreditManager; -import org.apache.qpid.server.flow.FlowCreditManager; - -public class LimitlessCreditManager extends AbstractFlowCreditManager implements FlowCreditManager -{ - - public void restoreCredit(long messageCredit, long bytesCredit) - { - } - - public void removeAllCredit() - { - } - - public boolean hasCredit() - { - return true; - } - - public boolean useCreditForMessage(long msgSize) - { - return true; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MaxChannelsTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MaxChannelsTest.java deleted file mode 100644 index 459fc94484..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MaxChannelsTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.test.utils.QpidTestCase; - -public class MaxChannelsTest extends QpidTestCase -{ - private AMQProtocolEngine _session; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _session = BrokerTestHelper_0_8.createProtocolSession(); - } - - public void testChannels() throws Exception - { - // check the channel count is correct - int channelCount = _session.getChannels().size(); - assertEquals("Initial channel count wrong", 0, channelCount); - - long maxChannels = 10L; - _session.setMaximumNumberOfChannels(maxChannels); - assertEquals("Number of channels not correctly set.", maxChannels, _session.getMaximumNumberOfChannels()); - - for (long currentChannel = 1L; currentChannel <= maxChannels; currentChannel++) - { - _session.receiveChannelOpen( (int) currentChannel); - } - assertFalse("Connection should not be closed after opening " + maxChannels + " channels",_session.isClosed()); - assertEquals("Maximum number of channels not set.", maxChannels, _session.getChannels().size()); - _session.receiveChannelOpen((int) maxChannels+1); - assertTrue("Connection should be closed after opening " + (maxChannels + 1) + " channels",_session.isClosed()); - } - - @Override - public void tearDown() throws Exception - { - try - { - _session.getVirtualHost().close(); - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockAMQMessage.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockAMQMessage.java deleted file mode 100644 index 1cc3607298..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockAMQMessage.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -public class MockAMQMessage extends AMQMessage -{ - public MockAMQMessage(long messageId) - { - super(new MockStoredMessage(messageId)); - } - - public MockAMQMessage(long messageId, String headerName, Object headerValue) - { - super(new MockStoredMessage(messageId, headerName, headerValue)); - } - - @Override - public long getSize() - { - return 0l; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockStoredMessage.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockStoredMessage.java deleted file mode 100755 index c6aea39aa6..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockStoredMessage.java +++ /dev/null @@ -1,127 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.protocol.v0_8; - -import java.nio.ByteBuffer; - -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.store.MessageHandle; -import org.apache.qpid.server.store.StoredMessage; - -public class MockStoredMessage implements StoredMessage<MessageMetaData>, MessageHandle<MessageMetaData> -{ - private long _messageId; - private MessageMetaData _metaData; - private final ByteBuffer _content; - - public MockStoredMessage(long messageId) - { - this(messageId, (String)null, null); - } - - public MockStoredMessage(long messageId, String headerName, Object headerValue) - { - this(messageId, new MessagePublishInfo(null, false, false, null), new ContentHeaderBody(new BasicContentHeaderProperties()), headerName, headerValue); - } - - public MockStoredMessage(long messageId, MessagePublishInfo info, ContentHeaderBody chb) - { - this(messageId, info, chb, null, null); - } - - public MockStoredMessage(long messageId, MessagePublishInfo info, ContentHeaderBody chb, String headerName, Object headerValue) - { - _messageId = messageId; - if (headerName != null) - { - FieldTable headers = new FieldTable(); - headers.setString(headerName, headerValue == null? null :String.valueOf(headerValue)); - ( chb.getProperties()).setHeaders(headers); - } - _metaData = new MessageMetaData(info, chb); - _content = ByteBuffer.allocate(_metaData.getContentSize()); - } - - public MessageMetaData getMetaData() - { - return _metaData; - } - - public long getMessageNumber() - { - return _messageId; - } - - public void addContent(ByteBuffer src) - { - src = src.duplicate(); - _content.put(src); - } - - @Override - public StoredMessage<MessageMetaData> allContentAdded() - { - _content.flip(); - return this; - } - - public int getContent(int offset, ByteBuffer dst) - { - ByteBuffer src = _content.duplicate(); - src.position(offset); - src = src.slice(); - if(dst.remaining() < src.limit()) - { - src.limit(dst.remaining()); - } - dst.put(src); - return src.limit(); - } - - - - public ByteBuffer getContent(int offsetInMessage, int size) - { - ByteBuffer buf = ByteBuffer.allocate(size); - getContent(offsetInMessage, buf); - buf.position(0); - return buf; - } - - public void remove() - { - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/QueueBrowserUsesNoAckTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/QueueBrowserUsesNoAckTest.java deleted file mode 100644 index 264350ff8d..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/QueueBrowserUsesNoAckTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.util.Collections; -import java.util.List; - -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.MessageCounter; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.test.utils.QpidTestCase; - -public class QueueBrowserUsesNoAckTest extends QpidTestCase -{ - private AMQChannel _channel; - private AMQQueue _queue; - private MessageStore _messageStore; - private String _queueName; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _channel = BrokerTestHelper_0_8.createChannel(); - VirtualHostImpl virtualHost = _channel.getVirtualHost(); - _queueName = getTestName(); - _queue = BrokerTestHelper.createQueue(_queueName, virtualHost); - _messageStore = virtualHost.getMessageStore(); - } - - @Override - public void tearDown() throws Exception - { - try - { - if (_channel != null) - { - _channel.getVirtualHost().close(); - } - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - private AMQChannel getChannel() - { - return _channel; - } - - private InternalTestProtocolSession getSession() - { - return (InternalTestProtocolSession)_channel.getConnection(); - } - - private AMQQueue getQueue() - { - return _queue; - } - - public void testQueueBrowserUsesNoAck() throws Exception - { - int sendMessageCount = 2; - int prefetch = 1; - - //Check store is empty - checkStoreContents(0); - - //Send required messages to the queue - BrokerTestHelper_0_8.publishMessages(getChannel(), - sendMessageCount, - _queueName, - ExchangeDefaults.DEFAULT_EXCHANGE_NAME); - - //Ensure they are stored - checkStoreContents(sendMessageCount); - - //Check that there are no unacked messages - assertEquals("Channel should have no unacked msgs ", 0, - getChannel().getUnacknowledgedMessageMap().size()); - - //Set the prefetch on the session to be less than the sent messages - getChannel().setCredit(0, prefetch); - - //browse the queue - AMQShortString browser = browse(getChannel(), getQueue()); - - getQueue().deliverAsync(); - - //Wait for messages to fill the prefetch - getSession().awaitDelivery(prefetch); - - //Get those messages - List<InternalTestProtocolSession.DeliveryPair> messages = - getSession().getDelivers(getChannel().getChannelId(), browser, - prefetch); - - //Ensure we received the prefetched messages - assertEquals(prefetch, messages.size()); - - //Check the process didn't suspend the subscription as this would - // indicate we are using the prefetch credit. i.e. using acks not No-Ack - assertTrue("The subscription has been suspended", - !getChannel().getSubscription(browser).isSuspended()); - } - - private void checkStoreContents(int messageCount) - { - MessageCounter counter = new MessageCounter(); - _messageStore.newMessageStoreReader().visitMessages(counter); - - assertEquals("Message header count incorrect in the MetaDataMap", messageCount, counter.getCount()); - } - - private AMQShortString browse(AMQChannel channel, AMQQueue queue) throws Exception - { - FieldTable filters = new FieldTable(); - filters.put(AMQPFilterTypes.NO_CONSUME.getValue(), true); - - return channel.consumeFromSource(null, Collections.<MessageSource>singleton(queue), true, filters, true, false); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ReferenceCountingTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ReferenceCountingTest.java deleted file mode 100644 index de3b68a0bc..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ReferenceCountingTest.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import java.util.UUID; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.EnqueueableMessage; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.store.MessageCounter; -import org.apache.qpid.server.store.MessageDurability; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.store.TestMemoryMessageStore; -import org.apache.qpid.server.store.Transaction; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.test.utils.QpidTestCase; - -/** - * Tests that reference counting works correctly with AMQMessage and the message store - */ -public class ReferenceCountingTest extends QpidTestCase -{ - private TestMemoryMessageStore _store; - - - protected void setUp() throws Exception - { - _store = new TestMemoryMessageStore(); - } - - /** - * Check that when the reference count is decremented the message removes itself from the store - */ - public void testMessageGetsRemoved() throws AMQException - { - ContentHeaderBody chb = createPersistentContentHeader(); - - MessagePublishInfo info = new MessagePublishInfo(null, false, false, null); - - final MessageMetaData mmd = new MessageMetaData(info, chb); - - StoredMessage storedMessage = _store.addMessage(mmd).allContentAdded(); - Transaction txn = _store.newTransaction(); - txn.enqueueMessage(createTransactionLogResource("dummyQ"), createEnqueueableMessage(storedMessage)); - txn.commitTran(); - AMQMessage message = new AMQMessage(storedMessage); - - MessageReference ref = message.newReference(); - - assertEquals(1, getStoreMessageCount()); - - ref.release(); - - assertEquals(0, getStoreMessageCount()); - } - - private int getStoreMessageCount() - { - MessageCounter counter = new MessageCounter(); - _store.newMessageStoreReader().visitMessages(counter); - return counter.getCount(); - } - - private ContentHeaderBody createPersistentContentHeader() - { - BasicContentHeaderProperties bchp = new BasicContentHeaderProperties(); - bchp.setDeliveryMode((byte)2); - ContentHeaderBody chb = new ContentHeaderBody(bchp); - return chb; - } - - public void testMessageRemains() throws AMQException - { - - MessagePublishInfo info = new MessagePublishInfo(null, false, false, null); - - final ContentHeaderBody chb = createPersistentContentHeader(); - - final MessageMetaData mmd = new MessageMetaData(info, chb); - - StoredMessage storedMessage = _store.addMessage(mmd).allContentAdded(); - Transaction txn = _store.newTransaction(); - txn.enqueueMessage(createTransactionLogResource("dummyQ"), createEnqueueableMessage(storedMessage)); - txn.commitTran(); - AMQMessage message = new AMQMessage(storedMessage); - - - MessageReference ref = message.newReference(); - - assertEquals(1, getStoreMessageCount()); - MessageReference ref2 = message.newReference(); - ref.release(); - assertEquals(1, getStoreMessageCount()); - } - - private TransactionLogResource createTransactionLogResource(final String queueName) - { - return new TransactionLogResource() - { - @Override - public String getName() - { - return queueName; - } - - @Override - public UUID getId() - { - return UUID.nameUUIDFromBytes(queueName.getBytes()); - } - - @Override - public MessageDurability getMessageDurability() - { - return MessageDurability.DEFAULT; - } - }; - } - - private EnqueueableMessage createEnqueueableMessage(final StoredMessage storedMessage) - { - return new EnqueueableMessage() - { - @Override - public long getMessageNumber() - { - return storedMessage.getMessageNumber(); - } - - @Override - public boolean isPersistent() - { - return true; - } - - @Override - public StoredMessage getStoredMessage() - { - return storedMessage; - } - }; - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(ReferenceCountingTest.class); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapTest.java deleted file mode 100644 index ca52173e66..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v0_8; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Collection; - -import junit.framework.TestCase; - -import org.apache.qpid.server.message.MessageInstance; - -public class UnacknowledgedMessageMapTest extends TestCase -{ - public void testDeletedMessagesCantBeAcknowledged() - { - UnacknowledgedMessageMap map = new UnacknowledgedMessageMapImpl(100); - final int expectedSize = 5; - MessageInstance[] msgs = populateMap(map,expectedSize); - assertEquals(expectedSize,map.size()); - Collection<MessageInstance> acknowledged = map.acknowledge(100, true); - assertEquals(expectedSize, acknowledged.size()); - assertEquals(0,map.size()); - for(int i = 0; i < expectedSize; i++) - { - assertTrue("Message " + i + " is missing", acknowledged.contains(msgs[i])); - } - - map = new UnacknowledgedMessageMapImpl(100); - msgs = populateMap(map,expectedSize); - // simulate some messages being ttl expired - when(msgs[2].lockAcquisition()).thenReturn(Boolean.FALSE); - when(msgs[4].lockAcquisition()).thenReturn(Boolean.FALSE); - - assertEquals(expectedSize,map.size()); - - - acknowledged = map.acknowledge(100, true); - assertEquals(expectedSize-2, acknowledged.size()); - assertEquals(0,map.size()); - for(int i = 0; i < expectedSize; i++) - { - assertEquals(i != 2 && i != 4, acknowledged.contains(msgs[i])); - } - - } - - public MessageInstance[] populateMap(final UnacknowledgedMessageMap map, int size) - { - MessageInstance[] msgs = new MessageInstance[size]; - for(int i = 0; i < size; i++) - { - msgs[i] = createMessageInstance(i); - map.add((long)i,msgs[i]); - } - return msgs; - } - - private MessageInstance createMessageInstance(final int id) - { - MessageInstance instance = mock(MessageInstance.class); - when(instance.lockAcquisition()).thenReturn(Boolean.TRUE); - return instance; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/pom.xml b/qpid/java/broker-plugins/amqp-1-0-protocol/pom.xml deleted file mode 100644 index 7242cb122a..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-amqp-1-0-protocol</artifactId> - <name>Qpid AMQP 1-0 Protocol Broker Plug-in</name> - <description>AMQP 1-0 protocol broker plug-in</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-amqp-1-0-common</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <version>${log4j-version}</version> - </dependency> - - </dependencies> - - <build> - </build> - -</project> diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Connection_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Connection_1_0.java deleted file mode 100644 index d1254cb289..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Connection_1_0.java +++ /dev/null @@ -1,553 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CONNECTION_FORMAT; - -import java.net.SocketAddress; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.security.auth.Subject; - -import org.apache.qpid.amqp_1_0.transport.ConnectionEndpoint; -import org.apache.qpid.amqp_1_0.transport.ConnectionEventListener; -import org.apache.qpid.amqp_1_0.transport.LinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.SessionEndpoint; -import org.apache.qpid.amqp_1_0.transport.SessionEventListener; -import org.apache.qpid.amqp_1_0.type.transport.AmqpError; -import org.apache.qpid.amqp_1_0.type.transport.End; -import org.apache.qpid.amqp_1_0.type.transport.Error; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.protocol.SessionModelListener; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.stats.StatisticsCounter; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class Connection_1_0 implements ConnectionEventListener, AMQConnectionModel<Connection_1_0,Session_1_0> -{ - - private final AmqpPort<?> _port; - private final Broker<?> _broker; - private final SubjectCreator _subjectCreator; - private final ProtocolEngine_1_0_0_SASL _protocolEngine; - private VirtualHostImpl _vhost; - private final Transport _transport; - private final ConnectionEndpoint _conn; - private final long _connectionId; - private final Collection<Session_1_0> _sessions = Collections.synchronizedCollection(new ArrayList<Session_1_0>()); - private final Object _reference = new Object(); - private final Subject _subject = new Subject(); - - private final CopyOnWriteArrayList<SessionModelListener> _sessionListeners = - new CopyOnWriteArrayList<SessionModelListener>(); - - private final StatisticsCounter _messageDeliveryStatistics, _messageReceiptStatistics, _dataDeliveryStatistics, _dataReceiptStatistics; - - private final LogSubject _logSubject = new LogSubject() - { - @Override - public String toLogString() - { - return "[" + - MessageFormat.format(CONNECTION_FORMAT, - getConnectionId(), - getClientId(), - getRemoteAddressString(), - _vhost.getName()) - + "] "; - - } - }; - - private volatile boolean _stopped; - - - private List<Action<? super Connection_1_0>> _closeTasks = - Collections.synchronizedList(new ArrayList<Action<? super Connection_1_0>>()); - - private final Queue<Action<? super Connection_1_0>> _asyncTaskList = - new ConcurrentLinkedQueue<>(); - - - private boolean _closedOnOpen; - - - - public Connection_1_0(Broker<?> broker, - ConnectionEndpoint conn, - long connectionId, - AmqpPort<?> port, - Transport transport, - final SubjectCreator subjectCreator, - final ProtocolEngine_1_0_0_SASL protocolEngine) - { - _protocolEngine = protocolEngine; - _broker = broker; - _port = port; - _transport = transport; - _conn = conn; - _connectionId = connectionId; - _subject.getPrincipals().add(new ConnectionPrincipal(this)); - _subjectCreator = subjectCreator; - _messageDeliveryStatistics = new StatisticsCounter("messages-delivered-" + getConnectionId()); - _dataDeliveryStatistics = new StatisticsCounter("data-delivered-" + getConnectionId()); - _messageReceiptStatistics = new StatisticsCounter("messages-received-" + getConnectionId()); - _dataReceiptStatistics = new StatisticsCounter("data-received-" + getConnectionId()); - } - - public Object getReference() - { - return _reference; - } - - @Override - public void openReceived() - { - String host = _conn.getLocalHostname(); - _vhost = ((AmqpPort)_port).getVirtualHost(host); - if(_vhost == null) - { - final Error err = new Error(); - err.setCondition(AmqpError.NOT_FOUND); - err.setDescription("Unknown hostname in connection open: '" + host + "'"); - _conn.close(err); - _closedOnOpen = true; - } - else - { - _vhost.getConnectionRegistry().registerConnection(this); - Subject authSubject = _subjectCreator.createSubjectWithGroups(_conn.getUser()); - _subject.getPrincipals().addAll(authSubject.getPrincipals()); - _subject.getPublicCredentials().addAll(authSubject.getPublicCredentials()); - _subject.getPrivateCredentials().addAll(authSubject.getPrivateCredentials()); - } - } - public void remoteSessionCreation(SessionEndpoint endpoint) - { - if(!_closedOnOpen) - { - final Session_1_0 session = new Session_1_0(this, endpoint); - _sessions.add(session); - sessionAdded(session); - endpoint.setSessionEventListener(new SessionEventListener() - { - @Override - public void remoteLinkCreation(final LinkEndpoint endpoint) - { - Subject.doAs(session.getSubject(), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - session.remoteLinkCreation(endpoint); - return null; - } - }); - } - - @Override - public void remoteEnd(final End end) - { - Subject.doAs(session.getSubject(), new PrivilegedAction<Object>() - { - @Override - public Object run() - { - session.remoteEnd(end); - return null; - } - }); - } - }); - } - } - - void sessionEnded(Session_1_0 session) - { - if(!_closedOnOpen) - { - - _sessions.remove(session); - sessionRemoved(session); - } - } - - public void removeDeleteTask(final Action<? super Connection_1_0> task) - { - _closeTasks.remove( task ); - } - - public void addDeleteTask(final Action<? super Connection_1_0> task) - { - _closeTasks.add( task ); - } - - private void addAsyncTask(final Action<Connection_1_0> action) - { - _asyncTaskList.add(action); - notifyWork(); - } - - - public void closeReceived() - { - Collection<Session_1_0> sessions = new ArrayList(_sessions); - - for(Session_1_0 session : sessions) - { - session.remoteEnd(new End()); - } - - List<Action<? super Connection_1_0>> taskCopy; - - synchronized (_closeTasks) - { - taskCopy = new ArrayList<Action<? super Connection_1_0>>(_closeTasks); - } - for(Action<? super Connection_1_0> task : taskCopy) - { - task.performAction(this); - } - synchronized (_closeTasks) - { - _closeTasks.clear(); - } - if(_vhost != null) - { - _vhost.getConnectionRegistry().deregisterConnection(this); - } - - - } - - public void closed() - { - closeReceived(); - } - - - @Override - public void closeAsync(AMQConstant cause, String message) - { - Action<Connection_1_0> action = new Action<Connection_1_0>() - { - @Override - public void performAction(final Connection_1_0 object) - { - _conn.close(); - - } - }; - addAsyncTask(action); - - } - - @Override - public void block() - { - // TODO - } - - @Override - public void unblock() - { - // TODO - } - - @Override - public void closeSessionAsync(final Session_1_0 session, final AMQConstant cause, final String message) - { - addAsyncTask(new Action<Connection_1_0>() - { - @Override - public void performAction(final Connection_1_0 object) - { - session.close(cause, message); - } - }); - } - - @Override - public long getConnectionId() - { - return _connectionId; - } - - @Override - public List<Session_1_0> getSessionModels() - { - return new ArrayList<Session_1_0>(_sessions); - } - - @Override - public LogSubject getLogSubject() - { - return _logSubject; - } - - @Override - public String getRemoteAddressString() - { - return String.valueOf(_conn.getRemoteAddress()); - } - - public SocketAddress getRemoteAddress() - { - return _conn.getRemoteAddress(); - } - - @Override - public String getRemoteProcessPid() - { - return null; // TODO - } - - @Override - public String getClientId() - { - return _conn.getRemoteContainerId(); - } - - @Override - public String getRemoteContainerName() - { - return _conn.getRemoteContainerId(); - } - - @Override - public String getClientVersion() - { - return ""; //TODO - } - - @Override - public String getClientProduct() - { - return ""; //TODO - } - - public Principal getAuthorizedPrincipal() - { - Set<AuthenticatedPrincipal> authPrincipals = _subject.getPrincipals(AuthenticatedPrincipal.class); - return authPrincipals.isEmpty() ? null : authPrincipals.iterator().next(); - } - - @Override - public long getSessionCountLimit() - { - return 0; // TODO - } - - @Override - public long getLastIoTime() - { - return 0; // TODO - } - - @Override - public String getVirtualHostName() - { - return _vhost == null ? null : _vhost.getName(); - } - - @Override - public AmqpPort<?> getPort() - { - return _port; - } - - public ServerProtocolEngine getProtocolEngine() - { - return _protocolEngine; - } - - @Override - public Transport getTransport() - { - return _transport; - } - - @Override - public void stop() - { - _stopped = true; - } - - @Override - public boolean isStopped() - { - return _stopped; - } - - @Override - public void registerMessageReceived(long messageSize, long timestamp) - { - _messageReceiptStatistics.registerEvent(1L, timestamp); - _dataReceiptStatistics.registerEvent(messageSize, timestamp); - _vhost.registerMessageReceived(messageSize,timestamp); - - } - - @Override - public void registerMessageDelivered(long messageSize) - { - - _messageDeliveryStatistics.registerEvent(1L); - _dataDeliveryStatistics.registerEvent(messageSize); - _vhost.registerMessageDelivered(messageSize); - } - - @Override - public StatisticsCounter getMessageDeliveryStatistics() - { - return _messageDeliveryStatistics; - } - - @Override - public StatisticsCounter getMessageReceiptStatistics() - { - return _messageReceiptStatistics; - } - - @Override - public StatisticsCounter getDataDeliveryStatistics() - { - return _dataDeliveryStatistics; - } - - @Override - public StatisticsCounter getDataReceiptStatistics() - { - return _dataReceiptStatistics; - } - - @Override - public void resetStatistics() - { - _dataDeliveryStatistics.reset(); - _dataReceiptStatistics.reset(); - _messageDeliveryStatistics.reset(); - _messageReceiptStatistics.reset(); - } - - - - AMQConnectionModel getModel() - { - return this; - } - - - Subject getSubject() - { - return _subject; - } - - public VirtualHostImpl getVirtualHost() - { - return _vhost; - } - - - @Override - public void addSessionListener(final SessionModelListener listener) - { - _sessionListeners.add(listener); - } - - @Override - public void removeSessionListener(final SessionModelListener listener) - { - _sessionListeners.remove(listener); - } - - private void sessionAdded(final AMQSessionModel<?,?> session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionAdded(session); - } - } - - private void sessionRemoved(final AMQSessionModel<?,?> session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionRemoved(session); - } - } - - - public void transportStateChanged() - { - for (Session_1_0 session : _sessions) - { - session.transportStateChanged(); - } - } - - @Override - public void notifyWork() - { - _protocolEngine.notifyWork(); - } - - @Override - public boolean isMessageAssignmentSuspended() - { - return _protocolEngine.isMessageAssignmentSuspended(); - } - - public void processPending() - { - for (AMQSessionModel session : getSessionModels()) - { - session.processPending(); - } - - while(_asyncTaskList.peek() != null) - { - Action<? super Connection_1_0> asyncAction = _asyncTaskList.poll(); - asyncAction.performAction(this); - } - - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.java deleted file mode 100644 index 680c05ec0a..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.java +++ /dev/null @@ -1,550 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import java.nio.ByteBuffer; -import java.util.List; - -import org.apache.qpid.amqp_1_0.codec.ValueHandler; -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.messaging.SectionEncoderImpl; -import org.apache.qpid.amqp_1_0.transport.SendingLinkEndpoint; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.codec.AMQPDescribedTypeRegistry; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.amqp_1_0.type.messaging.Header; -import org.apache.qpid.amqp_1_0.type.messaging.Modified; -import org.apache.qpid.amqp_1_0.type.messaging.Released; -import org.apache.qpid.amqp_1_0.type.transaction.TransactionalState; -import org.apache.qpid.amqp_1_0.type.transport.SenderSettleMode; -import org.apache.qpid.amqp_1_0.type.transport.Transfer; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.consumer.AbstractConsumerTarget; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.LinkRegistry; -import org.apache.qpid.server.protocol.MessageConverterRegistry; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; - -class ConsumerTarget_1_0 extends AbstractConsumerTarget -{ - private final boolean _acquires; - private SendingLink_1_0 _link; - - private long _deliveryTag = 0L; - - private Binary _transactionId; - private final AMQPDescribedTypeRegistry _typeRegistry; - private final SectionEncoder _sectionEncoder; - private ConsumerImpl _consumer; - - public ConsumerTarget_1_0(final SendingLink_1_0 link, - boolean acquires) - { - super(State.SUSPENDED); - _link = link; - _typeRegistry = link.getEndpoint().getSession().getConnection().getDescribedTypeRegistry(); - _sectionEncoder = new SectionEncoderImpl(_typeRegistry); - _acquires = acquires; - } - - public ConsumerImpl getConsumer() - { - return _consumer; - } - - private SendingLinkEndpoint getEndpoint() - { - return _link.getEndpoint(); - } - - @Override - public boolean doIsSuspended() - { - return _link.getSession().getConnectionModel().isStopped() || getState() != State.ACTIVE; - - } - - public boolean close() - { - boolean closed = false; - State state = getState(); - - getSendLock(); - try - { - while(!closed && state != State.CLOSED) - { - closed = updateState(state, State.CLOSED); - if(!closed) - { - state = getState(); - } - } - return closed; - } - finally - { - releaseSendLock(); - } - } - - public void doSend(final ConsumerImpl consumer, final MessageInstance entry, boolean batch) - { - // TODO - ServerMessage serverMessage = entry.getMessage(); - Message_1_0 message; - if(serverMessage instanceof Message_1_0) - { - message = (Message_1_0) serverMessage; - } - else - { - final MessageConverter converter = MessageConverterRegistry.getConverter(serverMessage.getClass(), Message_1_0.class); - message = (Message_1_0) converter.convert(serverMessage, _link.getVirtualHost()); - } - - Transfer transfer = new Transfer(); - //TODO - - - List<ByteBuffer> fragments = message.getFragments(); - ByteBuffer payload; - if(fragments.size() == 1) - { - payload = fragments.get(0); - } - else - { - int size = 0; - for(ByteBuffer fragment : fragments) - { - size += fragment.remaining(); - } - - payload = ByteBuffer.allocate(size); - - for(ByteBuffer fragment : fragments) - { - payload.put(fragment.duplicate()); - } - - payload.flip(); - } - - if(entry.getDeliveryCount() != 0) - { - payload = payload.duplicate(); - ValueHandler valueHandler = new ValueHandler(_typeRegistry); - - Header oldHeader = null; - try - { - ByteBuffer encodedBuf = payload.duplicate(); - Object value = valueHandler.parse(payload); - if(value instanceof Header) - { - oldHeader = (Header) value; - } - else - { - payload.position(0); - } - } - catch (AmqpErrorException e) - { - //TODO - throw new ConnectionScopedRuntimeException(e); - } - - Header header = new Header(); - if(oldHeader != null) - { - header.setDurable(oldHeader.getDurable()); - header.setPriority(oldHeader.getPriority()); - header.setTtl(oldHeader.getTtl()); - } - header.setDeliveryCount(UnsignedInteger.valueOf(entry.getDeliveryCount())); - _sectionEncoder.reset(); - _sectionEncoder.encodeObject(header); - Binary encodedHeader = _sectionEncoder.getEncoding(); - - ByteBuffer oldPayload = payload; - payload = ByteBuffer.allocate(oldPayload.remaining() + encodedHeader.getLength()); - payload.put(encodedHeader.getArray(),encodedHeader.getArrayOffset(),encodedHeader.getLength()); - payload.put(oldPayload); - payload.flip(); - } - - transfer.setPayload(payload); - byte[] data = new byte[8]; - ByteBuffer.wrap(data).putLong(_deliveryTag++); - final Binary tag = new Binary(data); - - transfer.setDeliveryTag(tag); - - synchronized(_link.getLock()) - { - if(_link.isAttached()) - { - if(SenderSettleMode.SETTLED.equals(getEndpoint().getSendingSettlementMode())) - { - transfer.setSettled(true); - } - else - { - UnsettledAction action = _acquires - ? new DispositionAction(tag, entry) - : new DoNothingAction(tag, entry); - - _link.addUnsettled(tag, action, entry); - } - - if(_transactionId != null) - { - TransactionalState state = new TransactionalState(); - state.setTxnId(_transactionId); - transfer.setState(state); - } - // TODO - need to deal with failure here - if(_acquires && _transactionId != null) - { - ServerTransaction txn = _link.getTransaction(_transactionId); - if(txn != null) - { - txn.addPostTransactionAction(new ServerTransaction.Action(){ - - public void postCommit() - { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void onRollback() - { - if(entry.isAcquiredBy(getConsumer())) - { - entry.release(); - _link.getEndpoint().updateDisposition(tag, (DeliveryState)null, true); - - - } - } - }); - } - - } - getSession().getConnectionModel().registerMessageDelivered(message.getSize()); - getEndpoint().transfer(transfer); - } - else - { - entry.release(); - } - } - - } - - public void flushBatched() - { - // TODO - } - - public void queueDeleted() - { - //TODO - getEndpoint().setSource(null); - getEndpoint().close(); - - final LinkRegistry linkReg = getSession().getConnection() - .getVirtualHost() - .getLinkRegistry(getEndpoint().getSession().getConnection().getRemoteContainerId()); - linkReg.unregisterSendingLink(getEndpoint().getName()); - } - - public boolean allocateCredit(final ServerMessage msg) - { - synchronized (_link.getLock()) - { - - ServerProtocolEngine protocolEngine = getSession().getConnection().getProtocolEngine(); - final boolean hasCredit = _link.isAttached() && getEndpoint().hasCreditToSend() && !protocolEngine.isTransportBlockedForWriting(); - if(!hasCredit && getState() == State.ACTIVE) - { - suspend(); - } - - return hasCredit; - } - } - - - public void suspend() - { - synchronized(_link.getLock()) - { - updateState(State.ACTIVE, State.SUSPENDED); - } - } - - - public void restoreCredit(final ServerMessage message) - { - //TODO - } - - public void queueEmpty() - { - synchronized(_link.getLock()) - { - if(_link.drained()) - { - updateState(State.ACTIVE, State.SUSPENDED); - } - } - } - - public void flowStateChanged() - { - synchronized(_link.getLock()) - { - ServerProtocolEngine protocolEngine = getSession().getConnection().getProtocolEngine(); - if(isSuspended() && getEndpoint() != null && !protocolEngine.isTransportBlockedForWriting()) - { - updateState(State.SUSPENDED, State.ACTIVE); - _transactionId = _link.getTransactionId(); - } - } - } - - public Session_1_0 getSession() - { - return _link.getSession(); - } - - public void flush() - { - _consumer.flush(); - } - - private class DispositionAction implements UnsettledAction - { - - private final MessageInstance _queueEntry; - private final Binary _deliveryTag; - - public DispositionAction(Binary tag, MessageInstance queueEntry) - { - _deliveryTag = tag; - _queueEntry = queueEntry; - } - - public boolean process(DeliveryState state, final Boolean settled) - { - - Binary transactionId = null; - final Outcome outcome; - // If disposition is settled this overrides the txn? - if(state instanceof TransactionalState) - { - transactionId = ((TransactionalState)state).getTxnId(); - outcome = ((TransactionalState)state).getOutcome(); - } - else if (state instanceof Outcome) - { - outcome = (Outcome) state; - } - else - { - outcome = null; - } - - - ServerTransaction txn = _link.getTransaction(transactionId); - - if(outcome instanceof Accepted) - { - _queueEntry.lockAcquisition(); - txn.dequeue(_queueEntry.getEnqueueRecord(), - new ServerTransaction.Action() - { - - public void postCommit() - { - if(_queueEntry.isAcquiredBy(getConsumer())) - { - _queueEntry.delete(); - } - } - - public void onRollback() - { - - } - }); - txn.addPostTransactionAction(new ServerTransaction.Action() - { - public void postCommit() - { - //_link.getEndpoint().settle(_deliveryTag); - _link.getEndpoint().updateDisposition(_deliveryTag, (DeliveryState)outcome, true); - _link.getEndpoint().sendFlowConditional(); - } - - public void onRollback() - { - if(Boolean.TRUE.equals(settled)) - { - final Modified modified = new Modified(); - modified.setDeliveryFailed(true); - _link.getEndpoint().updateDisposition(_deliveryTag, modified, true); - _link.getEndpoint().sendFlowConditional(); - _queueEntry.incrementDeliveryCount(); - _queueEntry.release(); - } - } - }); - } - else if(outcome instanceof Released) - { - txn.addPostTransactionAction(new ServerTransaction.Action() - { - public void postCommit() - { - - _queueEntry.release(); - _link.getEndpoint().settle(_deliveryTag); - } - - public void onRollback() - { - _link.getEndpoint().settle(_deliveryTag); - } - }); - } - - else if(outcome instanceof Modified) - { - txn.addPostTransactionAction(new ServerTransaction.Action() - { - public void postCommit() - { - - _queueEntry.release(); - if(Boolean.TRUE.equals(((Modified)outcome).getDeliveryFailed())) - { - _queueEntry.incrementDeliveryCount(); - } - _link.getEndpoint().settle(_deliveryTag); - } - - public void onRollback() - { - if(Boolean.TRUE.equals(settled)) - { - final Modified modified = new Modified(); - modified.setDeliveryFailed(true); - _link.getEndpoint().updateDisposition(_deliveryTag, modified, true); - _link.getEndpoint().sendFlowConditional(); - } - } - }); - } - - return (transactionId == null && outcome != null); - } - } - - private class DoNothingAction implements UnsettledAction - { - public DoNothingAction(final Binary tag, - final MessageInstance queueEntry) - { - } - - public boolean process(final DeliveryState state, final Boolean settled) - { - Binary transactionId = null; - Outcome outcome = null; - // If disposition is settled this overrides the txn? - if(state instanceof TransactionalState) - { - transactionId = ((TransactionalState)state).getTxnId(); - outcome = ((TransactionalState)state).getOutcome(); - } - else if (state instanceof Outcome) - { - outcome = (Outcome) state; - } - return true; - } - } - - @Override - public AMQSessionModel getSessionModel() - { - return getSession(); - } - - @Override - public void acquisitionRemoved(final MessageInstance node) - { - } - - @Override - public void consumerAdded(final ConsumerImpl sub) - { - _consumer = sub; - } - - @Override - public void consumerRemoved(final ConsumerImpl sub) - { - close(); - } - - @Override - public long getUnacknowledgedBytes() - { - // TODO - return 0; - } - - @Override - public long getUnacknowledgedMessages() - { - // TODO - return 0; - } - - @Override - protected void processClosed() - { - - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Destination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Destination.java deleted file mode 100644 index d45758391c..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Destination.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - - -public interface Destination -{ - - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ExchangeDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ExchangeDestination.java deleted file mode 100644 index b842c44a16..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ExchangeDestination.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.amqp_1_0.type.messaging.Rejected; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusDurability; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusExpiryPolicy; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.txn.ServerTransaction; - -public class ExchangeDestination implements ReceivingDestination, SendingDestination -{ - private static final Accepted ACCEPTED = new Accepted(); - public static final Rejected REJECTED = new Rejected(); - private static final Outcome[] OUTCOMES = { ACCEPTED, REJECTED}; - - private ExchangeImpl _exchange; - private TerminusDurability _durability; - private TerminusExpiryPolicy _expiryPolicy; - private String _initialRoutingAddress; - - public ExchangeDestination(ExchangeImpl exchange, TerminusDurability durable, TerminusExpiryPolicy expiryPolicy) - { - _exchange = exchange; - _durability = durable; - _expiryPolicy = expiryPolicy; - } - - public Outcome[] getOutcomes() - { - return OUTCOMES; - } - - public Outcome send(final Message_1_0 message, ServerTransaction txn) - { - final InstanceProperties instanceProperties = - new InstanceProperties() - { - - @Override - public Object getProperty(final Property prop) - { - switch(prop) - { - case MANDATORY: - return false; - case REDELIVERED: - return false; - case PERSISTENT: - return message.isPersistent(); - case IMMEDIATE: - return false; - case EXPIRATION: - return message.getExpiration(); - } - return null; - }}; - - String routingAddress; - MessageMetaData_1_0.MessageHeader_1_0 messageHeader = message.getMessageHeader(); - if(_initialRoutingAddress == null) - { - routingAddress = messageHeader.getSubject(); - if(routingAddress == null) - { - if (messageHeader.getHeader("routing-key") instanceof String) - { - routingAddress = (String) messageHeader.getHeader("routing-key"); - } - else if (messageHeader.getHeader("routing_key") instanceof String) - { - routingAddress = (String) messageHeader.getHeader("routing_key"); - } - else if (messageHeader.getTo() != null - && messageHeader.getTo().startsWith(_exchange.getName() + "/")) - { - routingAddress = messageHeader.getTo().substring(1+_exchange.getName().length()); - } - else - { - routingAddress = ""; - } - } - } - else - { - if (messageHeader.getTo() != null - && messageHeader.getTo().startsWith(_exchange.getName() + "/" + _initialRoutingAddress + "/")) - { - routingAddress = messageHeader.getTo().substring(2+_exchange.getName().length()+_initialRoutingAddress.length()); - } - else - { - routingAddress = _initialRoutingAddress; - } - } - int enqueues = _exchange.send(message, - routingAddress, - instanceProperties, - txn, - null); - - - return enqueues == 0 ? REJECTED : ACCEPTED; - } - - TerminusDurability getDurability() - { - return _durability; - } - - TerminusExpiryPolicy getExpiryPolicy() - { - return _expiryPolicy; - } - - public int getCredit() - { - // TODO - fix - return 20000; - } - - public ExchangeImpl getExchange() - { - return _exchange; - } - - public void setInitialRoutingAddress(final String initialRoutingAddress) - { - _initialRoutingAddress = initialRoutingAddress; - } - - public String getInitialRoutingAddress() - { - return _initialRoutingAddress; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Link_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Link_1_0.java deleted file mode 100644 index 5ce24f406d..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Link_1_0.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import org.apache.qpid.server.protocol.LinkModel; - -public interface Link_1_0 extends LinkModel -{ - void start(); -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_v1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_v1_0.java deleted file mode 100644 index 0a6fec1200..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_v1_0.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.UnsignedByte; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpValue; -import org.apache.qpid.amqp_1_0.type.messaging.ApplicationProperties; -import org.apache.qpid.amqp_1_0.type.messaging.Data; -import org.apache.qpid.amqp_1_0.type.messaging.Header; -import org.apache.qpid.amqp_1_0.type.messaging.Properties; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; - -@PluggableService -public class MessageConverter_Internal_to_v1_0 extends MessageConverter_to_1_0<InternalMessage> -{ - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - - public Class<InternalMessage> getInputClass() - { - return InternalMessage.class; - } - - - @Override - protected MessageMetaData_1_0 convertMetaData(final InternalMessage serverMessage, - final SectionEncoder sectionEncoder) - { - List<Section> sections = new ArrayList<Section>(3); - Header header = new Header(); - - header.setDurable(serverMessage.isPersistent()); - header.setPriority(UnsignedByte.valueOf(serverMessage.getMessageHeader().getPriority())); - if(serverMessage.getExpiration() != 0l && serverMessage.getArrivalTime() !=0l && serverMessage.getExpiration() >= serverMessage.getArrivalTime()) - { - header.setTtl(UnsignedInteger.valueOf(serverMessage.getExpiration()-serverMessage.getArrivalTime())); - } - - sections.add(header); - - Properties properties = new Properties(); - properties.setCorrelationId(serverMessage.getMessageHeader().getCorrelationId()); - properties.setCreationTime(new Date(serverMessage.getMessageHeader().getTimestamp())); - properties.setMessageId(serverMessage.getMessageHeader().getMessageId()); - final String userId = serverMessage.getMessageHeader().getUserId(); - if(userId != null) - { - properties.setUserId(new Binary(userId.getBytes(UTF_8))); - } - properties.setReplyTo(serverMessage.getMessageHeader().getReplyTo()); - - sections.add(properties); - - if(!serverMessage.getMessageHeader().getHeaderNames().isEmpty()) - { - ApplicationProperties applicationProperties = new ApplicationProperties(serverMessage.getMessageHeader().getHeaderMap() ); - sections.add(applicationProperties); - } - return new MessageMetaData_1_0(sections, sectionEncoder); - - } - - protected Section getBodySection(final InternalMessage serverMessage, final String mimeType) - { - return convertToBody(serverMessage.getMessageBody()); - } - - - @Override - public String getType() - { - return "Internal to v1-0"; - } - - - public Section convertToBody(Object object) - { - if(object instanceof String) - { - return new AmqpValue(object); - } - else if(object instanceof byte[]) - { - return new Data(new Binary((byte[])object)); - } - else if(object instanceof Map) - { - return new AmqpValue(MessageConverter_to_1_0.fixMapValues((Map)object)); - } - else if(object instanceof List) - { - return new AmqpValue(MessageConverter_to_1_0.fixListValues((List)object)); - } - else - { - ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - try - { - ObjectOutputStream os = new ObjectOutputStream(bytesOut); - os.writeObject(object); - return new Data(new Binary(bytesOut.toByteArray())); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.java deleted file mode 100644 index 266f3b6868..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import org.apache.qpid.amqp_1_0.messaging.SectionDecoderImpl; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.UnsignedByte; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.UnsignedLong; -import org.apache.qpid.amqp_1_0.type.UnsignedShort; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpSequence; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpValue; -import org.apache.qpid.amqp_1_0.type.messaging.Data; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.transport.codec.BBEncoder; -import org.apache.qpid.typedmessage.TypedBytesContentWriter; -import org.apache.qpid.typedmessage.TypedBytesFormatException; - -public class MessageConverter_from_1_0 -{ - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - public static Object convertBodyToObject(final Message_1_0 serverMessage) - { - byte[] data = new byte[(int) serverMessage.getSize()]; - serverMessage.getStoredMessage().getContent(0, ByteBuffer.wrap(data)); - - SectionDecoderImpl sectionDecoder = new SectionDecoderImpl(MessageConverter_v1_0_to_Internal.TYPE_REGISTRY); - - Object bodyObject; - try - { - List<Section> sections = sectionDecoder.parseAll(ByteBuffer.wrap(data)); - ListIterator<Section> iterator = sections.listIterator(); - Section previousSection = null; - while(iterator.hasNext()) - { - Section section = iterator.next(); - if(!(section instanceof AmqpValue || section instanceof Data || section instanceof AmqpSequence)) - { - iterator.remove(); - } - else - { - if(previousSection != null && (previousSection.getClass() != section.getClass() || section instanceof AmqpValue)) - { - throw new ConnectionScopedRuntimeException("Message is badly formed and has multiple body section which are not all Data or not all AmqpSequence"); - } - else - { - previousSection = section; - } - } - } - - - if(sections.isEmpty()) - { - // should actually be illegal - bodyObject = new byte[0]; - } - else - { - Section firstBodySection = sections.get(0); - if(firstBodySection instanceof AmqpValue) - { - bodyObject = convertValue(((AmqpValue)firstBodySection).getValue()); - } - else if(firstBodySection instanceof Data) - { - int totalSize = 0; - for(Section section : sections) - { - totalSize += ((Data)section).getValue().getLength(); - } - byte[] bodyData = new byte[totalSize]; - ByteBuffer buf = ByteBuffer.wrap(bodyData); - for(Section section : sections) - { - buf.put(((Data)section).getValue().asByteBuffer()); - } - bodyObject = bodyData; - } - else - { - ArrayList totalSequence = new ArrayList(); - for(Section section : sections) - { - totalSequence.addAll(((AmqpSequence)section).getValue()); - } - bodyObject = convertValue(totalSequence); - } - } - - } - catch (AmqpErrorException e) - { - throw new ConnectionScopedRuntimeException(e); - } - return bodyObject; - } - - private static final Set<Class> STANDARD_TYPES = new HashSet<>(Arrays.<Class>asList(Boolean.class, - Byte.class, - Short.class, - Integer.class, - Long.class, - Float.class, - Double.class, - Character.class, - String.class, - byte[].class, - UUID.class)); - - private static Map convertMap(final Map map) - { - Map resultMap = new LinkedHashMap(); - Iterator<Map.Entry> iterator = map.entrySet().iterator(); - while(iterator.hasNext()) - { - Map.Entry entry = iterator.next(); - resultMap.put(convertValue(entry.getKey()), convertValue(entry.getValue())); - - } - return resultMap; - } - - public static Object convertValue(final Object value) - { - if(value != null && !STANDARD_TYPES.contains(value)) - { - if(value instanceof Map) - { - return convertMap((Map)value); - } - else if(value instanceof List) - { - return convertList((List)value); - } - else if(value instanceof UnsignedByte) - { - return ((UnsignedByte)value).shortValue(); - } - else if(value instanceof UnsignedShort) - { - return ((UnsignedShort)value).intValue(); - } - else if(value instanceof UnsignedInteger) - { - return ((UnsignedInteger)value).longValue(); - } - else if(value instanceof UnsignedLong) - { - return ((UnsignedLong)value).longValue(); - } - else if(value instanceof Symbol) - { - return value.toString(); - } - else if(value instanceof Date) - { - return ((Date)value).getTime(); - } - else if(value instanceof Binary) - { - Binary binary = (Binary)value; - byte[] data = new byte[binary.getLength()]; - binary.asByteBuffer().get(data); - return data; - } - else - { - // Throw exception instead? - return value.toString(); - } - } - else - { - return value; - } - } - - private static List convertList(final List list) - { - List result = new ArrayList(list.size()); - for(Object entry : list) - { - result.add(convertValue(entry)); - } - return result; - } - - public static byte[] convertToBody(Object object) - { - if(object instanceof String) - { - return ((String)object).getBytes(UTF_8); - } - else if(object instanceof byte[]) - { - return (byte[]) object; - } - else if(object instanceof Map) - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeMap((Map)object); - ByteBuffer buf = encoder.segment(); - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - - } - else if(object instanceof List) - { - try - { - ByteBuffer buf; - if(onlyPrimitiveTypes((List)object)) - { - TypedBytesContentWriter writer = new TypedBytesContentWriter(); - for(Object value : (List)object) - { - writer.writeObject(value); - } - buf = writer.getData(); - - } - else - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeList((List) object); - buf = encoder.segment(); - } - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - } - catch (TypedBytesFormatException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - else - { - ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - try - { - ObjectOutputStream os = new ObjectOutputStream(bytesOut); - os.writeObject(object); - return bytesOut.toByteArray(); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - } - - public static boolean onlyPrimitiveTypes(final List list) - { - for(Object value : list) - { - if(!(value instanceof String - || value instanceof Integer - || value instanceof Long - || value instanceof Double - || value instanceof Float - || value instanceof Byte - || value instanceof Short - || value instanceof Character - || value instanceof Boolean - || value instanceof byte[])) - { - return false; - } - } - return true; - } - - public static String getBodyMimeType(Object object) - { - if(object instanceof String) - { - return "text/plain"; - } - else if(object instanceof byte[]) - { - return "application/octet-stream"; - } - else if(object instanceof Map) - { - return "amqp/map"; - } - else if(object instanceof List) - { - return onlyPrimitiveTypes((List)object) ? "jms/stream-message" : "amqp/list"; - } - else - { - return "application/java-object-stream"; - } - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.java deleted file mode 100644 index e9e81bb623..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import java.io.EOFException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; - -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.messaging.SectionEncoderImpl; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.codec.AMQPDescribedTypeRegistry; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpValue; -import org.apache.qpid.amqp_1_0.type.messaging.Data; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.typedmessage.TypedBytesContentReader; -import org.apache.qpid.typedmessage.TypedBytesFormatException; -import org.apache.qpid.util.GZIPUtils; - -public abstract class MessageConverter_to_1_0<M extends ServerMessage> implements MessageConverter<M, Message_1_0> -{ - private final AMQPDescribedTypeRegistry _typeRegistry = AMQPDescribedTypeRegistry.newInstance() - .registerTransportLayer() - .registerMessagingLayer() - .registerTransactionLayer() - .registerSecurityLayer(); - - @Override - public final Class<Message_1_0> getOutputClass() - { - return Message_1_0.class; - } - - @Override - public final Message_1_0 convert(M message, VirtualHostImpl vhost) - { - - SectionEncoder sectionEncoder = new SectionEncoderImpl(_typeRegistry); - return new Message_1_0(convertToStoredMessage(message, sectionEncoder)); - } - - - private StoredMessage<MessageMetaData_1_0> convertToStoredMessage(final M serverMessage, SectionEncoder sectionEncoder) - { - final MessageMetaData_1_0 metaData = convertMetaData(serverMessage, sectionEncoder); - return convertServerMessage(metaData, serverMessage, sectionEncoder); - } - - abstract protected MessageMetaData_1_0 convertMetaData(final M serverMessage, SectionEncoder sectionEncoder); - - - private static Section convertMessageBody(String mimeType, byte[] data) - { - if("text/plain".equals(mimeType) || "text/xml".equals(mimeType)) - { - String text = new String(data); - return new AmqpValue(text); - } - else if("jms/map-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - LinkedHashMap map = new LinkedHashMap(); - final int entries = reader.readIntImpl(); - for (int i = 0; i < entries; i++) - { - try - { - String propName = reader.readStringImpl(); - Object value = reader.readObject(); - - map.put(propName, value); - } - catch (EOFException e) - { - throw new IllegalArgumentException(e); - } - catch (TypedBytesFormatException e) - { - throw new IllegalArgumentException(e); - } - - } - - return new AmqpValue(fixMapValues(map)); - - } - else if("amqp/map".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - final Map<String,Object> map = decoder.readMap(); - - return new AmqpValue(fixMapValues(map)); - - } - else if("amqp/list".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - return new AmqpValue(fixListValues(decoder.readList())); - } - else if("jms/stream-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - List list = new ArrayList(); - while (reader.remaining() != 0) - { - try - { - list.add(fixValue(reader.readObject())); - } - catch (TypedBytesFormatException e) - { - throw new ConnectionScopedRuntimeException(e); - } - catch (EOFException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - return new AmqpValue(list); - } - else - { - return new Data(new Binary(data)); - - } - } - - static Map fixMapValues(final Map<String, Object> map) - { - for(Map.Entry<String,Object> entry : map.entrySet()) - { - entry.setValue(fixValue(entry.getValue())); - } - return map; - } - - static Object fixValue(final Object value) - { - if(value instanceof byte[]) - { - return new Binary((byte[])value); - } - else if(value instanceof Map) - { - return fixMapValues((Map)value); - } - else if(value instanceof List) - { - return fixListValues((List)value); - } - else - { - return value; - } - } - - static List fixListValues(final List list) - { - ListIterator iterator = list.listIterator(); - while(iterator.hasNext()) - { - Object value = iterator.next(); - iterator.set(fixValue(value)); - - } - return list; - } - - private StoredMessage<MessageMetaData_1_0> convertServerMessage(final MessageMetaData_1_0 metaData, - final M serverMessage, - SectionEncoder sectionEncoder) - { - final String mimeType = serverMessage.getMessageHeader().getMimeType(); - byte[] data = new byte[(int) serverMessage.getSize()]; - serverMessage.getContent(ByteBuffer.wrap(data), 0); - byte[] uncompressed; - - if(Symbol.valueOf(GZIPUtils.GZIP_CONTENT_ENCODING).equals(metaData.getPropertiesSection().getContentEncoding()) - && (uncompressed = GZIPUtils.uncompressBufferToArray(ByteBuffer.wrap(data)))!=null) - { - data = uncompressed; - metaData.getPropertiesSection().setContentEncoding(null); - } - - - Section bodySection = convertMessageBody(mimeType, data); - - final ByteBuffer allData = encodeConvertedMessage(metaData, bodySection, sectionEncoder); - - return new StoredMessage<MessageMetaData_1_0>() - { - @Override - public MessageMetaData_1_0 getMetaData() - { - return metaData; - } - - @Override - public long getMessageNumber() - { - return serverMessage.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - ByteBuffer buf = allData.duplicate(); - buf.position(offsetInMessage); - buf = buf.slice(); - int size; - if(dst.remaining()<buf.remaining()) - { - buf.limit(dst.remaining()); - size = dst.remaining(); - } - else - { - size = buf.remaining(); - } - dst.put(buf); - return size; - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - ByteBuffer buf = allData.duplicate(); - buf.position(offsetInMessage); - buf = buf.slice(); - if(size < buf.remaining()) - { - buf.limit(size); - } - return buf; - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private ByteBuffer encodeConvertedMessage(MessageMetaData_1_0 metaData, Section bodySection, SectionEncoder sectionEncoder) - { - int headerSize = (int) metaData.getStorableSize(); - - sectionEncoder.reset(); - sectionEncoder.encodeObject(bodySection); - Binary dataEncoding = sectionEncoder.getEncoding(); - - final ByteBuffer allData = ByteBuffer.allocate(headerSize + dataEncoding.getLength()); - metaData.writeToBuffer(allData); - allData.put(dataEncoding.getArray(),dataEncoding.getArrayOffset(),dataEncoding.getLength()); - return allData; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_v1_0_to_Internal.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_v1_0_to_Internal.java deleted file mode 100644 index a17a9585c1..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_v1_0_to_Internal.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.codec.AMQPDescribedTypeRegistry; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -@PluggableService -public class MessageConverter_v1_0_to_Internal implements MessageConverter<Message_1_0, InternalMessage> -{ - - static final AMQPDescribedTypeRegistry TYPE_REGISTRY = AMQPDescribedTypeRegistry.newInstance(); - static - { - TYPE_REGISTRY.registerTransportLayer(); - TYPE_REGISTRY.registerMessagingLayer(); - TYPE_REGISTRY.registerTransactionLayer(); - TYPE_REGISTRY.registerSecurityLayer(); - } - - @Override - public Class<Message_1_0> getInputClass() - { - return Message_1_0.class; - } - - @Override - public Class<InternalMessage> getOutputClass() - { - return InternalMessage.class; - } - - @Override - public InternalMessage convert(Message_1_0 serverMessage, VirtualHostImpl vhost) - { - Object bodyObject = MessageConverter_from_1_0.convertBodyToObject(serverMessage); - - return InternalMessage.convert(serverMessage.getMessageNumber(), serverMessage.isPersistent(), serverMessage.getMessageHeader(), bodyObject); - } - - @Override - public String getType() - { - return "v1-0 to Internal"; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.java deleted file mode 100644 index 8f8a868365..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import java.nio.ByteBuffer; - -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; - -@PluggableService -public class MessageMetaDataType_1_0 implements MessageMetaDataType<MessageMetaData_1_0> -{ - - public static final int TYPE = 2; - public static final String V1_0_0 = "v1_0_0"; - - @Override - public int ordinal() - { - return TYPE; - } - - @Override - public MessageMetaData_1_0 createMetaData(ByteBuffer buf) - { - return MessageMetaData_1_0.FACTORY.createMetaData(buf); - } - - @Override - public ServerMessage<MessageMetaData_1_0> createMessage(StoredMessage<MessageMetaData_1_0> msg) - { - return new Message_1_0(msg); - } - - public int hashCode() - { - return ordinal(); - } - - public boolean equals(Object o) - { - return o != null && o.getClass() == getClass(); - } - - @Override - public String getType() - { - return V1_0_0; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.java deleted file mode 100755 index d31909f642..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.java +++ /dev/null @@ -1,599 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.protocol.v1_0; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.amqp_1_0.codec.ValueHandler; -import org.apache.qpid.amqp_1_0.messaging.SectionDecoder; -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.codec.AMQPDescribedTypeRegistry; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpSequence; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpValue; -import org.apache.qpid.amqp_1_0.type.messaging.ApplicationProperties; -import org.apache.qpid.amqp_1_0.type.messaging.Data; -import org.apache.qpid.amqp_1_0.type.messaging.DeliveryAnnotations; -import org.apache.qpid.amqp_1_0.type.messaging.Footer; -import org.apache.qpid.amqp_1_0.type.messaging.Header; -import org.apache.qpid.amqp_1_0.type.messaging.MessageAnnotations; -import org.apache.qpid.amqp_1_0.type.messaging.Properties; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.store.StorableMessageMetaData; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; - -public class MessageMetaData_1_0 implements StorableMessageMetaData -{ - private static final Logger _logger = LoggerFactory.getLogger(MessageMetaData_1_0.class); - // TODO move to somewhere more useful - public static final Symbol JMS_TYPE = Symbol.valueOf("x-opt-jms-type"); - public static final MessageMetaDataType.Factory<MessageMetaData_1_0> FACTORY = new MetaDataFactory(); - private static final MessageMetaDataType_1_0 TYPE = new MessageMetaDataType_1_0(); - - - private Header _header; - private Properties _properties; - private Map _deliveryAnnotations; - private Map _messageAnnotations; - private Map _appProperties; - private Map _footer; - - private List<ByteBuffer> _encodedSections = new ArrayList<ByteBuffer>(3); - - private volatile ByteBuffer _encoded; - private MessageHeader_1_0 _messageHeader; - - - public MessageMetaData_1_0(List<Section> sections, SectionEncoder encoder) - { - this(sections, encodeSections(sections, encoder)); - } - - public Properties getPropertiesSection() - { - return _properties; - } - - - public Header getHeaderSection() - { - return _header; - } - - private static ArrayList<ByteBuffer> encodeSections(final List<Section> sections, final SectionEncoder encoder) - { - ArrayList<ByteBuffer> encodedSections = new ArrayList<ByteBuffer>(sections.size()); - for(Section section : sections) - { - encoder.encodeObject(section); - encodedSections.add(encoder.getEncoding().asByteBuffer()); - encoder.reset(); - } - return encodedSections; - } - - public MessageMetaData_1_0(ByteBuffer[] fragments, SectionDecoder decoder) - { - this(fragments, decoder, new ArrayList<ByteBuffer>(3)); - } - - public MessageMetaData_1_0(ByteBuffer[] fragments, SectionDecoder decoder, List<ByteBuffer> immutableSections) - { - this(constructSections(fragments, decoder,immutableSections), immutableSections); - } - - private MessageMetaData_1_0(List<Section> sections, List<ByteBuffer> encodedSections) - { - _encodedSections = encodedSections; - - Iterator<Section> sectIter = sections.iterator(); - - Section section = sectIter.hasNext() ? sectIter.next() : null; - if(section instanceof Header) - { - _header = (Header) section; - section = sectIter.hasNext() ? sectIter.next() : null; - } - - if(section instanceof DeliveryAnnotations) - { - _deliveryAnnotations = ((DeliveryAnnotations) section).getValue(); - section = sectIter.hasNext() ? sectIter.next() : null; - } - - if(section instanceof MessageAnnotations) - { - _messageAnnotations = ((MessageAnnotations) section).getValue(); - section = sectIter.hasNext() ? sectIter.next() : null; - } - - if(section instanceof Properties) - { - _properties = (Properties) section; - section = sectIter.hasNext() ? sectIter.next() : null; - } - - if(section instanceof ApplicationProperties) - { - _appProperties = ((ApplicationProperties) section).getValue(); - section = sectIter.hasNext() ? sectIter.next() : null; - } - - if(section instanceof Footer) - { - _footer = ((Footer) section).getValue(); - section = sectIter.hasNext() ? sectIter.next() : null; - } - - _messageHeader = new MessageHeader_1_0(); - - } - - private static List<Section> constructSections(final ByteBuffer[] fragments, final SectionDecoder decoder, List<ByteBuffer> encodedSections) - { - List<Section> sections = new ArrayList<Section>(3); - - ByteBuffer src; - if(fragments.length == 1) - { - src = fragments[0].duplicate(); - } - else - { - int size = 0; - for(ByteBuffer buf : fragments) - { - size += buf.remaining(); - } - src = ByteBuffer.allocate(size); - for(ByteBuffer buf : fragments) - { - src.put(buf.duplicate()); - } - src.flip(); - - } - - try - { - int startBarePos = -1; - int lastPos = src.position(); - Section s = decoder.readSection(src); - - - - if(s instanceof Header) - { - sections.add(s); - lastPos = src.position(); - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - - if(s instanceof DeliveryAnnotations) - { - sections.add(s); - lastPos = src.position(); - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - - if(s instanceof MessageAnnotations) - { - sections.add(s); - lastPos = src.position(); - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - - if(s instanceof Properties) - { - sections.add(s); - if(startBarePos == -1) - { - startBarePos = lastPos; - } - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - - if(s instanceof ApplicationProperties) - { - sections.add(s); - if(startBarePos == -1) - { - startBarePos = lastPos; - } - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - - if(s instanceof AmqpValue) - { - if(startBarePos == -1) - { - startBarePos = lastPos; - } - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - else if(s instanceof Data) - { - if(startBarePos == -1) - { - startBarePos = lastPos; - } - do - { - s = src.hasRemaining() ? decoder.readSection(src) : null; - } while(s instanceof Data); - } - else if(s instanceof AmqpSequence) - { - if(startBarePos == -1) - { - startBarePos = lastPos; - } - do - { - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - while(s instanceof AmqpSequence); - } - - if(s instanceof Footer) - { - sections.add(s); - } - - - int pos = 0; - for(ByteBuffer buf : fragments) - { -/* - if(pos < startBarePos) - { - if(pos + buf.remaining() > startBarePos) - { - ByteBuffer dup = buf.duplicate(); - dup.position(dup.position()+startBarePos-pos); - dup.slice(); - encodedSections.add(dup); - } - } - else -*/ - { - encodedSections.add(buf.duplicate()); - } - pos += buf.remaining(); - } - - return sections; - } - catch (AmqpErrorException e) - { - _logger.error("Decoding read section error", e); - throw new IllegalArgumentException(e); - } - } - - - public MessageMetaDataType getType() - { - return TYPE; - } - - - public int getStorableSize() - { - int size = 0; - - for(ByteBuffer bin : _encodedSections) - { - size += bin.limit(); - } - - return size; - } - - private ByteBuffer encodeAsBuffer() - { - ByteBuffer buf = ByteBuffer.allocate(getStorableSize()); - - for(ByteBuffer bin : _encodedSections) - { - buf.put(bin.duplicate()); - } - - return buf; - } - - public int writeToBuffer(ByteBuffer dest) - { - ByteBuffer buf = _encoded; - - if(buf == null) - { - buf = encodeAsBuffer(); - _encoded = buf; - } - - buf = buf.duplicate(); - - buf.position(0); - - if(dest.remaining() < buf.limit()) - { - buf.limit(dest.remaining()); - } - dest.put(buf); - return buf.limit(); - } - - public int getContentSize() - { - ByteBuffer buf = _encoded; - - if(buf == null) - { - buf = encodeAsBuffer(); - _encoded = buf; - } - return buf.remaining(); - } - - public boolean isPersistent() - { - return _header != null && Boolean.TRUE.equals(_header.getDurable()); - } - - public MessageHeader_1_0 getMessageHeader() - { - return _messageHeader; - } - - - - - private static class MetaDataFactory implements MessageMetaDataType.Factory<MessageMetaData_1_0> - { - private final AMQPDescribedTypeRegistry _typeRegistry = AMQPDescribedTypeRegistry.newInstance(); - - private MetaDataFactory() - { - _typeRegistry.registerTransportLayer(); - _typeRegistry.registerMessagingLayer(); - _typeRegistry.registerTransactionLayer(); - _typeRegistry.registerSecurityLayer(); - } - - public MessageMetaData_1_0 createMetaData(ByteBuffer buf) - { - ValueHandler valueHandler = new ValueHandler(_typeRegistry); - - ArrayList<Section> sections = new ArrayList<Section>(3); - ArrayList<ByteBuffer> encodedSections = new ArrayList<ByteBuffer>(3); - - while(buf.hasRemaining()) - { - try - { - ByteBuffer encodedBuf = buf.duplicate(); - Object parse = valueHandler.parse(buf); - sections.add((Section) parse); - encodedBuf.limit(buf.position()); - encodedSections.add(encodedBuf); - - } - catch (AmqpErrorException e) - { - //TODO - throw new ConnectionScopedRuntimeException(e); - } - - } - - return new MessageMetaData_1_0(sections,encodedSections); - - } - } - - public class MessageHeader_1_0 implements AMQMessageHeader - { - - public String getCorrelationId() - { - if(_properties == null || _properties.getCorrelationId() == null) - { - return null; - } - else - { - return _properties.getCorrelationId().toString(); - } - } - - public long getExpiration() - { - return 0; //TODO - } - - public String getMessageId() - { - if(_properties == null || _properties.getMessageId() == null) - { - return null; - } - else - { - return _properties.getMessageId().toString(); - } - } - - public String getMimeType() - { - - if(_properties == null || _properties.getContentType() == null) - { - return null; - } - else - { - return _properties.getContentType().toString(); - } - } - - public String getEncoding() - { - return null; //TODO - } - - public byte getPriority() - { - if(_header == null || _header.getPriority() == null) - { - return 4; //javax.jms.Message.DEFAULT_PRIORITY; - } - else - { - return _header.getPriority().byteValue(); - } - } - - public long getTimestamp() - { - if(_properties == null || _properties.getCreationTime() == null) - { - return 0L; - } - else - { - return _properties.getCreationTime().getTime(); - } - - } - - public String getType() - { - String subject = getSubject(); - if(subject != null) - { - return subject; - } - - // Use legacy annotation if present and there was no subject - if(_messageAnnotations == null || _messageAnnotations.get(JMS_TYPE) == null) - { - return null; - } - else - { - return _messageAnnotations.get(JMS_TYPE).toString(); - } - } - - public String getReplyTo() - { - if(_properties == null || _properties.getReplyTo() == null) - { - return null; - } - else - { - return _properties.getReplyTo().toString(); - } - } - - public String getAppId() - { - //TODO - return null; - } - - public String getUserId() - { - // TODO - return null; - } - - public Object getHeader(final String name) - { - return _appProperties == null ? null : _appProperties.get(name); - } - - public boolean containsHeaders(final Set<String> names) - { - if(_appProperties == null) - { - return false; - } - - for(String key : names) - { - if(!_appProperties.containsKey(key)) - { - return false; - } - } - return true; - } - - @Override - public Collection<String> getHeaderNames() - { - if(_appProperties == null) - { - return Collections.emptySet(); - } - return Collections.unmodifiableCollection(_appProperties.keySet()); - } - - public boolean containsHeader(final String name) - { - return _appProperties != null && _appProperties.containsKey(name); - } - - public String getSubject() - { - return _properties == null ? null : _properties.getSubject(); - } - - public String getTo() - { - return _properties == null ? null : _properties.getTo(); - } - - public Map<String, Object> getHeadersAsMap() - { - return new HashMap<String, Object>(_appProperties); - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageSourceDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageSourceDestination.java deleted file mode 100644 index 16c2de9271..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageSourceDestination.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.server.message.MessageSource; - -public class MessageSourceDestination implements SendingDestination -{ - private static final Accepted ACCEPTED = new Accepted(); - private static final Outcome[] OUTCOMES = new Outcome[] { ACCEPTED }; - - - private MessageSource _queue; - - public MessageSourceDestination(MessageSource queue) - { - _queue = queue; - } - - public Outcome[] getOutcomes() - { - return OUTCOMES; - } - - public int getCredit() - { - // TODO - fix - return 100; - } - - public MessageSource getQueue() - { - return _queue; - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.java deleted file mode 100644 index 18f5ba9e2e..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - - -import java.lang.ref.SoftReference; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -import org.apache.qpid.server.message.AbstractServerMessageImpl; -import org.apache.qpid.server.store.StoredMessage; - -public class Message_1_0 extends AbstractServerMessageImpl<Message_1_0, MessageMetaData_1_0> -{ - - private volatile SoftReference<List<ByteBuffer>> _fragmentsRef; - private long _arrivalTime; - private final long _size; - - - public Message_1_0(final StoredMessage<MessageMetaData_1_0> storedMessage) - { - super(storedMessage, null); - final List<ByteBuffer> fragments = restoreFragments(getStoredMessage()); - _fragmentsRef = new SoftReference<>(fragments); - _size = calculateSize(fragments); - } - - private long calculateSize(final List<ByteBuffer> fragments) - { - - long size = 0l; - if(fragments != null) - { - for(ByteBuffer buf : fragments) - { - size += buf.remaining(); - } - } - return size; - } - - private static List<ByteBuffer> restoreFragments(StoredMessage<MessageMetaData_1_0> storedMessage) - { - ArrayList<ByteBuffer> fragments = new ArrayList<ByteBuffer>(); - final int FRAGMENT_SIZE = 2048; - int offset = 0; - ByteBuffer b; - do - { - - b = storedMessage.getContent(offset,FRAGMENT_SIZE); - if(b.hasRemaining()) - { - fragments.add(b); - offset+= b.remaining(); - } - } - while(b.hasRemaining()); - return fragments; - } - - public Message_1_0(final StoredMessage<MessageMetaData_1_0> storedMessage, - final List<ByteBuffer> fragments, - final Object connectionReference) - { - super(storedMessage, connectionReference); - _fragmentsRef = new SoftReference<>(fragments); - _size = calculateSize(fragments); - _arrivalTime = System.currentTimeMillis(); - } - - public String getInitialRoutingAddress() - { - Object routingKey = getMessageHeader().getHeader("routing-key"); - if(routingKey != null) - { - return routingKey.toString(); - } - else - { - return getMessageHeader().getTo(); - } - } - - private MessageMetaData_1_0 getMessageMetaData() - { - return getStoredMessage().getMetaData(); - } - - public MessageMetaData_1_0.MessageHeader_1_0 getMessageHeader() - { - return getMessageMetaData().getMessageHeader(); - } - - public long getSize() - { - return _size; - } - - public long getExpiration() - { - return getMessageHeader().getExpiration(); - } - - public long getArrivalTime() - { - return _arrivalTime; - } - - public List<ByteBuffer> getFragments() - { - - List<ByteBuffer> fragments = _fragmentsRef.get(); - if(fragments == null) - { - fragments = restoreFragments(getStoredMessage()); - _fragmentsRef = new SoftReference<>(fragments); - } - return fragments; - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java deleted file mode 100644 index 10058c1e0a..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.amqp_1_0.type.messaging.Rejected; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusDurability; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusExpiryPolicy; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.txn.ServerTransaction; - -public class NodeReceivingDestination implements ReceivingDestination -{ - private static final Accepted ACCEPTED = new Accepted(); - public static final Rejected REJECTED = new Rejected(); - private static final Outcome[] OUTCOMES = { ACCEPTED, REJECTED}; - - private MessageDestination _destination; - private TerminusDurability _durability; - private TerminusExpiryPolicy _expiryPolicy; - - public NodeReceivingDestination(MessageDestination destination, TerminusDurability durable, TerminusExpiryPolicy expiryPolicy) - { - _destination = destination; - _durability = durable; - _expiryPolicy = expiryPolicy; - } - - public Outcome[] getOutcomes() - { - return OUTCOMES; - } - - public Outcome send(final Message_1_0 message, ServerTransaction txn) - { - final InstanceProperties instanceProperties = - new InstanceProperties() - { - - @Override - public Object getProperty(final Property prop) - { - switch(prop) - { - case MANDATORY: - return false; - case REDELIVERED: - return false; - case PERSISTENT: - return message.isPersistent(); - case IMMEDIATE: - return false; - case EXPIRATION: - return message.getExpiration(); - } - return null; - }}; - - String routingAddress; - MessageMetaData_1_0.MessageHeader_1_0 messageHeader = message.getMessageHeader(); - routingAddress = messageHeader.getSubject(); - if(routingAddress == null) - { - if (messageHeader.getHeader("routing-key") instanceof String) - { - routingAddress = (String) messageHeader.getHeader("routing-key"); - } - else if (messageHeader.getHeader("routing_key") instanceof String) - { - routingAddress = (String) messageHeader.getHeader("routing_key"); - } - else if (messageHeader.getTo() != null - && messageHeader.getTo().startsWith(_destination.getName() + "/")) - { - routingAddress = messageHeader.getTo().substring(1+_destination.getName().length()); - } - else - { - routingAddress = ""; - } - } - - int enqueues = _destination.send(message, routingAddress, instanceProperties, txn, null); - - - return enqueues == 0 ? REJECTED : ACCEPTED; - } - - TerminusDurability getDurability() - { - return _durability; - } - - TerminusExpiryPolicy getExpiryPolicy() - { - return _expiryPolicy; - } - - public int getCredit() - { - // TODO - fix - return 20000; - } - - public MessageDestination getDestination() - { - return _destination; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngineCreator_1_0_0_SASL.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngineCreator_1_0_0_SASL.java deleted file mode 100644 index e72dc17b57..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngineCreator_1_0_0_SASL.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.ProtocolEngineCreator; -import org.apache.qpid.transport.network.NetworkConnection; - -@PluggableService -public class ProtocolEngineCreator_1_0_0_SASL implements ProtocolEngineCreator -{ - private static final byte[] AMQP_SASL_1_0_0_HEADER = - new byte[] { (byte) 'A', - (byte) 'M', - (byte) 'Q', - (byte) 'P', - (byte) 3, - (byte) 1, - (byte) 0, - (byte) 0 - }; - - public ProtocolEngineCreator_1_0_0_SASL() - { - } - - public Protocol getVersion() - { - return Protocol.AMQP_1_0; - } - - - public byte[] getHeaderIdentifier() - { - return AMQP_SASL_1_0_0_HEADER; - } - - public ServerProtocolEngine newProtocolEngine(Broker<?> broker, - NetworkConnection network, - AmqpPort<?> port, - Transport transport, - long id) - { - return new ProtocolEngine_1_0_0_SASL(network, broker, id, port, transport); - } - - private static ProtocolEngineCreator INSTANCE = new ProtocolEngineCreator_1_0_0_SASL(); - - public static ProtocolEngineCreator getInstance() - { - return INSTANCE; - } - - @Override - public String getType() - { - return getVersion().toString(); - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngine_1_0_0_SASL.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngine_1_0_0_SASL.java deleted file mode 100644 index 013126cfe0..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngine_1_0_0_SASL.java +++ /dev/null @@ -1,631 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import java.io.PrintWriter; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import javax.security.auth.Subject; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.amqp_1_0.codec.FrameWriter; -import org.apache.qpid.amqp_1_0.codec.ProtocolHandler; -import org.apache.qpid.amqp_1_0.framing.AMQFrame; -import org.apache.qpid.amqp_1_0.framing.OversizeFrameException; -import org.apache.qpid.amqp_1_0.framing.SASLFrameHandler; -import org.apache.qpid.amqp_1_0.transport.ConnectionEndpoint; -import org.apache.qpid.amqp_1_0.transport.Container; -import org.apache.qpid.amqp_1_0.transport.FrameOutputHandler; -import org.apache.qpid.amqp_1_0.transport.SaslServerProvider; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.FrameBody; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.common.QpidProperties; -import org.apache.qpid.common.ServerPropertyNames; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.UsernamePrincipal; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.network.NetworkConnection; - -public class ProtocolEngine_1_0_0_SASL implements ServerProtocolEngine, FrameOutputHandler -{ - - private final AmqpPort<?> _port; - private final Transport _transport; - private long _readBytes; - private long _writtenBytes; - - private volatile long _lastReadTime; - private volatile long _lastWriteTime; - private final Broker<?> _broker; - private long _createTime = System.currentTimeMillis(); - private ConnectionEndpoint _endpoint; - private long _connectionId; - private final AtomicBoolean _stateChanged = new AtomicBoolean(); - private final AtomicReference<Action<ServerProtocolEngine>> _workListener = new AtomicReference<>(); - - - private static final ByteBuffer HEADER = - ByteBuffer.wrap(new byte[] - { - (byte)'A', - (byte)'M', - (byte)'Q', - (byte)'P', - (byte) 3, - (byte) 1, - (byte) 0, - (byte) 0 - }); - - private static final ByteBuffer PROTOCOL_HEADER = - ByteBuffer.wrap(new byte[] - { - (byte)'A', - (byte)'M', - (byte)'Q', - (byte)'P', - (byte) 0, - (byte) 1, - (byte) 0, - (byte) 0 - }); - - - private FrameWriter _frameWriter; - private ProtocolHandler _frameHandler; - private ByteBuffer _buf = ByteBuffer.allocate(1024 * 1024); - private Object _sendLock = new Object(); - private byte _major; - private byte _minor; - private byte _revision; - private PrintWriter _out; - private NetworkConnection _network; - private ByteBufferSender _sender; - private Connection_1_0 _connection; - private volatile boolean _transportBlockedForWriting; - - - static enum State { - A, - M, - Q, - P, - PROTOCOL, - MAJOR, - MINOR, - REVISION, - FRAME - } - - private State _state = State.A; - - private final AtomicReference<Thread> _messageAssignmentSuspended = new AtomicReference<>(); - - - - - public ProtocolEngine_1_0_0_SASL(final NetworkConnection networkDriver, final Broker<?> broker, - long id, AmqpPort<?> port, Transport transport) - { - _connectionId = id; - _broker = broker; - _port = port; - _transport = transport; - if(networkDriver != null) - { - setNetworkConnection(networkDriver, networkDriver.getSender()); - } - } - - - @Override - public boolean isMessageAssignmentSuspended() - { - Thread lock = _messageAssignmentSuspended.get(); - return lock != null && _messageAssignmentSuspended.get() != Thread.currentThread(); - } - - @Override - public void setMessageAssignmentSuspended(final boolean messageAssignmentSuspended) - { - _messageAssignmentSuspended.set(messageAssignmentSuspended ? Thread.currentThread() : null); - - for(AMQSessionModel<?,?> session : _connection.getSessionModels()) - { - for(Consumer<?> consumer : session.getConsumers()) - { - ConsumerImpl consumerImpl = (ConsumerImpl) consumer; - if (!messageAssignmentSuspended) - { - consumerImpl.getTarget().notifyCurrentState(); - } - else - { - // ensure that by the time the method returns, no consumer can be in the process of - // delivering a message. - consumerImpl.getSendLock(); - consumerImpl.releaseSendLock(); - } - } - } - } - - - public SocketAddress getRemoteAddress() - { - return _network.getRemoteAddress(); - } - - public SocketAddress getLocalAddress() - { - return _network.getLocalAddress(); - } - - public long getReadBytes() - { - return _readBytes; - } - - public long getWrittenBytes() - { - return _writtenBytes; - } - - public void writerIdle() - { - //Todo - } - - public void readerIdle() - { - //Todo - } - - @Override - public void encryptedTransport() - { - } - - public void setNetworkConnection(final NetworkConnection network, final ByteBufferSender sender) - { - _network = network; - _sender = sender; - - Container container = new Container(_broker.getId().toString()); - - SubjectCreator subjectCreator = _port.getAuthenticationProvider().getSubjectCreator(_transport.isSecure()); - _endpoint = new ConnectionEndpoint(container, asSaslServerProvider(subjectCreator)); - _endpoint.setLogger(new ConnectionEndpoint.FrameReceiptLogger() - { - @Override - public boolean isEnabled() - { - return FRAME_LOGGER.isDebugEnabled(); - } - - @Override - public void received(final SocketAddress remoteAddress, final short channel, final Object frame) - { - FRAME_LOGGER.debug("RECV[" + remoteAddress + "|" + channel + "] : " + frame); - } - }); - Map<Symbol,Object> serverProperties = new LinkedHashMap<Symbol, Object>(); - serverProperties.put(Symbol.valueOf(ServerPropertyNames.PRODUCT), QpidProperties.getProductName()); - serverProperties.put(Symbol.valueOf(ServerPropertyNames.VERSION), QpidProperties.getReleaseVersion()); - serverProperties.put(Symbol.valueOf(ServerPropertyNames.QPID_BUILD), QpidProperties.getBuildVersion()); - serverProperties.put(Symbol.valueOf(ServerPropertyNames.QPID_INSTANCE_NAME), _broker.getName()); - - _endpoint.setProperties(serverProperties); - - _endpoint.setRemoteAddress(getRemoteAddress()); - _connection = new Connection_1_0(_broker, _endpoint, _connectionId, _port, _transport, subjectCreator, this); - - _endpoint.setConnectionEventListener(_connection); - _endpoint.setFrameOutputHandler(this); - _endpoint.setSaslFrameOutput(this); - - _endpoint.setOnSaslComplete(new Runnable() - { - public void run() - { - if (_endpoint.isAuthenticated()) - { - _sender.send(PROTOCOL_HEADER.duplicate()); - _sender.flush(); - } - else - { - _network.close(); - } - } - }); - _frameWriter = new FrameWriter(_endpoint.getDescribedTypeRegistry()); - _frameHandler = new SASLFrameHandler(_endpoint); - - _sender.send(HEADER.duplicate()); - _sender.flush(); - - List<String> mechanisms = subjectCreator.getMechanisms(); - _endpoint.initiateSASL(mechanisms.toArray(new String[mechanisms.size()])); - - - } - - private SaslServerProvider asSaslServerProvider(final SubjectCreator subjectCreator) - { - return new SaslServerProvider() - { - @Override - public SaslServer getSaslServer(String mechanism, String fqdn) throws SaslException - { - return subjectCreator.createSaslServer(mechanism, fqdn, _network.getPeerPrincipal()); - } - - @Override - public Principal getAuthenticatedPrincipal(SaslServer server) - { - return new UsernamePrincipal(server.getAuthorizationID()); - } - }; - } - - public String getAddress() - { - return getRemoteAddress().toString(); - } - - public boolean isDurable() - { - return false; - } - - private final Logger RAW_LOGGER = LoggerFactory.getLogger("RAW"); - - - public synchronized void received(final ByteBuffer msg) - { - try - { - _lastReadTime = System.currentTimeMillis(); - if(RAW_LOGGER.isDebugEnabled()) - { - ByteBuffer dup = msg.duplicate(); - byte[] data = new byte[dup.remaining()]; - dup.get(data); - Binary bin = new Binary(data); - RAW_LOGGER.debug("RECV[" + getRemoteAddress() + "] : " + bin.toString()); - } - _readBytes += msg.remaining(); - switch(_state) - { - case A: - if (msg.hasRemaining()) - { - msg.get(); - } - else - { - break; - } - case M: - if (msg.hasRemaining()) - { - msg.get(); - } - else - { - _state = State.M; - break; - } - - case Q: - if (msg.hasRemaining()) - { - msg.get(); - } - else - { - _state = State.Q; - break; - } - case P: - if (msg.hasRemaining()) - { - msg.get(); - } - else - { - _state = State.P; - break; - } - case PROTOCOL: - if (msg.hasRemaining()) - { - msg.get(); - } - else - { - _state = State.PROTOCOL; - break; - } - case MAJOR: - if (msg.hasRemaining()) - { - _major = msg.get(); - } - else - { - _state = State.MAJOR; - break; - } - case MINOR: - if (msg.hasRemaining()) - { - _minor = msg.get(); - } - else - { - _state = State.MINOR; - break; - } - case REVISION: - if (msg.hasRemaining()) - { - _revision = msg.get(); - - _state = State.FRAME; - } - else - { - _state = State.REVISION; - break; - } - case FRAME: - if (msg.hasRemaining()) - { - Subject.doAs(_connection.getSubject(), new PrivilegedAction<Void>() - { - @Override - public Void run() - { - _frameHandler = _frameHandler.parse(msg); - return null; - } - }); - - } - } - } - catch(RuntimeException e) - { - exception(e); - } - } - - public void exception(Throwable throwable) - { - // noop - exception method is not used by new i/o layer - } - - public void closed() - { - try - { - // todo - try - { - _endpoint.inputClosed(); - } - finally - { - if (_endpoint != null && _endpoint.getConnectionEventListener() != null) - { - ((Connection_1_0) _endpoint.getConnectionEventListener()).closed(); - } - } - } - catch(RuntimeException e) - { - exception(e); - } - } - - public long getCreateTime() - { - return _createTime; - } - - - public boolean canSend() - { - return true; - } - - public void send(final AMQFrame amqFrame) - { - send(amqFrame, null); - } - - private static final Logger FRAME_LOGGER = LoggerFactory.getLogger("FRM"); - - - public void send(final AMQFrame amqFrame, ByteBuffer buf) - { - - synchronized (_sendLock) - { - _lastWriteTime = System.currentTimeMillis(); - if (FRAME_LOGGER.isDebugEnabled()) - { - FRAME_LOGGER.debug("SEND[" - + getRemoteAddress() - + "|" - + amqFrame.getChannel() - + "] : " - + amqFrame.getFrameBody()); - } - - _frameWriter.setValue(amqFrame); - - ByteBuffer dup = ByteBuffer.allocate(_endpoint.getMaxFrameSize()); - - int size = _frameWriter.writeToBuffer(dup); - if (size > _endpoint.getMaxFrameSize()) - { - throw new OversizeFrameException(amqFrame, size); - } - - dup.flip(); - _writtenBytes += dup.limit(); - - if (RAW_LOGGER.isDebugEnabled()) - { - ByteBuffer dup2 = dup.duplicate(); - byte[] data = new byte[dup2.remaining()]; - dup2.get(data); - Binary bin = new Binary(data); - RAW_LOGGER.debug("SEND[" + getRemoteAddress() + "] : " + bin.toString()); - } - - _sender.send(dup); - _sender.flush(); - - - } - } - - public void send(short channel, FrameBody body) - { - AMQFrame frame = AMQFrame.createAMQFrame(channel, body); - send(frame); - - } - - - - public void close() - { - _sender.close(); - } - - public void setLogOutput(final PrintWriter out) - { - _out = out; - } - - public long getConnectionId() - { - return _connectionId; - } - - @Override - public Subject getSubject() - { - return _connection.getSubject(); - } - - public long getLastReadTime() - { - return _lastReadTime; - } - - public long getLastWriteTime() - { - return _lastWriteTime; - } - - @Override - public boolean isTransportBlockedForWriting() - { - return _transportBlockedForWriting; - } - @Override - public void setTransportBlockedForWriting(final boolean blocked) - { - _transportBlockedForWriting = blocked; - _connection.transportStateChanged(); - - } - - public void flushBatched() - { - _sender.flush(); - } - - @Override - public void processPending() - { - _connection.processPending(); - - } - - @Override - public boolean hasWork() - { - return _stateChanged.get(); - } - - @Override - public void notifyWork() - { - _stateChanged.set(true); - - final Action<ServerProtocolEngine> listener = _workListener.get(); - if(listener != null) - { - listener.performAction(this); - } - } - - @Override - public void clearWork() - { - _stateChanged.set(false); - } - - @Override - public void setWorkListener(final Action<ServerProtocolEngine> listener) - { - _workListener.set(listener); - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/QueueDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/QueueDestination.java deleted file mode 100644 index e8e31dcd15..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/QueueDestination.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.MessageEnqueueRecord; -import org.apache.qpid.server.txn.ServerTransaction; - -public class QueueDestination extends MessageSourceDestination implements SendingDestination, ReceivingDestination -{ - private static final Accepted ACCEPTED = new Accepted(); - private static final Outcome[] OUTCOMES = new Outcome[] { ACCEPTED }; - - - public QueueDestination(AMQQueue queue) - { - super(queue); - } - - public Outcome[] getOutcomes() - { - return OUTCOMES; - } - - public Outcome send(final Message_1_0 message, ServerTransaction txn) - { - - txn.enqueue(getQueue(),message, new ServerTransaction.EnqueueAction() - { - MessageReference _reference = message.newReference(); - - - public void postCommit(MessageEnqueueRecord... records) - { - try - { - getQueue().enqueue(message, null, records[0]); - } - finally - { - _reference.release(); - } - } - - public void onRollback() - { - _reference.release(); - } - }); - - - return ACCEPTED; - } - - public int getCredit() - { - // TODO - fix - return 100; - } - - public AMQQueue getQueue() - { - return (AMQQueue) super.getQueue(); - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java deleted file mode 100644 index 4ae0596e25..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.Outcome; - -import org.apache.qpid.server.txn.ServerTransaction; - -public interface ReceivingDestination extends Destination -{ - - Outcome[] getOutcomes(); - - Outcome send(Message_1_0 message, ServerTransaction txn); - - int getCredit(); -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLinkAttachment.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLinkAttachment.java deleted file mode 100644 index 46b9682c74..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLinkAttachment.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.transport.DeliveryStateHandler; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.SendingLinkEndpoint; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Source; -import org.apache.qpid.amqp_1_0.type.Target; - -public class ReceivingLinkAttachment -{ - private final Session_1_0 _session; - private final ReceivingLinkEndpoint _endpoint; - - public ReceivingLinkAttachment(final Session_1_0 session, final ReceivingLinkEndpoint endpoint) - { - _session = session; - _endpoint = endpoint; - } - - public Session_1_0 getSession() - { - return _session; - } - - public ReceivingLinkEndpoint getEndpoint() - { - return _endpoint; - } - - public Source getSource() - { - return getEndpoint().getSource(); - } - - public void setDeliveryStateHandler(final DeliveryStateHandler handler) - { - getEndpoint().setDeliveryStateHandler(handler); - } - - public void updateDisposition(final Binary deliveryTag, final DeliveryState state, final boolean settled) - { - getEndpoint().updateDisposition(deliveryTag, state, settled); - } - - public Target getTarget() - { - return getEndpoint().getTarget(); - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLink_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLink_1_0.java deleted file mode 100644 index 5deec2bb35..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLink_1_0.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.qpid.amqp_1_0.messaging.SectionDecoderImpl; -import org.apache.qpid.amqp_1_0.transport.DeliveryStateHandler; -import org.apache.qpid.amqp_1_0.transport.LinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkListener; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.Target; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusDurability; -import org.apache.qpid.amqp_1_0.type.transaction.TransactionalState; -import org.apache.qpid.amqp_1_0.type.transport.Detach; -import org.apache.qpid.amqp_1_0.type.transport.ReceiverSettleMode; -import org.apache.qpid.amqp_1_0.type.transport.Transfer; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.store.MessageHandle; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class ReceivingLink_1_0 implements ReceivingLinkListener, Link_1_0, DeliveryStateHandler -{ - private VirtualHostImpl _vhost; - - private ReceivingDestination _destination; - private SectionDecoderImpl _sectionDecoder; - private volatile ReceivingLinkAttachment _attachment; - - - private ArrayList<Transfer> _incompleteMessage; - private TerminusDurability _durability; - - private Map<Binary, Outcome> _unsettledMap = Collections.synchronizedMap(new HashMap<Binary, Outcome>()); - private boolean _resumedMessage; - private Binary _messageDeliveryTag; - private ReceiverSettleMode _receivingSettlementMode; - - - public ReceivingLink_1_0(ReceivingLinkAttachment receivingLinkAttachment, VirtualHostImpl vhost, - ReceivingDestination destination) - { - _vhost = vhost; - _destination = destination; - _attachment = receivingLinkAttachment; - _receivingSettlementMode = receivingLinkAttachment.getEndpoint().getReceivingSettlementMode(); - - receivingLinkAttachment.setDeliveryStateHandler(this); - - _durability = ((Target)receivingLinkAttachment.getTarget()).getDurable(); - - _sectionDecoder = new SectionDecoderImpl(receivingLinkAttachment.getEndpoint().getSession().getConnection().getDescribedTypeRegistry()); - - - } - - public void messageTransfer(Transfer xfr) - { - // TODO - cope with fragmented messages - - List<ByteBuffer> fragments = null; - - - - if(Boolean.TRUE.equals(xfr.getMore()) && _incompleteMessage == null) - { - _incompleteMessage = new ArrayList<Transfer>(); - _incompleteMessage.add(xfr); - _resumedMessage = Boolean.TRUE.equals(xfr.getResume()); - _messageDeliveryTag = xfr.getDeliveryTag(); - return; - } - else if(_incompleteMessage != null) - { - _incompleteMessage.add(xfr); - - if(Boolean.TRUE.equals(xfr.getMore())) - { - return; - } - - fragments = new ArrayList<ByteBuffer>(_incompleteMessage.size()); - for(Transfer t : _incompleteMessage) - { - fragments.add(t.getPayload()); - } - _incompleteMessage=null; - - } - else - { - _resumedMessage = Boolean.TRUE.equals(xfr.getResume()); - _messageDeliveryTag = xfr.getDeliveryTag(); - fragments = Collections.singletonList(xfr.getPayload()); - } - - if(_resumedMessage) - { - if(_unsettledMap.containsKey(_messageDeliveryTag)) - { - Outcome outcome = _unsettledMap.get(_messageDeliveryTag); - boolean settled = ReceiverSettleMode.FIRST.equals(getReceivingSettlementMode()); - getEndpoint().updateDisposition(_messageDeliveryTag, (DeliveryState) outcome, settled); - if(settled) - { - _unsettledMap.remove(_messageDeliveryTag); - } - } - else - { - System.err.println("UNEXPECTED!!"); - System.err.println("Delivery Tag: " + _messageDeliveryTag); - System.err.println("_unsettledMap: " + _unsettledMap); - - } - } - else - { - MessageMetaData_1_0 mmd = null; - List<ByteBuffer> immutableSections = new ArrayList<ByteBuffer>(3); - mmd = new MessageMetaData_1_0(fragments.toArray(new ByteBuffer[fragments.size()]), - _sectionDecoder, - immutableSections); - - MessageHandle<MessageMetaData_1_0> handle = _vhost.getMessageStore().addMessage(mmd); - - boolean skipping = true; - int offset = 0; - - for(ByteBuffer bareMessageBuf : immutableSections) - { - handle.addContent(bareMessageBuf.duplicate()); - offset += bareMessageBuf.remaining(); - } - final StoredMessage<MessageMetaData_1_0> storedMessage = handle.allContentAdded(); - Message_1_0 message = new Message_1_0(storedMessage, fragments, getSession().getConnection().getReference()); - MessageReference<Message_1_0> reference = message.newReference(); - - Binary transactionId = null; - org.apache.qpid.amqp_1_0.type.DeliveryState xfrState = xfr.getState(); - if(xfrState != null) - { - if(xfrState instanceof TransactionalState) - { - transactionId = ((TransactionalState)xfrState).getTxnId(); - } - } - - ServerTransaction transaction = null; - if(transactionId != null) - { - transaction = getSession().getTransaction(transactionId); - } - else - { - Session_1_0 session = getSession(); - transaction = session != null ? session.getTransaction(null) : new AutoCommitTransaction(_vhost.getMessageStore()); - } - - Outcome outcome = _destination.send(message, transaction); - - DeliveryState resultantState; - - if(transactionId == null) - { - resultantState = (DeliveryState) outcome; - } - else - { - TransactionalState transactionalState = new TransactionalState(); - transactionalState.setOutcome(outcome); - transactionalState.setTxnId(transactionId); - resultantState = transactionalState; - - } - - - boolean settled = transaction instanceof AutoCommitTransaction && ReceiverSettleMode.FIRST.equals(getReceivingSettlementMode()); - - final Binary deliveryTag = xfr.getDeliveryTag(); - - if(!settled) - { - _unsettledMap.put(deliveryTag, outcome); - } - - getEndpoint().updateDisposition(deliveryTag, resultantState, settled); - - getSession().getConnectionModel().registerMessageReceived(message.getSize(), message.getArrivalTime()); - - if(!(transaction instanceof AutoCommitTransaction)) - { - ServerTransaction.Action a; - transaction.addPostTransactionAction(new ServerTransaction.Action() - { - public void postCommit() - { - getEndpoint().updateDisposition(deliveryTag, null, true); - } - - public void onRollback() - { - getEndpoint().updateDisposition(deliveryTag, null, true); - } - }); - } - - reference.release(); - } - } - - private ReceiverSettleMode getReceivingSettlementMode() - { - return _receivingSettlementMode; - } - - public void remoteDetached(LinkEndpoint endpoint, Detach detach) - { - //TODO - // if not durable or close - if(!TerminusDurability.UNSETTLED_STATE.equals(_durability) || - (detach != null && Boolean.TRUE.equals(detach.getClosed()))) - { - endpoint.close(); - } - else if(detach == null || detach.getError() != null) - { - _attachment = null; - } - } - - public void start() - { - getEndpoint().setLinkCredit(UnsignedInteger.valueOf(_destination.getCredit())); - getEndpoint().setCreditWindow(); - } - - public ReceivingLinkEndpoint getEndpoint() - { - return _attachment.getEndpoint(); - } - - - public Session_1_0 getSession() - { - ReceivingLinkAttachment attachment = _attachment; - return attachment == null ? null : attachment.getSession(); - } - - public void handle(Binary deliveryTag, DeliveryState state, Boolean settled) - { - if(Boolean.TRUE.equals(settled)) - { - _unsettledMap.remove(deliveryTag); - } - } - - public void setLinkAttachment(ReceivingLinkAttachment linkAttachment) - { - _attachment = linkAttachment; - _receivingSettlementMode = linkAttachment.getEndpoint().getReceivingSettlementMode(); - ReceivingLinkEndpoint endpoint = linkAttachment.getEndpoint(); - Map initialUnsettledMap = endpoint.getInitialUnsettledMap(); - - Map<Binary, Outcome> unsettledCopy = new HashMap<Binary, Outcome>(_unsettledMap); - for(Map.Entry<Binary, Outcome> entry : unsettledCopy.entrySet()) - { - Binary deliveryTag = entry.getKey(); - if(!initialUnsettledMap.containsKey(deliveryTag)) - { - _unsettledMap.remove(deliveryTag); - } - } - - } - - public Map getUnsettledOutcomeMap() - { - return _unsettledMap; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingDestination.java deleted file mode 100644 index 6d601c9dda..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingDestination.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - - -public interface SendingDestination extends Destination -{ - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkAttachment.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkAttachment.java deleted file mode 100644 index 09a2ddea3a..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkAttachment.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.transport.DeliveryStateHandler; -import org.apache.qpid.amqp_1_0.transport.SendingLinkEndpoint; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Source; - -public class SendingLinkAttachment -{ - private final Session_1_0 _session; - private final SendingLinkEndpoint _endpoint; - - public SendingLinkAttachment(final Session_1_0 session, final SendingLinkEndpoint endpoint) - { - _session = session; - _endpoint = endpoint; - } - - public Session_1_0 getSession() - { - return _session; - } - - public SendingLinkEndpoint getEndpoint() - { - return _endpoint; - } - - public Source getSource() - { - return getEndpoint().getSource(); - } - - public void setDeliveryStateHandler(final DeliveryStateHandler handler) - { - getEndpoint().setDeliveryStateHandler(handler); - } - - public void updateDisposition(final Binary deliveryTag, final DeliveryState state, final boolean settled) - { - getEndpoint().updateDisposition(deliveryTag, state, settled); - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLink_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLink_1_0.java deleted file mode 100644 index ec57284a78..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLink_1_0.java +++ /dev/null @@ -1,719 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import java.security.AccessControlException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.amqp_1_0.transport.DeliveryStateHandler; -import org.apache.qpid.amqp_1_0.transport.LinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.SendingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.SendingLinkListener; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.amqp_1_0.type.messaging.ExactSubjectFilter; -import org.apache.qpid.amqp_1_0.type.messaging.Filter; -import org.apache.qpid.amqp_1_0.type.messaging.MatchingSubjectFilter; -import org.apache.qpid.amqp_1_0.type.messaging.Modified; -import org.apache.qpid.amqp_1_0.type.messaging.NoLocalFilter; -import org.apache.qpid.amqp_1_0.type.messaging.Released; -import org.apache.qpid.amqp_1_0.type.messaging.Source; -import org.apache.qpid.amqp_1_0.type.messaging.StdDistMode; -import org.apache.qpid.amqp_1_0.type.messaging.Target; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusDurability; -import org.apache.qpid.amqp_1_0.type.transport.AmqpError; -import org.apache.qpid.amqp_1_0.type.transport.Detach; -import org.apache.qpid.amqp_1_0.type.transport.Error; -import org.apache.qpid.amqp_1_0.type.transport.Transfer; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.filter.SelectorParsingException; -import org.apache.qpid.filter.selector.ParseException; -import org.apache.qpid.server.binding.BindingImpl; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.filter.FilterManager; -import org.apache.qpid.server.filter.JMSSelectorFilter; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.model.ExclusivityPolicy; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class SendingLink_1_0 implements SendingLinkListener, Link_1_0, DeliveryStateHandler -{ - private static final Logger _logger = LoggerFactory.getLogger(SendingLink_1_0.class); - - private VirtualHostImpl _vhost; - private SendingDestination _destination; - - private ConsumerImpl _consumer; - private ConsumerTarget_1_0 _target; - - private boolean _draining; - private final Map<Binary, MessageInstance> _unsettledMap = - new HashMap<Binary, MessageInstance>(); - - private final ConcurrentMap<Binary, UnsettledAction> _unsettledActionMap = - new ConcurrentHashMap<Binary, UnsettledAction>(); - private volatile SendingLinkAttachment _linkAttachment; - private TerminusDurability _durability; - private List<MessageInstance> _resumeFullTransfers = new ArrayList<MessageInstance>(); - private List<Binary> _resumeAcceptedTransfers = new ArrayList<Binary>(); - private Runnable _closeAction; - private final MessageSource _queue; - - - public SendingLink_1_0(final SendingLinkAttachment linkAttachment, - final VirtualHostImpl vhost, - final SendingDestination destination) - throws AmqpErrorException - { - _vhost = vhost; - _destination = destination; - _linkAttachment = linkAttachment; - final Source source = (Source) linkAttachment.getSource(); - _durability = source.getDurable(); - linkAttachment.setDeliveryStateHandler(this); - QueueDestination qd = null; - - EnumSet<ConsumerImpl.Option> options = EnumSet.noneOf(ConsumerImpl.Option.class); - - - boolean noLocal = false; - JMSSelectorFilter messageFilter = null; - - if(destination instanceof MessageSourceDestination) - { - _queue = ((MessageSourceDestination) _destination).getQueue(); - - if(_queue instanceof AMQQueue && ((AMQQueue)_queue).getAvailableAttributes().contains("topic")) - { - source.setDistributionMode(StdDistMode.COPY); - } - - Map<Symbol,Filter> filters = source.getFilter(); - - Map<Symbol,Filter> actualFilters = new HashMap<Symbol,Filter>(); - - if(filters != null) - { - for(Map.Entry<Symbol,Filter> entry : filters.entrySet()) - { - if(entry.getValue() instanceof NoLocalFilter) - { - actualFilters.put(entry.getKey(), entry.getValue()); - noLocal = true; - } - else if(messageFilter == null && entry.getValue() instanceof org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter) - { - - org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter selectorFilter = (org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter) entry.getValue(); - try - { - messageFilter = new JMSSelectorFilter(selectorFilter.getValue()); - - actualFilters.put(entry.getKey(), entry.getValue()); - } - catch (ParseException | SelectorParsingException e) - { - Error error = new Error(); - error.setCondition(AmqpError.INVALID_FIELD); - error.setDescription("Invalid JMS Selector: " + selectorFilter.getValue()); - error.setInfo(Collections.singletonMap(Symbol.valueOf("field"), Symbol.valueOf("filter"))); - throw new AmqpErrorException(error); - } - - - } - } - } - source.setFilter(actualFilters.isEmpty() ? null : actualFilters); - - _target = new ConsumerTarget_1_0(this, source.getDistributionMode() != StdDistMode.COPY); - if(source.getDistributionMode() != StdDistMode.COPY) - { - options.add(ConsumerImpl.Option.ACQUIRES); - options.add(ConsumerImpl.Option.SEES_REQUEUES); - } - - } - else if(destination instanceof ExchangeDestination) - { - try - { - - ExchangeDestination exchangeDestination = (ExchangeDestination) destination; - - boolean isDurable = exchangeDestination.getDurability() == TerminusDurability.CONFIGURATION - || exchangeDestination.getDurability() == TerminusDurability.UNSETTLED_STATE; - String name; - if(isDurable) - { - String remoteContainerId = getEndpoint().getSession().getConnection().getRemoteContainerId(); - remoteContainerId = remoteContainerId.replace("_","__").replace(".", "_:"); - - String endpointName = linkAttachment.getEndpoint().getName(); - endpointName = endpointName - .replace("_", "__") - .replace(".", "_:") - .replace("(", "_O") - .replace(")", "_C") - .replace("<", "_L") - .replace(">", "_R"); - name = "qpid_/" + remoteContainerId + "_/" + endpointName; - } - else - { - name = UUID.randomUUID().toString(); - } - - AMQQueue queue = _vhost.getQueue(name); - ExchangeImpl exchange = exchangeDestination.getExchange(); - - if(queue == null) - { - Map<String,Object> attributes = new HashMap<String,Object>(); - attributes.put(Queue.ID, UUID.randomUUID()); - attributes.put(Queue.NAME, name); - attributes.put(Queue.DURABLE, isDurable); - attributes.put(Queue.LIFETIME_POLICY, LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS); - attributes.put(Queue.EXCLUSIVE, ExclusivityPolicy.LINK); - - queue = _vhost.createQueue(attributes); - } - else - { - Collection<BindingImpl> bindings = queue.getBindings(); - List<BindingImpl> bindingsToRemove = new ArrayList<BindingImpl>(); - for(BindingImpl existingBinding : bindings) - { - if(existingBinding.getExchange() != exchange) - { - bindingsToRemove.add(existingBinding); - } - } - for(BindingImpl existingBinding : bindingsToRemove) - { - existingBinding.delete(); - } - } - - - String binding = null; - - Map<Symbol,Filter> filters = source.getFilter(); - Map<Symbol,Filter> actualFilters = new HashMap<Symbol,Filter>(); - boolean hasBindingFilter = false; - if(filters != null && !filters.isEmpty()) - { - - for(Map.Entry<Symbol,Filter> entry : filters.entrySet()) - { - if(!hasBindingFilter - && entry.getValue() instanceof ExactSubjectFilter - && exchange.getType().equals(ExchangeDefaults.DIRECT_EXCHANGE_CLASS)) - { - ExactSubjectFilter filter = (ExactSubjectFilter) filters.values().iterator().next(); - source.setFilter(filters); - binding = filter.getValue(); - actualFilters.put(entry.getKey(), entry.getValue()); - hasBindingFilter = true; - } - else if(!hasBindingFilter - && entry.getValue() instanceof MatchingSubjectFilter - && exchange.getType().equals(ExchangeDefaults.TOPIC_EXCHANGE_CLASS)) - { - MatchingSubjectFilter filter = (MatchingSubjectFilter) filters.values().iterator().next(); - source.setFilter(filters); - binding = filter.getValue(); - actualFilters.put(entry.getKey(), entry.getValue()); - hasBindingFilter = true; - } - else if(entry.getValue() instanceof NoLocalFilter) - { - actualFilters.put(entry.getKey(), entry.getValue()); - noLocal = true; - } - else if(messageFilter == null && entry.getValue() instanceof org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter) - { - - org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter selectorFilter = (org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter) entry.getValue(); - try - { - messageFilter = new JMSSelectorFilter(selectorFilter.getValue()); - - actualFilters.put(entry.getKey(), entry.getValue()); - } - catch (ParseException | SelectorParsingException e) - { - Error error = new Error(); - error.setCondition(AmqpError.INVALID_FIELD); - error.setDescription("Invalid JMS Selector: " + selectorFilter.getValue()); - error.setInfo(Collections.singletonMap(Symbol.valueOf("field"), Symbol.valueOf("filter"))); - throw new AmqpErrorException(error); - } - - - } - } - } - _queue = queue; - source.setFilter(actualFilters.isEmpty() ? null : actualFilters); - if(binding != null) - { - exchange.addBinding(binding, queue,null); - } - if(exchangeDestination.getInitialRoutingAddress() != null) - { - exchange.addBinding(exchangeDestination.getInitialRoutingAddress(),queue,null); - } - if(binding == null - && exchangeDestination.getInitialRoutingAddress() == null - && exchange.getType().equals(ExchangeDefaults.FANOUT_EXCHANGE_CLASS)) - { - exchange.addBinding(queue.getName(), queue, null); - } - else if(binding == null - && exchangeDestination.getInitialRoutingAddress() == null - && exchange.getType().equals(ExchangeDefaults.TOPIC_EXCHANGE_CLASS)) - { - exchange.addBinding("#", queue, null); - } - - source.setDistributionMode(StdDistMode.COPY); - - qd = new QueueDestination(queue); - } - catch (QueueExistsException e) - { - _logger.error("A randomly generated temporary queue name collided with an existing queue",e); - throw new ConnectionScopedRuntimeException(e); - } - - - _target = new ConsumerTarget_1_0(this, true); - options.add(ConsumerImpl.Option.ACQUIRES); - options.add(ConsumerImpl.Option.SEES_REQUEUES); - - } - else - { - throw new ConnectionScopedRuntimeException("Unknown destination type"); - } - - if(_target != null) - { - if(noLocal) - { - options.add(ConsumerImpl.Option.NO_LOCAL); - } - - if(_durability == TerminusDurability.CONFIGURATION || - _durability == TerminusDurability.UNSETTLED_STATE ) - { - options.add(ConsumerImpl.Option.DURABLE); - } - - try - { - final String name; - if(getEndpoint().getTarget() instanceof Target) - { - Target target = (Target) getEndpoint().getTarget(); - name = target.getAddress() == null ? getEndpoint().getName() : target.getAddress(); - } - else - { - name = getEndpoint().getName(); - } - - FilterManager filters = null; - if(messageFilter != null) - { - filters = new FilterManager(); - filters.add(messageFilter.getName(), messageFilter); - } - - _consumer = _queue.addConsumer(_target, - filters, - Message_1_0.class, name, options); - } - catch (MessageSource.ExistingExclusiveConsumer e) - { - _logger.info("Cannot add a consumer to the destination as there is already an exclusive consumer"); - throw new ConnectionScopedRuntimeException(e); - } - catch (MessageSource.ExistingConsumerPreventsExclusive e) - { - _logger.info("Cannot add an exclusive consumer to the destination as there is already a consumer"); - throw new ConnectionScopedRuntimeException(e); - } - catch (MessageSource.ConsumerAccessRefused e) - { - _logger.info("Cannot add an exclusive consumer to the destination as there is an incompatible exclusivity policy"); - throw new ConnectionScopedRuntimeException(e); - } - } - - } - - public void resume(SendingLinkAttachment linkAttachment) - { - _linkAttachment = linkAttachment; - } - - public void remoteDetached(final LinkEndpoint endpoint, final Detach detach) - { - //TODO - // if not durable or close - if(Boolean.TRUE.equals(detach.getClosed()) - || !(TerminusDurability.UNSETTLED_STATE.equals(_durability)|| TerminusDurability.CONFIGURATION.equals(_durability))) - { - _consumer.close(); - - Modified state = new Modified(); - state.setDeliveryFailed(true); - - for(UnsettledAction action : _unsettledActionMap.values()) - { - - action.process(state,Boolean.TRUE); - } - _unsettledActionMap.clear(); - - endpoint.close(); - - if(_destination instanceof ExchangeDestination - && (_durability == TerminusDurability.CONFIGURATION - || _durability == TerminusDurability.UNSETTLED_STATE)) - { - try - { - _vhost.removeQueue((AMQQueue)_queue); - } - catch (AccessControlException e) - { - //TODO - _logger.error("Error registering subscription", e); - } - } - - if(_closeAction != null) - { - _closeAction.run(); - } - - } - else if(detach.getError() != null - && !_linkAttachment.getEndpoint().getSession().isSyntheticError(detach.getError())) - { - _linkAttachment = null; - _target.flowStateChanged(); - } - else - { - endpoint.detach(); - } - } - - public void start() - { - //TODO - } - - public SendingLinkEndpoint getEndpoint() - { - return _linkAttachment == null ? null : _linkAttachment.getEndpoint() ; - } - - public Session_1_0 getSession() - { - return _linkAttachment == null ? null : _linkAttachment.getSession(); - } - - public void flowStateChanged() - { - if(Boolean.TRUE.equals(getEndpoint().getDrain()) - && hasCredit()) - { - _draining = true; - _target.flush(); - } - - while(!_resumeAcceptedTransfers.isEmpty() && getEndpoint().hasCreditToSend()) - { - Accepted accepted = new Accepted(); - synchronized(getLock()) - { - - Transfer xfr = new Transfer(); - Binary dt = _resumeAcceptedTransfers.remove(0); - xfr.setDeliveryTag(dt); - xfr.setState(accepted); - xfr.setResume(Boolean.TRUE); - getEndpoint().transfer(xfr); - } - - } - if(_resumeAcceptedTransfers.isEmpty()) - { - _target.flowStateChanged(); - } - - } - - boolean hasCredit() - { - return getEndpoint().getLinkCredit().compareTo(UnsignedInteger.ZERO) > 0; - } - - public boolean isDraining() - { - return false; //TODO - } - - public boolean drained() - { - if(getEndpoint() != null) - { - synchronized(getEndpoint().getLock()) - { - if(_draining) - { - //TODO - getEndpoint().drained(); - _draining = false; - return true; - } - else - { - return false; - } - } - } - else - { - return false; - } - } - - public void addUnsettled(Binary tag, UnsettledAction unsettledAction, MessageInstance queueEntry) - { - _unsettledActionMap.put(tag,unsettledAction); - if(getTransactionId() == null) - { - _unsettledMap.put(tag, queueEntry); - } - } - - public void removeUnsettled(Binary tag) - { - _unsettledActionMap.remove(tag); - } - - public void handle(Binary deliveryTag, DeliveryState state, Boolean settled) - { - UnsettledAction action = _unsettledActionMap.get(deliveryTag); - boolean localSettle = false; - if(action != null) - { - localSettle = action.process(state, settled); - if(localSettle && !Boolean.TRUE.equals(settled)) - { - _linkAttachment.updateDisposition(deliveryTag, state, true); - } - } - if(Boolean.TRUE.equals(settled) || localSettle) - { - _unsettledActionMap.remove(deliveryTag); - _unsettledMap.remove(deliveryTag); - } - } - - ServerTransaction getTransaction(Binary transactionId) - { - return _linkAttachment.getSession().getTransaction(transactionId); - } - - public Binary getTransactionId() - { - SendingLinkEndpoint endpoint = getEndpoint(); - return endpoint == null ? null : endpoint.getTransactionId(); - } - - public synchronized Object getLock() - { - return _linkAttachment == null ? this : getEndpoint().getLock(); - } - - public boolean isDetached() - { - return _linkAttachment == null || getEndpoint().isDetached(); - } - - public boolean isAttached() - { - return _linkAttachment != null && getEndpoint().isAttached(); - } - - public synchronized void setLinkAttachment(SendingLinkAttachment linkAttachment) - { - - if(_consumer.isActive()) - { - _target.suspend(); - } - - _linkAttachment = linkAttachment; - - SendingLinkEndpoint endpoint = linkAttachment.getEndpoint(); - endpoint.setDeliveryStateHandler(this); - Map initialUnsettledMap = endpoint.getInitialUnsettledMap(); - Map<Binary, MessageInstance> unsettledCopy = new HashMap<Binary, MessageInstance>(_unsettledMap); - _resumeAcceptedTransfers.clear(); - _resumeFullTransfers.clear(); - - for(Map.Entry<Binary, MessageInstance> entry : unsettledCopy.entrySet()) - { - Binary deliveryTag = entry.getKey(); - final MessageInstance queueEntry = entry.getValue(); - if(initialUnsettledMap == null || !initialUnsettledMap.containsKey(deliveryTag)) - { - queueEntry.setRedelivered(); - queueEntry.release(); - _unsettledMap.remove(deliveryTag); - } - else if(initialUnsettledMap.get(deliveryTag) instanceof Outcome) - { - Outcome outcome = (Outcome) initialUnsettledMap.get(deliveryTag); - - if(outcome instanceof Accepted) - { - AutoCommitTransaction txn = new AutoCommitTransaction(_vhost.getMessageStore()); - if(_consumer.acquires()) - { - if(queueEntry.acquire() || queueEntry.isAcquired()) - { - txn.dequeue(Collections.singleton(queueEntry), - new ServerTransaction.Action() - { - public void postCommit() - { - queueEntry.delete(); - } - - public void onRollback() - { - } - }); - } - } - } - else if(outcome instanceof Released) - { - AutoCommitTransaction txn = new AutoCommitTransaction(_vhost.getMessageStore()); - if(_consumer.acquires()) - { - txn.dequeue(Collections.singleton(queueEntry), - new ServerTransaction.Action() - { - public void postCommit() - { - queueEntry.release(); - } - - public void onRollback() - { - //To change body of implemented methods use File | Settings | File Templates. - } - }); - } - } - //_unsettledMap.remove(deliveryTag); - initialUnsettledMap.remove(deliveryTag); - _resumeAcceptedTransfers.add(deliveryTag); - } - else - { - _resumeFullTransfers.add(queueEntry); - // exists in receivers map, but not yet got an outcome ... should resend with resume = true - } - // TODO - else - } - - - } - - public Map getUnsettledOutcomeMap() - { - Map<Binary, MessageInstance> unsettled = new HashMap<Binary, MessageInstance>(_unsettledMap); - - for(Map.Entry<Binary, MessageInstance> entry : unsettled.entrySet()) - { - entry.setValue(null); - } - - return unsettled; - } - - public void setCloseAction(Runnable action) - { - _closeAction = action; - } - - public VirtualHostImpl getVirtualHost() - { - return _vhost; - } - - public ConsumerImpl getConsumer() - { - return _consumer; - } - - public ConsumerTarget_1_0 getConsumerTarget() - { - return _target; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java deleted file mode 100644 index b65fe06980..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java +++ /dev/null @@ -1,962 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CHANNEL_FORMAT; - -import java.security.AccessControlException; -import java.security.PrivilegedAction; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.amqp_1_0.transport.LinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkListener; -import org.apache.qpid.amqp_1_0.transport.SendingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.SendingLinkListener; -import org.apache.qpid.amqp_1_0.transport.SessionEndpoint; -import org.apache.qpid.amqp_1_0.transport.SessionEventListener; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.LifetimePolicy; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.messaging.DeleteOnClose; -import org.apache.qpid.amqp_1_0.type.messaging.DeleteOnNoLinks; -import org.apache.qpid.amqp_1_0.type.messaging.DeleteOnNoLinksOrMessages; -import org.apache.qpid.amqp_1_0.type.messaging.DeleteOnNoMessages; -import org.apache.qpid.amqp_1_0.type.messaging.Source; -import org.apache.qpid.amqp_1_0.type.messaging.Target; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusDurability; -import org.apache.qpid.amqp_1_0.type.transaction.Coordinator; -import org.apache.qpid.amqp_1_0.type.transaction.TxnCapability; -import org.apache.qpid.amqp_1_0.type.transport.AmqpError; -import org.apache.qpid.amqp_1_0.type.transport.ConnectionError; -import org.apache.qpid.amqp_1_0.type.transport.Detach; -import org.apache.qpid.amqp_1_0.type.transport.End; -import org.apache.qpid.amqp_1_0.type.transport.Error; -import org.apache.qpid.amqp_1_0.type.transport.Role; -import org.apache.qpid.amqp_1_0.type.transport.Transfer; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.connection.SessionPrincipal; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.model.ConfigurationChangeListener; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.model.Session; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.ConsumerListener; -import org.apache.qpid.server.protocol.LinkRegistry; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class Session_1_0 implements SessionEventListener, AMQSessionModel<Session_1_0, Connection_1_0>, LogSubject -{ - private static final Logger _logger = LoggerFactory.getLogger(Session_1_0.class); - private static final Symbol LIFETIME_POLICY = Symbol.valueOf("lifetime-policy"); - private final SessionEndpoint _endpoint; - private AutoCommitTransaction _transaction; - - private final LinkedHashMap<Integer, ServerTransaction> _openTransactions = - new LinkedHashMap<Integer, ServerTransaction>(); - - private final CopyOnWriteArrayList<Action<? super Session_1_0>> _taskList = - new CopyOnWriteArrayList<Action<? super Session_1_0>>(); - - private final Connection_1_0 _connection; - private UUID _id = UUID.randomUUID(); - private AtomicBoolean _closed = new AtomicBoolean(); - private final Subject _subject = new Subject(); - - private final CopyOnWriteArrayList<Consumer<?>> _consumers = new CopyOnWriteArrayList<Consumer<?>>(); - private final CopyOnWriteArrayList<SendingLink_1_0> _sendingLinks = new CopyOnWriteArrayList<>(); - private final ConfigurationChangeListener _consumerClosedListener = new ConsumerClosedListener(); - private final CopyOnWriteArrayList<ConsumerListener> _consumerListeners = new CopyOnWriteArrayList<ConsumerListener>(); - private Session<?> _modelObject; - - - public Session_1_0(final Connection_1_0 connection, final SessionEndpoint endpoint) - { - _endpoint = endpoint; - _connection = connection; - _subject.getPrincipals().addAll(connection.getSubject().getPrincipals()); - _subject.getPrincipals().add(new SessionPrincipal(this)); - } - - public void remoteLinkCreation(final LinkEndpoint endpoint) - { - - Destination destination; - Link_1_0 link = null; - Error error = null; - - final - LinkRegistry - linkRegistry = getVirtualHost().getLinkRegistry(endpoint.getSession().getConnection().getRemoteContainerId()); - - - if(endpoint.getRole() == Role.SENDER) - { - - final SendingLink_1_0 previousLink = (SendingLink_1_0) linkRegistry.getDurableSendingLink(endpoint.getName()); - - if(previousLink == null) - { - - Target target = (Target) endpoint.getTarget(); - Source source = (Source) endpoint.getSource(); - - - if(source != null) - { - if(Boolean.TRUE.equals(source.getDynamic())) - { - AMQQueue tempQueue = createTemporaryQueue(source.getDynamicNodeProperties()); - source.setAddress(tempQueue.getName()); - } - String addr = source.getAddress(); - if(!addr.startsWith("/") && addr.contains("/")) - { - String[] parts = addr.split("/",2); - ExchangeImpl exchg = getVirtualHost().getExchange(parts[0]); - if(exchg != null) - { - ExchangeDestination exchangeDestination = - new ExchangeDestination(exchg, source.getDurable(), source.getExpiryPolicy()); - exchangeDestination.setInitialRoutingAddress(parts[1]); - destination = exchangeDestination; - - } - else - { - endpoint.setSource(null); - destination = null; - } - } - else - { - MessageSource queue = getVirtualHost().getMessageSource(addr); - if(queue != null) - { - destination = new MessageSourceDestination(queue); - } - else - { - ExchangeImpl exchg = getVirtualHost().getExchange(addr); - if(exchg != null) - { - destination = new ExchangeDestination(exchg, source.getDurable(), source.getExpiryPolicy()); - } - else - { - endpoint.setSource(null); - destination = null; - } - } - } - - } - else - { - destination = null; - } - - if(destination != null) - { - final SendingLinkEndpoint sendingLinkEndpoint = (SendingLinkEndpoint) endpoint; - try - { - final SendingLink_1_0 sendingLink = new SendingLink_1_0(new SendingLinkAttachment(this, sendingLinkEndpoint), - getVirtualHost(), - (SendingDestination) destination - ); - - sendingLinkEndpoint.setLinkEventListener(new SubjectSpecificSendingLinkListener(sendingLink)); - registerConsumer(sendingLink); - - link = sendingLink; - if(TerminusDurability.UNSETTLED_STATE.equals(source.getDurable()) || TerminusDurability.CONFIGURATION.equals(source.getDurable())) - { - linkRegistry.registerSendingLink(endpoint.getName(), sendingLink); - } - } - catch(AmqpErrorException e) - { - _logger.error("Error creating sending link", e); - destination = null; - sendingLinkEndpoint.setSource(null); - error = e.getError(); - } - } - } - else - { - Source newSource = (Source) endpoint.getSource(); - - Source oldSource = (Source) previousLink.getEndpoint().getSource(); - final TerminusDurability newSourceDurable = newSource == null ? null : newSource.getDurable(); - if(newSourceDurable != null) - { - oldSource.setDurable(newSourceDurable); - if(newSourceDurable.equals(TerminusDurability.NONE)) - { - linkRegistry.unregisterSendingLink(endpoint.getName()); - } - } - endpoint.setSource(oldSource); - SendingLinkEndpoint sendingLinkEndpoint = (SendingLinkEndpoint) endpoint; - previousLink.setLinkAttachment(new SendingLinkAttachment(this, sendingLinkEndpoint)); - sendingLinkEndpoint.setLinkEventListener(new SubjectSpecificSendingLinkListener(previousLink)); - link = previousLink; - endpoint.setLocalUnsettled(previousLink.getUnsettledOutcomeMap()); - } - } - else - { - if(endpoint.getTarget() instanceof Coordinator) - { - Coordinator coordinator = (Coordinator) endpoint.getTarget(); - TxnCapability[] capabilities = coordinator.getCapabilities(); - boolean localTxn = false; - boolean multiplePerSession = false; - if(capabilities != null) - { - for(TxnCapability capability : capabilities) - { - if(capability.equals(TxnCapability.LOCAL_TXN)) - { - localTxn = true; - } - else if(capability.equals(TxnCapability.MULTI_TXNS_PER_SSN)) - { - multiplePerSession = true; - } - else - { - error = new Error(); - error.setCondition(AmqpError.NOT_IMPLEMENTED); - error.setDescription("Unsupported capability: " + capability); - break; - } - } - } - - /* if(!localTxn) - { - capabilities.add(TxnCapabilities.LOCAL_TXN); - }*/ - - final ReceivingLinkEndpoint receivingLinkEndpoint = (ReceivingLinkEndpoint) endpoint; - final TxnCoordinatorLink_1_0 coordinatorLink = - new TxnCoordinatorLink_1_0(getVirtualHost(), this, receivingLinkEndpoint, _openTransactions); - receivingLinkEndpoint.setLinkEventListener(new SubjectSpecificReceivingLinkListener(coordinatorLink)); - link = coordinatorLink; - - - } - else - { - - ReceivingLink_1_0 previousLink = - (ReceivingLink_1_0) linkRegistry.getDurableReceivingLink(endpoint.getName()); - - if(previousLink == null) - { - - Target target = (Target) endpoint.getTarget(); - - if(target != null) - { - if(Boolean.TRUE.equals(target.getDynamic())) - { - - AMQQueue tempQueue = createTemporaryQueue(target.getDynamicNodeProperties()); - target.setAddress(tempQueue.getName()); - } - - String addr = target.getAddress(); - if(!addr.startsWith("/") && addr.contains("/")) - { - String[] parts = addr.split("/",2); - ExchangeImpl exchange = getVirtualHost().getExchange(parts[0]); - if(exchange != null) - { - ExchangeDestination exchangeDestination = - new ExchangeDestination(exchange, - target.getDurable(), - target.getExpiryPolicy()); - - exchangeDestination.setInitialRoutingAddress(parts[1]); - - destination = exchangeDestination; - - } - else - { - endpoint.setTarget(null); - destination = null; - } - } - else - { - MessageDestination messageDestination = getVirtualHost().getMessageDestination(addr); - if(messageDestination != null) - { - destination = new NodeReceivingDestination(messageDestination, target.getDurable(), - target.getExpiryPolicy()); - } - else - { - AMQQueue queue = getVirtualHost().getQueue(addr); - if(queue != null) - { - - destination = new QueueDestination(queue); - } - else - { - endpoint.setTarget(null); - destination = null; - } - - } - } - - } - else - { - destination = null; - } - if(destination != null) - { - final ReceivingLinkEndpoint receivingLinkEndpoint = (ReceivingLinkEndpoint) endpoint; - final ReceivingLink_1_0 receivingLink = new ReceivingLink_1_0(new ReceivingLinkAttachment(this, receivingLinkEndpoint), - getVirtualHost(), - (ReceivingDestination) destination); - - receivingLinkEndpoint.setLinkEventListener(new SubjectSpecificReceivingLinkListener(receivingLink)); - - link = receivingLink; - if(TerminusDurability.UNSETTLED_STATE.equals(target.getDurable()) - || TerminusDurability.CONFIGURATION.equals(target.getDurable())) - { - linkRegistry.registerReceivingLink(endpoint.getName(), receivingLink); - } - } - } - else - { - ReceivingLinkEndpoint receivingLinkEndpoint = (ReceivingLinkEndpoint) endpoint; - previousLink.setLinkAttachment(new ReceivingLinkAttachment(this, receivingLinkEndpoint)); - receivingLinkEndpoint.setLinkEventListener(previousLink); - link = previousLink; - endpoint.setLocalUnsettled(previousLink.getUnsettledOutcomeMap()); - - } - } - } - - endpoint.attach(); - - if(link == null) - { - if(error == null) - { - error = new Error(); - error.setCondition(AmqpError.NOT_FOUND); - } - endpoint.close(error); - } - else - { - link.start(); - } - } - - private void registerConsumer(final SendingLink_1_0 link) - { - ConsumerImpl consumer = link.getConsumer(); - if(consumer instanceof Consumer<?>) - { - Consumer<?> modelConsumer = (Consumer<?>) consumer; - _consumers.add(modelConsumer); - _sendingLinks.add(link); - modelConsumer.addChangeListener(_consumerClosedListener); - consumerAdded(modelConsumer); - } - } - - - private AMQQueue createTemporaryQueue(Map properties) - { - final String queueName = UUID.randomUUID().toString(); - AMQQueue queue = null; - try - { - LifetimePolicy lifetimePolicy = properties == null - ? null - : (LifetimePolicy) properties.get(LIFETIME_POLICY); - Map<String,Object> attributes = new HashMap<String,Object>(); - attributes.put(org.apache.qpid.server.model.Queue.ID, UUID.randomUUID()); - attributes.put(org.apache.qpid.server.model.Queue.NAME, queueName); - attributes.put(org.apache.qpid.server.model.Queue.DURABLE, false); - - if(lifetimePolicy instanceof DeleteOnNoLinks) - { - attributes.put(org.apache.qpid.server.model.Queue.LIFETIME_POLICY, - org.apache.qpid.server.model.LifetimePolicy.DELETE_ON_NO_LINKS); - } - else if(lifetimePolicy instanceof DeleteOnNoLinksOrMessages) - { - attributes.put(org.apache.qpid.server.model.Queue.LIFETIME_POLICY, - org.apache.qpid.server.model.LifetimePolicy.IN_USE); - } - else if(lifetimePolicy instanceof DeleteOnClose) - { - attributes.put(org.apache.qpid.server.model.Queue.LIFETIME_POLICY, - org.apache.qpid.server.model.LifetimePolicy.DELETE_ON_CONNECTION_CLOSE); - } - else if(lifetimePolicy instanceof DeleteOnNoMessages) - { - attributes.put(org.apache.qpid.server.model.Queue.LIFETIME_POLICY, - org.apache.qpid.server.model.LifetimePolicy.IN_USE); - } - else - { - attributes.put(org.apache.qpid.server.model.Queue.LIFETIME_POLICY, - org.apache.qpid.server.model.LifetimePolicy.DELETE_ON_CONNECTION_CLOSE); - } - - - // TODO convert AMQP 1-0 node properties to queue attributes - - queue = getVirtualHost().createQueue(attributes); - } - catch (AccessControlException e) - { - //TODO - _logger.info("Security error", e); - throw new ConnectionScopedRuntimeException(e); - } - catch (QueueExistsException e) - { - _logger.error("A temporary queue was created with a name which collided with an existing queue name"); - throw new ConnectionScopedRuntimeException(e); - } - - return queue; - } - - public ServerTransaction getTransaction(Binary transactionId) - { - // TODO should treat invalid id differently to null - ServerTransaction transaction = _openTransactions.get(binaryToInteger(transactionId)); - if(transaction == null) - { - if(_transaction == null) - { - _transaction = new AutoCommitTransaction(_connection.getVirtualHost().getMessageStore()); - } - transaction = _transaction; - } - return transaction; - } - - public void remoteEnd(End end) - { - Iterator<Map.Entry<Integer, ServerTransaction>> iter = _openTransactions.entrySet().iterator(); - - while(iter.hasNext()) - { - Map.Entry<Integer, ServerTransaction> entry = iter.next(); - entry.getValue().rollback(); - iter.remove(); - } - - for(LinkEndpoint linkEndpoint : _endpoint.getLocalLinkEndpoints()) - { - linkEndpoint.remoteDetached(new Detach()); - } - - _connection.sessionEnded(this); - performCloseTasks(); - if(_modelObject != null) - { - _modelObject.delete(); - } - - } - - Integer binaryToInteger(final Binary txnId) - { - if(txnId == null) - { - return null; - } - - if(txnId.getLength() > 4) - throw new IllegalArgumentException(); - - int id = 0; - byte[] data = txnId.getArray(); - for(int i = 0; i < txnId.getLength(); i++) - { - id <<= 8; - id += ((int)data[i+txnId.getArrayOffset()] & 0xff); - } - - return id; - - } - - Binary integerToBinary(final int txnId) - { - byte[] data = new byte[4]; - data[3] = (byte) (txnId & 0xff); - data[2] = (byte) ((txnId & 0xff00) >> 8); - data[1] = (byte) ((txnId & 0xff0000) >> 16); - data[0] = (byte) ((txnId & 0xff000000) >> 24); - return new Binary(data); - - } - - @Override - public UUID getId() - { - return _id; - } - - @Override - public Connection_1_0 getConnectionModel() - { - return _connection; - } - - @Override - public String getClientID() - { - // TODO - return ""; - } - - @Override - public void close() - { - performCloseTasks(); - _endpoint.end(); - if(_modelObject != null) - { - _modelObject.delete(); - } - } - - protected void performCloseTasks() - { - - if(_closed.compareAndSet(false, true)) - { - List<Action<? super Session_1_0>> taskList = new ArrayList<Action<? super Session_1_0>>(_taskList); - _taskList.clear(); - for(Action<? super Session_1_0> task : taskList) - { - task.performAction(this); - } - } - } - - - @Override - public void close(AMQConstant cause, String message) - { - performCloseTasks(); - final End end = new End(); - final Error theError = new Error(); - theError.setDescription(message); - theError.setCondition(ConnectionError.CONNECTION_FORCED); - end.setError(theError); - _endpoint.end(end); - } - - @Override - public void transportStateChanged() - { - for(SendingLink_1_0 link : _sendingLinks) - { - ConsumerTarget_1_0 target = link.getConsumerTarget(); - target.flowStateChanged(); - - - } - - - } - - @Override - public LogSubject getLogSubject() - { - return this; - } - - @Override - public void checkTransactionStatus(long openWarn, long openClose, long idleWarn, long idleClose) - { - // TODO - required for AMQSessionModel / long running transaction detection - } - - @Override - public void block(AMQQueue queue) - { - // TODO - required for AMQSessionModel / producer side flow control - } - - @Override - public void unblock(AMQQueue queue) - { - // TODO - required for AMQSessionModel / producer side flow control - } - - @Override - public void block() - { - // TODO - required for AMQSessionModel / producer side flow control - } - - @Override - public void unblock() - { - // TODO - required for AMQSessionModel / producer side flow control - } - - @Override - public boolean getBlocking() - { - // TODO - return false; - } - - @Override - public Object getConnectionReference() - { - return getConnection().getReference(); - } - - @Override - public int getUnacknowledgedMessageCount() - { - // TODO - return 0; - } - - @Override - public Long getTxnCount() - { - // TODO - return 0l; - } - - @Override - public Long getTxnStart() - { - // TODO - return 0l; - } - - @Override - public Long getTxnCommits() - { - // TODO - return 0l; - } - - @Override - public Long getTxnRejects() - { - // TODO - return 0l; - } - - @Override - public int getChannelId() - { - return _endpoint.getSendingChannel(); - } - - @Override - public int getConsumerCount() - { - return getConsumers().size(); - } - - - - public String toLogString() - { - long connectionId = getConnectionModel().getConnectionId(); - - String remoteAddress = getConnectionModel().getRemoteAddressString(); - - return "[" + - MessageFormat.format(CHANNEL_FORMAT, - connectionId, - getClientID(), - remoteAddress, - getVirtualHost().getName(), - _endpoint.getSendingChannel()) + "] "; - } - - @Override - public int compareTo(AMQSessionModel o) - { - return getId().compareTo(o.getId()); - } - - public Connection_1_0 getConnection() - { - return _connection; - } - - @Override - public void addDeleteTask(final Action<? super Session_1_0> task) - { - if(!_closed.get()) - { - _taskList.add(task); - } - } - - @Override - public void removeDeleteTask(final Action<? super Session_1_0> task) - { - _taskList.remove(task); - } - - public Subject getSubject() - { - return _subject; - } - - VirtualHostImpl getVirtualHost() - { - return _connection.getVirtualHost(); - } - - - private class SubjectSpecificReceivingLinkListener implements ReceivingLinkListener - { - private final ReceivingLinkListener _linkListener; - - public SubjectSpecificReceivingLinkListener(final ReceivingLinkListener linkListener) - { - _linkListener = linkListener; - } - - @Override - public void messageTransfer(final Transfer xfr) - { - Subject.doAs(_subject, new PrivilegedAction<Object>() - { - @Override - public Object run() - { - _linkListener.messageTransfer(xfr); - return null; - } - }); - } - - @Override - public void remoteDetached(final LinkEndpoint endpoint, final Detach detach) - { - Subject.doAs(_subject, new PrivilegedAction<Object>() - { - @Override - public Object run() - { - _linkListener.remoteDetached(endpoint, detach); - return null; - } - }); - } - } - - private class SubjectSpecificSendingLinkListener implements SendingLinkListener - { - private final SendingLink_1_0 _previousLink; - - public SubjectSpecificSendingLinkListener(final SendingLink_1_0 previousLink) - { - _previousLink = previousLink; - } - - @Override - public void flowStateChanged() - { - Subject.doAs(_subject, new PrivilegedAction<Object>() - { - @Override - public Object run() - { - _previousLink.flowStateChanged(); - return null; - } - }); - } - - @Override - public void remoteDetached(final LinkEndpoint endpoint, final Detach detach) - { - Subject.doAs(_subject, new PrivilegedAction<Object>() - { - @Override - public Object run() - { - _previousLink.remoteDetached(endpoint, detach); - return null; - } - }); - } - } - - - @Override - public Collection<Consumer<?>> getConsumers() - { - return Collections.unmodifiableCollection(_consumers); - } - - @Override - public void addConsumerListener(final ConsumerListener listener) - { - _consumerListeners.add(listener); - } - - @Override - public void removeConsumerListener(final ConsumerListener listener) - { - _consumerListeners.remove(listener); - } - - @Override - public void setModelObject(final Session<?> session) - { - _modelObject = session; - } - - @Override - public Session<?> getModelObject() - { - return _modelObject; - } - - @Override - public long getTransactionStartTime() - { - return 0L; - } - - @Override - public long getTransactionUpdateTime() - { - return 0L; - } - - @Override - public void processPending() - { - for(Consumer<?> consumer : getConsumers()) - { - - ((ConsumerImpl)consumer).getTarget().processPending(); - } - } - - private void consumerAdded(Consumer<?> consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerAdded(consumer); - } - } - - private void consumerRemoved(Consumer<?> consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerRemoved(consumer); - } - } - - private class ConsumerClosedListener implements ConfigurationChangeListener - { - @Override - public void stateChanged(final ConfiguredObject object, final org.apache.qpid.server.model.State oldState, final org.apache.qpid.server.model.State newState) - { - if(newState == org.apache.qpid.server.model.State.DELETED) - { - consumerRemoved((Consumer<?>)object); - } - } - - @Override - public void childAdded(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void childRemoved(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void attributeSet(final ConfiguredObject object, - final String attributeName, - final Object oldAttributeValue, - final Object newAttributeValue) - { - - } - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorLink_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorLink_1_0.java deleted file mode 100644 index 2d60291c2f..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorLink_1_0.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.amqp_1_0.messaging.SectionDecoder; -import org.apache.qpid.amqp_1_0.messaging.SectionDecoderImpl; -import org.apache.qpid.amqp_1_0.transport.LinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkListener; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpValue; -import org.apache.qpid.amqp_1_0.type.transaction.Declare; -import org.apache.qpid.amqp_1_0.type.transaction.Declared; -import org.apache.qpid.amqp_1_0.type.transaction.Discharge; -import org.apache.qpid.amqp_1_0.type.transport.AmqpError; -import org.apache.qpid.amqp_1_0.type.transport.Detach; -import org.apache.qpid.amqp_1_0.type.transport.Error; -import org.apache.qpid.amqp_1_0.type.transport.Transfer; -import org.apache.qpid.server.txn.LocalTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class TxnCoordinatorLink_1_0 implements ReceivingLinkListener, Link_1_0 -{ - private static final Logger _logger = LoggerFactory.getLogger(TxnCoordinatorLink_1_0.class); - private VirtualHostImpl _vhost; - private ReceivingLinkEndpoint _endpoint; - - private ArrayList<Transfer> _incompleteMessage; - private SectionDecoder _sectionDecoder; - private LinkedHashMap<Integer, ServerTransaction> _openTransactions; - private Session_1_0 _session; - - - public TxnCoordinatorLink_1_0(VirtualHostImpl vhost, - Session_1_0 session_1_0, ReceivingLinkEndpoint endpoint, - LinkedHashMap<Integer, ServerTransaction> openTransactions) - { - _vhost = vhost; - _session = session_1_0; - _endpoint = endpoint; - _sectionDecoder = new SectionDecoderImpl(endpoint.getSession().getConnection().getDescribedTypeRegistry()); - _openTransactions = openTransactions; - } - - public void messageTransfer(Transfer xfr) - { - // TODO - cope with fragmented messages - - ByteBuffer payload = null; - - - if(Boolean.TRUE.equals(xfr.getMore()) && _incompleteMessage == null) - { - _incompleteMessage = new ArrayList<Transfer>(); - _incompleteMessage.add(xfr); - return; - } - else if(_incompleteMessage != null) - { - _incompleteMessage.add(xfr); - if(Boolean.TRUE.equals(xfr.getMore())) - { - return; - } - - int size = 0; - for(Transfer t : _incompleteMessage) - { - size += t.getPayload().limit(); - } - payload = ByteBuffer.allocate(size); - for(Transfer t : _incompleteMessage) - { - payload.put(t.getPayload().duplicate()); - } - payload.flip(); - _incompleteMessage=null; - - } - else - { - payload = xfr.getPayload(); - } - - - // Only interested int he amqp-value section that holds the message to the coordinator - try - { - List<Section> sections = _sectionDecoder.parseAll(payload); - - for(Section section : sections) - { - if(section instanceof AmqpValue) - { - Object command = ((AmqpValue) section).getValue(); - - if(command instanceof Declare) - { - Integer txnId = Integer.valueOf(0); - Iterator<Integer> existingTxn = _openTransactions.keySet().iterator(); - while(existingTxn.hasNext()) - { - txnId = existingTxn.next(); - } - txnId = Integer.valueOf(txnId.intValue() + 1); - - _openTransactions.put(txnId, new LocalTransaction(_vhost.getMessageStore())); - - Declared state = new Declared(); - - - - state.setTxnId(_session.integerToBinary(txnId)); - _endpoint.updateDisposition(xfr.getDeliveryTag(), state, true); - - } - else if(command instanceof Discharge) - { - Discharge discharge = (Discharge) command; - - DeliveryState state = xfr.getState(); - discharge(_session.binaryToInteger(discharge.getTxnId()), discharge.getFail()); - _endpoint.updateDisposition(xfr.getDeliveryTag(), new Accepted(), true); - - } - } - } - - } - catch (AmqpErrorException e) - { - //TODO - _logger.error("AMQP error", e); - } - - } - - public void remoteDetached(LinkEndpoint endpoint, Detach detach) - { - //TODO - endpoint.detach(); - } - - private Error discharge(Integer transactionId, boolean fail) - { - Error error = null; - ServerTransaction txn = _openTransactions.get(transactionId); - if(txn != null) - { - if(fail) - { - txn.rollback(); - } - else - { - txn.commit(); - } - _openTransactions.remove(transactionId); - } - else - { - error = new Error(); - error.setCondition(AmqpError.NOT_FOUND); - error.setDescription("Unknown transactionId" + transactionId); - } - return error; - } - - - - public void start() - { - _endpoint.setLinkCredit(UnsignedInteger.ONE); - _endpoint.setCreditWindow(); - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/UnsettledAction.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/UnsettledAction.java deleted file mode 100644 index 0fee4086b4..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/UnsettledAction.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.DeliveryState; - -public interface UnsettledAction -{ - boolean process(DeliveryState state, Boolean settled); -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/pom.xml b/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/pom.xml deleted file mode 100644 index 6349661ad9..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-amqp-msg-conv-0-10-to-1-0</artifactId> - <name>Qpid AMQP 0-10 to 1-0 Message Conversion Broker Plug-in</name> - <description>AMQP message conversion (0-10 to 1-0) broker plug-in</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-common</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-plugins-amqp-0-10-protocol</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-amqp-1-0-common</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-plugins-amqp-1-0-protocol</artifactId> - <version>${project.version}</version> - </dependency> - </dependencies> - - <build> - </build> - -</project> diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0.java b/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0.java deleted file mode 100644 index 506e6b1850..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.protocol.converter.v0_10_v1_0; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.UnsignedByte; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.ApplicationProperties; -import org.apache.qpid.amqp_1_0.type.messaging.Header; -import org.apache.qpid.amqp_1_0.type.messaging.Properties; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage; -import org.apache.qpid.server.protocol.v1_0.MessageConverter_to_1_0; -import org.apache.qpid.server.protocol.v1_0.MessageMetaData_1_0; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.MessageDeliveryMode; -import org.apache.qpid.transport.MessageProperties; - -@PluggableService -public class MessageConverter_0_10_to_1_0 extends MessageConverter_to_1_0<MessageTransferMessage> -{ - @Override - public Class<MessageTransferMessage> getInputClass() - { - return MessageTransferMessage.class; - } - - - @Override - protected MessageMetaData_1_0 convertMetaData(MessageTransferMessage serverMessage, - SectionEncoder sectionEncoder) - { - List<Section> sections = new ArrayList<Section>(3); - final MessageProperties msgProps = serverMessage.getHeader().getMessageProperties(); - final DeliveryProperties deliveryProps = serverMessage.getHeader().getDeliveryProperties(); - - Header header = new Header(); - if(deliveryProps != null) - { - header.setDurable(deliveryProps.hasDeliveryMode() && deliveryProps.getDeliveryMode() == MessageDeliveryMode.PERSISTENT); - if(deliveryProps.hasPriority()) - { - header.setPriority(UnsignedByte.valueOf((byte) deliveryProps.getPriority().getValue())); - } - if(deliveryProps.hasTtl()) - { - header.setTtl(UnsignedInteger.valueOf(deliveryProps.getTtl())); - } - sections.add(header); - } - - Properties props = new Properties(); - - /* - TODO: the current properties are not currently set: - - absoluteExpiryTime - creationTime - groupId - groupSequence - replyToGroupId - to - */ - - if(msgProps != null) - { - if(msgProps.hasContentEncoding()) - { - props.setContentEncoding(Symbol.valueOf(msgProps.getContentEncoding())); - } - - if(msgProps.hasCorrelationId()) - { - props.setCorrelationId(msgProps.getCorrelationId()); - } - - if(msgProps.hasMessageId()) - { - props.setMessageId(msgProps.getMessageId()); - } - if(msgProps.hasReplyTo()) - { - props.setReplyTo(msgProps.getReplyTo().getExchange()+"/"+msgProps.getReplyTo().getRoutingKey()); - } - if(msgProps.hasContentType()) - { - props.setContentType(Symbol.valueOf(msgProps.getContentType())); - - // Modify the content type when we are dealing with java object messages produced by the Qpid 0.x client - if(props.getContentType() == Symbol.valueOf("application/java-object-stream")) - { - props.setContentType(Symbol.valueOf("application/x-java-serialized-object")); - } - } - - props.setSubject(serverMessage.getInitialRoutingAddress()); - - if(msgProps.hasUserId()) - { - props.setUserId(new Binary(msgProps.getUserId())); - } - - sections.add(props); - - Map<String, Object> applicationProperties = msgProps.getApplicationHeaders(); - - if(applicationProperties != null) - { - if(applicationProperties.containsKey("qpid.subject")) - { - props.setSubject(String.valueOf(applicationProperties.get("qpid.subject"))); - applicationProperties = new LinkedHashMap<>(applicationProperties); - applicationProperties.remove("qpid.subject"); - } - sections.add(new ApplicationProperties(applicationProperties)); - - } - } - return new MessageMetaData_1_0(sections, sectionEncoder); - } - - @Override - public String getType() - { - return "v0-10 to v1-0"; - } -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.java b/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.java deleted file mode 100644 index 789789ac33..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.converter.v0_10_v1_0; - -import java.nio.ByteBuffer; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_10.MessageMetaData_0_10; -import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage; -import org.apache.qpid.server.protocol.v1_0.MessageConverter_from_1_0; -import org.apache.qpid.server.protocol.v1_0.MessageMetaData_1_0; -import org.apache.qpid.server.protocol.v1_0.Message_1_0; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.ReplyTo; - -@PluggableService -public class MessageConverter_1_0_to_v0_10 implements MessageConverter<Message_1_0, MessageTransferMessage> -{ - - public Class<Message_1_0> getInputClass() - { - return Message_1_0.class; - } - - @Override - public Class<MessageTransferMessage> getOutputClass() - { - return MessageTransferMessage.class; - } - - @Override - public MessageTransferMessage convert(Message_1_0 serverMsg, VirtualHostImpl vhost) - { - return new MessageTransferMessage(convertToStoredMessage(serverMsg, vhost), null); - } - - private StoredMessage<MessageMetaData_0_10> convertToStoredMessage(final Message_1_0 serverMsg, - final VirtualHostImpl vhost) - { - Object bodyObject = MessageConverter_from_1_0.convertBodyToObject(serverMsg); - - final byte[] messageContent = MessageConverter_from_1_0.convertToBody(bodyObject); - - final MessageMetaData_0_10 messageMetaData_0_10 = convertMetaData(serverMsg, - vhost, - MessageConverter_from_1_0.getBodyMimeType(bodyObject), - messageContent.length); - - return new StoredMessage<MessageMetaData_0_10>() - { - @Override - public MessageMetaData_0_10 getMetaData() - { - return messageMetaData_0_10; - } - - @Override - public long getMessageNumber() - { - return serverMsg.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - int size = messageContent.length - offsetInMessage; - if(dst.remaining() < size) - { - size = dst.remaining(); - } - ByteBuffer buf = ByteBuffer.wrap(messageContent, offsetInMessage, size); - dst.put(buf); - return size; - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return ByteBuffer.wrap(messageContent, offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData_0_10 convertMetaData(Message_1_0 serverMsg, - final VirtualHostImpl vhost, - final String bodyMimeType, - final int size) - { - DeliveryProperties deliveryProps = new DeliveryProperties(); - MessageProperties messageProps = new MessageProperties(); - - final MessageMetaData_1_0.MessageHeader_1_0 origHeader = serverMsg.getMessageHeader(); - - - deliveryProps.setExpiration(serverMsg.getExpiration()); - deliveryProps.setPriority(MessageDeliveryPriority.get(origHeader.getPriority())); - deliveryProps.setRoutingKey(serverMsg.getInitialRoutingAddress()); - deliveryProps.setTimestamp(origHeader.getTimestamp()); - - messageProps.setContentEncoding(origHeader.getEncoding()); - messageProps.setContentLength(size); - messageProps.setContentType(bodyMimeType); - if(origHeader.getCorrelationId() != null) - { - messageProps.setCorrelationId(origHeader.getCorrelationId().getBytes()); - } - final String origReplyTo = origHeader.getReplyTo(); - if(origReplyTo != null && !origReplyTo.equals("")) - { - ReplyTo replyTo; - if(origReplyTo.startsWith("/")) - { - replyTo = new ReplyTo("",origReplyTo); - } - else if(origReplyTo.contains("/")) - { - String[] parts = origReplyTo.split("/",2); - replyTo = new ReplyTo(parts[0],parts[1]); - } - else if(vhost.getExchange(origReplyTo) != null) - { - replyTo = new ReplyTo(origReplyTo,""); - } - else - { - replyTo = new ReplyTo("",origReplyTo); - } - messageProps.setReplyTo(replyTo); - } - - Map<String, Object> appHeaders = - (Map<String, Object>) MessageConverter_from_1_0.convertValue(serverMsg.getMessageHeader() - .getHeadersAsMap()); - if(origHeader.getSubject() != null && !appHeaders.containsKey("qpid.subject")) - { - appHeaders = new LinkedHashMap<>(appHeaders); - appHeaders.put("qpid.subject", origHeader.getSubject()); - } - messageProps.setApplicationHeaders(appHeaders); - - Header header = new Header(deliveryProps, messageProps, null); - return new MessageMetaData_0_10(header, size, serverMsg.getArrivalTime()); - } - - - - @Override - public String getType() - { - return "v1-0 to v0-10"; - } - - -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/pom.xml b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/pom.xml deleted file mode 100644 index 560c916063..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-amqp-msg-conv-0-8-to-0-10</artifactId> - <name>Qpid AMQP 0-8 to 0-10 Message Conversion Broker Plug-in</name> - <description>AMQP message conversion (0-8, 0-9 and 0-9-1 to 0-10) broker plug-in</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-common</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-plugins-amqp-0-8-protocol</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-plugins-amqp-0-10-protocol</artifactId> - <version>${project.version}</version> - </dependency> - </dependencies> - - <build> - </build> - -</project> diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.java b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.java deleted file mode 100644 index a9637e9d4e..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.converter.v0_8_v0_10; - -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import org.apache.qpid.AMQPInvalidClassException; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage; -import org.apache.qpid.server.protocol.v0_8.AMQMessage; -import org.apache.qpid.server.protocol.v0_8.MessageMetaData; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryMode; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.ReplyTo; - -@PluggableService -public class MessageConverter_0_10_to_0_8 implements MessageConverter<MessageTransferMessage, AMQMessage> -{ - private static final int BASIC_CLASS_ID = 60; - - public static BasicContentHeaderProperties convertContentHeaderProperties(MessageTransferMessage messageTransferMessage, - VirtualHostImpl vhost) - { - BasicContentHeaderProperties props = new BasicContentHeaderProperties(); - - Header header = messageTransferMessage.getHeader(); - DeliveryProperties deliveryProps = header.getDeliveryProperties(); - MessageProperties messageProps = header.getMessageProperties(); - - if(deliveryProps != null) - { - if(deliveryProps.hasDeliveryMode()) - { - props.setDeliveryMode((deliveryProps.getDeliveryMode() == MessageDeliveryMode.PERSISTENT - ? BasicContentHeaderProperties.PERSISTENT - : BasicContentHeaderProperties.NON_PERSISTENT)); - } - if(deliveryProps.hasExpiration()) - { - props.setExpiration(deliveryProps.getExpiration()); - } - if(deliveryProps.hasPriority()) - { - props.setPriority((byte) deliveryProps.getPriority().getValue()); - } - if(deliveryProps.hasTimestamp()) - { - props.setTimestamp(deliveryProps.getTimestamp()); - } - } - if(messageProps != null) - { - if(messageProps.hasAppId()) - { - props.setAppId(new AMQShortString(messageProps.getAppId())); - } - if(messageProps.hasContentType()) - { - props.setContentType(messageProps.getContentType()); - } - if(messageProps.hasCorrelationId()) - { - props.setCorrelationId(new AMQShortString(messageProps.getCorrelationId())); - } - if(messageProps.hasContentEncoding()) - { - props.setEncoding(messageProps.getContentEncoding()); - } - if(messageProps.hasMessageId()) - { - props.setMessageId("ID:" + messageProps.getMessageId().toString()); - } - if(messageProps.hasReplyTo()) - { - ReplyTo replyTo = messageProps.getReplyTo(); - String exchangeName = replyTo.getExchange(); - String routingKey = replyTo.getRoutingKey(); - if(exchangeName == null) - { - exchangeName = ""; - } - - ExchangeImpl exchange = vhost.getExchange(exchangeName); - String exchangeClass = exchange == null - ? ExchangeDefaults.DIRECT_EXCHANGE_CLASS - : exchange.getType(); - props.setReplyTo(exchangeClass + "://" + exchangeName + "//?routingkey='" + (routingKey == null - ? "" - : routingKey + "'")); - - } - if(messageProps.hasUserId()) - { - props.setUserId(new AMQShortString(messageProps.getUserId())); - } - - if(messageProps.hasApplicationHeaders()) - { - Map<String, Object> appHeaders = new HashMap<String, Object>(messageProps.getApplicationHeaders()); - if(messageProps.getApplicationHeaders().containsKey("x-jms-type")) - { - props.setType(String.valueOf(appHeaders.remove("x-jms-type"))); - } - - FieldTable ft = new FieldTable(); - for(Map.Entry<String, Object> entry : appHeaders.entrySet()) - { - try - { - ft.put(AMQShortString.validValueOf(entry.getKey()), entry.getValue()); - } - catch (AMQPInvalidClassException e) - { - // TODO - // log here, but ignore - just can;t convert - } - } - props.setHeaders(ft); - - } - } - - return props; - } - - @Override - public Class<MessageTransferMessage> getInputClass() - { - return MessageTransferMessage.class; - } - - @Override - public Class<AMQMessage> getOutputClass() - { - return AMQMessage.class; - } - - @Override - public AMQMessage convert(MessageTransferMessage message, VirtualHostImpl vhost) - { - return new AMQMessage(convertToStoredMessage(message, vhost)); - } - - private StoredMessage<MessageMetaData> convertToStoredMessage(final MessageTransferMessage message, - VirtualHostImpl vhost) - { - final MessageMetaData metaData = convertMetaData(message, vhost); - return new StoredMessage<org.apache.qpid.server.protocol.v0_8.MessageMetaData>() - { - @Override - public MessageMetaData getMetaData() - { - return metaData; - } - - @Override - public long getMessageNumber() - { - return message.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - return message.getContent(dst, offsetInMessage); - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return message.getContent(offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData convertMetaData(MessageTransferMessage message, VirtualHostImpl vhost) - { - return new MessageMetaData(convertPublishBody(message), - convertContentHeaderBody(message, vhost), - message.getArrivalTime()); - } - - private ContentHeaderBody convertContentHeaderBody(MessageTransferMessage message, VirtualHostImpl vhost) - { - BasicContentHeaderProperties props = convertContentHeaderProperties(message, vhost); - ContentHeaderBody chb = new ContentHeaderBody(props); - chb.setBodySize(message.getSize()); - return chb; - } - - private MessagePublishInfo convertPublishBody(MessageTransferMessage message) - { - DeliveryProperties delvProps = message.getHeader().getDeliveryProperties(); - final AMQShortString exchangeName = (delvProps == null || delvProps.getExchange() == null) - ? null - : new AMQShortString(delvProps.getExchange()); - final AMQShortString routingKey = (delvProps == null || delvProps.getRoutingKey() == null) - ? null - : new AMQShortString(delvProps.getRoutingKey()); - final boolean immediate = delvProps != null && delvProps.getImmediate(); - final boolean mandatory = delvProps != null && !delvProps.getDiscardUnroutable(); - - return new MessagePublishInfo(exchangeName, immediate, mandatory, routingKey); - } - - @Override - public String getType() - { - return "v0-10 to v0-8"; - } -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.java b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.java deleted file mode 100644 index ee16d96d5b..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.converter.v0_8_v0_10; - -import java.net.URISyntaxException; -import java.nio.ByteBuffer; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_10.MessageMetaData_0_10; -import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage; -import org.apache.qpid.server.protocol.v0_8.AMQMessage; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.ReplyTo; -import org.apache.qpid.url.AMQBindingURL; - -@PluggableService -public class MessageConverter_0_8_to_0_10 implements MessageConverter<AMQMessage, MessageTransferMessage> -{ - @Override - public Class<AMQMessage> getInputClass() - { - return AMQMessage.class; - } - - @Override - public Class<MessageTransferMessage> getOutputClass() - { - return MessageTransferMessage.class; - } - - @Override - public MessageTransferMessage convert(AMQMessage message_0_8, VirtualHostImpl vhost) - { - return new MessageTransferMessage(convertToStoredMessage(message_0_8), null); - } - - private StoredMessage<MessageMetaData_0_10> convertToStoredMessage(final AMQMessage message_0_8) - { - final MessageMetaData_0_10 messageMetaData_0_10 = convertMetaData(message_0_8); - return new StoredMessage<MessageMetaData_0_10>() - { - @Override - public MessageMetaData_0_10 getMetaData() - { - return messageMetaData_0_10; - } - - @Override - public long getMessageNumber() - { - return message_0_8.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - return message_0_8.getContent(dst, offsetInMessage); - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return message_0_8.getContent(offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData_0_10 convertMetaData(AMQMessage message_0_8) - { - DeliveryProperties deliveryProps = new DeliveryProperties(); - MessageProperties messageProps = new MessageProperties(); - - int size = (int) message_0_8.getSize(); - ByteBuffer body = ByteBuffer.allocate(size); - message_0_8.getContent(body, 0); - body.flip(); - - BasicContentHeaderProperties properties = - message_0_8.getContentHeaderBody().getProperties(); - - final AMQShortString exchange = message_0_8.getMessagePublishInfo().getExchange(); - if(exchange != null) - { - deliveryProps.setExchange(exchange.toString()); - } - - deliveryProps.setExpiration(message_0_8.getExpiration()); - deliveryProps.setImmediate(message_0_8.isImmediate()); - deliveryProps.setPriority(MessageDeliveryPriority.get(properties.getPriority())); - deliveryProps.setRoutingKey(message_0_8.getInitialRoutingAddress()); - deliveryProps.setTimestamp(properties.getTimestamp()); - - messageProps.setContentEncoding(properties.getEncodingAsString()); - messageProps.setContentLength(size); - if(properties.getAppId() != null) - { - messageProps.setAppId(properties.getAppId().getBytes()); - } - messageProps.setContentType(properties.getContentTypeAsString()); - if(properties.getCorrelationId() != null) - { - messageProps.setCorrelationId(properties.getCorrelationId().getBytes()); - } - - if(properties.getReplyTo() != null && properties.getReplyTo().length() != 0) - { - String origReplyToString = properties.getReplyTo().asString(); - ReplyTo replyTo = new ReplyTo(); - // if the string looks like a binding URL, then attempt to parse it... - try - { - AMQBindingURL burl = new AMQBindingURL(origReplyToString); - AMQShortString routingKey = burl.getRoutingKey(); - if(routingKey != null) - { - replyTo.setRoutingKey(routingKey.asString()); - } - - AMQShortString exchangeName = burl.getExchangeName(); - if(exchangeName != null) - { - replyTo.setExchange(exchangeName.asString()); - } - } - catch (URISyntaxException e) - { - replyTo.setRoutingKey(origReplyToString); - } - messageProps.setReplyTo(replyTo); - - } - - if(properties.getMessageId() != null) - { - try - { - String messageIdAsString = properties.getMessageIdAsString(); - if(messageIdAsString.startsWith("ID:")) - { - messageIdAsString = messageIdAsString.substring(3); - } - UUID uuid = UUID.fromString(messageIdAsString); - messageProps.setMessageId(uuid); - } - catch(IllegalArgumentException e) - { - // ignore - can't parse - } - } - - - - if(properties.getUserId() != null) - { - messageProps.setUserId(properties.getUserId().getBytes()); - } - - FieldTable fieldTable = properties.getHeaders(); - - Map<String, Object> appHeaders = FieldTable.convertToMap(fieldTable); - - if(properties.getType() != null) - { - appHeaders.put("x-jms-type", properties.getTypeAsString()); - } - - - messageProps.setApplicationHeaders(appHeaders); - - Header header = new Header(deliveryProps, messageProps, null); - - - return new MessageMetaData_0_10(header, size, message_0_8.getArrivalTime()); - } - - @Override - public String getType() - { - return "v0-8 to v0-10"; - } -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/pom.xml b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/pom.xml deleted file mode 100644 index 659d3d3cf5..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-amqp-msg-conv-0-8-to-1-0</artifactId> - <name>Qpid AMQP 0-8 to 1-0 Message Conversion Broker Plug-in</name> - <description>AMQP message conversion (0-8, 0-9 and 0-9-1 to 1-0) broker plug-in</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-common</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-plugins-amqp-0-8-protocol</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-amqp-1-0-common</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-plugins-amqp-1-0-protocol</artifactId> - <version>${project.version}</version> - </dependency> - </dependencies> - - <build> - </build> - -</project> diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0.java b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0.java deleted file mode 100644 index 553b1ba662..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.converter.v0_8_v1_0; - -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.UnsignedByte; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.ApplicationProperties; -import org.apache.qpid.amqp_1_0.type.messaging.Header; -import org.apache.qpid.amqp_1_0.type.messaging.Properties; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_8.AMQMessage; -import org.apache.qpid.server.protocol.v1_0.MessageConverter_to_1_0; -import org.apache.qpid.server.protocol.v1_0.MessageMetaData_1_0; -import org.apache.qpid.url.AMQBindingURL; - -@PluggableService -public class MessageConverter_0_8_to_1_0 extends MessageConverter_to_1_0<AMQMessage> -{ - @Override - public Class<AMQMessage> getInputClass() - { - return AMQMessage.class; - } - - protected MessageMetaData_1_0 convertMetaData(final AMQMessage serverMessage, SectionEncoder sectionEncoder) - { - - List<Section> sections = new ArrayList<Section>(3); - - Header header = new Header(); - - header.setDurable(serverMessage.isPersistent()); - - BasicContentHeaderProperties contentHeader = - serverMessage.getContentHeaderBody().getProperties(); - - header.setPriority(UnsignedByte.valueOf(contentHeader.getPriority())); - final long expiration = serverMessage.getExpiration(); - final long arrivalTime = serverMessage.getArrivalTime(); - - if(expiration > arrivalTime) - { - header.setTtl(UnsignedInteger.valueOf(expiration - arrivalTime)); - } - sections.add(header); - - - Properties props = new Properties(); - - /* - TODO: The following properties are not currently set: - - creationTime - groupId - groupSequence - replyToGroupId - to - */ - - props.setContentEncoding(Symbol.valueOf(contentHeader.getEncodingAsString())); - - props.setContentType(Symbol.valueOf(contentHeader.getContentTypeAsString())); - - // Modify the content type when we are dealing with java object messages produced by the Qpid 0.x client - if(props.getContentType() == Symbol.valueOf("application/java-object-stream")) - { - props.setContentType(Symbol.valueOf("application/x-java-serialized-object")); - } - - final AMQShortString correlationId = contentHeader.getCorrelationId(); - if(correlationId != null) - { - props.setCorrelationId(new Binary(correlationId.getBytes())); - } - - final AMQShortString messageId = contentHeader.getMessageId(); - if(messageId != null) - { - props.setMessageId(new Binary(messageId.getBytes())); - } - final String originalReplyTo = String.valueOf(contentHeader.getReplyTo()); - try - { - AMQBindingURL burl = new AMQBindingURL(originalReplyTo); - String replyTo; - - if(burl.getExchangeName() != null && !burl.getExchangeName().equals(AMQShortString.EMPTY_STRING)) - { - replyTo = burl.getExchangeName().asString(); - - if(burl.getRoutingKey() != null) - { - replyTo += "/" + burl.getRoutingKey().asString(); - } - - } - else if(burl.getQueueName() != null && !burl.getQueueName().equals(AMQShortString.EMPTY_STRING)) - { - replyTo = burl.getQueueName().asString(); - } - else if(burl.getRoutingKey() != null) - { - replyTo = burl.getRoutingKey().asString(); - } - else - { - replyTo = originalReplyTo; - } - - props.setReplyTo(replyTo); - } - catch (URISyntaxException e) - { - props.setReplyTo(originalReplyTo); - } - - - - props.setSubject(serverMessage.getInitialRoutingAddress()); - if(contentHeader.getUserId() != null) - { - props.setUserId(new Binary(contentHeader.getUserId().getBytes())); - } - - sections.add(props); - - Map<String, Object> applicationProperties = FieldTable.convertToMap(contentHeader.getHeaders()); - - if(applicationProperties.containsKey("qpid.subject")) - { - props.setSubject(String.valueOf(applicationProperties.get("qpid.subject"))); - applicationProperties = new LinkedHashMap<>(applicationProperties); - applicationProperties.remove("qpid.subject"); - } - sections.add(new ApplicationProperties(applicationProperties)); - - return new MessageMetaData_1_0(sections, sectionEncoder); - } - - @Override - public String getType() - { - return "v0-8 to v1-0"; - } -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.java b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.java deleted file mode 100644 index d4529aedb1..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.protocol.converter.v0_8_v1_0; - -import java.nio.ByteBuffer; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_8.AMQMessage; -import org.apache.qpid.server.protocol.v0_8.MessageMetaData; -import org.apache.qpid.server.protocol.v1_0.MessageConverter_from_1_0; -import org.apache.qpid.server.protocol.v1_0.MessageMetaData_1_0; -import org.apache.qpid.server.protocol.v1_0.Message_1_0; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -@PluggableService -public class MessageConverter_1_0_to_v0_8 implements MessageConverter<Message_1_0, AMQMessage> -{ - private static final int BASIC_CLASS_ID = 60; - - - public Class<Message_1_0> getInputClass() - { - return Message_1_0.class; - } - - @Override - public Class<AMQMessage> getOutputClass() - { - return AMQMessage.class; - } - - @Override - public AMQMessage convert(Message_1_0 serverMsg, VirtualHostImpl vhost) - { - return new AMQMessage(convertToStoredMessage(serverMsg), null); - } - - private StoredMessage<MessageMetaData> convertToStoredMessage(final Message_1_0 serverMsg) - { - Object bodyObject = MessageConverter_from_1_0.convertBodyToObject(serverMsg); - - - - - final byte[] messageContent = MessageConverter_from_1_0.convertToBody(bodyObject); - final MessageMetaData messageMetaData_0_8 = convertMetaData(serverMsg, - MessageConverter_from_1_0.getBodyMimeType(bodyObject), - messageContent.length); - - return new StoredMessage<MessageMetaData>() - { - @Override - public MessageMetaData getMetaData() - { - return messageMetaData_0_8; - } - - @Override - public long getMessageNumber() - { - return serverMsg.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - int size = messageContent.length - offsetInMessage; - if(dst.remaining() < size) - { - size = dst.remaining(); - } - ByteBuffer buf = ByteBuffer.wrap(messageContent, offsetInMessage, size); - dst.put(buf); - return size; - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return ByteBuffer.wrap(messageContent, offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData convertMetaData(final Message_1_0 serverMsg, final String bodyMimeType, final int size) - { - - final MessageMetaData_1_0.MessageHeader_1_0 header = serverMsg.getMessageHeader(); - String key = header.getTo(); - if(key == null) - { - key = header.getSubject(); - } - - MessagePublishInfo publishInfo = new MessagePublishInfo(null, false, false, AMQShortString.valueOf(key)); - - - final BasicContentHeaderProperties props = new BasicContentHeaderProperties(); - props.setAppId(serverMsg.getMessageHeader().getAppId()); - props.setContentType(bodyMimeType); - props.setCorrelationId(serverMsg.getMessageHeader().getCorrelationId()); - props.setDeliveryMode(serverMsg.isPersistent() ? BasicContentHeaderProperties.PERSISTENT : BasicContentHeaderProperties.NON_PERSISTENT); - props.setExpiration(serverMsg.getExpiration()); - props.setMessageId(serverMsg.getMessageHeader().getMessageId()); - props.setPriority(serverMsg.getMessageHeader().getPriority()); - props.setReplyTo(serverMsg.getMessageHeader().getReplyTo()); - props.setTimestamp(serverMsg.getMessageHeader().getTimestamp()); - props.setUserId(serverMsg.getMessageHeader().getUserId()); - - Map<String,Object> headerProps = new LinkedHashMap<String, Object>(); - - if(header.getSubject() != null) - { - headerProps.put("qpid.subject", header.getSubject()); - } - - for(String headerName : serverMsg.getMessageHeader().getHeaderNames()) - { - headerProps.put(headerName, MessageConverter_from_1_0.convertValue(serverMsg.getMessageHeader().getHeader(headerName))); - } - - props.setHeaders(FieldTable.convertToFieldTable(headerProps)); - - final ContentHeaderBody chb = new ContentHeaderBody(props); - chb.setBodySize(size); - - return new MessageMetaData(publishInfo, chb, serverMsg.getArrivalTime()); - } - - - @Override - public String getType() - { - return "v1-0 to v0-8"; - } - - -} diff --git a/qpid/java/broker-plugins/derby-store/pom.xml b/qpid/java/broker-plugins/derby-store/pom.xml deleted file mode 100644 index 1f247c7dcb..0000000000 --- a/qpid/java/broker-plugins/derby-store/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-derby-store</artifactId> - <name>Qpid Derby Message Store</name> - <description>Apache Derby DB message store broker plug-in</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>org.apache.derby</groupId> - <artifactId>derby</artifactId> - <version>${derby-version}</version> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <version>${log4j-version}</version> - </dependency> - - <!-- test dependencies --> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-test-utils</artifactId> - <version>${project.version}</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <type>test-jar</type> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <resources> - <resource> - <directory>src/main/resources</directory> - </resource> - <resource> - <directory>src/main/java</directory> - <includes> - <include>resources/</include> - </includes> - </resource> - </resources> - </build> - -</project> diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java deleted file mode 100644 index df5eec025b..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java +++ /dev/null @@ -1,331 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.store.derby; - - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.store.*; - -public abstract class AbstractDerbyMessageStore extends AbstractJDBCMessageStore -{ - private final AtomicBoolean _messageStoreOpen = new AtomicBoolean(false); - - private long _persistentSizeLowThreshold; - private long _persistentSizeHighThreshold; - private long _totalStoreSize; - private boolean _limitBusted; - - private ConfiguredObject<?> _parent; - - @Override - public final void openMessageStore(final ConfiguredObject<?> parent) - { - if (_messageStoreOpen.compareAndSet(false, true)) - { - _parent = parent; - initMessageStore(parent); - - DerbyUtils.loadDerbyDriver(); - - doOpen(parent); - - final SizeMonitoringSettings sizeMonitorSettings = (SizeMonitoringSettings) parent; - _persistentSizeHighThreshold = sizeMonitorSettings.getStoreOverfullSize(); - _persistentSizeLowThreshold = sizeMonitorSettings.getStoreUnderfullSize(); - - if (_persistentSizeLowThreshold > _persistentSizeHighThreshold || _persistentSizeLowThreshold < 0l) - { - _persistentSizeLowThreshold = _persistentSizeHighThreshold; - } - - createOrOpenMessageStoreDatabase(); - setInitialSize(); - setMaximumMessageId(); - } - } - - protected abstract void doOpen(final ConfiguredObject<?> parent); - - @Override - public final void upgradeStoreStructure() throws StoreException - { - checkMessageStoreOpen(); - - upgrade(_parent); - } - - @Override - public final void closeMessageStore() - { - if (_messageStoreOpen.compareAndSet(true, false)) - { - try - { - doClose(); - } - finally - { - super.closeMessageStore(); - } - } - } - - protected abstract void doClose(); - - @Override - protected boolean isMessageStoreOpen() - { - return _messageStoreOpen.get(); - } - - @Override - protected void checkMessageStoreOpen() - { - if (!_messageStoreOpen.get()) - { - throw new IllegalStateException("Message store is not open"); - } - } - - @Override - protected String getSqlBlobType() - { - return "blob"; - } - - @Override - protected String getSqlVarBinaryType(int size) - { - return "varchar("+size+") for bit data"; - } - - @Override - protected String getSqlBigIntType() - { - return "bigint"; - } - - @Override - protected byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException - { - return DerbyUtils.getBlobAsBytes(rs, col); - } - - @Override - protected boolean tableExists(final String tableName, final Connection conn) throws SQLException - { - return DerbyUtils.tableExists(tableName, conn); - } - - @Override - protected void storedSizeChange(final int delta) - { - if(getPersistentSizeHighThreshold() > 0) - { - synchronized(this) - { - // the delta supplied is an approximation of a store size change. we don;t want to check the statistic every - // time, so we do so only when there's been enough change that it is worth looking again. We do this by - // assuming the total size will change by less than twice the amount of the message data change. - long newSize = _totalStoreSize += 3*delta; - - Connection conn = null; - try - { - - if(!_limitBusted && newSize > getPersistentSizeHighThreshold()) - { - conn = newAutoCommitConnection(); - _totalStoreSize = getSizeOnDisk(conn); - if(_totalStoreSize > getPersistentSizeHighThreshold()) - { - _limitBusted = true; - _eventManager.notifyEvent(Event.PERSISTENT_MESSAGE_SIZE_OVERFULL); - } - } - else if(_limitBusted && newSize < getPersistentSizeLowThreshold()) - { - long oldSize = _totalStoreSize; - conn = newAutoCommitConnection(); - _totalStoreSize = getSizeOnDisk(conn); - if(oldSize <= _totalStoreSize) - { - - reduceSizeOnDisk(conn); - - _totalStoreSize = getSizeOnDisk(conn); - } - - if(_totalStoreSize < getPersistentSizeLowThreshold()) - { - _limitBusted = false; - _eventManager.notifyEvent(Event.PERSISTENT_MESSAGE_SIZE_UNDERFULL); - } - - - } - } - catch (SQLException e) - { - JdbcUtils.closeConnection(conn, getLogger()); - throw new StoreException("Exception while processing store size change", e); - } - } - } - } - - private void setInitialSize() - { - Connection conn = null; - try - { - conn = newAutoCommitConnection(); - _totalStoreSize = getSizeOnDisk(conn); - } - catch (SQLException e) - { - getLogger().error("Unable to set initial store size", e); - } - finally - { - JdbcUtils.closeConnection(conn, getLogger()); - } - } - - private long getSizeOnDisk(Connection conn) - { - PreparedStatement stmt = null; - try - { - String sizeQuery = "SELECT SUM(T2.NUMALLOCATEDPAGES * T2.PAGESIZE) TOTALSIZE" + - " FROM " + - " SYS.SYSTABLES systabs," + - " TABLE (SYSCS_DIAG.SPACE_TABLE(systabs.tablename)) AS T2" + - " WHERE systabs.tabletype = 'T'"; - - stmt = conn.prepareStatement(sizeQuery); - - ResultSet rs = null; - long size = 0l; - - try - { - rs = stmt.executeQuery(); - while(rs.next()) - { - size = rs.getLong(1); - } - } - finally - { - if(rs != null) - { - rs.close(); - } - } - - return size; - - } - catch (SQLException e) - { - throw new StoreException("Error establishing on disk size", e); - } - finally - { - JdbcUtils.closePreparedStatement(stmt, getLogger()); - } - } - - private void reduceSizeOnDisk(Connection conn) - { - CallableStatement cs = null; - PreparedStatement stmt = null; - try - { - String tableQuery = - "SELECT S.SCHEMANAME, T.TABLENAME FROM SYS.SYSSCHEMAS S, SYS.SYSTABLES T WHERE S.SCHEMAID = T.SCHEMAID AND T.TABLETYPE='T'"; - stmt = conn.prepareStatement(tableQuery); - ResultSet rs = null; - - List<String> schemas = new ArrayList<String>(); - List<String> tables = new ArrayList<String>(); - - try - { - rs = stmt.executeQuery(); - while(rs.next()) - { - schemas.add(rs.getString(1)); - tables.add(rs.getString(2)); - } - } - finally - { - if(rs != null) - { - rs.close(); - } - } - - - cs = conn.prepareCall - ("CALL SYSCS_UTIL.SYSCS_COMPRESS_TABLE(?, ?, ?)"); - - for(int i = 0; i < schemas.size(); i++) - { - cs.setString(1, schemas.get(i)); - cs.setString(2, tables.get(i)); - cs.setShort(3, (short) 0); - cs.execute(); - } - } - catch (SQLException e) - { - throw new StoreException("Error reducing on disk size", e); - } - finally - { - JdbcUtils.closePreparedStatement(stmt, getLogger()); - JdbcUtils.closePreparedStatement(cs, getLogger()); - } - } - - private long getPersistentSizeLowThreshold() - { - return _persistentSizeLowThreshold; - } - - private long getPersistentSizeHighThreshold() - { - return _persistentSizeHighThreshold; - } - -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyConfigurationStore.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyConfigurationStore.java deleted file mode 100644 index d96dc8d224..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyConfigurationStore.java +++ /dev/null @@ -1,242 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.store.derby; - - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.store.AbstractJDBCConfigurationStore; -import org.apache.qpid.server.store.ConfiguredObjectRecord; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.server.store.FileBasedSettings; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MessageStoreProvider; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.util.FileUtils; - -/** - * Implementation of a DurableConfigurationStore backed by Apache Derby - * that also provides a MessageStore.A - */ -public class DerbyConfigurationStore extends AbstractJDBCConfigurationStore - implements MessageStoreProvider, DurableConfigurationStore -{ - private static final Logger LOGGER = LoggerFactory.getLogger(DerbyConfigurationStore.class); - - private final AtomicBoolean _configurationStoreOpen = new AtomicBoolean(); - private final ProvidedMessageStore _providedMessageStore = new ProvidedMessageStore(); - - private String _connectionURL; - - private ConfiguredObject<?> _parent; - private final Class<? extends ConfiguredObject> _rootClass; - - public DerbyConfigurationStore(final Class<? extends ConfiguredObject> rootClass) - { - _rootClass = rootClass; - } - - @Override - public void openConfigurationStore(ConfiguredObject<?> parent, - final boolean overwrite, - final ConfiguredObjectRecord... initialRecords) - throws StoreException - { - if (_configurationStoreOpen.compareAndSet(false, true)) - { - _parent = parent; - DerbyUtils.loadDerbyDriver(); - - _connectionURL = DerbyUtils.createConnectionUrl(parent.getName(), ((FileBasedSettings)_parent).getStorePath()); - - createOrOpenConfigurationStoreDatabase(overwrite); - - if(hasNoConfigurationEntries()) - { - update(true, initialRecords); - } - } - } - - @Override - public void upgradeStoreStructure() throws StoreException - { - checkConfigurationStoreOpen(); - upgradeIfNecessary(_parent); - } - - @Override - protected Connection getConnection() throws SQLException - { - checkConfigurationStoreOpen(); - return DriverManager.getConnection(_connectionURL); - } - - @Override - public void closeConfigurationStore() throws StoreException - { - if (_providedMessageStore.isMessageStoreOpen()) - { - throw new IllegalStateException("Cannot close the store as the provided message store is still open"); - } - - if (_configurationStoreOpen.compareAndSet(true, false)) - { - try - { - DerbyUtils.shutdownDatabase(_connectionURL); - } - catch (SQLException e) - { - throw new StoreException("Error closing configuration store", e); - } - } - } - - @Override - protected String getSqlBlobType() - { - return "blob"; - } - - @Override - protected String getSqlVarBinaryType(int size) - { - return "varchar("+size+") for bit data"; - } - - @Override - protected String getSqlBigIntType() - { - return "bigint"; - } - - @Override - protected String getBlobAsString(ResultSet rs, int col) throws SQLException - { - return DerbyUtils.getBlobAsString(rs, col); - } - - @Override - public void onDelete(ConfiguredObject<?> parent) - { - if (_providedMessageStore.isMessageStoreOpen()) - { - throw new IllegalStateException("Cannot delete the store as the provided message store is still open"); - } - - FileBasedSettings fileBasedSettings = (FileBasedSettings) parent; - String storePath = fileBasedSettings.getStorePath(); - - if (!DerbyUtils.MEMORY_STORE_LOCATION.equals(storePath)) - { - if (storePath != null) - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("Deleting store " + storePath); - } - - File configFile = new File(storePath); - if (!FileUtils.delete(configFile, true)) - { - LOGGER.info("Failed to delete the store at location " + storePath); - } - } - } - } - - @Override - public MessageStore getMessageStore() - { - return _providedMessageStore; - } - - @Override - protected boolean tableExists(final String tableName, final Connection conn) throws SQLException - { - return DerbyUtils.tableExists(tableName, conn); - } - - @Override - protected void checkConfigurationStoreOpen() - { - if (!_configurationStoreOpen.get()) - { - throw new IllegalStateException("Configuration store is not open"); - } - } - - @Override - protected Logger getLogger() - { - return LOGGER; - } - - private class ProvidedMessageStore extends AbstractDerbyMessageStore - { - @Override - protected void doOpen(final ConfiguredObject<?> parent) - { - // Nothing to do, store provided by DerbyConfigurationStore - } - - @Override - protected Connection getConnection() throws SQLException - { - checkMessageStoreOpen(); - return DerbyConfigurationStore.this.getConnection(); - } - - @Override - protected void doClose() - { - // Nothing to do, store provided by DerbyConfigurationStore - } - - @Override - public String getStoreLocation() - { - return ((FileBasedSettings)(DerbyConfigurationStore.this._parent)).getStorePath(); - } - - @Override - public File getStoreLocationAsFile() - { - return DerbyUtils.isInMemoryDatabase(getStoreLocation()) ? null : new File(getStoreLocation()); - } - - @Override - protected Logger getLogger() - { - return DerbyConfigurationStore.this.getLogger(); - } - } -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyMessageStore.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyMessageStore.java deleted file mode 100644 index 10fed76b60..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyMessageStore.java +++ /dev/null @@ -1,118 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.store.derby; - - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.store.FileBasedSettings; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.util.FileUtils; - -/** - * Implementation of a MessageStore backed by Apache Derby. - */ -public class DerbyMessageStore extends AbstractDerbyMessageStore -{ - private static final Logger LOGGER = LoggerFactory.getLogger(DerbyMessageStore.class); - - private String _connectionURL; - private ConfiguredObject<?> _parent; - - @Override - protected void doOpen(final ConfiguredObject<?> parent) - { - _parent = parent; - _connectionURL = DerbyUtils.createConnectionUrl(parent.getName(), ((FileBasedSettings)_parent).getStorePath()); - } - - @Override - protected Connection getConnection() throws SQLException - { - checkMessageStoreOpen(); - return DriverManager.getConnection(_connectionURL); - } - - @Override - protected void doClose() - { - try - { - DerbyUtils.shutdownDatabase(_connectionURL); - } - catch (SQLException e) - { - throw new StoreException("Error closing configuration store", e); - } - } - - @Override - public void onDelete(ConfiguredObject parent) - { - if (isMessageStoreOpen()) - { - throw new IllegalStateException("Cannot delete the store as the provided message store is still open"); - } - - FileBasedSettings fileBasedSettings = (FileBasedSettings)parent; - String storePath = fileBasedSettings.getStorePath(); - - if (storePath != null) - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("Deleting store " + storePath); - } - - File configFile = new File(storePath); - if (!FileUtils.delete(configFile, true)) - { - LOGGER.info("Failed to delete the store at location " + storePath); - } - } - } - - @Override - protected Logger getLogger() - { - return LOGGER; - } - - - @Override - public String getStoreLocation() - { - return ((FileBasedSettings)_parent).getStorePath(); - } - - @Override - public File getStoreLocationAsFile() - { - return DerbyUtils.isInMemoryDatabase(getStoreLocation()) ? null : new File(getStoreLocation()); - } -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfig.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfig.java deleted file mode 100644 index d3a1fa2bbc..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.derby; - -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.model.SystemConfig; -import org.apache.qpid.server.store.FileBasedSettings; -import org.apache.qpid.server.store.SizeMonitoringSettings; - -public interface DerbySystemConfig<X extends DerbySystemConfig<X>> extends SystemConfig<X>, FileBasedSettings, - SizeMonitoringSettings -{ - @ManagedAttribute(mandatory = true) - String getStorePath(); - - @ManagedAttribute(mandatory = true, defaultValue = "0") - Long getStoreUnderfullSize(); - - @ManagedAttribute(mandatory = true, defaultValue = "0") - Long getStoreOverfullSize(); -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfigImpl.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfigImpl.java deleted file mode 100644 index 0cc4f2b18c..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfigImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.derby; - -import java.util.Map; - -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.model.AbstractSystemConfig; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerShutdownProvider; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.SystemConfigFactoryConstructor; -import org.apache.qpid.server.store.DurableConfigurationStore; - -@ManagedObject(category = false, type = DerbySystemConfigImpl.SYSTEM_CONFIG_TYPE) -public class DerbySystemConfigImpl extends AbstractSystemConfig<DerbySystemConfigImpl> implements DerbySystemConfig<DerbySystemConfigImpl> -{ - public static final String SYSTEM_CONFIG_TYPE = "DERBY"; - - @ManagedAttributeField - private String _storePath; - @ManagedAttributeField - private Long _storeUnderfullSize; - @ManagedAttributeField - private Long _storeOverfullSize; - - @SystemConfigFactoryConstructor - public DerbySystemConfigImpl(final TaskExecutor taskExecutor, - final EventLogger eventLogger, - final LogRecorder logRecorder, - final Map<String,Object> attributes, - final BrokerShutdownProvider brokerShutdownProvider) - { - super(taskExecutor, eventLogger, logRecorder, attributes, brokerShutdownProvider); - } - - @Override - protected DurableConfigurationStore createStoreObject() - { - return new DerbyConfigurationStore(Broker.class); - } - - @Override - public String getStorePath() - { - return _storePath; - } - - @Override - public Long getStoreUnderfullSize() - { - return _storeUnderfullSize; - } - - @Override - public Long getStoreOverfullSize() - { - return _storeOverfullSize; - } -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.java deleted file mode 100644 index 8116274261..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.java +++ /dev/null @@ -1,234 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.store.derby; - - -import java.io.File; -import java.io.IOException; -import java.io.Writer; -import java.nio.charset.Charset; -import java.sql.Blob; -import java.sql.Connection; -import java.sql.Driver; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.store.StoreException; - -public class DerbyUtils -{ - public static final String MEMORY_STORE_LOCATION = ":memory:"; - public static final String DERBY_SINGLE_DB_SHUTDOWN_CODE = "08006"; - private static final String SQL_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver"; - private static final String TABLE_EXISTENCE_QUERY = "SELECT 1 FROM SYS.SYSTABLES WHERE TABLENAME = ?"; - private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); - - private static final Logger DERBY_LOG = LoggerFactory.getLogger("DERBY"); - public static final DerbyLogWriter DERBY_LOG_WRITER = new DerbyLogWriter(); - public static final String DERBY_STREAM_ERROR_METHOD = "derby.stream.error.method"; - - public static void loadDerbyDriver() - { - try - { - // set the error log output - System.setProperty(DERBY_STREAM_ERROR_METHOD, - "org.apache.qpid.server.store.derby.DerbyUtils.getDerbyLogWriter"); - - Class<Driver> driverClass = (Class<Driver>) Class.forName(SQL_DRIVER_NAME); - } - catch (ClassNotFoundException e) - { - throw new StoreException("Failed to load driver " + SQL_DRIVER_NAME, e); - } - } - - public static Writer getDerbyLogWriter() - { - return DERBY_LOG_WRITER; - } - - public static String createConnectionUrl(final String name, final String databasePath) - { - // Derby wont use an existing directory, so we append parent name - if (isInMemoryDatabase(databasePath)) - { - return "jdbc:derby:" + MEMORY_STORE_LOCATION + "/" + name + ";create=true"; - } - else - { - File environmentPath = new File(databasePath); - if (!environmentPath.exists()) - { - if (!environmentPath.mkdirs()) - { - throw new IllegalArgumentException("Environment path " - + environmentPath - + " could not be read or created. " - + "Ensure the path is correct and that the permissions are correct."); - } - } - return "jdbc:derby:" + databasePath + "/" + name + ";create=true"; - } - - } - - public static boolean isInMemoryDatabase(final String databasePath) - { - return MEMORY_STORE_LOCATION.equals(databasePath); - } - - public static void shutdownDatabase(String connectionURL) throws SQLException - { - try - { - Connection conn = DriverManager.getConnection(connectionURL + ";shutdown=true"); - // Shouldn't reach this point - shutdown=true should throw SQLException - conn.close(); - } - catch (SQLException e) - { - if (e.getSQLState().equalsIgnoreCase(DerbyUtils.DERBY_SINGLE_DB_SHUTDOWN_CODE)) - { - //expected and represents a clean shutdown of this database only, do nothing. - } - else - { - throw e; - } - } - } - - public static String getBlobAsString(ResultSet rs, int col) throws SQLException - { - Blob blob = rs.getBlob(col); - if(blob == null) - { - return null; - } - byte[] bytes = blob.getBytes(1, (int) blob.length()); - return new String(bytes, UTF8_CHARSET); - } - - protected static byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException - { - Blob dataAsBlob = rs.getBlob(col); - return dataAsBlob.getBytes(1,(int) dataAsBlob.length()); - } - - public static boolean tableExists(final String tableName, final Connection conn) throws SQLException - { - PreparedStatement stmt = conn.prepareStatement(TABLE_EXISTENCE_QUERY); - try - { - stmt.setString(1, tableName); - ResultSet rs = stmt.executeQuery(); - try - { - return rs.next(); - } - finally - { - rs.close(); - } - } - finally - { - stmt.close(); - } - } - - - private static class DerbyLogWriter extends Writer - { - - public static final String DERBY_STARTUP_MESSAGE = "Booting Derby version "; - public static final String DERBY_SHUTDOWN_MESSAGE = "Shutting down instance "; - public static final String DERBY_CLASS_LOADER_STARTED_MESSAGE = "Database Class Loader started"; - public static final String DERBY_SYSTEM_HOME = "derby.system.home"; - public static final String DASHED_LINE = "\\s*-*\\s*"; - - private final ThreadLocal<StringBuilder> _threadLocalBuffer = new ThreadLocal<StringBuilder>() - { - @Override - protected StringBuilder initialValue() - { - return new StringBuilder(); - } - }; - - @Override - public void write(final char[] cbuf, final int off, final int len) throws IOException - { - _threadLocalBuffer.get().append(cbuf, off, len); - } - - @Override - public void flush() throws IOException - { - String logMessage = _threadLocalBuffer.get().toString(); - if(!logMessage.matches(DASHED_LINE)) - { - if(logMessage.contains(DERBY_STARTUP_MESSAGE)) - { - // the first line of the message containing the startup message is the current date/time, which - // we can remove - logMessage = logMessage.substring(logMessage.indexOf('\n') + 1); - } - - // This is pretty hideous, but since the Derby logging doesn't have any way of informing us of priority - // we simply have to assume everything is a warning except known startup / shutdown messages - // which we match using known prefixes. - - if(logMessage.startsWith(DERBY_STARTUP_MESSAGE) - || logMessage.startsWith(DERBY_SHUTDOWN_MESSAGE)) - { - DERBY_LOG.info(logMessage); - } - else if(logMessage.startsWith(DERBY_SYSTEM_HOME) - || logMessage.startsWith(DERBY_STREAM_ERROR_METHOD) - || logMessage.startsWith("java.vendor") - || logMessage.startsWith(DERBY_CLASS_LOADER_STARTED_MESSAGE)) - { - DERBY_LOG.debug(logMessage); - } - else - { - DERBY_LOG.warn(logMessage); - } - - } - _threadLocalBuffer.set(new StringBuilder()); - } - - @Override - public void close() throws IOException - { - - } - } -} - diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHost.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHost.java deleted file mode 100644 index 4935d5e707..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHost.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.qpid.server.virtualhost.derby; - -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.SizeMonitoringSettings; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public interface DerbyVirtualHost<X extends DerbyVirtualHost<X>> extends VirtualHostImpl<X,AMQQueue<?>,ExchangeImpl<?>>, org.apache.qpid.server.store.FileBasedSettings, SizeMonitoringSettings -{ - String STORE_PATH = "storePath"; - - @ManagedAttribute(mandatory = true, defaultValue = "${qpid.work_dir}${file.separator}${this:name}${file.separator}messages") - String getStorePath(); - - @ManagedAttribute(mandatory = true, defaultValue = "0") - Long getStoreUnderfullSize(); - - @ManagedAttribute(mandatory = true, defaultValue = "0") - Long getStoreOverfullSize(); -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHostImpl.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHostImpl.java deleted file mode 100644 index dbaf5e55b7..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHostImpl.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.virtualhost.derby; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.derby.DerbyMessageStore; -import org.apache.qpid.server.util.FileHelper; -import org.apache.qpid.server.virtualhost.AbstractVirtualHost; - -import java.util.Map; - -@ManagedObject(category = false, type = DerbyVirtualHostImpl.VIRTUAL_HOST_TYPE) -public class DerbyVirtualHostImpl extends AbstractVirtualHost<DerbyVirtualHostImpl> implements DerbyVirtualHost<DerbyVirtualHostImpl> -{ - public static final String VIRTUAL_HOST_TYPE = "DERBY"; - - @ManagedAttributeField - private String _storePath; - - @ManagedAttributeField - private Long _storeUnderfullSize; - - @ManagedAttributeField - private Long _storeOverfullSize; - - @ManagedObjectFactoryConstructor - public DerbyVirtualHostImpl(final Map<String, Object> attributes, - final VirtualHostNode<?> virtualHostNode) - { - super(attributes, virtualHostNode); - } - - - @Override - protected MessageStore createMessageStore() - { - return new DerbyMessageStore(); - } - - @Override - public String getStorePath() - { - return _storePath; - } - - @Override - public Long getStoreUnderfullSize() - { - return _storeUnderfullSize; - } - - @Override - public Long getStoreOverfullSize() - { - return _storeOverfullSize; - } - - @Override - protected void validateMessageStoreCreation() - { - if (!new FileHelper().isWritableDirectory(getStorePath())) - { - throw new IllegalConfigurationException("The store path is not writable directory"); - } - } -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNode.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNode.java deleted file mode 100644 index 81a9167924..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNode.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.qpid.server.virtualhostnode.derby; - - -import org.apache.qpid.server.model.ManagedAttribute; - -public interface DerbyVirtualHostNode<X extends DerbyVirtualHostNode<X>> extends org.apache.qpid.server.model.VirtualHostNode<X>, org.apache.qpid.server.store.FileBasedSettings -{ - String STORE_PATH = "storePath"; - - @ManagedAttribute(mandatory = true, defaultValue = "${qpid.work_dir}${file.separator}${this:name}${file.separator}config") - String getStorePath(); -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeImpl.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeImpl.java deleted file mode 100644 index 8224a22929..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeImpl.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.virtualhostnode.derby; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.logging.messages.ConfigStoreMessages; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.server.store.derby.DerbyConfigurationStore; -import org.apache.qpid.server.util.FileHelper; -import org.apache.qpid.server.virtualhostnode.AbstractStandardVirtualHostNode; - -@ManagedObject( category = false, - type = DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE, - validChildTypes = "org.apache.qpid.server.virtualhostnode.derby.DerbyVirtualHostNodeImpl#getSupportedChildTypes()" ) -public class DerbyVirtualHostNodeImpl extends AbstractStandardVirtualHostNode<DerbyVirtualHostNodeImpl> implements DerbyVirtualHostNode<DerbyVirtualHostNodeImpl> -{ - public static final String VIRTUAL_HOST_NODE_TYPE = "DERBY"; - - @ManagedAttributeField - private String _storePath; - - @ManagedObjectFactoryConstructor - public DerbyVirtualHostNodeImpl(Map<String, Object> attributes, Broker<?> parent) - { - super(attributes, parent); - } - - @Override - protected void writeLocationEventLog() - { - getEventLogger().message(getConfigurationStoreLogSubject(), ConfigStoreMessages.STORE_LOCATION(getStorePath())); - } - - @Override - protected DurableConfigurationStore createConfigurationStore() - { - return new DerbyConfigurationStore(VirtualHost.class); - } - - @Override - public String getStorePath() - { - return _storePath; - } - - @Override - public String toString() - { - return getClass().getSimpleName() + " [id=" + getId() + ", name=" + getName() + ", storePath=" + getStorePath() + "]"; - } - - - public static Map<String, Collection<String>> getSupportedChildTypes() - { - return Collections.singletonMap(VirtualHost.class.getSimpleName(), getSupportedVirtualHostTypes(true)); - } - - @Override - public void validateOnCreate() - { - if (!new FileHelper().isWritableDirectory(getStorePath())) - { - throw new IllegalConfigurationException("The store path is not writable directory"); - } - } -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/add.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/add.js deleted file mode 100644 index 323b8e9750..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/add.js +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dijit/registry", - "dojo/text!virtualhost/sizemonitoring/add.html", - "qpid/common/util", - "dijit/form/ValidationTextBox", - "dijit/form/NumberTextBox", - "dojo/domReady!"], - function (xhr, parser, dom, domConstruct, json, registry, template, util) - { - return { - show: function (data) - { - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode).then(function(instances) - { - registry.byId("addVirtualHost.storeUnderfullSize").set("regExpGen", util.numericOrContextVarRegexp); - registry.byId("addVirtualHost.storeOverfullSize").set("regExpGen", util.numericOrContextVarRegexp); - }); - } - }; - } -); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/edit.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/edit.js deleted file mode 100644 index c1018313b8..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/edit.js +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -define(["qpid/common/util", "dijit/registry", "dojo/domReady!"], - function (util, registry) - { - return { - show: function(data) - { - util.parseHtmlIntoDiv(data.containerNode, "virtualhost/sizemonitoring/edit.html", - function() - { - registry.byId("editVirtualHost.storeUnderfullSize").set("regExpGen", util.numericOrContextVarRegexp); - registry.byId("editVirtualHost.storeOverfullSize").set("regExpGen", util.numericOrContextVarRegexp); - }); - } - }; - } -); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/show.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/show.js deleted file mode 100644 index e53ad75fe4..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/show.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["qpid/common/util", - "dojo/domReady!"], - function (util) - { - var fields = ["storePath", "storeUnderfullSize", "storeOverfullSize"]; - - function Derby(data) - { - util.buildUI(data.containerNode, data.parent, "virtualhost/sizemonitoring/show.html", fields, this); - } - - Derby.prototype.update = function(data) - { - util.updateUI(data, fields, this); - } - - return Derby; - } -); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/add.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/add.js deleted file mode 100644 index d981f1e13f..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/add.js +++ /dev/null @@ -1,41 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dijit/registry", - "dojo/text!virtualhostnode/derby/add.html", - "dijit/form/ValidationTextBox", - "dijit/form/CheckBox", - "dojo/domReady!"], - function (xhr, parser, dom, domConstruct, json, registry, template) - { - return { - show: function (data) - { - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode); - } - }; - } -); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/edit.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/edit.js deleted file mode 100644 index a7f5d05719..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/edit.js +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -define(["qpid/common/util", "dijit/registry", "dojo/domReady!"], - function (util, registry) - { - return { - show: function(data) - { - util.parseHtmlIntoDiv(data.containerNode, "virtualhostnode/filebased/edit.html", - function() - { - registry.byId("editVirtualHostNode.storePath").set("disabled", data.data.state != "STOPPED"); - }); - } - }; - } -); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/show.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/show.js deleted file mode 100644 index ffbe4bfacd..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/show.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["qpid/common/util", "dojo/domReady!"], - function (util) - { - var fields = ["storePath"]; - - function DerbyNode(data) - { - this.parent = data.parent; - util.buildUI(data.containerNode, data.parent, "virtualhostnode/derby/show.html", fields, this); - } - - DerbyNode.prototype.update=function(data) - { - util.updateUI(data, fields, this); - }; - - return DerbyNode; -}); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/add.html b/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/add.html deleted file mode 100644 index 4e82ab09e9..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/add.html +++ /dev/null @@ -1,35 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Store path:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHostNode.storePath" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'storePath', - placeHolder: 'path/to/store', - title: 'Enter store path', - promptMessage: 'File system location for the configuration store'"/> - </div> - </div> - <div class="clear"></div> -</div> diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/show.html b/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/show.html deleted file mode 100644 index d86d9cfa03..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/show.html +++ /dev/null @@ -1,21 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> - -<div class="clear"> - <div class="formLabel-labelCell">Configuration store path:</div> - <div class="storePath"></div> -</div> diff --git a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreConfigurationTest.java b/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreConfigurationTest.java deleted file mode 100644 index 4a71fe2faf..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreConfigurationTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.derby; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.qpid.server.model.ConfiguredObjectFactory; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.store.AbstractDurableConfigurationStoreTestCase; -import org.apache.qpid.server.virtualhostnode.derby.DerbyVirtualHostNode; - -public class DerbyMessageStoreConfigurationTest extends AbstractDurableConfigurationStoreTestCase -{ - - @Override - protected VirtualHostNode createVirtualHostNode(String storeLocation, ConfiguredObjectFactory factory) - { - final DerbyVirtualHostNode parent = mock(DerbyVirtualHostNode.class); - when(parent.getStorePath()).thenReturn(storeLocation); - return parent; - } - - @Override - protected DerbyConfigurationStore createConfigStore() throws Exception - { - return new DerbyConfigurationStore(VirtualHost.class); - } - -} diff --git a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreQuotaEventsTest.java b/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreQuotaEventsTest.java deleted file mode 100644 index 0aeb6bd0e8..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreQuotaEventsTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.derby; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.Map; - -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MessageStoreQuotaEventsTestBase; -import org.apache.qpid.server.virtualhost.derby.DerbyVirtualHost; - -public class DerbyMessageStoreQuotaEventsTest extends MessageStoreQuotaEventsTestBase -{ - private static final int NUMBER_OF_MESSAGES_TO_OVERFILL_STORE = 10; - - /** - * Estimated using an assumption that a physical disk space occupied by a - * message is 3 times bigger then a message size - */ - private static final long OVERFULL_SIZE = (long) (MESSAGE_DATA.length * 3 * NUMBER_OF_MESSAGES_TO_OVERFILL_STORE * 0.8); - - private static final long UNDERFULL_SIZE = (long) (OVERFULL_SIZE * 0.8); - - @Override - protected int getNumberOfMessagesToFillStore() - { - return NUMBER_OF_MESSAGES_TO_OVERFILL_STORE; - } - - @Override - protected VirtualHost createVirtualHost(String storeLocation) - { - final DerbyVirtualHost parent = mock(DerbyVirtualHost.class); - when(parent.getContext()).thenReturn(createContextSettings()); - when(parent.getContextKeys(false)).thenReturn(Collections.emptySet()); - when(parent.getStorePath()).thenReturn(storeLocation); - when(parent.getStoreOverfullSize()).thenReturn(OVERFULL_SIZE); - when(parent.getStoreUnderfullSize()).thenReturn(UNDERFULL_SIZE); - return parent; - } - - @Override - protected MessageStore createStore() throws Exception - { - return new DerbyMessageStore(); - } - - private Map<String, String> createContextSettings() - { - return Collections.emptyMap(); - } - - -} diff --git a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreTest.java b/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreTest.java deleted file mode 100644 index 0b1847bb59..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.derby; - - -import java.io.File; - -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MessageStoreTestCase; -import org.apache.qpid.server.virtualhost.derby.DerbyVirtualHost; -import org.apache.qpid.util.FileUtils; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class DerbyMessageStoreTest extends MessageStoreTestCase -{ - private String _storeLocation; - - @Override - public void tearDown() throws Exception - { - try - { - deleteStoreIfExists(); - } - finally - { - super.tearDown(); - } - } - - public void testOnDelete() throws Exception - { - File location = new File(_storeLocation); - assertTrue("Store does not exist at " + _storeLocation, location.exists()); - - getStore().closeMessageStore(); - assertTrue("Store does not exist at " + _storeLocation, location.exists()); - - DerbyVirtualHost mockVH = mock(DerbyVirtualHost.class); - when(mockVH.getStorePath()).thenReturn(_storeLocation); - - getStore().onDelete(mockVH); - assertFalse("Store exists at " + _storeLocation, location.exists()); - } - - @Override - protected VirtualHost createVirtualHost() - { - _storeLocation = TMP_FOLDER + File.separator + getTestName(); - deleteStoreIfExists(); - - final DerbyVirtualHost parent = mock(DerbyVirtualHost.class); - when(parent.getStorePath()).thenReturn(_storeLocation); - return parent; - } - - private void deleteStoreIfExists() - { - if (_storeLocation != null) - { - File location = new File(_storeLocation); - if (location.exists()) - { - FileUtils.delete(location, true); - } - } - } - - @Override - protected MessageStore createMessageStore() - { - return new DerbyMessageStore(); - } - -} diff --git a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeTest.java b/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeTest.java deleted file mode 100644 index 5afbc7aceb..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeTest.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.virtualhostnode.derby; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.nio.file.Files; -import java.nio.file.attribute.PosixFileAttributeView; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.configuration.updater.TaskExecutorImpl; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.ConfiguredObjectFactoryImpl; -import org.apache.qpid.server.model.SystemConfig; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.model.adapter.BrokerAdapter; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; - -public class DerbyVirtualHostNodeTest extends QpidTestCase -{ - private TaskExecutor _taskExecutor; - private File _workDir; - private Broker<BrokerAdapter> _broker; - - @Override - public void setUp() throws Exception - { - super.setUp(); - _taskExecutor = new TaskExecutorImpl(); - _taskExecutor.start(); - _workDir = TestFileUtils.createTestDirectory("qpid.work_dir", true); - setTestSystemProperty("qpid.work_dir", _workDir.getAbsolutePath()); - _broker = createBroker(); - } - - public void tearDown() throws Exception - { - try - { - _broker.close(); - } - finally - { - _taskExecutor.stop(); - TestFileUtils.delete(_workDir, true); - super.tearDown(); - } - } - - public void testCreateAndCloseVirtualHostNode() throws Exception - { - String nodeName = getTestName(); - Map<String, Object> nodeData = new HashMap<>(); - nodeData.put(VirtualHostNode.NAME, nodeName); - nodeData.put(VirtualHostNode.TYPE, DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE); - - VirtualHostNode<?> virtualHostNode = (VirtualHostNode<?>)_broker.createChild(VirtualHostNode.class, nodeData); - virtualHostNode.start(); - virtualHostNode.close(); - } - - - public void testCreateDuplicateVirtualHostNodeAndClose() throws Exception - { - - String nodeName = getTestName(); - Map<String, Object> nodeData = new HashMap<>(); - nodeData.put(VirtualHostNode.NAME, nodeName); - nodeData.put(VirtualHostNode.TYPE, DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE); - - VirtualHostNode<?> virtualHostNode = (VirtualHostNode<?>)_broker.createChild(VirtualHostNode.class, nodeData); - virtualHostNode.start(); - - try - { - _broker.createChild(VirtualHostNode.class, nodeData); - } - catch(Exception e) - { - assertEquals("Unexpected message", "Child of type " + virtualHostNode.getClass().getSimpleName() + " already exists with name of " + getTestName(), e.getMessage()); - } - virtualHostNode.close(); - } - - public void testOnCreateValidationForFileStorePath() throws Exception - { - File file = new File(_workDir, getTestName()); - file.createNewFile(); - - String nodeName = getTestName(); - Map<String, Object> nodeData = new HashMap<>(); - nodeData.put(VirtualHostNode.NAME, nodeName); - nodeData.put(VirtualHostNode.TYPE, DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE); - nodeData.put(DerbyVirtualHostNodeImpl.STORE_PATH, file.getAbsolutePath()); - try - { - _broker.createChild(VirtualHostNode.class, nodeData); - fail("Cannot create store for the file store path"); - } - catch(IllegalConfigurationException e) - { - // pass - } - - } - - - public void testOnCreateValidationForNonWritableStorePath() throws Exception - { - if (Files.getFileStore(_workDir.toPath()).supportsFileAttributeView(PosixFileAttributeView.class)) - { - File file = new File(_workDir, getTestName()); - file.mkdirs(); - if (file.setWritable(false, false)) - { - String nodeName = getTestName(); - Map<String, Object> nodeData = new HashMap<>(); - nodeData.put(VirtualHostNode.NAME, nodeName); - nodeData.put(VirtualHostNode.TYPE, DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE); - nodeData.put(DerbyVirtualHostNodeImpl.STORE_PATH, file.getAbsolutePath()); - try - { - _broker.createChild(VirtualHostNode.class, nodeData); - fail("Cannot create store for the non writable store path"); - } - catch (IllegalConfigurationException e) - { - // pass - } - } - } - } - - private BrokerAdapter createBroker() - { - Map<String, Object> brokerAttributes = Collections.<String, Object>singletonMap(Broker.NAME, "Broker"); - SystemConfig parent = mock(SystemConfig.class); - when(parent.getEventLogger()).thenReturn(new EventLogger()); - when(parent.getCategoryClass()).thenReturn(SystemConfig.class); - when(parent.getTaskExecutor()).thenReturn(_taskExecutor); - when(parent.getChildExecutor()).thenReturn(_taskExecutor); - when(parent.getModel()).thenReturn(BrokerModel.getInstance()); - when(parent.getObjectFactory()).thenReturn(new ConfiguredObjectFactoryImpl(BrokerModel.getInstance())); - BrokerAdapter broker = new BrokerAdapter(brokerAttributes, parent); - broker.start(); - return broker; - } -} diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/pom.xml b/qpid/java/broker-plugins/jdbc-provider-bone/pom.xml deleted file mode 100644 index 2f742459f0..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-jdbc-provider-bone</artifactId> - <name>Qpid JDBC Message Store Connection Pooling Plug-in</name> - <description>JDBC Message Store Connection Pooling broker plug-in using BoneCP</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>com.jolbox</groupId> - <artifactId>bonecp</artifactId> - <version>${bonecp-version}</version> - <exclusions> - <exclusion> - <!-- exclude and specify a fixed version below --> - <groupId>com.google.guava</groupId> - <artifactId>guava</artifactId> - </exclusion> - </exclusions> - </dependency> - - <dependency> - <groupId>com.google.guava</groupId> - <artifactId>guava</artifactId> - <version>${guava-version}</version> - <scope>runtime</scope> - </dependency> - - </dependencies> - - <build> - <resources> - <resource> - <directory>src/main/resources</directory> - </resource> - <resource> - <directory>src/main/java</directory> - <includes> - <include>resources/</include> - </includes> - </resource> - </resources> - </build> - -</project> diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProvider.java b/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProvider.java deleted file mode 100644 index 2687a32bf9..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProvider.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.jdbc.bonecp; - -import static org.apache.qpid.server.store.jdbc.bonecp.BoneCPConnectionProviderFactory.MAX_CONNECTIONS_PER_PARTITION; -import static org.apache.qpid.server.store.jdbc.bonecp.BoneCPConnectionProviderFactory.MIN_CONNECTIONS_PER_PARTITION; -import static org.apache.qpid.server.store.jdbc.bonecp.BoneCPConnectionProviderFactory.PARTITION_COUNT; - -import com.jolbox.bonecp.BoneCP; -import com.jolbox.bonecp.BoneCPConfig; -import org.apache.qpid.server.store.jdbc.ConnectionProvider; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Map; - -public class BoneCPConnectionProvider implements ConnectionProvider -{ - public static final int DEFAULT_MIN_CONNECTIONS_PER_PARTITION = 5; - public static final int DEFAULT_MAX_CONNECTIONS_PER_PARTITION = 10; - public static final int DEFAULT_PARTITION_COUNT = 4; - - private final BoneCP _connectionPool; - - public BoneCPConnectionProvider(String connectionUrl, String username, String password, Map<String, String> providerAttributes) throws SQLException - { - BoneCPConfig config = new BoneCPConfig(); - config.setJdbcUrl(connectionUrl); - if (username != null) - { - config.setUsername(username); - config.setPassword(password); - } - - config.setMinConnectionsPerPartition(convertToIntWithDefault(MIN_CONNECTIONS_PER_PARTITION, providerAttributes, DEFAULT_MIN_CONNECTIONS_PER_PARTITION)); - config.setMaxConnectionsPerPartition(convertToIntWithDefault(MAX_CONNECTIONS_PER_PARTITION, providerAttributes, DEFAULT_MAX_CONNECTIONS_PER_PARTITION)); - config.setPartitionCount(convertToIntWithDefault(PARTITION_COUNT, providerAttributes, DEFAULT_PARTITION_COUNT)); - - _connectionPool = new BoneCP(config); - } - - private int convertToIntWithDefault(String key, Map<String, String> context, int defaultValue) - { - if (context.containsKey(key)) - { - try - { - return Integer.parseInt(context.get(key)); - } - catch (NumberFormatException e) - { - return defaultValue; - } - } - else - { - return defaultValue; - } - } - @Override - public Connection getConnection() throws SQLException - { - return _connectionPool.getConnection(); - } - - @Override - public void close() throws SQLException - { - _connectionPool.shutdown(); - } -} diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProviderFactory.java b/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProviderFactory.java deleted file mode 100644 index f894a6a27a..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProviderFactory.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.jdbc.bonecp; - -import static java.util.Arrays.asList; -import static java.util.Collections.unmodifiableSet; - -import org.apache.qpid.server.plugin.JDBCConnectionProviderFactory; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.jdbc.ConnectionProvider; - -import java.sql.SQLException; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -@PluggableService -public class BoneCPConnectionProviderFactory implements JDBCConnectionProviderFactory -{ - public static final String PARTITION_COUNT = "qpid.jdbcstore.bonecp.partitionCount"; - public static final String MAX_CONNECTIONS_PER_PARTITION = "qpid.jdbcstore.bonecp.maxConnectionsPerPartition"; - public static final String MIN_CONNECTIONS_PER_PARTITION = "qpid.jdbcstore.bonecp.minConnectionsPerPartition"; - - private final Set<String> _supportedAttributes = unmodifiableSet(new HashSet<String>(asList(PARTITION_COUNT, MAX_CONNECTIONS_PER_PARTITION, MIN_CONNECTIONS_PER_PARTITION))); - - @Override - public String getType() - { - return "BONECP"; - } - - public ConnectionProvider getConnectionProvider(String connectionUrl, String username, String password, Map<String, String> providerAttributes) - throws SQLException - { - return new BoneCPConnectionProvider(connectionUrl, username, password, providerAttributes); - } - - @Override - public Set<String> getProviderAttributeNames() - { - return _supportedAttributes; - } -} diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/add.js b/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/add.js deleted file mode 100644 index 0ec991ea16..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/add.js +++ /dev/null @@ -1,44 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/json", - "dojo/string", - "dojo/store/Memory", - "dijit/form/FilteringSelect", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, parser, array, event, json, string, Memory, FilteringSelect) { - return { - show: function(data) { - data.context.addInheritedContext({ - "qpid.jdbcstore.bonecp.partitionCount": "4", - "qpid.jdbcstore.bonecp.minConnectionsPerPartition": "5", - "qpid.jdbcstore.bonecp.maxConnectionsPerPartition": "10" - }); - } - }; - }); diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/edit.js b/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/edit.js deleted file mode 100644 index 6876e3850b..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/edit.js +++ /dev/null @@ -1,33 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "qpid/common/util", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, parser, util) { - return { - show: function(data) { } - }; - }); diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/show.js b/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/show.js deleted file mode 100644 index 3d15cdbc37..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/show.js +++ /dev/null @@ -1,66 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/_base/lang", - "dojo/_base/connect", - "dojo/parser", - "dojo/string", - "dojox/html/entities", - "dojo/query", - "dojo/json", - "dojo/domReady!"], - function (xhr, lang, connect, parser, json, entities, query, json) - { - var fieldNames = ["maxConnectionsPerPartition", "minConnectionsPerPartition", "partitionCount"]; - - function BoneCP(data) - { - var containerNode = data.containerNode; - this.parent = data.parent; - var that = this; - xhr.get({url: "store/pool/bonecp/show.html", - sync: true, - load: function(template) { - containerNode.innerHTML = template; - parser.parse(containerNode).then(function(instances) - { - for(var i=0; i<fieldNames.length;i++) - { - var fieldName = fieldNames[i]; - that[fieldName]= query("." + fieldName, containerNode)[0]; - } - }); - }}); - } - - BoneCP.prototype.update=function(data) - { - - for(var i=0; i<fieldNames.length;i++) - { - var fieldName = fieldNames[i]; - var value = data && data.context ? data.context["qpid.jdbcstore.bonecp."+fieldName] : ""; - this[fieldName].innerHTML= value?entities.encode(String(value)):""; - } - }; - - return BoneCP; -}); diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/store/pool/bonecp/show.html b/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/store/pool/bonecp/show.html deleted file mode 100644 index f4e59bfa9a..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/store/pool/bonecp/show.html +++ /dev/null @@ -1,37 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Bone Connection Pool Settings', open: false"> - <div class="clear"> - <div class="formLabel-labelCell">Partition Count:</div> - <div class="partitionCount"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Minimum connections per Partition:</div> - <div class="minConnectionsPerPartition"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Maximum connections per Partition:</div> - <div class="maxConnectionsPerPartition"></div> - </div> - <div class="clear"></div> - </div> -</div> - diff --git a/qpid/java/broker-plugins/jdbc-store/pom.xml b/qpid/java/broker-plugins/jdbc-store/pom.xml deleted file mode 100644 index a330ab12d5..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-jdbc-store</artifactId> - <name>Qpid JDBC Message Store Broker Plug-in</name> - <description>JDBC message store broker plug-in</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <version>${log4j-version}</version> - </dependency> - - <!-- test dependencies --> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-test-utils</artifactId> - <version>${project.version}</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <type>test-jar</type> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.apache.derby</groupId> - <artifactId>derby</artifactId> - <version>${derby-version}</version> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <resources> - <resource> - <directory>src/main/resources</directory> - </resource> - <resource> - <directory>src/main/java</directory> - <includes> - <include>resources/</include> - </includes> - </resource> - </resources> - </build> - -</project> diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProvider.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProvider.java deleted file mode 100644 index a96d46af18..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProvider.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.jdbc; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -class DefaultConnectionProvider implements ConnectionProvider -{ - private final String _connectionUrl; - private final String _username; - private final String _password; - - public DefaultConnectionProvider(String connectionUrl, String username, String password) - { - _connectionUrl = connectionUrl; - _username = username; - _password = password; - } - - @Override - public Connection getConnection() throws SQLException - { - if (_username == null) - { - return DriverManager.getConnection(_connectionUrl); - } - else - { - return DriverManager.getConnection(_connectionUrl, _username, _password); - } - } - - @Override - public void close() throws SQLException - { - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProviderFactory.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProviderFactory.java deleted file mode 100644 index 0a829696f0..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProviderFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.jdbc; - -import org.apache.qpid.server.plugin.JDBCConnectionProviderFactory; -import org.apache.qpid.server.plugin.PluggableService; - -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -@PluggableService -public class DefaultConnectionProviderFactory implements JDBCConnectionProviderFactory -{ - public static final String TYPE = "NONE"; - - @Override - public String getType() - { - return TYPE; - } - - @Override - public ConnectionProvider getConnectionProvider(String connectionUrl, String username, String password, Map<String, String> providerAttributes) - { - return new DefaultConnectionProvider(connectionUrl, username, password); - } - - @Override - public Set<String> getProviderAttributeNames() - { - return Collections.emptySet(); - } - -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericAbstractJDBCMessageStore.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericAbstractJDBCMessageStore.java deleted file mode 100644 index e062af45a7..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericAbstractJDBCMessageStore.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.store.jdbc; - - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.server.util.FutureResult; -import org.apache.qpid.server.store.Transaction; - -public abstract class GenericAbstractJDBCMessageStore extends org.apache.qpid.server.store.AbstractJDBCMessageStore -{ - private final AtomicBoolean _messageStoreOpen = new AtomicBoolean(false); - private final List<RecordedJDBCTransaction> _transactions = new CopyOnWriteArrayList<>(); - - private ConfiguredObject<?> _parent; - - @Override - public final void openMessageStore(ConfiguredObject<?> parent) - { - if (_messageStoreOpen.compareAndSet(false, true)) - { - _parent = parent; - - doOpen(parent); - - createOrOpenMessageStoreDatabase(); - setMaximumMessageId(); - } - } - - protected abstract void doOpen(final ConfiguredObject<?> parent) - throws StoreException; - - @Override - public final void upgradeStoreStructure() throws StoreException - { - checkMessageStoreOpen(); - - upgrade(_parent); - } - - @Override - public final void closeMessageStore() - { - if (_messageStoreOpen.compareAndSet(true, false)) - { - try - { - while(!_transactions.isEmpty()) - { - RecordedJDBCTransaction txn = _transactions.get(0); - txn.abortTran(); - } - } - finally - { - doClose(); - super.closeMessageStore(); - } - - } - } - - protected abstract void doClose(); - - protected boolean isMessageStoreOpen() - { - return _messageStoreOpen.get(); - } - - @Override - protected void checkMessageStoreOpen() - { - if (!_messageStoreOpen.get()) - { - throw new IllegalStateException("Message store is not open"); - } - } - - @Override - protected void storedSizeChange(int contentSize) - { - } - - @Override - public Transaction newTransaction() - { - return new RecordedJDBCTransaction(); - } - - - private class RecordedJDBCTransaction extends JDBCTransaction - { - private RecordedJDBCTransaction() - { - super(); - GenericAbstractJDBCMessageStore.this._transactions.add(this); - } - - @Override - public void commitTran() - { - try - { - super.commitTran(); - } - finally - { - GenericAbstractJDBCMessageStore.this._transactions.remove(this); - } - } - - @Override - public FutureResult commitTranAsync() - { - try - { - return super.commitTranAsync(); - } - finally - { - GenericAbstractJDBCMessageStore.this._transactions.remove(this); - } - } - - @Override - public void abortTran() - { - try - { - super.abortTran(); - } - finally - { - GenericAbstractJDBCMessageStore.this._transactions.remove(this); - } - } - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java deleted file mode 100644 index cd6ca85ee5..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.store.jdbc; - - -import java.io.File; -import java.nio.charset.Charset; -import java.security.PrivilegedAction; -import java.sql.Blob; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.plugin.JDBCConnectionProviderFactory; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.store.AbstractJDBCConfigurationStore; -import org.apache.qpid.server.store.ConfiguredObjectRecord; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MessageStoreProvider; -import org.apache.qpid.server.store.StoreException; - -/** - * Implementation of a DurableConfigurationStore backed by Generic JDBC Database - * that also provides a MessageStore. - */ -public class GenericJDBCConfigurationStore extends AbstractJDBCConfigurationStore implements MessageStoreProvider -{ - private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); - - private static final Logger LOGGER = LoggerFactory.getLogger(GenericJDBCConfigurationStore.class); - - private final AtomicBoolean _configurationStoreOpen = new AtomicBoolean(); - private final MessageStore _providedMessageStore = new ProvidedMessageStore(); - - private String _connectionURL; - private ConnectionProvider _connectionProvider; - - private String _blobType; - private String _varBinaryType; - private String _bigIntType; - private boolean _useBytesMethodsForBlob; - - private ConfiguredObject<?> _parent; - private final Class<? extends ConfiguredObject> _rootClass; - - public GenericJDBCConfigurationStore(final Class<? extends ConfiguredObject> rootClass) - { - _rootClass = rootClass; - } - - @Override - public void openConfigurationStore(ConfiguredObject<?> parent, - final boolean overwrite, - final ConfiguredObjectRecord... initialRecords) - throws StoreException - { - if (_configurationStoreOpen.compareAndSet(false, true)) - { - _parent = parent; - - JDBCSettings settings = (JDBCSettings)parent; - _connectionURL = settings.getConnectionUrl(); - - JDBCDetails details = JDBCDetails.getDetailsForJdbcUrl(_connectionURL, parent); - - if (!details.isKnownVendor() && getLogger().isInfoEnabled()) - { - getLogger().info("Do not recognize vendor from connection URL: " + _connectionURL - + " Using fallback settings " + details); - } - if (details.isOverridden() && getLogger().isInfoEnabled()) - { - getLogger().info("One or more JDBC details were overridden from context. " - + " Using settings : " + details); - } - - String connectionPoolType = settings.getConnectionPoolType() == null ? DefaultConnectionProviderFactory.TYPE : settings.getConnectionPoolType(); - - JDBCConnectionProviderFactory connectionProviderFactory = - JDBCConnectionProviderFactory.FACTORIES.get(connectionPoolType); - if(connectionProviderFactory == null) - { - LOGGER.warn("Unknown connection pool type: " - + connectionPoolType - + ". no connection pooling will be used"); - connectionProviderFactory = new DefaultConnectionProviderFactory(); - } - - try - { - Map<String, String> providerAttributes = new HashMap<>(); - Set<String> providerAttributeNames = new HashSet<String>(connectionProviderFactory.getProviderAttributeNames()); - providerAttributeNames.retainAll(parent.getContextKeys(false)); - for(String attr : providerAttributeNames) - { - providerAttributes.put(attr, parent.getContextValue(String.class, attr)); - } - - _connectionProvider = connectionProviderFactory.getConnectionProvider(_connectionURL, - settings.getUsername(), - getPlainTextPassword(settings), - providerAttributes); - } - catch (SQLException e) - { - throw new StoreException("Failed to create connection provider for connectionUrl: " + _connectionURL + - " and username: " + settings.getUsername(), e); - } - _blobType = details.getBlobType(); - _varBinaryType = details.getVarBinaryType(); - _useBytesMethodsForBlob = details.isUseBytesMethodsForBlob(); - _bigIntType = details.getBigintType(); - - createOrOpenConfigurationStoreDatabase(overwrite); - if(hasNoConfigurationEntries()) - { - update(true, initialRecords); - } - } - } - - @Override - public void upgradeStoreStructure() throws StoreException - { - checkConfigurationStoreOpen(); - upgradeIfNecessary(_parent); - } - - @Override - protected Connection getConnection() throws SQLException - { - return _connectionProvider.getConnection(); - } - - @Override - public void closeConfigurationStore() throws StoreException - { - if (_configurationStoreOpen.compareAndSet(true, false)) - { - try - { - _connectionProvider.close(); - } - catch (SQLException e) - { - throw new StoreException("Unable to close connection provider ", e); - } - } - } - - @Override - protected String getSqlBlobType() - { - return _blobType; - } - - @Override - protected String getSqlVarBinaryType(int size) - { - return String.format(_varBinaryType, size); - } - - @Override - public String getSqlBigIntType() - { - return _bigIntType; - } - - @Override - protected String getBlobAsString(ResultSet rs, int col) throws SQLException - { - byte[] bytes; - if(_useBytesMethodsForBlob) - { - bytes = rs.getBytes(col); - return new String(bytes,UTF8_CHARSET); - } - else - { - Blob blob = rs.getBlob(col); - if(blob == null) - { - return null; - } - bytes = blob.getBytes(1, (int)blob.length()); - } - return new String(bytes, UTF8_CHARSET); - - } - - protected byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException - { - if(_useBytesMethodsForBlob) - { - return rs.getBytes(col); - } - else - { - Blob dataAsBlob = rs.getBlob(col); - return dataAsBlob.getBytes(1,(int) dataAsBlob.length()); - - } - } - - @Override - protected void checkConfigurationStoreOpen() - { - if (!_configurationStoreOpen.get()) - { - throw new IllegalStateException("Configuration store is not open"); - } - } - - @Override - protected Logger getLogger() - { - return LOGGER; - } - - @Override - public MessageStore getMessageStore() - { - return _providedMessageStore; - } - - protected String getPlainTextPassword(final JDBCSettings settings) - { - return Subject.doAs(SecurityManager.getSubjectWithAddedSystemRights(), new PrivilegedAction<String>() - { - @Override - public String run() - { - return settings.getPassword(); - } - }); - } - - private class ProvidedMessageStore extends GenericAbstractJDBCMessageStore - { - @Override - protected void doOpen(final ConfiguredObject<?> parent) - { - // Nothing to do, store provided by DerbyConfigurationStore - } - - @Override - protected Connection getConnection() throws SQLException - { - return GenericJDBCConfigurationStore.this.getConnection(); - } - - @Override - protected void doClose() - { - // Nothing to do, store provided by DerbyConfigurationStore - } - - @Override - public String getStoreLocation() - { - return GenericJDBCConfigurationStore.this._connectionURL; - } - - @Override - public File getStoreLocationAsFile() - { - return null; - } - - @Override - protected Logger getLogger() - { - return GenericJDBCConfigurationStore.this.getLogger(); - } - - @Override - protected String getSqlBlobType() - { - return GenericJDBCConfigurationStore.this.getSqlBlobType(); - } - - @Override - protected String getSqlVarBinaryType(int size) - { - return GenericJDBCConfigurationStore.this.getSqlVarBinaryType(size); - } - - @Override - protected String getSqlBigIntType() - { - return GenericJDBCConfigurationStore.this.getSqlBigIntType(); - } - - @Override - protected byte[] getBlobAsBytes(final ResultSet rs, final int col) throws SQLException - { - return GenericJDBCConfigurationStore.this.getBlobAsBytes(rs, col); - } - } - - -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java deleted file mode 100644 index 32ddd89833..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java +++ /dev/null @@ -1,199 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -* -*/ -package org.apache.qpid.server.store.jdbc; - - -import java.io.File; -import java.security.PrivilegedAction; -import java.sql.Blob; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.plugin.JDBCConnectionProviderFactory; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.store.StoreException; - -/** - * Implementation of a MessageStore backed by a Generic JDBC Database. - */ -public class GenericJDBCMessageStore extends GenericAbstractJDBCMessageStore -{ - - private static final Logger _logger = LoggerFactory.getLogger(GenericJDBCMessageStore.class); - - protected String _connectionURL; - private ConnectionProvider _connectionProvider; - - private String _blobType; - private String _varBinaryType; - private String _bigIntType; - private boolean _useBytesMethodsForBlob; - - @Override - protected void doOpen(final ConfiguredObject<?> parent) throws StoreException - { - JDBCSettings settings = (JDBCSettings)parent; - _connectionURL = settings.getConnectionUrl(); - - JDBCDetails details = JDBCDetails.getDetailsForJdbcUrl(_connectionURL, parent); - - if (!details.isKnownVendor() && getLogger().isInfoEnabled()) - { - getLogger().info("Do not recognize vendor from connection URL: " + _connectionURL - + " Using fallback settings " + details); - } - if (details.isOverridden() && getLogger().isInfoEnabled()) - { - getLogger().info("One or more JDBC details were overridden from context. " - + " Using settings : " + details); - } - - _blobType = details.getBlobType(); - _varBinaryType = details.getVarBinaryType(); - _useBytesMethodsForBlob = details.isUseBytesMethodsForBlob(); - _bigIntType = details.getBigintType(); - - String connectionPoolType = settings.getConnectionPoolType() == null ? DefaultConnectionProviderFactory.TYPE : settings.getConnectionPoolType(); - - JDBCConnectionProviderFactory connectionProviderFactory = - JDBCConnectionProviderFactory.FACTORIES.get(connectionPoolType); - if(connectionProviderFactory == null) - { - _logger.warn("Unknown connection pool type: " + connectionPoolType + ". No connection pooling will be used"); - connectionProviderFactory = new DefaultConnectionProviderFactory(); - } - - try - { - Map<String, String> providerAttributes = new HashMap<>(); - Set<String> providerAttributeNames = new HashSet<String>(connectionProviderFactory.getProviderAttributeNames()); - providerAttributeNames.retainAll(parent.getContextKeys(false)); - for(String attr : providerAttributeNames) - { - providerAttributes.put(attr, parent.getContextValue(String.class, attr)); - } - - _connectionProvider = connectionProviderFactory.getConnectionProvider(_connectionURL, - settings.getUsername(), - getPlainTextPassword(settings), - providerAttributes); - } - catch (SQLException e) - { - throw new StoreException("Failed to create connection provider for connectionUrl: " + _connectionURL + - " and username: " + settings.getUsername()); - } - - } - - @Override - protected Connection getConnection() throws SQLException - { - return _connectionProvider.getConnection(); - } - - protected void doClose() - { - try - { - _connectionProvider.close(); - } - catch (SQLException e) - { - throw new StoreException("Unable to close connection provider ", e); - } - } - - - @Override - protected Logger getLogger() - { - return _logger; - } - - @Override - protected String getSqlBlobType() - { - return _blobType; - } - - @Override - protected String getSqlVarBinaryType(int size) - { - return String.format(_varBinaryType, size); - } - - @Override - protected byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException - { - if(_useBytesMethodsForBlob) - { - return rs.getBytes(col); - } - else - { - Blob dataAsBlob = rs.getBlob(col); - return dataAsBlob.getBytes(1,(int) dataAsBlob.length()); - - } - } - - @Override - public String getSqlBigIntType() - { - return _bigIntType; - } - - @Override - public String getStoreLocation() - { - return _connectionURL; - } - - @Override - public File getStoreLocationAsFile() - { - return null; - } - - protected String getPlainTextPassword(final JDBCSettings settings) - { - return Subject.doAs(SecurityManager.getSubjectWithAddedSystemRights(), new PrivilegedAction<String>() - { - @Override - public String run() - { - return settings.getPassword(); - } - }); - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCDetails.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCDetails.java deleted file mode 100644 index eec2d49a80..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCDetails.java +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.qpid.server.store.jdbc; - -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.apache.qpid.server.model.ConfiguredObject; - -public abstract class JDBCDetails -{ - public static final String CONTEXT_JDBCSTORE_BIGINTTYPE = "qpid.jdbcstore.bigIntType"; - public static final String CONTEXT_JDBCSTORE_VARBINARYTYPE = "qpid.jdbcstore.varBinaryType"; - public static final String CONTEXT_JDBCSTORE_BLOBTYPE = "qpid.jdbcstore.blobType"; - public static final String CONTEXT_JDBCSTORE_USEBYTESFORBLOB = "qpid.jdbcstore.useBytesForBlob"; - - public abstract String getVendor(); - - public abstract String getBlobType(); - - public abstract String getVarBinaryType(); - - public abstract String getBigintType(); - - public abstract boolean isUseBytesMethodsForBlob(); - - public abstract boolean isKnownVendor(); - - public abstract boolean isOverridden(); - - static class KnownJDBCDetails extends JDBCDetails - { - private static final JDBCDetails FALLBACK = new KnownJDBCDetails("fallback", "blob", "varchar(%d) for bit data", "bigint", false, - false); - private static final JDBCDetails ORACLE = new KnownJDBCDetails("oracle", "blob", "raw(%d)", "number", false, - true); - private static final JDBCDetails SYBASE = new KnownJDBCDetails("sybase", "image", "varbinary(%d)", "bigint", false, - true); - private static final JDBCDetails POSTGRES = new KnownJDBCDetails("postgresql", "bytea", "bytea", "bigint", true, - true); - private static final JDBCDetails DERBY = new KnownJDBCDetails("derby", "blob", "varchar(%d) for bit data", "bigint", false, - true); - - static - { - Map<String, JDBCDetails> map = new HashMap<>(); - - try - { - map.put(ORACLE.getVendor(), ORACLE); - map.put(SYBASE.getVendor(), SYBASE); - map.put(POSTGRES.getVendor(), POSTGRES); - map.put(DERBY.getVendor(), DERBY); - map.put(FALLBACK.getVendor(), FALLBACK); - } - finally - { - VENDOR_DETAILS = Collections.unmodifiableMap(map); - } - } - - private final static Map<String, JDBCDetails> VENDOR_DETAILS; - - private final String _vendor; - private final String _blobType; - private final String _varBinaryType; - private final String _bigintType; - private final boolean _useBytesMethodsForBlob; - private final boolean _isKnownVendor; - - KnownJDBCDetails(String vendor, - String blobType, - String varBinaryType, - String bigIntType, - boolean useBytesMethodsForBlob, - boolean knownVendor) - { - _vendor = vendor; - _blobType = blobType; - _varBinaryType = varBinaryType; - _bigintType = bigIntType; - _useBytesMethodsForBlob = useBytesMethodsForBlob; - _isKnownVendor = knownVendor; - } - - @Override - public String getVendor() - { - return _vendor; - } - - @Override - public String getBlobType() - { - return _blobType; - } - - @Override - public String getVarBinaryType() - { - return _varBinaryType; - } - - @Override - public boolean isUseBytesMethodsForBlob() - { - return _useBytesMethodsForBlob; - } - - @Override - public String getBigintType() - { - return _bigintType; - } - - @Override - public boolean isKnownVendor() - { - return _isKnownVendor; - } - - @Override - public boolean isOverridden() - { - return false; - } - - } - - @Override - public String toString() - { - return "JDBCDetails{" + - "vendor='" + getVendor() + '\'' + - ", blobType='" + getBlobType() + '\'' + - ", varBinaryType='" + getVarBinaryType() + '\'' + - ", bigIntType='" + getBigintType() + '\'' + - ", useBytesMethodsForBlob=" + isUseBytesMethodsForBlob() + - ", knownVendor=" + isKnownVendor() + - ", overridden=" + isOverridden() + - '}'; - } - - @Override - public boolean equals(final Object o) - { - if (this == o) - { - return true; - } - if (o == null || getClass() != o.getClass()) - { - return false; - } - - final JDBCDetails that = (JDBCDetails) o; - - if (isKnownVendor() != that.isKnownVendor()) - { - return false; - } - if (isOverridden() != that.isOverridden()) - { - return false; - } - if (isUseBytesMethodsForBlob() != that.isUseBytesMethodsForBlob()) - { - return false; - } - if (getBigintType() != null ? !getBigintType().equals(that.getBigintType()) : that.getBigintType() != null) - { - return false; - } - if (getBlobType() != null ? !getBlobType().equals(that.getBlobType()) : that.getBlobType() != null) - { - return false; - } - if (getVarBinaryType() != null ? !getVarBinaryType().equals(that.getVarBinaryType()) : that.getVarBinaryType() != null) - { - return false; - } - if (getVendor() != null ? !getVendor().equals(that.getVendor()) : that.getVendor() != null) - { - return false; - } - - return true; - } - - @Override - public int hashCode() - { - int result = getVendor() != null ? getVendor().hashCode() : 0; - result = 31 * result + (getBlobType() != null ? getBlobType().hashCode() : 0); - result = 31 * result + (getVarBinaryType() != null ? getVarBinaryType().hashCode() : 0); - result = 31 * result + (getBigintType() != null ? getBigintType().hashCode() : 0); - result = 31 * result + (isUseBytesMethodsForBlob() ? 1 : 0); - result = 31 * result + (isKnownVendor() ? 1 : 0); - result = 31 * result + (isOverridden() ? 1 : 0); - return result; - } - - public static JDBCDetails getDetailsForJdbcUrl(String jdbcUrl, final ConfiguredObject<?> object) - { - final Set<String> contextKeys = object.getContextKeys(false); - Map<String,String> mapConversion = new AbstractMap<String, String>() - { - @Override - public Set<Entry<String, String>> entrySet() - { - return new AbstractSet<Entry<String, String>>() - { - @Override - public Iterator<Entry<String, String>> iterator() - { - final Iterator<String> underlying = contextKeys.iterator(); - return new Iterator<Entry<String, String>>() - { - @Override - public boolean hasNext() - { - return underlying.hasNext(); - } - - @Override - public Entry<String, String> next() - { - final String key = underlying.next(); - final String value = object.getContextValue(String.class, key); - return new Entry<String,String>() - { - - @Override - public String getKey() - { - return key; - } - - @Override - public String getValue() - { - return value; - } - - @Override - public String setValue(final String value) - { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - }; - } - - @Override - public int size() - { - return contextKeys.size(); - } - }; - } - }; - return getDetailsForJdbcUrl(jdbcUrl, mapConversion); - } - public static JDBCDetails getDetailsForJdbcUrl(String jdbcUrl, final Map<String, String> contextMap) - { - String[] components = jdbcUrl.split(":", 3); - final JDBCDetails details; - if(components.length >= 2) - { - String vendor = components[1]; - if (KnownJDBCDetails.VENDOR_DETAILS.containsKey(vendor)) - { - details = KnownJDBCDetails.VENDOR_DETAILS.get(vendor); - } - else - { - details = KnownJDBCDetails.FALLBACK; - } - } - else - { - details = KnownJDBCDetails.FALLBACK; - } - - - return new JDBCDetails() - { - @Override - public String getVendor() - { - return details.getVendor(); - } - - @Override - public String getBlobType() - { - return contextMap.containsKey(CONTEXT_JDBCSTORE_BLOBTYPE) - ? String.valueOf(contextMap.get(CONTEXT_JDBCSTORE_BLOBTYPE)) : details.getBlobType(); - } - - @Override - public String getVarBinaryType() - { - return contextMap.containsKey(CONTEXT_JDBCSTORE_VARBINARYTYPE) - ? String.valueOf(contextMap.get(CONTEXT_JDBCSTORE_VARBINARYTYPE)) : details.getVarBinaryType(); - } - - @Override - public String getBigintType() - { - return contextMap.containsKey(CONTEXT_JDBCSTORE_BIGINTTYPE) - ? String.valueOf(contextMap.get(CONTEXT_JDBCSTORE_BIGINTTYPE)) : details.getBigintType(); - } - - @Override - public boolean isUseBytesMethodsForBlob() - { - return contextMap.containsKey(CONTEXT_JDBCSTORE_USEBYTESFORBLOB) - ? Boolean.parseBoolean(contextMap.get(CONTEXT_JDBCSTORE_USEBYTESFORBLOB)) : details.isUseBytesMethodsForBlob(); - } - - @Override - public boolean isKnownVendor() - { - return details.isKnownVendor(); - } - - @Override - public boolean isOverridden() - { - return contextMap.containsKey(CONTEXT_JDBCSTORE_USEBYTESFORBLOB) - || contextMap.containsKey(CONTEXT_JDBCSTORE_BIGINTTYPE) - || contextMap.containsKey(CONTEXT_JDBCSTORE_VARBINARYTYPE) - || contextMap.containsKey(CONTEXT_JDBCSTORE_BLOBTYPE); - } - }; - - } - -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSettings.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSettings.java deleted file mode 100644 index d784ece0e4..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSettings.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.qpid.server.store.jdbc; - -import org.apache.qpid.server.store.Settings; - -public interface JDBCSettings extends Settings -{ - String getConnectionUrl(); - - String getConnectionPoolType(); - - String getUsername(); - - String getPassword(); -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfig.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfig.java deleted file mode 100644 index 9fe64577bb..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfig.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.jdbc; - -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.model.SystemConfig; - -public interface JDBCSystemConfig<X extends JDBCSystemConfig<X>> extends SystemConfig<X>, JDBCSettings -{ - @ManagedAttribute(mandatory=true, defaultValue = "${systemConfig.connectionUrl}") - String getConnectionUrl(); - - @ManagedAttribute(defaultValue=DefaultConnectionProviderFactory.TYPE) - String getConnectionPoolType(); - - @ManagedAttribute(defaultValue = "${systemConfig.username}") - String getUsername(); - - @ManagedAttribute(secure=true, defaultValue = "${systemConfig.password}") - String getPassword(); -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfigImpl.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfigImpl.java deleted file mode 100644 index 9c3d33fc04..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfigImpl.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.jdbc; - -import java.util.Map; - -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.model.AbstractSystemConfig; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerShutdownProvider; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.SystemConfigFactoryConstructor; -import org.apache.qpid.server.store.DurableConfigurationStore; - -@ManagedObject( category = false, type = JDBCSystemConfigImpl.SYSTEM_CONFIG_TYPE) -public class JDBCSystemConfigImpl extends AbstractSystemConfig<JDBCSystemConfigImpl> implements JDBCSystemConfig<JDBCSystemConfigImpl> -{ - public static final String SYSTEM_CONFIG_TYPE = "JDBC"; - - @ManagedAttributeField - private String _connectionUrl; - @ManagedAttributeField - private String _connectionPoolType; - @ManagedAttributeField - private String _username; - @ManagedAttributeField - private String _password; - - @SystemConfigFactoryConstructor - public JDBCSystemConfigImpl(final TaskExecutor taskExecutor, - final EventLogger eventLogger, - final LogRecorder logRecorder, - final Map<String,Object> attributes, - final BrokerShutdownProvider brokerShutdownProvider) - { - super(taskExecutor, eventLogger, logRecorder, attributes, brokerShutdownProvider); - } - - @Override - protected DurableConfigurationStore createStoreObject() - { - return new GenericJDBCConfigurationStore(Broker.class); - } - - @Override - public String getConnectionUrl() - { - return _connectionUrl; - } - - @Override - public String getConnectionPoolType() - { - return _connectionPoolType; - } - - @Override - public String getUsername() - { - return _username; - } - - @Override - public String getPassword() - { - return _password; - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHost.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHost.java deleted file mode 100644 index 8608848d98..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHost.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.qpid.server.virtualhost.jdbc; - -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.jdbc.DefaultConnectionProviderFactory; -import org.apache.qpid.server.store.jdbc.JDBCSettings; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public interface JDBCVirtualHost<X extends JDBCVirtualHost<X>> extends VirtualHostImpl<X, AMQQueue<?>, ExchangeImpl<?>>, - JDBCSettings -{ - @ManagedAttribute(mandatory=true) - String getConnectionUrl(); - - @ManagedAttribute(defaultValue=DefaultConnectionProviderFactory.TYPE) - String getConnectionPoolType(); - - @ManagedAttribute - String getUsername(); - - @ManagedAttribute(secure=true) - String getPassword(); -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHostImpl.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHostImpl.java deleted file mode 100644 index 434e887596..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHostImpl.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.virtualhost.jdbc; - -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.jdbc.GenericJDBCMessageStore; -import org.apache.qpid.server.virtualhost.AbstractVirtualHost; - -import java.util.Map; - -@ManagedObject(category = false, type = JDBCVirtualHostImpl.VIRTUAL_HOST_TYPE) -public class JDBCVirtualHostImpl extends AbstractVirtualHost<JDBCVirtualHostImpl> implements JDBCVirtualHost<JDBCVirtualHostImpl> -{ - public static final String VIRTUAL_HOST_TYPE = "JDBC"; - - @ManagedAttributeField - private String _connectionUrl; - - @ManagedAttributeField - private String _connectionPoolType; - - @ManagedAttributeField - private String _username; - - @ManagedAttributeField - private String _password; - - @ManagedObjectFactoryConstructor - public JDBCVirtualHostImpl(final Map<String, Object> attributes, - final VirtualHostNode<?> virtualHostNode) - { - super(attributes, virtualHostNode); - } - - @Override - protected MessageStore createMessageStore() - { - return new GenericJDBCMessageStore(); - } - - @Override - public String getConnectionUrl() - { - return _connectionUrl; - } - - @Override - public String getConnectionPoolType() - { - return _connectionPoolType; - } - - @Override - public String getUsername() - { - return _username; - } - - @Override - public String getPassword() - { - return _password; - } - - @Override - public String toString() - { - return getClass().getSimpleName() + " [id=" + getId() + ", name=" + getName() + - ", connectionUrl=" + getConnectionUrl() + - ", connectionPoolType=" + getConnectionPoolType() + - ", username=" + getUsername() + "]"; - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNode.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNode.java deleted file mode 100644 index 0ac75b3877..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNode.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.virtualhostnode.jdbc; - -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.store.jdbc.DefaultConnectionProviderFactory; -import org.apache.qpid.server.store.jdbc.JDBCSettings; - -public interface JDBCVirtualHostNode<X extends JDBCVirtualHostNode<X>> extends VirtualHostNode<X>, JDBCSettings -{ - @ManagedAttribute(mandatory=true) - String getConnectionUrl(); - - @ManagedAttribute(defaultValue=DefaultConnectionProviderFactory.TYPE) - String getConnectionPoolType(); - - @ManagedAttribute - String getUsername(); - - @ManagedAttribute(secure=true) - String getPassword(); -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNodeImpl.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNodeImpl.java deleted file mode 100644 index cb20549b80..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNodeImpl.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.virtualhostnode.jdbc; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.server.store.jdbc.GenericJDBCConfigurationStore; -import org.apache.qpid.server.virtualhostnode.AbstractStandardVirtualHostNode; - -@ManagedObject(type = JDBCVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE, category = false , - validChildTypes = "org.apache.qpid.server.virtualhostnode.jdbc.JDBCVirtualHostNodeImpl#getSupportedChildTypes()") -public class JDBCVirtualHostNodeImpl extends AbstractStandardVirtualHostNode<JDBCVirtualHostNodeImpl> implements JDBCVirtualHostNode<JDBCVirtualHostNodeImpl> -{ - public static final String VIRTUAL_HOST_NODE_TYPE = "JDBC"; - - @ManagedAttributeField - private String _connectionUrl; - - @ManagedAttributeField - private String _connectionPoolType; - - @ManagedAttributeField - private String _username; - - @ManagedAttributeField - private String _password; - - @ManagedObjectFactoryConstructor - public JDBCVirtualHostNodeImpl(Map<String, Object> attributes, Broker<?> parent) - { - super(attributes, parent); - } - - @Override - protected void writeLocationEventLog() - { - } - - @Override - protected DurableConfigurationStore createConfigurationStore() - { - return new GenericJDBCConfigurationStore(VirtualHost.class); - } - - @Override - public String getConnectionUrl() - { - return _connectionUrl; - } - - @Override - public String getConnectionPoolType() - { - return _connectionPoolType; - } - - @Override - public String getUsername() - { - return _username; - } - - @Override - public String getPassword() - { - return _password; - } - - @Override - public String toString() - { - return getClass().getSimpleName() + " [id=" + getId() + ", name=" + getName() + - ", connectionUrl=" + getConnectionUrl() + - ", connectionPoolType=" + getConnectionPoolType() + - ", username=" + getUsername() + "]"; - } - - - public static Map<String, Collection<String>> getSupportedChildTypes() - { - return Collections.singletonMap(VirtualHost.class.getSimpleName(), getSupportedVirtualHostTypes(true)); - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/add.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/add.js deleted file mode 100644 index 44405c610b..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/add.js +++ /dev/null @@ -1,41 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/json", - "dojo/string", - "dojo/store/Memory", - "dijit/form/FilteringSelect", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, parser, array, event, json, string, Memory, FilteringSelect) { - return { - show: function(data) - { - data.context.removeDynamicallyAddedInheritedContext(); - } - }; - }); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/edit.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/edit.js deleted file mode 100644 index 675a919b3d..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/edit.js +++ /dev/null @@ -1,26 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], - function () - { - return {show: function(data) {}}; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/show.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/show.js deleted file mode 100644 index 39cb2bf507..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/show.js +++ /dev/null @@ -1,33 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], - function () - { - function NonePool(data) - { - } - - NonePool.prototype.update=function(data) - { - }; - - return NonePool; -}); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/add.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/add.js deleted file mode 100644 index 8de6206373..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/add.js +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -define(["dojo/_base/xhr", - "dojo/_base/array", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dojo/string", - "dojo/store/Memory", - "dijit/registry", - "dojo/text!virtualhost/jdbc/add.html", - "dojo/text!service/helper?action=pluginList&plugin=JDBCConnectionProviderFactory", - "qpid/common/util", - "dijit/form/ValidationTextBox", - "dijit/form/CheckBox", - "dojo/domReady!"], - function (xhr, array, parser, dom, domConstruct, json, string, Memory, registry, template, poolTypeJsonString, util) - { - return { - show: function (data) - { - var that = this; - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode).then(function(instances) - { - that._postParse(data); - }); - }, - _postParse: function (data) - { - var that = this; - registry.byId("addVirtualHost.connectionUrl").set("regExpGen", util.jdbcUrlOrContextVarRegexp); - registry.byId("addVirtualHost.username").set("regExpGen", util.nameOrContextVarRegexp); - var poolTypes = json.parse(poolTypeJsonString); - var poolTypesData = []; - for (var i =0 ; i < poolTypes.length; i++) - { - poolTypesData[i]= {id: poolTypes[i], name: poolTypes[i]}; - } - var poolTypesStore = new Memory({ data: poolTypesData }); - var poolTypeControl = registry.byId("addVirtualHost.connectionPoolType"); - poolTypeControl.set("store", poolTypesStore); - poolTypeControl.set("value", "NONE"); - - var poolTypeFieldsDiv = dom.byId("addVirtualHost.poolSpecificDiv"); - poolTypeControl.on("change", - function(type) - { - if(type && string.trim(type) != "") - { - var widgets = registry.findWidgets(poolTypeFieldsDiv); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(poolTypeFieldsDiv); - require(["qpid/management/store/pool/"+type.toLowerCase()+"/add"], - function(poolType) - { - poolType.show({containerNode:poolTypeFieldsDiv, context: data.parent.virtualHostContext}); - }); - } - } - ); - } - }; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/edit.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/edit.js deleted file mode 100644 index 4a2a3763bd..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/edit.js +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -define(["qpid/common/util", - "dojo/text!service/helper?action=pluginList&plugin=JDBCConnectionProviderFactory", - "dojo/_base/array", - "dojo/json", - "dojo/string", - "dojo/store/Memory", - "dojo/dom", - "dojo/dom-construct", - "dijit/registry", - "dojo/domReady!"], - function (util, poolTypeJsonString, array, json, string, Memory, dom, domConstruct, registry) - { - - return { - show: function(data) - { - var that = this; - util.parseHtmlIntoDiv(data.containerNode, "virtualhost/jdbc/edit.html", - function(){that._postParse(data)}); - }, - _postParse: function(data) - { - registry.byId("editVirtualHost.connectionUrl").set("regExpGen", util.jdbcUrlOrContextVarRegexp); - registry.byId("editVirtualHost.username").set("regExpGen", util.nameOrContextVarRegexp); - - var poolTypes = json.parse(poolTypeJsonString); - var poolTypesData = []; - for (var i =0 ; i < poolTypes.length; i++) - { - poolTypesData[i]= {id: poolTypes[i], name: poolTypes[i]}; - } - var poolTypesStore = new Memory({ data: poolTypesData }); - var poolTypeControl = registry.byId("editVirtualHost.connectionPoolType"); - poolTypeControl.set("store", poolTypesStore); - poolTypeControl.set("value", data.data.connectionPoolType); - - var passwordControl = registry.byId("editVirtualHost.password"); - if (data.data.password) - { - passwordControl.set("placeHolder", "*******"); - } - - var poolTypeFieldsDiv = dom.byId("editVirtualHost.poolSpecificDiv"); - poolTypeControl.on("change", - function(type) - { - if(type && string.trim(type) != "") - { - var widgets = registry.findWidgets(poolTypeFieldsDiv); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(poolTypeFieldsDiv); - - require(["qpid/management/store/pool/"+type.toLowerCase()+"/edit"], - function(poolType) - { - poolType.show({containerNode:poolTypeFieldsDiv, data: data.data, context: data.parent.context}) - }); - } - } - ); - } - }; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/show.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/show.js deleted file mode 100644 index b717f2091d..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/show.js +++ /dev/null @@ -1,64 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["qpid/common/util", "dojo/query", "dojo/_base/array", "dojo/dom-construct", "dijit/registry", "dojo/domReady!"], - function (util, query, array, domConstruct, registry) - { - var fieldNames = ["connectionUrl", "username", "connectionPoolType"]; - - function JDBC(data) - { - var that = this; - util.buildUI(data.containerNode, data.parent, "virtualhostnode/jdbc/show.html", fieldNames, this, function() - { - that.usernameAttributeContainer=query(".usernameAttributeContainer", data.containerNode)[0]; - that.connectionPoolTypeAttributeContainer=query(".connectionPoolTypeAttributeContainer", data.containerNode)[0]; - }); - } - - JDBC.prototype.update = function(data) - { - var previousConnectionPoolType = this.connectionPoolType ? this.connectionPoolType.innerHTML : null; - util.updateUI(data, fieldNames, this); - this.usernameAttributeContainer.style.display = data.username ? "block" : "none"; - if (data.connectionPoolType && (!this.poolDetails || previousConnectionPoolType != data.connectionPoolType)) - { - var that = this; - require(["qpid/management/store/pool/" + data.connectionPoolType.toLowerCase() + "/show"], - function(PoolDetails) - { - var widgets = registry.findWidgets(that.connectionPoolTypeAttributeContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(that.connectionPoolTypeAttributeContainer); - - that.poolDetails = new PoolDetails({containerNode:that.connectionPoolTypeAttributeContainer, parent: that}); - that.poolDetails.update(data); - } - ); - } - else - { - this.poolDetails.update(data); - } - } - - return JDBC; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/add.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/add.js deleted file mode 100644 index 071c0c8b23..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/add.js +++ /dev/null @@ -1,85 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/_base/array", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dojo/string", - "dojo/store/Memory", - "dijit/registry", - "dojo/text!virtualhostnode/jdbc/add.html", - "dojo/text!service/helper?action=pluginList&plugin=JDBCConnectionProviderFactory", - "qpid/common/util", - "dijit/form/ValidationTextBox", - "dijit/form/CheckBox", - "dojo/domReady!"], - function (xhr, array, parser, dom, domConstruct, json, string, Memory, registry, template, poolTypeJsonString, util) - { - return { - show: function (data) - { - var that = this; - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode).then(function(instances) - { - that._postParse(data); - }); - }, - _postParse: function(data) - { - var that = this; - registry.byId("addVirtualHostNode.connectionUrl").set("regExpGen", util.jdbcUrlOrContextVarRegexp); - registry.byId("addVirtualHostNode.username").set("regExpGen", util.nameOrContextVarRegexp); - - var poolTypes = json.parse(poolTypeJsonString); - var poolTypesData = []; - for (var i =0 ; i < poolTypes.length; i++) - { - poolTypesData[i]= {id: poolTypes[i], name: poolTypes[i]}; - } - var poolTypesStore = new Memory({ data: poolTypesData }); - var poolTypeControl = registry.byId("addVirtualHostNode.connectionPoolType"); - poolTypeControl.set("store", poolTypesStore); - poolTypeControl.set("value", "NONE"); - - var poolTypeFieldsDiv = dom.byId("addVirtualHostNode.poolSpecificDiv"); - poolTypeControl.on("change", - function(type) - { - if(type && string.trim(type) != "") - { - var widgets = registry.findWidgets(poolTypeFieldsDiv); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(poolTypeFieldsDiv); - require(["qpid/management/store/pool/"+type.toLowerCase()+"/add"], - function(poolType) - { - poolType.show({containerNode:poolTypeFieldsDiv, context: data.parent.virtualHostNodeContext}); - }); - } - } - ); - } - }; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/edit.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/edit.js deleted file mode 100644 index cccfa95d4c..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/edit.js +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -define(["qpid/common/util", - "dojo/text!service/helper?action=pluginList&plugin=JDBCConnectionProviderFactory", - "dojo/_base/array", - "dojo/json", - "dojo/string", - "dojo/store/Memory", - "dojo/dom", - "dojo/dom-construct", - "dijit/registry", - "dojo/domReady!"], - function (util, poolTypeJsonString, array, json, string, Memory, dom, domConstruct, registry) - { - return { - show: function(data) - { - var that = this; - util.parseHtmlIntoDiv(data.containerNode, "virtualhostnode/jdbc/edit.html", function(){ that._postParse(data);}); - }, - _postParse: function(data) - { - registry.byId("editVirtualHostNode.connectionUrl").set("regExpGen", util.jdbcUrlOrContextVarRegexp); - registry.byId("editVirtualHostNode.username").set("regExpGen", util.nameOrContextVarRegexp); - - var poolTypes = json.parse(poolTypeJsonString); - var poolTypesData = []; - for (var i =0 ; i < poolTypes.length; i++) - { - poolTypesData[i]= {id: poolTypes[i], name: poolTypes[i]}; - } - var poolTypesStore = new Memory({ data: poolTypesData }); - var poolTypeControl = registry.byId("editVirtualHostNode.connectionPoolType"); - poolTypeControl.set("store", poolTypesStore); - poolTypeControl.set("value", data.data.connectionPoolType); - - var passwordControl = registry.byId("editVirtualHostNode.password"); - if (data.data.password) - { - passwordControl.set("placeHolder", "*******"); - } - - var poolTypeFieldsDiv = dom.byId("editVirtualHostNode.poolSpecificDiv"); - poolTypeControl.on("change", - function(type) - { - if(type && string.trim(type) != "") - { - var widgets = registry.findWidgets(poolTypeFieldsDiv); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(poolTypeFieldsDiv); - - require(["qpid/management/store/pool/"+type.toLowerCase()+"/edit"], - function(poolType) - { - poolType.show({containerNode:poolTypeFieldsDiv, data: data.data, context: data.parent.context}) - - if (!(data.data.state == "STOPPED" || data.data.state == "ERRORED")) - { - var widgets = registry.findWidgets(poolTypeFieldsDiv); - array.forEach(widgets, function(item) { item.set("disabled", true);}); - } - }); - } - } - ); - } - }; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/show.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/show.js deleted file mode 100644 index 019962fc64..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/show.js +++ /dev/null @@ -1,68 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -define(["qpid/common/util", "dojo/query", "dojo/_base/array", "dojo/dom-construct", "dijit/registry", "dojo/domReady!"], - function (util, query, array, domConstruct, registry) - { - var fieldNames = ["connectionUrl", "username", "connectionPoolType"]; - - function Jdbc(data) - { - this.parent = data.parent; - var that = this; - util.buildUI(data.containerNode, data.parent, "virtualhostnode/jdbc/show.html", fieldNames, this, - function() - { - that.usernameAttributeContainer=query(".usernameAttributeContainer", data.containerNode)[0]; - that.connectionPoolTypeAttributeContainer=query(".connectionPoolTypeAttributeContainer", data.containerNode)[0]; - }); - } - - Jdbc.prototype.update=function(data) - { - var previousConnectionPoolType = this.connectionPoolType ? this.connectionPoolType.innerHTML : null; - this.parent.editNodeButton.set("disabled", !(data.state == "STOPPED" || data.state == "ERRORED")); - util.updateUI(data, fieldNames, this); - - this.usernameAttributeContainer.style.display = data.username ? "block" : "none"; - if (data.connectionPoolType && (!this.poolDetails || previousConnectionPoolType != data.connectionPoolType)) - { - var that = this; - require(["qpid/management/store/pool/" + data.connectionPoolType.toLowerCase() + "/show"], - function(PoolDetails) - { - var widgets = registry.findWidgets(that.connectionPoolTypeAttributeContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(that.connectionPoolTypeAttributeContainer); - - that.poolDetails = new PoolDetails({containerNode:that.connectionPoolTypeAttributeContainer, parent: that}); - that.poolDetails.update(data); - } - ); - } - else - { - this.poolDetails.update(data); - } - }; - - return Jdbc; -}); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/add.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/add.html deleted file mode 100644 index 7fc7f17565..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/add.html +++ /dev/null @@ -1,76 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">JDBC Url*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHost.connectionUrl" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'connectionUrl', - placeHolder: 'jdbc:provider:info', - required: true, - missingMessage: 'JDBC URL must be supplied', - title: 'Enter JDBC URL'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Username*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHost.username" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'username', - placeHolder: 'username', - required: true, - missingMessage: 'Username must be supplied', - title: 'Enter username'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Password*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="password" id="addVirtualHost.password" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'password', - placeHolder: 'password', - required: true, - missingMessage: 'Password must be supplied', - title: 'Enter password'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Connection Pool*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHost.connectionPoolType" - data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'connectionPoolType', - required: true, - missingMessage: 'Connection Pool type must be supplied', - title: 'Select Connection Pool', - placeHolder: 'Select pool type'" /> - </div> - </div> - - <div class="clear"></div> - <div id="addVirtualHost.poolSpecificDiv"></div> - <div class="infoMessage">The virtual host will have the same name as the node.</div> -</div> diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/edit.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/edit.html deleted file mode 100644 index 10212079eb..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/edit.html +++ /dev/null @@ -1,78 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">JDBC Url*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editVirtualHost.connectionUrl" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'connectionUrl', - placeHolder: 'jdbc:provider:info', - required: true, - missingMessage: 'JDBC URL must be supplied', - title: 'Enter JDBC URL'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Username*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editVirtualHost.username" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'username', - placeHolder: 'username', - required: true, - missingMessage: 'Username must be supplied', - title: 'Enter username'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Password*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="password" id="editVirtualHost.password" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'password', - placeHolder: 'password', - type: 'password', - required: false, - missingMessage: 'Password must be supplied', - title: 'Enter password'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Connection Pool*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editVirtualHost.connectionPoolType" - data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'connectionPoolType', - required: true, - missingMessage: 'Connection Pool type must be supplied', - title: 'Select Connection Pool', - placeHolder: 'Select pool type'" /> - </div> - </div> - - <div class="clear"></div> - <div id="editVirtualHost.poolSpecificDiv"></div> - -</div> diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/store/pool/none/add.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/store/pool/none/add.html deleted file mode 100644 index 2666129a1f..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/store/pool/none/add.html +++ /dev/null @@ -1,17 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> - diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/add.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/add.html deleted file mode 100644 index f9561d4c51..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/add.html +++ /dev/null @@ -1,77 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">JDBC Url*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHostNode.connectionUrl" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'connectionUrl', - placeHolder: 'jdbc:provider:info', - required: true, - promptMessage: 'JDBC URL specifying the connection to the database', - title: 'Enter JDBC URL'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Username*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHostNode.username" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'username', - placeHolder: 'username', - required: true, - promptMessage: 'Database user name', - title: 'Enter username'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Password*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="password" id="addVirtualHostNode.password" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'password', - placeHolder: 'password', - required: true, - promptMessage: 'Database password', - title: 'Enter password'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Connection Pool*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHostNode.connectionPoolType" - data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'connectionPoolType', - required: true, - promptMessage: 'Connection pool type to use when connecting to the database', - title: 'Select the connection pool type', - placeHolder: 'Select pool type'" /> - </div> - </div> - - <div class="clear"></div> - <div id="addVirtualHostNode.poolSpecificDiv"></div> -</div> diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/edit.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/edit.html deleted file mode 100644 index c8cc56d1cb..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/edit.html +++ /dev/null @@ -1,77 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">JDBC Url*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editVirtualHostNode.connectionUrl" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'connectionUrl', - placeHolder: 'jdbc:provider:info', - required: true, - missingMessage: 'JDBC URL must be supplied', - title: 'Enter JDBC URL'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Username*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editVirtualHostNode.username" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'username', - placeHolder: 'username', - required: true, - missingMessage: 'Username must be supplied', - title: 'Enter username'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Password*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="password" id="editVirtualHostNode.password" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'password', - placeHolder: 'password', - required: false, - missingMessage: 'Password must be supplied', - title: 'Enter password'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Connection Pool*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editVirtualHostNode.connectionPoolType" - data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'connectionPoolType', - required: true, - missingMessage: 'Connection Pool type must be supplied', - title: 'Select Connection Pool', - placeHolder: 'Select pool type'" /> - </div> - </div> - - <div class="clear"></div> - <div id="editVirtualHostNode.poolSpecificDiv"></div> -</div> diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/show.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/show.html deleted file mode 100644 index b6145f59b6..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/show.html +++ /dev/null @@ -1,34 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell">Connection URL:</div> - <div class="connectionUrl"></div> - </div> - <div class="clear usernameAttributeContainer"> - <div class="formLabel-labelCell">Username:</div> - <div class="username"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Connection Pool Type:</div> - <div class="connectionPoolType"></div> - </div> - <div class="clear connectionPoolTypeAttributeContainer"/> - - <div class="clear"></div> -</div> - diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/store/pool/none/add.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/store/pool/none/add.html deleted file mode 100644 index 2666129a1f..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/store/pool/none/add.html +++ /dev/null @@ -1,17 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> - diff --git a/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCDetailsTest.java b/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCDetailsTest.java deleted file mode 100644 index 67e9960ca7..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCDetailsTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.qpid.server.store.jdbc; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - -public class JDBCDetailsTest extends TestCase -{ - public void testDerby() - { - JDBCDetails derbyDetails = JDBCDetails.getDetailsForJdbcUrl("jdbc:derby:sample", - Collections.<String, String>emptyMap()); - assertEquals("derby", derbyDetails.getVendor()); - assertEquals("varchar(%d) for bit data", derbyDetails.getVarBinaryType()); - assertEquals("bigint", derbyDetails.getBigintType()); - assertEquals("blob", derbyDetails.getBlobType()); - assertFalse(derbyDetails.isUseBytesMethodsForBlob()); - - assertTrue(derbyDetails.isKnownVendor()); - assertFalse(derbyDetails.isOverridden()); - } - - public void testUnknownVendor_UsesFallbackDetails() - { - JDBCDetails details = JDBCDetails.getDetailsForJdbcUrl("jdbc:homedb:", Collections.<String, String>emptyMap()); - assertEquals("fallback", details.getVendor()); - assertEquals("varchar(%d) for bit data", details.getVarBinaryType()); - assertEquals("bigint", details.getBigintType()); - assertEquals("blob", details.getBlobType()); - assertEquals(false, details.isUseBytesMethodsForBlob()); - assertFalse(details.isOverridden()); - assertFalse(details.isKnownVendor()); - } - - public void testDerbyWithOverride() - { - - Map<String, String> contextMap = new HashMap<>(); - contextMap.put(JDBCDetails.CONTEXT_JDBCSTORE_VARBINARYTYPE, "myvarbin"); - - JDBCDetails derbyDetails = JDBCDetails.getDetailsForJdbcUrl("jdbc:derby:sample", contextMap); - assertEquals("derby", derbyDetails.getVendor()); - assertEquals("myvarbin", derbyDetails.getVarBinaryType()); - assertEquals("bigint", derbyDetails.getBigintType()); - assertEquals("blob", derbyDetails.getBlobType()); - assertFalse(derbyDetails.isUseBytesMethodsForBlob()); - - assertTrue(derbyDetails.isKnownVendor()); - assertTrue(derbyDetails.isOverridden()); - } - - - - - public void testRecognisedDriver_AllDetailsProvidedByContext() - { - Map<String, String> contextMap = new HashMap<>(); - contextMap.put(JDBCDetails.CONTEXT_JDBCSTORE_VARBINARYTYPE, "myvarbin"); - contextMap.put(JDBCDetails.CONTEXT_JDBCSTORE_BIGINTTYPE, "mybigint"); - contextMap.put(JDBCDetails.CONTEXT_JDBCSTORE_BLOBTYPE, "myblob"); - contextMap.put(JDBCDetails.CONTEXT_JDBCSTORE_USEBYTESFORBLOB, "true"); - - JDBCDetails details = JDBCDetails.getDetailsForJdbcUrl("jdbc:sybase:", contextMap); - assertEquals("sybase", details.getVendor()); - assertEquals("myvarbin", details.getVarBinaryType()); - assertEquals("mybigint", details.getBigintType()); - assertEquals("myblob", details.getBlobType()); - assertEquals(true, details.isUseBytesMethodsForBlob()); - assertTrue(details.isKnownVendor()); - assertTrue(details.isOverridden()); - } - -}
\ No newline at end of file diff --git a/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCMessageStoreTest.java b/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCMessageStoreTest.java deleted file mode 100644 index 3a85ae3257..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCMessageStoreTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store.jdbc; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashSet; -import java.util.Set; - -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MessageStoreTestCase; -import org.apache.qpid.server.virtualhost.jdbc.JDBCVirtualHost; - -public class JDBCMessageStoreTest extends MessageStoreTestCase -{ - private String _connectionURL; - - @Override - public void tearDown() throws Exception - { - try - { - shutdownDerby(); - } - finally - { - super.tearDown(); - } - } - - public void testOnDelete() throws Exception - { - Set<String> expectedTables = GenericJDBCMessageStore.MESSAGE_STORE_TABLE_NAMES; - assertTablesExist(expectedTables, true); - getStore().closeMessageStore(); - assertTablesExist(expectedTables, true); - getStore().onDelete(mock(JDBCVirtualHost.class)); - assertTablesExist(expectedTables, false); - } - - @Override - protected VirtualHost createVirtualHost() - { - _connectionURL = "jdbc:derby:memory:/" + getTestName() + ";create=true"; - - final JDBCVirtualHost jdbcVirtualHost = mock(JDBCVirtualHost.class); - when(jdbcVirtualHost.getConnectionUrl()).thenReturn(_connectionURL); - when(jdbcVirtualHost.getUsername()).thenReturn("test"); - when(jdbcVirtualHost.getPassword()).thenReturn("pass"); - return jdbcVirtualHost; - } - - - @Override - protected MessageStore createMessageStore() - { - return new GenericJDBCMessageStore(); - } - - private void assertTablesExist(Set<String> expectedTables, boolean exists) throws SQLException - { - Set<String> existingTables = getTableNames(); - for (String tableName : expectedTables) - { - assertEquals("Table " + tableName + (exists ? " is not found" : " actually exist"), exists, - existingTables.contains(tableName)); - } - } - - private Set<String> getTableNames() throws SQLException - { - Set<String> tableNames = new HashSet<String>(); - Connection conn = null; - try - { - conn = openConnection(); - DatabaseMetaData metaData = conn.getMetaData(); - ResultSet tables = metaData.getTables(null, null, null, new String[] { "TABLE" }); - try - { - while (tables.next()) - { - tableNames.add(tables.getString("TABLE_NAME")); - } - } - finally - { - tables.close(); - } - } - finally - { - if (conn != null) - { - conn.close(); - } - } - return tableNames; - } - - private Connection openConnection() throws SQLException - { - return DriverManager.getConnection(_connectionURL); - } - - - private void shutdownDerby() throws SQLException - { - Connection connection = null; - try - { - connection = DriverManager.getConnection("jdbc:derby:memory:/" + getTestName() + ";shutdown=true"); - } - catch(SQLException e) - { - if (e.getSQLState().equalsIgnoreCase("08006")) - { - //expected and represents a clean shutdown of this database only, do nothing. - } - else - { - throw e; - } - } - finally - { - if (connection != null) - { - connection.close(); - } - } - } -} diff --git a/qpid/java/broker-plugins/management-amqp/pom.xml b/qpid/java/broker-plugins/management-amqp/pom.xml deleted file mode 100644 index 9540560000..0000000000 --- a/qpid/java/broker-plugins/management-amqp/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <artifactId>qpid-java-build</artifactId> - <groupId>org.apache.qpid</groupId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-management-amqp</artifactId> - <name>Qpid AMQP Management Protocol Broker Plug-in</name> - <description>Qpid AMQP Management broker plug-in</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - </dependencies> - - <build> - </build> - -</project> diff --git a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagedEntityType.java b/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagedEntityType.java deleted file mode 100644 index 10a16faa56..0000000000 --- a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagedEntityType.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.amqp; - -import java.util.Arrays; - -class ManagedEntityType -{ - private final String _name; - private final ManagedEntityType[] _parents; - private final String[] _attributes; - private final String[] _operations; - - ManagedEntityType(final String name, - final ManagedEntityType[] parents, - final String[] attributes, - final String[] operations) - { - _name = name; - _parents = parents; - _attributes = attributes; - _operations = operations; - } - - public String getName() - { - return _name; - } - - public ManagedEntityType[] getParents() - { - return _parents; - } - - public String[] getAttributes() - { - return _attributes; - } - - public String[] getOperations() - { - return _operations; - } - - @Override - public String toString() - { - return "ManagedEntityType{" + - "name='" + _name + '\'' + - ", parents=" + Arrays.toString(_parents) + - ", attributes=" + Arrays.toString(_attributes) + - ", operations=" + Arrays.toString(_operations) + - '}'; - } -} diff --git a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNode.java b/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNode.java deleted file mode 100644 index 8e64757cbb..0000000000 --- a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNode.java +++ /dev/null @@ -1,1449 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.amqp; - -import java.nio.charset.Charset; -import java.security.AccessControlException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.consumer.ConsumerTarget; -import org.apache.qpid.server.filter.FilterManager; -import org.apache.qpid.server.filter.Filterable; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.message.internal.InternalMessageHeader; -import org.apache.qpid.server.model.ConfigurationChangeListener; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.SystemNodeCreator; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.MessageConverterRegistry; -import org.apache.qpid.server.store.MessageDurability; -import org.apache.qpid.server.store.MessageEnqueueRecord; -import org.apache.qpid.server.store.StorableMessageMetaData; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.StateChangeListener; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -class ManagementNode implements MessageSource, MessageDestination -{ - - public static final String NAME_ATTRIBUTE = "name"; - public static final String IDENTITY_ATTRIBUTE = "identity"; - public static final String TYPE_ATTRIBUTE = "type"; - public static final String OPERATION_HEADER = "operation"; - public static final String SELF_NODE_NAME = "self"; - public static final String MANAGEMENT_TYPE = "org.amqp.management"; - public static final String GET_TYPES = "GET-TYPES"; - public static final String GET_ATTRIBUTES = "GET-ATTRIBUTES"; - public static final String GET_OPERATIONS = "GET-OPERATIONS"; - public static final String QUERY = "QUERY"; - public static final String ENTITY_TYPE_HEADER = "entityType"; - public static final String STATUS_CODE_HEADER = "statusCode"; - public static final int STATUS_CODE_OK = 200; - public static final String ATTRIBUTES_HEADER = "attributes"; - public static final String OFFSET_HEADER = "offset"; - public static final String COUNT_HEADER = "count"; - public static final String MANAGEMENT_NODE_NAME = "$management"; - public static final String CREATE_OPERATION = "CREATE"; - public static final String READ_OPERATION = "READ"; - public static final String UPDATE_OPERATION = "UPDATE"; - public static final String DELETE_OPERATION = "DELETE"; - public static final String STATUS_DESCRIPTION_HEADER = "statusDescription"; - public static final int NOT_FOUND_STATUS_CODE = 404; - public static final int NOT_IMPLEMENTED_STATUS_CODE = 501; - public static final int STATUS_CODE_NO_CONTENT = 204; - public static final int STATUS_CODE_FORBIDDEN = 403; - public static final int STATUS_CODE_BAD_REQUEST = 400; - public static final int STATUS_CODE_INTERNAL_ERROR = 500; - public static final String ATTRIBUTE_NAMES = "attributeNames"; - public static final String RESULTS = "results"; - - - private final VirtualHostImpl _virtualHost; - - private final UUID _id; - - private final CopyOnWriteArrayList<ConsumerRegistrationListener<? super MessageSource>> _consumerRegistrationListeners = - new CopyOnWriteArrayList<ConsumerRegistrationListener<? super MessageSource>>(); - - private final SystemNodeCreator.SystemNodeRegistry _registry; - private final ConfiguredObject<?> _managedObject; - private Map<String, ManagementNodeConsumer> _consumers = new ConcurrentHashMap<String, ManagementNodeConsumer>(); - - private Map<String,ManagedEntityType> _entityTypes = Collections.synchronizedMap(new LinkedHashMap<String, ManagedEntityType>()); - - private Map<ManagedEntityType,Map<String,ConfiguredObject>> _entities = Collections.synchronizedMap(new LinkedHashMap<ManagedEntityType,Map<String,ConfiguredObject>>()); - - - public ManagementNode(final SystemNodeCreator.SystemNodeRegistry registry, - final ConfiguredObject<?> configuredObject) - { - _virtualHost = registry.getVirtualHost(); - _registry = registry; - final String name = configuredObject.getId() + MANAGEMENT_NODE_NAME; - _id = UUID.nameUUIDFromBytes(name.getBytes(Charset.defaultCharset())); - - - _managedObject = configuredObject; - - configuredObject.addChangeListener(new ModelObjectListener()); - - } - - private Class getManagementClass(Class objectClass) - { - - if(objectClass.getAnnotation(ManagedObject.class)!=null) - { - return objectClass; - } - List<Class> allClasses = Collections.singletonList(objectClass); - List<Class> testedClasses = new ArrayList<Class>(); - do - { - testedClasses.addAll( allClasses ); - allClasses = new ArrayList<Class>(); - for(Class c : testedClasses) - { - for(Class i : c.getInterfaces()) - { - if(!allClasses.contains(i)) - { - allClasses.add(i); - } - } - if(c.getSuperclass() != null && !allClasses.contains(c.getSuperclass())) - { - allClasses.add(c.getSuperclass()); - } - } - allClasses.removeAll(testedClasses); - for(Class c : allClasses) - { - if(c.getAnnotation(ManagedObject.class) != null) - { - return c; - } - } - } - while(!allClasses.isEmpty()); - return null; - } - - private boolean populateTypeMetaData(final Class<? extends ConfiguredObject> objectClass, boolean allowCreate) - { - Class clazz = getManagementClass(objectClass); - if( clazz != null) - { - ManagedObject annotation = (ManagedObject) clazz.getAnnotation(ManagedObject.class); - populateTypeMetaData(clazz, annotation); - return true; - } - else - { - return false; - } - } - - private ManagedEntityType populateTypeMetaData(Class clazz, - final ManagedObject entityType) - { - - ManagedEntityType managedEntityType = _entityTypes.get(clazz.getName()); - - if(managedEntityType == null) - { - List<String> opsList = new ArrayList<String>(Arrays.asList(entityType.operations())); - if(entityType.creatable()) - { - boolean isCreatableChild = false; - Collection<Class<? extends ConfiguredObject>> parentTypes = _managedObject.getModel().getParentTypes(clazz); - for(Class<? extends ConfiguredObject> parentConfig : parentTypes) - { - isCreatableChild = parentConfig.isAssignableFrom(_managedObject.getClass()); - if(isCreatableChild) - { - opsList.add(CREATE_OPERATION); - break; - } - } - } - opsList.addAll(Arrays.asList(READ_OPERATION, UPDATE_OPERATION, DELETE_OPERATION)); - - Set<ManagedEntityType> parentSet = new HashSet<ManagedEntityType>(); - - List<Class> allClasses = new ArrayList<Class>(Arrays.asList(clazz.getInterfaces())); - if(clazz.getSuperclass() != null) - { - allClasses.add(clazz.getSuperclass()); - } - - for(Class parentClazz : allClasses) - { - if(parentClazz.getAnnotation(ManagedObject.class) != null) - { - ManagedEntityType parentType = populateTypeMetaData(parentClazz, - (ManagedObject) parentClazz.getAnnotation( - ManagedObject.class) - ); - parentSet.add(parentType); - parentSet.addAll(Arrays.asList(parentType.getParents())); - - } - } - managedEntityType = new ManagedEntityType(clazz.getName(), parentSet.toArray(new ManagedEntityType[parentSet.size()]), - (String[])(_managedObject.getModel().getTypeRegistry().getAttributeNames( - clazz).toArray(new String[0])), - opsList.toArray(new String[opsList.size()])); - _entityTypes.put(clazz.getName(),managedEntityType); - _entities.put(managedEntityType, Collections.synchronizedMap(new LinkedHashMap<String, ConfiguredObject>())); - - if(ConfiguredObject.class.isAssignableFrom(clazz)) - { - Collection<Class<? extends ConfiguredObject>> childTypes = _managedObject.getModel().getChildTypes(clazz); - for(Class<? extends ConfiguredObject> childClass : childTypes) - { - populateTypeMetaData(childClass, true); - } - } - - } - - return managedEntityType; - - } - - @Override - public <M extends ServerMessage<? extends StorableMessageMetaData>> int send(final M message, - final String routingAddress, - final InstanceProperties instanceProperties, - final ServerTransaction txn, - final Action<? super MessageInstance> postEnqueueAction) - { - - @SuppressWarnings("unchecked") - MessageConverter converter = - MessageConverterRegistry.getConverter(message.getClass(), InternalMessage.class); - - final InternalMessage msg = (InternalMessage) converter.convert(message, _virtualHost); - - if(validateMessage(msg)) - { - txn.addPostTransactionAction(new ServerTransaction.Action() - { - @Override - public void postCommit() - { - enqueue(msg, instanceProperties, postEnqueueAction); - } - - @Override - public void onRollback() - { - - } - }); - - return 1; - } - else - { - return 0; - } - } - - private boolean validateMessage(final ServerMessage message) - { - AMQMessageHeader header = message.getMessageHeader(); - return containsStringHeader(header, TYPE_ATTRIBUTE) && containsStringHeader(header, OPERATION_HEADER) - && (containsStringHeader(header, NAME_ATTRIBUTE) || containsStringHeader(header, IDENTITY_ATTRIBUTE)); - } - - private boolean containsStringHeader(final AMQMessageHeader header, String name) - { - return header.containsHeader(name) && header.getHeader(name) instanceof String; - } - - synchronized void enqueue(InternalMessage message, InstanceProperties properties, Action<? super MessageInstance> postEnqueueAction) - { - if(postEnqueueAction != null) - { - postEnqueueAction.performAction(new ConsumedMessageInstance(message, properties)); - } - - - - String name = (String) message.getMessageHeader().getHeader(NAME_ATTRIBUTE); - String id = (String) message.getMessageHeader().getHeader(IDENTITY_ATTRIBUTE); - String type = (String) message.getMessageHeader().getHeader(TYPE_ATTRIBUTE); - String operation = (String) message.getMessageHeader().getHeader(OPERATION_HEADER); - - InternalMessage response; - - if(SELF_NODE_NAME.equals(name) && type.equals(MANAGEMENT_TYPE)) - { - response = performManagementOperation(message); - } - else if(CREATE_OPERATION.equals(operation)) - { - response = performCreateOperation(message, type); - } - else - { - - ConfiguredObject entity = findSubject(name, id, type); - - if(entity != null) - { - response = performOperation(message, entity); - } - else - { - if(id != null) - { - response = createFailureResponse(message, - NOT_FOUND_STATUS_CODE, - "No entity with id {0} of type {1} found", id, type); - } - else - { - response = createFailureResponse(message, - NOT_FOUND_STATUS_CODE, - "No entity with name {0} of type {1} found", name, type); - } - } - } - - - ManagementNodeConsumer consumer = _consumers.get(message.getMessageHeader().getReplyTo()); - response.setInitialRoutingAddress(message.getMessageHeader().getReplyTo()); - if(consumer != null) - { - // TODO - check same owner - consumer.send(response); - } - else - { - _virtualHost.getDefaultDestination().send(response, - message.getMessageHeader().getReplyTo(), InstanceProperties.EMPTY, - new AutoCommitTransaction(_virtualHost.getMessageStore()), - null); - } - // TODO - route to a queue - - } - - private InternalMessage performCreateOperation(final InternalMessage message, final String type) - { - InternalMessage response; - ManagedEntityType entityType = _entityTypes.get(type); - if(type != null) - { - if(Arrays.asList(entityType.getOperations()).contains(CREATE_OPERATION)) - { - Object messageBody = message.getMessageBody(); - if(messageBody instanceof Map) - { - try - { - - Class<? extends ConfiguredObject> clazz = - (Class<? extends ConfiguredObject>) Class.forName(type); - try - { - ConfiguredObject child = _managedObject.createChild(clazz, (Map) messageBody); - if(child == null) - { - child = _entities.get(entityType).get(message.getMessageHeader().getHeader(NAME_ATTRIBUTE)); - } - response = performReadOperation(message, child); - } - catch(AccessControlException e) - { - response = createFailureResponse(message, STATUS_CODE_FORBIDDEN, e.getMessage()); - } - } - catch (ClassNotFoundException e) - { - response = createFailureResponse(message, - STATUS_CODE_INTERNAL_ERROR, "Unable to instantiate an instance of {0} ", type); - } - } - else - { - response = createFailureResponse(message, - STATUS_CODE_BAD_REQUEST, - "The message body in the request was not of the correct type"); - } - } - else - { - response = createFailureResponse(message, - STATUS_CODE_FORBIDDEN, - "Cannot CREATE entities of type {0}", type); - } - } - else - { - response = createFailureResponse(message, - NOT_FOUND_STATUS_CODE, - "Unknown type {0}",type); - } - return response; - } - - private InternalMessage performOperation(final InternalMessage requestMessage, final ConfiguredObject entity) - { - String operation = (String) requestMessage.getMessageHeader().getHeader(OPERATION_HEADER); - - if(READ_OPERATION.equals(operation)) - { - return performReadOperation(requestMessage, entity); - } - else if(DELETE_OPERATION.equals(operation)) - { - return performDeleteOperation(requestMessage, entity); - } - else if(UPDATE_OPERATION.equals(operation)) - { - return performUpdateOperation(requestMessage, entity); - } - else - { - return createFailureResponse(requestMessage, NOT_IMPLEMENTED_STATUS_CODE, "Unable to perform the {0} operation",operation); - } - } - - private InternalMessage performReadOperation(final InternalMessage requestMessage, final ConfiguredObject entity) - { - final InternalMessageHeader requestHeader = requestMessage.getMessageHeader(); - final MutableMessageHeader responseHeader = new MutableMessageHeader(); - responseHeader.setCorrelationId(requestHeader.getCorrelationId() == null - ? requestHeader.getMessageId() - : requestHeader.getCorrelationId()); - responseHeader.setMessageId(UUID.randomUUID().toString()); - responseHeader.setHeader(NAME_ATTRIBUTE, entity.getName()); - responseHeader.setHeader(IDENTITY_ATTRIBUTE, entity.getId().toString()); - responseHeader.setHeader(STATUS_CODE_HEADER,STATUS_CODE_OK); - final String type = getManagementClass(entity.getClass()).getName(); - responseHeader.setHeader(TYPE_ATTRIBUTE, type); - - Map<String,Object> responseBody = new LinkedHashMap<String, Object>(); - final ManagedEntityType entityType = _entityTypes.get(type); - for(String attribute : entityType.getAttributes()) - { - responseBody.put(attribute, fixValue(entity.getAttribute(attribute))); - } - - return InternalMessage.createMapMessage(_virtualHost.getMessageStore(),responseHeader, responseBody); - } - - - private InternalMessage performDeleteOperation(final InternalMessage requestMessage, final ConfiguredObject entity) - { - final InternalMessageHeader requestHeader = requestMessage.getMessageHeader(); - final MutableMessageHeader responseHeader = new MutableMessageHeader(); - responseHeader.setCorrelationId(requestHeader.getCorrelationId() == null - ? requestHeader.getMessageId() - : requestHeader.getCorrelationId()); - responseHeader.setMessageId(UUID.randomUUID().toString()); - responseHeader.setHeader(NAME_ATTRIBUTE, entity.getName()); - responseHeader.setHeader(IDENTITY_ATTRIBUTE, entity.getId().toString()); - final String type = getManagementClass(entity.getClass()).getName(); - responseHeader.setHeader(TYPE_ATTRIBUTE, type); - try - { - entity.delete(); - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_NO_CONTENT); - } - catch(AccessControlException e) - { - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_FORBIDDEN); - } - - return InternalMessage.createMapMessage(_virtualHost.getMessageStore(),responseHeader, Collections.emptyMap()); - } - - - private InternalMessage performUpdateOperation(final InternalMessage requestMessage, final ConfiguredObject entity) - { - final InternalMessageHeader requestHeader = requestMessage.getMessageHeader(); - final MutableMessageHeader responseHeader = new MutableMessageHeader(); - responseHeader.setCorrelationId(requestHeader.getCorrelationId() == null - ? requestHeader.getMessageId() - : requestHeader.getCorrelationId()); - responseHeader.setMessageId(UUID.randomUUID().toString()); - responseHeader.setHeader(NAME_ATTRIBUTE, entity.getName()); - responseHeader.setHeader(IDENTITY_ATTRIBUTE, entity.getId().toString()); - final String type = getManagementClass(entity.getClass()).getName(); - responseHeader.setHeader(TYPE_ATTRIBUTE, type); - - Object messageBody = requestMessage.getMessageBody(); - if(messageBody instanceof Map) - { - try - { - entity.setAttributes((Map)messageBody); - return performReadOperation(requestMessage, entity); - } - catch(AccessControlException e) - { - return createFailureResponse(requestMessage, STATUS_CODE_FORBIDDEN, e.getMessage()); - } - } - else - { - return createFailureResponse(requestMessage, - STATUS_CODE_BAD_REQUEST, - "The message body in the request was not of the correct type"); - } - - - } - - private ConfiguredObject findSubject(final String name, final String id, final String type) - { - ConfiguredObject subject; - ManagedEntityType met = _entityTypes.get(type); - if(met == null) - { - return null; - } - - subject = findSubject(name, id, met); - if(subject == null) - { - ArrayList<ManagedEntityType> allTypes = new ArrayList<ManagedEntityType>(_entityTypes.values()); - for(ManagedEntityType entityType : allTypes) - { - if(Arrays.asList(entityType.getParents()).contains(met)) - { - subject = findSubject(name, id, entityType); - if(subject != null) - { - return subject; - } - } - } - } - return subject; - } - - private ConfiguredObject findSubject(final String name, final String id, final ManagedEntityType entityType) - { - - Map<String, ConfiguredObject> objects = _entities.get(entityType); - if(name != null) - { - ConfiguredObject subject = objects.get(name); - if(subject != null) - { - return subject; - } - } - else - { - final Collection<ConfiguredObject> values = new ArrayList<ConfiguredObject>(objects.values()); - for(ConfiguredObject o : values) - { - if(o.getId().toString().equals(id)) - { - return o; - } - } - } - return null; - } - - private InternalMessage createFailureResponse(final InternalMessage requestMessage, - final int statusCode, - final String stateDescription, - String... params) - { - final InternalMessageHeader requestHeader = requestMessage.getMessageHeader(); - final MutableMessageHeader responseHeader = new MutableMessageHeader(); - responseHeader.setCorrelationId(requestHeader.getCorrelationId() == null - ? requestHeader.getMessageId() - : requestHeader.getCorrelationId()); - responseHeader.setMessageId(UUID.randomUUID().toString()); - for(String header : requestHeader.getHeaderNames()) - { - responseHeader.setHeader(header, requestHeader.getHeader(header)); - } - responseHeader.setHeader(STATUS_CODE_HEADER, statusCode); - responseHeader.setHeader(STATUS_DESCRIPTION_HEADER, MessageFormat.format(stateDescription, params)); - return InternalMessage.createBytesMessage(_virtualHost.getMessageStore(), responseHeader, new byte[0]); - - } - - private InternalMessage performManagementOperation(final InternalMessage msg) - { - final InternalMessage responseMessage; - final InternalMessageHeader requestHeader = msg.getMessageHeader(); - final MutableMessageHeader responseHeader = new MutableMessageHeader(); - responseHeader.setCorrelationId(requestHeader.getCorrelationId() == null - ? requestHeader.getMessageId() - : requestHeader.getCorrelationId()); - responseHeader.setMessageId(UUID.randomUUID().toString()); - - - String operation = (String) requestHeader.getHeader(OPERATION_HEADER); - if(GET_TYPES.equals(operation)) - { - responseMessage = performGetTypes(requestHeader, responseHeader); - } - else if(GET_ATTRIBUTES.equals(operation)) - { - responseMessage = performGetAttributes(requestHeader, responseHeader); - } - else if(GET_OPERATIONS.equals(operation)) - { - responseMessage = performGetOperations(requestHeader, responseHeader); - } - else if(QUERY.equals(operation)) - { - responseMessage = performQuery(requestHeader, msg.getMessageBody(), responseHeader); - } - else - { - responseMessage = InternalMessage.createBytesMessage(_virtualHost.getMessageStore(), requestHeader, new byte[0]); - } - return responseMessage; - } - - private InternalMessage performGetTypes(final InternalMessageHeader requestHeader, - final MutableMessageHeader responseHeader) - { - final InternalMessage responseMessage; - List<String> restriction; - if(requestHeader.containsHeader(ENTITY_TYPE_HEADER)) - { - restriction = new ArrayList<String>(Collections.singletonList( (String)requestHeader.getHeader(ENTITY_TYPE_HEADER))); - } - else - { - restriction = null; - } - - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_OK); - Map<String,Object> responseMap = new LinkedHashMap<String, Object>(); - Map<String,ManagedEntityType> entityMapCopy; - synchronized (_entityTypes) - { - entityMapCopy = new LinkedHashMap<String, ManagedEntityType>(_entityTypes); - } - - for(ManagedEntityType type : entityMapCopy.values()) - { - if(restriction == null || meetsIndirectRestriction(type,restriction)) - { - final ManagedEntityType[] parents = type.getParents(); - List<String> parentNames = new ArrayList<String>(); - if(parents != null) - { - for(ManagedEntityType parent : parents) - { - parentNames.add(parent.getName()); - } - } - responseMap.put(type.getName(), parentNames); - } - } - responseMessage = InternalMessage.createMapMessage(_virtualHost.getMessageStore(), responseHeader, responseMap); - return responseMessage; - } - - private InternalMessage performGetAttributes(final InternalMessageHeader requestHeader, - final MutableMessageHeader responseHeader) - { - final InternalMessage responseMessage; - String restriction; - if(requestHeader.containsHeader(ENTITY_TYPE_HEADER)) - { - restriction = (String) requestHeader.getHeader(ENTITY_TYPE_HEADER); - } - else - { - restriction = null; - } - - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_OK); - Map<String,Object> responseMap = new LinkedHashMap<String, Object>(); - Map<String,ManagedEntityType> entityMapCopy; - synchronized (_entityTypes) - { - entityMapCopy = new LinkedHashMap<String, ManagedEntityType>(_entityTypes); - } - - if(restriction == null) - { - for(ManagedEntityType type : entityMapCopy.values()) - { - responseMap.put(type.getName(), Arrays.asList(type.getAttributes())); - } - } - else if(entityMapCopy.containsKey(restriction)) - { - responseMap.put(restriction, Arrays.asList(entityMapCopy.get(restriction).getAttributes())); - } - - responseMessage = InternalMessage.createMapMessage(_virtualHost.getMessageStore(), responseHeader, responseMap); - return responseMessage; - } - - - private InternalMessage performGetOperations(final InternalMessageHeader requestHeader, - final MutableMessageHeader responseHeader) - { - final InternalMessage responseMessage; - String restriction; - if(requestHeader.containsHeader(ENTITY_TYPE_HEADER)) - { - restriction = (String) requestHeader.getHeader(ENTITY_TYPE_HEADER); - } - else - { - restriction = null; - } - - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_OK); - Map<String,Object> responseMap = new LinkedHashMap<String, Object>(); - Map<String,ManagedEntityType> entityMapCopy; - synchronized (_entityTypes) - { - entityMapCopy = new LinkedHashMap<String, ManagedEntityType>(_entityTypes); - } - - if(restriction == null) - { - for(ManagedEntityType type : entityMapCopy.values()) - { - responseMap.put(type.getName(), Arrays.asList(type.getOperations())); - } - } - else if(entityMapCopy.containsKey(restriction)) - { - ManagedEntityType type = entityMapCopy.get(restriction); - responseMap.put(type.getName(), Arrays.asList(type.getOperations())); - } - responseMessage = InternalMessage.createMapMessage(_virtualHost.getMessageStore(), responseHeader, responseMap); - return responseMessage; - } - - private InternalMessage performQuery(final InternalMessageHeader requestHeader, - final Object messageBody, final MutableMessageHeader responseHeader) - { - final InternalMessage responseMessage; - List<String> restriction; - List<String> attributes; - int offset; - int count; - - if(requestHeader.containsHeader(ENTITY_TYPE_HEADER)) - { - restriction = new ArrayList<String>(Collections.singletonList((String) requestHeader.getHeader( - ENTITY_TYPE_HEADER))); - responseHeader.setHeader(ENTITY_TYPE_HEADER, restriction); - } - else - { - restriction = new ArrayList<String>(_entityTypes.keySet()); - } - - - if(messageBody instanceof Map && ((Map)messageBody).get(ATTRIBUTE_NAMES) instanceof List) - { - attributes = (List<String>) ((Map)messageBody).get(ATTRIBUTE_NAMES); - } - else - { - LinkedHashMap<String,Void> attributeSet = new LinkedHashMap<String, Void>(); - for(String entityType : restriction) - { - ManagedEntityType type = _entityTypes.get(entityType); - if(type != null) - { - for(String attributeName : type.getAttributes()) - { - attributeSet.put(attributeName, null); - } - } - } - attributes = new ArrayList<String>(attributeSet.keySet()); - - } - - if(requestHeader.containsHeader(OFFSET_HEADER)) - { - offset = ((Number) requestHeader.getHeader(OFFSET_HEADER)).intValue(); - responseHeader.setHeader(OFFSET_HEADER,offset); - } - else - { - offset = 0; - } - - if(requestHeader.containsHeader(COUNT_HEADER)) - { - count = ((Number) requestHeader.getHeader(COUNT_HEADER)).intValue(); - } - else - { - count = Integer.MAX_VALUE; - } - - - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_OK); - List<List<? extends Object>> responseList = new ArrayList<List<? extends Object>>(); - int rowNo = 0; - for(String type : restriction) - { - ManagedEntityType entityType = _entityTypes.get(type); - if(entityType != null) - { - Map<String, ConfiguredObject> entityMap = _entities.get(entityType); - if(entityMap != null) - { - List<ConfiguredObject> entities; - synchronized(entityMap) - { - entities = new ArrayList<ConfiguredObject>(entityMap.values()); - } - for(ConfiguredObject entity : entities) - { - if(rowNo++ >= offset) - { - Object[] attrValue = new Object[attributes.size()]; - int col = 0; - for(String attr : attributes) - { - Object value; - if(TYPE_ATTRIBUTE.equals(attr)) - { - value = entityType.getName(); - } - else - { - value = fixValue(entity.getAttribute(attr)); - } - attrValue[col++] = value; - } - responseList.add(Arrays.asList(attrValue)); - } - if(responseList.size()==count+1) - { - break; - } - } - } - } - - if(responseList.size()==count) - { - break; - } - } - responseHeader.setHeader(COUNT_HEADER, responseList.size()); - Map<String,List> responseMap = new HashMap<String, List>(); - responseMap.put(ATTRIBUTE_NAMES, attributes); - responseMap.put(RESULTS, responseList); - responseMessage = InternalMessage.createMapMessage(_virtualHost.getMessageStore(), - responseHeader, - responseMap); - return responseMessage; - } - - private Object fixValue(final Object value) - { - Object fixedValue; - if(value instanceof Enum) - { - fixedValue = value.toString(); - } - else if(value instanceof Map) - { - Map<Object, Object> oldValue = (Map<Object, Object>) value; - Map<Object, Object> newValue = new LinkedHashMap<Object, Object>(); - for(Map.Entry<Object, Object> entry : oldValue.entrySet()) - { - newValue.put(fixValue(entry.getKey()),fixValue(entry.getValue())); - } - fixedValue = newValue; - } - else if(value instanceof Collection) - { - Collection oldValue = (Collection) value; - List newValue = new ArrayList(oldValue.size()); - for(Object o : oldValue) - { - newValue.add(fixValue(o)); - } - fixedValue = newValue; - } - else if(value != null && value.getClass().isArray() && !(value instanceof byte[])) - { - fixedValue = fixValue(Arrays.asList((Object[])value)); - } - else - { - fixedValue = value; - } - return fixedValue; - - } - - - private boolean meetsIndirectRestriction(final ManagedEntityType type, final List<String> restriction) - { - if(restriction.contains(type.getName())) - { - return true; - } - if(type.getParents() != null) - { - for(ManagedEntityType parent : type.getParents()) - { - if(meetsIndirectRestriction(parent, restriction)) - { - return true; - } - } - } - return false; - } - - @Override - public synchronized ManagementNodeConsumer addConsumer(final ConsumerTarget target, - final FilterManager filters, - final Class<? extends ServerMessage> messageClass, - final String consumerName, - final EnumSet<ConsumerImpl.Option> options) - { - - final ManagementNodeConsumer managementNodeConsumer = new ManagementNodeConsumer(consumerName,this, target); - target.consumerAdded(managementNodeConsumer); - _consumers.put(consumerName, managementNodeConsumer); - for(ConsumerRegistrationListener<? super MessageSource> listener : _consumerRegistrationListeners) - { - listener.consumerAdded(this, managementNodeConsumer); - } - return managementNodeConsumer; - } - - @Override - public synchronized Collection<ManagementNodeConsumer> getConsumers() - { - return new ArrayList<ManagementNodeConsumer>(_consumers.values()); - } - - @Override - public void addConsumerRegistrationListener(final ConsumerRegistrationListener<? super MessageSource> listener) - { - _consumerRegistrationListeners.add(listener); - } - - @Override - public void removeConsumerRegistrationListener(final ConsumerRegistrationListener listener) - { - _consumerRegistrationListeners.remove(listener); - } - - @Override - public boolean verifySessionAccess(final AMQSessionModel<?, ?> session) - { - return true; - } - - @Override - public String getName() - { - return MANAGEMENT_NODE_NAME; - } - - @Override - public UUID getId() - { - return _id; - } - - @Override - public MessageDurability getMessageDurability() - { - return MessageDurability.NEVER; - } - - private class ConsumedMessageInstance implements MessageInstance - { - private final ServerMessage _message; - private final InstanceProperties _properties; - - public ConsumedMessageInstance(final ServerMessage message, - final InstanceProperties properties) - { - _message = message; - _properties = properties; - } - - @Override - public int getDeliveryCount() - { - return 0; - } - - @Override - public void incrementDeliveryCount() - { - - } - - @Override - public void decrementDeliveryCount() - { - - } - - @Override - public void addStateChangeListener(final StateChangeListener<? super MessageInstance, State> listener) - { - - } - - @Override - public boolean removeStateChangeListener(final StateChangeListener<? super MessageInstance, State> listener) - { - return false; - } - - - @Override - public boolean acquiredByConsumer() - { - return false; - } - - @Override - public ConsumerImpl getAcquiringConsumer() - { - return null; - } - - @Override - public MessageEnqueueRecord getEnqueueRecord() - { - return null; - } - - @Override - public boolean isAcquiredBy(final ConsumerImpl consumer) - { - return false; - } - - @Override - public boolean removeAcquisitionFromConsumer(final ConsumerImpl consumer) - { - return false; - } - - @Override - public void setRedelivered() - { - - } - - @Override - public boolean isRedelivered() - { - return false; - } - - @Override - public ConsumerImpl getDeliveredConsumer() - { - return null; - } - - @Override - public void reject() - { - - } - - @Override - public boolean isRejectedBy(final ConsumerImpl consumer) - { - return false; - } - - @Override - public boolean getDeliveredToConsumer() - { - return true; - } - - @Override - public boolean expired() - { - return false; - } - - @Override - public boolean acquire(final ConsumerImpl sub) - { - return false; - } - - @Override - public boolean lockAcquisition() - { - return false; - } - - @Override - public boolean unlockAcquisition() - { - return false; - } - - @Override - public int getMaximumDeliveryCount() - { - return 0; - } - - @Override - public int routeToAlternate(final Action<? super MessageInstance> action, - final ServerTransaction txn) - { - return 0; - } - - - @Override - public Filterable asFilterable() - { - return null; - } - - @Override - public boolean isAvailable() - { - return false; - } - - @Override - public boolean acquire() - { - return false; - } - - @Override - public boolean isAcquired() - { - return false; - } - - @Override - public void release() - { - - } - - @Override - public boolean resend() - { - return false; - } - - @Override - public void delete() - { - - } - - @Override - public boolean isDeleted() - { - return false; - } - - @Override - public ServerMessage getMessage() - { - return _message; - } - - @Override - public InstanceProperties getInstanceProperties() - { - return _properties; - } - - @Override - public TransactionLogResource getOwningResource() - { - return ManagementNode.this; - } - } - - private class ModelObjectListener implements ConfigurationChangeListener - { - @Override - public void stateChanged(final ConfiguredObject object, final State oldState, final State newState) - { - if(newState == State.DELETED) - { - _registry.removeSystemNode(ManagementNode.this); - } - else if(newState == State.ACTIVE && object instanceof org.apache.qpid.server.model.VirtualHost) - { - populateTypeMetaData(object.getClass(), false); - final Class managementClass = getManagementClass(_managedObject.getClass()); - _entities.get(_entityTypes.get(managementClass.getName())).put(_managedObject.getName(), _managedObject); - - Collection<Class<? extends ConfiguredObject>> childClasses = object.getModel().getChildTypes(managementClass); - for(Class<? extends ConfiguredObject> childClass : childClasses) - { - if(getManagementClass(childClass) != null) - { - for(ConfiguredObject child : _managedObject.getChildren(childClass)) - { - _entities.get(_entityTypes.get(getManagementClass(childClass).getName())).put(child.getName(), child); - } - } - } - - } - } - - @Override - public void childAdded(final ConfiguredObject object, final ConfiguredObject child) - { - final Class managementClass = getManagementClass(child.getClass()); - final ManagedEntityType entityType = _entityTypes.get(managementClass.getName()); - if(entityType != null) - { - _entities.get(entityType).put(child.getName(), child); - } - } - - @Override - public void childRemoved(final ConfiguredObject object, final ConfiguredObject child) - { - final ManagedEntityType entityType = _entityTypes.get(getManagementClass(child.getClass()).getName()); - if(entityType != null) - { - _entities.get(entityType).remove(child.getName()); - } - } - - @Override - public void attributeSet(final ConfiguredObject object, - final String attributeName, - final Object oldAttributeValue, - final Object newAttributeValue) - { - - } - } - - private static class MutableMessageHeader implements AMQMessageHeader - { - private final LinkedHashMap<String, Object> _headers = new LinkedHashMap<String, Object>(); - private String _correlationId; - private long _expiration; - private String _userId; - private String _appId; - private String _messageId; - private String _mimeType; - private String _encoding; - private byte _priority; - private long _timestamp; - private String _type; - private String _replyTo; - - public void setCorrelationId(final String correlationId) - { - _correlationId = correlationId; - } - - public void setExpiration(final long expiration) - { - _expiration = expiration; - } - - public void setUserId(final String userId) - { - _userId = userId; - } - - public void setAppId(final String appId) - { - _appId = appId; - } - - public void setMessageId(final String messageId) - { - _messageId = messageId; - } - - public void setMimeType(final String mimeType) - { - _mimeType = mimeType; - } - - public void setEncoding(final String encoding) - { - _encoding = encoding; - } - - public void setPriority(final byte priority) - { - _priority = priority; - } - - public void setTimestamp(final long timestamp) - { - _timestamp = timestamp; - } - - public void setType(final String type) - { - _type = type; - } - - public void setReplyTo(final String replyTo) - { - _replyTo = replyTo; - } - - public String getCorrelationId() - { - return _correlationId; - } - - public long getExpiration() - { - return _expiration; - } - - public String getUserId() - { - return _userId; - } - - public String getAppId() - { - return _appId; - } - - public String getMessageId() - { - return _messageId; - } - - public String getMimeType() - { - return _mimeType; - } - - public String getEncoding() - { - return _encoding; - } - - public byte getPriority() - { - return _priority; - } - - public long getTimestamp() - { - return _timestamp; - } - - public String getType() - { - return _type; - } - - public String getReplyTo() - { - return _replyTo; - } - - @Override - public Object getHeader(final String name) - { - return _headers.get(name); - } - - @Override - public boolean containsHeaders(final Set<String> names) - { - return _headers.keySet().containsAll(names); - } - - @Override - public boolean containsHeader(final String name) - { - return _headers.containsKey(name); - } - - @Override - public Collection<String> getHeaderNames() - { - return Collections.unmodifiableCollection(_headers.keySet()); - } - - public void setHeader(String header, Object value) - { - _headers.put(header,value); - } - - } -} diff --git a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeConsumer.java b/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeConsumer.java deleted file mode 100644 index 28d8a6c88c..0000000000 --- a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeConsumer.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.amqp; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.consumer.ConsumerTarget; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.util.StateChangeListener; - -class ManagementNodeConsumer implements ConsumerImpl -{ - private final long _id = ConsumerImpl.CONSUMER_NUMBER_GENERATOR.getAndIncrement(); - private final ManagementNode _managementNode; - private final List<ManagementResponse> _queue = Collections.synchronizedList(new ArrayList<ManagementResponse>()); - private final ConsumerTarget _target; - private final String _name; - private final StateChangeListener<ConsumerTarget, ConsumerTarget.State> _targetChangeListener = new TargetChangeListener(); - - - public ManagementNodeConsumer(final String consumerName, final ManagementNode managementNode, ConsumerTarget target) - { - _name = consumerName; - _managementNode = managementNode; - _target = target; - target.addStateListener(_targetChangeListener); - } - - @Override - public void externalStateChange() - { - - } - - @Override - public long getBytesOut() - { - return 0; - } - - @Override - public long getMessagesOut() - { - return 0; - } - - @Override - public long getUnacknowledgedBytes() - { - return 0; - } - - @Override - public long getUnacknowledgedMessages() - { - return 0; - } - - @Override - public AMQSessionModel getSessionModel() - { - return _target.getSessionModel(); - } - - @Override - public MessageSource getMessageSource() - { - return _managementNode; - } - - @Override - public long getConsumerNumber() - { - return _id; - } - - @Override - public boolean isSuspended() - { - return false; - } - - @Override - public boolean isClosed() - { - return false; - } - - @Override - public boolean acquires() - { - return true; - } - - @Override - public boolean seesRequeues() - { - return false; - } - - @Override - public void close() - { - } - - @Override - public boolean trySendLock() - { - return _target.trySendLock(); - } - - @Override - public void getSendLock() - { - _target.getSendLock(); - } - - @Override - public void releaseSendLock() - { - _target.releaseSendLock(); - } - - - @Override - public boolean isActive() - { - return false; - } - - @Override - public String getName() - { - return _name; - } - - @Override - public void flush() - { - - } - - @Override - public ConsumerTarget getTarget() - { - return _target; - } - - ManagementNode getManagementNode() - { - return _managementNode; - } - - void send(final InternalMessage response) - { - _target.getSendLock(); - try - { - final ManagementResponse responseEntry = new ManagementResponse(this, response); - if(_queue.isEmpty() && _target.allocateCredit(response)) - { - _target.send(this, responseEntry, false); - } - else - { - _queue.add(responseEntry); - } - } - finally - { - _target.releaseSendLock(); - } - } - - private class TargetChangeListener implements StateChangeListener<ConsumerTarget, ConsumerTarget.State> - { - @Override - public void stateChanged(final ConsumerTarget object, - final ConsumerTarget.State oldState, - final ConsumerTarget.State newState) - { - if(newState == ConsumerTarget.State.ACTIVE) - { - deliverMessages(); - } - } - } - - private void deliverMessages() - { - _target.getSendLock(); - try - { - while(!_queue.isEmpty()) - { - - final ManagementResponse managementResponse = _queue.get(0); - if(!_target.isSuspended() && _target.allocateCredit(managementResponse.getMessage())) - { - _queue.remove(0); - _target.send(this, managementResponse, false); - } - else - { - break; - } - } - } - finally - { - _target.releaseSendLock(); - } - } -} diff --git a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeCreator.java b/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeCreator.java deleted file mode 100644 index e977c027a1..0000000000 --- a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeCreator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.amqp; - -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.SystemNodeCreator; - -@PluggableService -public class ManagementNodeCreator implements SystemNodeCreator -{ - @Override - public void register(final SystemNodeRegistry registry) - { - ManagementNode managementNode = new ManagementNode(registry,registry.getVirtualHost()); - registry.registerSystemNode(managementNode); - } - - @Override - public String getType() - { - return "AMQP-VIRTUALHOST-MANAGEMENT"; - } -} diff --git a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementResponse.java b/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementResponse.java deleted file mode 100644 index dd5b7540a7..0000000000 --- a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementResponse.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.amqp; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.filter.Filterable; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.store.MessageEnqueueRecord; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.StateChangeListener; - -class ManagementResponse implements MessageInstance -{ - private final ManagementNodeConsumer _consumer; - private int _deliveryCount; - private boolean _isRedelivered; - private boolean _isDelivered; - private boolean _isDeleted; - private InternalMessage _message; - - ManagementResponse(final ManagementNodeConsumer consumer, final InternalMessage message) - { - _consumer = consumer; - _message = message; - } - - @Override - public int getDeliveryCount() - { - return 0; - } - - @Override - public void incrementDeliveryCount() - { - _deliveryCount++; - } - - @Override - public void decrementDeliveryCount() - { - _deliveryCount--; - } - - @Override - public void addStateChangeListener(final StateChangeListener<? super MessageInstance, State> listener) - { - - } - - @Override - public boolean removeStateChangeListener(final StateChangeListener<? super MessageInstance, State> listener) - { - return false; - } - - - @Override - public boolean acquiredByConsumer() - { - return !isDeleted(); - } - - @Override - public ConsumerImpl getAcquiringConsumer() - { - return _consumer; - } - - @Override - public MessageEnqueueRecord getEnqueueRecord() - { - return null; - } - - @Override - public boolean isAcquiredBy(final ConsumerImpl consumer) - { - return consumer == _consumer && !isDeleted(); - } - - @Override - public boolean removeAcquisitionFromConsumer(final ConsumerImpl consumer) - { - return consumer == _consumer; - } - - @Override - public void setRedelivered() - { - _isRedelivered = true; - } - - @Override - public boolean isRedelivered() - { - return _isRedelivered; - } - - @Override - public ManagementNodeConsumer getDeliveredConsumer() - { - return isDeleted() ? null : _consumer; - } - - @Override - public void reject() - { - delete(); - } - - @Override - public boolean isRejectedBy(final ConsumerImpl consumer) - { - return false; - } - - @Override - public boolean getDeliveredToConsumer() - { - return _isDelivered; - } - - @Override - public boolean expired() - { - return false; - } - - @Override - public boolean acquire(final ConsumerImpl sub) - { - return false; - } - - @Override - public boolean lockAcquisition() - { - return false; - } - - @Override - public boolean unlockAcquisition() - { - return false; - } - - @Override - public int getMaximumDeliveryCount() - { - return 0; - } - - @Override - public int routeToAlternate(final Action<? super MessageInstance> action, - final ServerTransaction txn) - { - return 0; - } - - - @Override - public Filterable asFilterable() - { - return null; - } - - @Override - public boolean isAvailable() - { - return false; - } - - @Override - public boolean acquire() - { - return false; - } - - @Override - public boolean isAcquired() - { - return !isDeleted(); - } - - @Override - public void release() - { - delete(); - } - - @Override - public boolean resend() - { - return false; - } - - @Override - public void delete() - { - _isDeleted = true; - } - - @Override - public boolean isDeleted() - { - return _isDeleted; - } - - @Override - public ServerMessage getMessage() - { - return _message; - } - - @Override - public InstanceProperties getInstanceProperties() - { - return InstanceProperties.EMPTY; - } - - @Override - public TransactionLogResource getOwningResource() - { - return _consumer.getManagementNode(); - } -} diff --git a/qpid/java/broker-plugins/management-http/pom.xml b/qpid/java/broker-plugins/management-http/pom.xml deleted file mode 100644 index 50ff3e20f3..0000000000 --- a/qpid/java/broker-plugins/management-http/pom.xml +++ /dev/null @@ -1,140 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-management-http</artifactId> - <name>Qpid HTTP Management Broker Plug-in</name> - <description>HTTP Management broker plug-in</description> - - <properties> - <dojo-version>1.10.3</dojo-version> - </properties> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <version>${log4j-version}</version> - </dependency> - - <dependency> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-api</artifactId> - <version>${slf4j-version}</version> - </dependency> - - <dependency> - <groupId>org.apache.geronimo.specs</groupId> - <artifactId>geronimo-servlet_3.0_spec</artifactId> - <version>${geronimo-servlet-version}</version> - </dependency> - - <dependency> - <groupId>org.eclipse.jetty</groupId> - <artifactId>jetty-server</artifactId> - <version>${jetty-version}</version> - <exclusions> - <exclusion> - <groupId>org.eclipse.jetty.orbit</groupId> - <artifactId>javax.servlet</artifactId> - </exclusion> - </exclusions> - </dependency> - - <dependency> - <groupId>org.eclipse.jetty</groupId> - <artifactId>jetty-servlet</artifactId> - <version>${jetty-version}</version> - </dependency> - - <dependency> - <groupId>org.dojotoolkit</groupId> - <artifactId>dojo</artifactId> - <version>${dojo-version}</version> - <classifier>distribution</classifier> - <type>zip</type> - </dependency> - - <!-- test dependencies --> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-test-utils</artifactId> - <version>${project.version}</version> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <resources> - <resource> - <directory>src/main/resources</directory> - </resource> - <resource> - <directory>src/main/java</directory> - <includes> - <include>resources/</include> - </includes> - </resource> - <resource> - <directory>src/main/resources-maven</directory> - <filtering>true</filtering> - </resource> - </resources> - - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-jar-plugin</artifactId> - <!--version specified in parent pluginManagement --> - <configuration> - <archive> - <!-- add the dojo zip to the manifest Class-Path so that - it gets picked up when using classpath wildcard - expansion, which only collects .jar files --> - <manifestEntries> - <Class-Path>dojo-${dojo-version}-distribution.zip</Class-Path> - </manifestEntries> - </archive> - </configuration> - </plugin> - </plugins> - </build> - -</project> diff --git a/qpid/java/broker-plugins/management-http/src/main/appended-resources/META-INF/LICENSE.vm b/qpid/java/broker-plugins/management-http/src/main/appended-resources/META-INF/LICENSE.vm deleted file mode 100644 index 7a7430e2e3..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/appended-resources/META-INF/LICENSE.vm +++ /dev/null @@ -1,33 +0,0 @@ - - -#============================================== -# Third Party Dependency Licensing Information: -#============================================== - -resources/js/crypto-js/ - -This bundles portions of crypto-js, which is under the MIT licence: - - -Copyright (c) 2009-2013 Jeff Mott - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -#=============================================== diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/DojoHelper.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/DojoHelper.java deleted file mode 100644 index 31a777d0bb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/DojoHelper.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.management.plugin; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.Properties; - -public class DojoHelper -{ - private static final Logger _logger = LoggerFactory.getLogger(DojoHelper.class); - - public static final String VERSION_FILE = "dojoconfig.properties"; - public static final String DOJO_VERSION_PROPERTY = "dojo-version"; - public static final String DOJO_PATH_PROPERTY = "dojo-path"; - public static final String DIJIT_PATH_PROPERTY = "dijit-path"; - public static final String DOJOX_PATH_PROPERTY = "dojox-path"; - - private static String _version = "undefined"; - private static String _dojoPath = "/dojo-undefined/dojo"; - private static String _dijitPath = "/dojo-undefined/dijit"; - private static String _dojoxPath = "/dojo-undefined/dojox"; - - // Loads the value from the properties file. - static - { - Properties props = new Properties(); - - try - { - InputStream propertyStream = DojoHelper.class.getClassLoader().getResourceAsStream(VERSION_FILE); - if (propertyStream == null) - { - _logger.warn("Unable to find resource " + VERSION_FILE + " from classloader"); - } - else - { - try - { - props.load(propertyStream); - } - finally - { - try - { - propertyStream.close(); - } - catch (IOException e) - { - _logger.warn("Exception closing InputStream for " + VERSION_FILE + " resource:", e); - } - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Dumping Dojo Config:"); - for (Map.Entry<Object, Object> entry : props.entrySet()) - { - _logger.debug("Property: " + entry.getKey() + " Value: " + entry.getValue()); - } - - _logger.debug("End of property dump"); - } - - _version = props.getProperty(DOJO_VERSION_PROPERTY, _version); - _dojoPath = props.getProperty(DOJO_PATH_PROPERTY, _dojoPath); - _dijitPath = props.getProperty(DIJIT_PATH_PROPERTY, _dijitPath); - _dojoxPath = props.getProperty(DOJOX_PATH_PROPERTY, _dojoxPath); - } - } - catch (IOException e) - { - // Log a warning about this and leave the values initialized to unknown. - _logger.error("Exception loading " + VERSION_FILE + " resource:", e); - } - } - - public static String getDojoVersion() - { - return _version; - } - - public static String getDojoPath() - { - return _dojoPath; - } - - public static String getDijitPath() - { - return _dijitPath; - } - - public static String getDojoxPath() - { - return _dojoxPath; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java deleted file mode 100644 index fbe9f068b9..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java +++ /dev/null @@ -1,613 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin; - -import java.io.IOException; -import java.io.Writer; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import javax.servlet.DispatcherType; -import javax.servlet.MultipartConfigElement; -import javax.servlet.http.HttpServletRequest; - -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import org.eclipse.jetty.io.EndPoint; -import org.eclipse.jetty.server.Connector; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.SessionManager; -import org.eclipse.jetty.server.handler.ErrorHandler; -import org.eclipse.jetty.server.nio.SelectChannelConnector; -import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; -import org.eclipse.jetty.servlet.FilterHolder; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; -import org.apache.qpid.server.management.plugin.connector.TcpAndSslSelectChannelConnector; -import org.apache.qpid.server.management.plugin.filter.ForbiddingAuthorisationFilter; -import org.apache.qpid.server.management.plugin.filter.ForbiddingTraceFilter; -import org.apache.qpid.server.management.plugin.filter.RedirectingAuthorisationFilter; -import org.apache.qpid.server.management.plugin.servlet.DefinedFileServlet; -import org.apache.qpid.server.management.plugin.servlet.FileServlet; -import org.apache.qpid.server.management.plugin.servlet.LogFileServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.ApiDocsServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.HelperServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.LogFileListingServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.LogRecordsServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.LoggedOnUserPreferencesServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.LogoutServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.MessageContentServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.MessageServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.MetaDataServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.QueueReportServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.RestServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.SaslServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.StructureServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.UserPreferencesServlet; -import org.apache.qpid.server.model.*; -import org.apache.qpid.server.model.adapter.AbstractPluginAdapter; -import org.apache.qpid.server.model.port.HttpPort; -import org.apache.qpid.server.model.port.PortManager; -import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.transport.network.security.ssl.QpidMultipleTrustManager; -import org.apache.qpid.transport.network.security.ssl.SSLUtil; - -@ManagedObject( category = false, type = "MANAGEMENT-HTTP" ) -public class HttpManagement extends AbstractPluginAdapter<HttpManagement> implements HttpManagementConfiguration<HttpManagement>, PortManager -{ - private static final String PORT_SERVLET_ATTRIBUTE = "org.apache.qpid.server.model.Port"; - private final Logger _logger = LoggerFactory.getLogger(HttpManagement.class); - - // 10 minutes by default - public static final int DEFAULT_TIMEOUT_IN_SECONDS = 60 * 10; - public static final String TIME_OUT = "sessionTimeout"; - public static final String HTTP_BASIC_AUTHENTICATION_ENABLED = "httpBasicAuthenticationEnabled"; - public static final String HTTPS_BASIC_AUTHENTICATION_ENABLED = "httpsBasicAuthenticationEnabled"; - public static final String HTTP_SASL_AUTHENTICATION_ENABLED = "httpSaslAuthenticationEnabled"; - public static final String HTTPS_SASL_AUTHENTICATION_ENABLED = "httpsSaslAuthenticationEnabled"; - - public static final String PLUGIN_TYPE = "MANAGEMENT-HTTP"; - - private static final String OPERATIONAL_LOGGING_NAME = "Web"; - - private static final String JSESSIONID_COOKIE_PREFIX = "JSESSIONID_"; - - private Server _server; - - @ManagedAttributeField - private boolean _httpsSaslAuthenticationEnabled; - - @ManagedAttributeField - private boolean _httpSaslAuthenticationEnabled; - - @ManagedAttributeField - private boolean _httpsBasicAuthenticationEnabled; - - @ManagedAttributeField - private boolean _httpBasicAuthenticationEnabled; - - @ManagedAttributeField - private int _sessionTimeout; - - @ManagedAttributeField - private boolean _compressResponses; - - private boolean _allowPortActivation; - - @ManagedObjectFactoryConstructor - public HttpManagement(Map<String, Object> attributes, Broker broker) - { - super(attributes, broker); - } - - @StateTransition(currentState = {State.UNINITIALIZED,State.ERRORED}, desiredState = State.ACTIVE) - private ListenableFuture<Void> doStart() - { - getBroker().getEventLogger().message(ManagementConsoleMessages.STARTUP(OPERATIONAL_LOGGING_NAME)); - - Collection<Port<?>> httpPorts = getHttpPorts(getBroker().getPorts()); - _server = createServer(httpPorts); - try - { - _server.start(); - logOperationalListenMessages(httpPorts); - } - catch (Exception e) - { - throw new ServerScopedRuntimeException("Failed to start HTTP management on ports : " + httpPorts, e); - } - - getBroker().getEventLogger().message(ManagementConsoleMessages.READY(OPERATIONAL_LOGGING_NAME)); - setState(State.ACTIVE); - return Futures.immediateFuture(null); - } - - @Override - protected void onClose() - { - if (_server != null) - { - try - { - _server.stop(); - logOperationalShutdownMessage(_server); - } - catch (Exception e) - { - throw new ServerScopedRuntimeException("Failed to stop HTTP management on ports : " + getHttpPorts(getBroker().getPorts()), e); - } - } - - getBroker().getEventLogger().message(ManagementConsoleMessages.STOPPED(OPERATIONAL_LOGGING_NAME)); - } - - public int getSessionTimeout() - { - return _sessionTimeout; - } - - private Server createServer(Collection<Port<?>> ports) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Starting up web server on " + ports); - } - _allowPortActivation = true; - - Server server = new Server(); - - QueuedThreadPool threadPool = new QueuedThreadPool(); - threadPool.setName("HttpManagement"); - threadPool.setMaxQueued(getContextValue(Integer.class, JETTY_THREAD_POOL_MAX_QUEUED)); - threadPool.setMaxThreads(getContextValue(Integer.class, JETTY_THREAD_POOL_MAX_THREADS)); - threadPool.setMinThreads(getContextValue(Integer.class, JETTY_THREAD_POOL_MIN_THREADS)); - - server.setThreadPool(threadPool); - - int lastPort = -1; - for (Port<?> port : ports) - { - if(port instanceof HttpPort) - { - - if (!State.ACTIVE.equals(port.getDesiredState())) - { - continue; - } - ((HttpPort<?>)port).setPortManager(this); - - if(port.getState() != State.ACTIVE) - { - - // TODO - RG - probably does nothing - port.startAsync(); - } - Connector connector = null; - - Collection<Transport> transports = port.getTransports(); - if (!transports.contains(Transport.SSL)) - { - final Port thePort = port; - connector = new SelectChannelConnector() - { - @Override - public void customize(final EndPoint endpoint, final Request request) throws IOException - { - super.customize(endpoint, request); - request.setAttribute(PORT_SERVLET_ATTRIBUTE, thePort); - } - }; - } - else if (transports.contains(Transport.SSL)) - { - connector = createSslConnector((HttpPort<?>) port); - } - else - { - throw new IllegalArgumentException("Unexpected transport on port " - + port.getName() - + ":" - + transports); - } - lastPort = port.getPort(); - String bindingAddress = ((HttpPort)port).getBindingAddress(); - if (bindingAddress != null && !bindingAddress.trim().equals("") && !bindingAddress.trim().equals("*")) - { - connector.setHost(bindingAddress.trim()); - } - connector.setPort(port.getPort()); - server.addConnector(connector); - } - else - { - throw new IllegalArgumentException("Http management can only be added to an Http port"); - } - - } - - _allowPortActivation = false; - - ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS); - root.setContextPath("/"); - root.setCompactPath(true); - server.setHandler(root); - server.setSendServerVersion(false); - final ErrorHandler errorHandler = new ErrorHandler() - { - @Override - protected void writeErrorPageBody(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) - throws IOException - { - String uri= request.getRequestURI(); - - writeErrorPageMessage(request,writer,code,message,uri); - - for (int i= 0; i < 20; i++) - writer.write("<br/> \n"); - } - }; - root.setErrorHandler(errorHandler); - - // set servlet context attributes for broker and configuration - root.getServletContext().setAttribute(HttpManagementUtil.ATTR_BROKER, getBroker()); - root.getServletContext().setAttribute(HttpManagementUtil.ATTR_MANAGEMENT_CONFIGURATION, this); - - root.addFilter(new FilterHolder(new ForbiddingTraceFilter()), "/*", EnumSet.of(DispatcherType.REQUEST)); - FilterHolder restAuthorizationFilter = new FilterHolder(new ForbiddingAuthorisationFilter()); - restAuthorizationFilter.setInitParameter(ForbiddingAuthorisationFilter.INIT_PARAM_ALLOWED, "/service/sasl"); - root.addFilter(restAuthorizationFilter, "/api/*", EnumSet.of(DispatcherType.REQUEST)); - root.addFilter(restAuthorizationFilter, "/apidocs/*", EnumSet.of(DispatcherType.REQUEST)); - root.addFilter(restAuthorizationFilter, "/service/*", EnumSet.of(DispatcherType.REQUEST)); - root.addFilter(new FilterHolder(new RedirectingAuthorisationFilter()), HttpManagementUtil.ENTRY_POINT_PATH, EnumSet.of(DispatcherType.REQUEST)); - root.addFilter(new FilterHolder(new RedirectingAuthorisationFilter()), "/index.html", EnumSet.of(DispatcherType.REQUEST)); - root.addFilter(new FilterHolder(new RedirectingAuthorisationFilter()), "/", EnumSet.of(DispatcherType.REQUEST)); - - addRestServlet(root, "broker"); - addRestServlet(root, "virtualhostnode", VirtualHostNode.class); - addRestServlet(root, "authenticationprovider", AuthenticationProvider.class); - addRestServlet(root, "accesscontrolprovider", AccessControlProvider.class); - addRestServlet(root, "user", AuthenticationProvider.class, User.class); - addRestServlet(root, "groupprovider", GroupProvider.class); - addRestServlet(root, "group", GroupProvider.class, Group.class); - addRestServlet(root, "groupmember", GroupProvider.class, Group.class, GroupMember.class); - addRestServlet(root, "port", Port.class); - addRestServlet(root, "keystore", KeyStore.class); - addRestServlet(root, "truststore", TrustStore.class); - addRestServlet(root, "plugin", Plugin.class); - addRestServlet(root, "preferencesprovider", AuthenticationProvider.class, PreferencesProvider.class); - - addRestServlet(root, "replicationnode", VirtualHostNode.class, RemoteReplicationNode.class); - - addRestServlet(root, "virtualhost", VirtualHostNode.class, VirtualHost.class); - addRestServlet(root, "exchange", VirtualHostNode.class, VirtualHost.class, Exchange.class); - addRestServlet(root, "queue", VirtualHostNode.class, VirtualHost.class, Queue.class); - addRestServlet(root, "connection", VirtualHostNode.class, VirtualHost.class, Connection.class); - addRestServlet(root, "binding", VirtualHostNode.class, VirtualHost.class, Exchange.class, Queue.class, Binding.class); - addRestServlet(root, "session", VirtualHostNode.class, VirtualHost.class, Connection.class, Session.class); - - ServletHolder apiDocsServlet = new ServletHolder(new ApiDocsServlet(getModel(), Collections.<String>emptyList())); - root.addServlet(apiDocsServlet, "/apidocs"); - root.addServlet(apiDocsServlet, "/apidocs/"); - root.addServlet(apiDocsServlet, "/apidocs/latest"); - root.addServlet(apiDocsServlet, "/apidocs/latest/"); - root.addServlet(new ServletHolder(new UserPreferencesServlet()), "/service/userpreferences/*"); - root.addServlet(new ServletHolder(new LoggedOnUserPreferencesServlet()), "/service/preferences"); - root.addServlet(new ServletHolder(new StructureServlet()), "/service/structure"); - root.addServlet(new ServletHolder(new MessageServlet()), "/service/message/*"); - root.addServlet(new ServletHolder(new MessageContentServlet()), "/service/message-content/*"); - root.addServlet(new ServletHolder(new QueueReportServlet()), "/service/queuereport/*"); - - - root.addServlet(new ServletHolder(new LogRecordsServlet()), "/service/logrecords"); - - root.addServlet(new ServletHolder(new MetaDataServlet(getModel())), "/service/metadata"); - - root.addServlet(new ServletHolder(new SaslServlet()), "/service/sasl"); - - root.addServlet(new ServletHolder(new DefinedFileServlet("index.html")), HttpManagementUtil.ENTRY_POINT_PATH); - root.addServlet(new ServletHolder(new DefinedFileServlet("index.html")), "/"); - root.addServlet(new ServletHolder(new LogoutServlet()), "/logout"); - - root.addServlet(new ServletHolder(new FileServlet(DojoHelper.getDojoPath(), true)), "/dojo/dojo/*"); - root.addServlet(new ServletHolder(new FileServlet(DojoHelper.getDijitPath(), true)), "/dojo/dijit/*"); - root.addServlet(new ServletHolder(new FileServlet(DojoHelper.getDojoxPath(), true)), "/dojo/dojox/*"); - - root.addServlet(new ServletHolder(new FileServlet()), "*.js"); - root.addServlet(new ServletHolder(new FileServlet()), "*.css"); - root.addServlet(new ServletHolder(new FileServlet()), "*.html"); - root.addServlet(new ServletHolder(new FileServlet()), "*.png"); - root.addServlet(new ServletHolder(new FileServlet()), "*.gif"); - root.addServlet(new ServletHolder(new FileServlet()), "*.jpg"); - root.addServlet(new ServletHolder(new FileServlet()), "*.jpeg"); - root.addServlet(new ServletHolder(new FileServlet()), "*.json"); - root.addServlet(new ServletHolder(new FileServlet()), "*.txt"); - root.addServlet(new ServletHolder(new FileServlet()), "*.xsl"); - root.addServlet(new ServletHolder(new HelperServlet()), "/service/helper"); - root.addServlet(new ServletHolder(new LogFileListingServlet()), "/service/logfilenames"); - root.addServlet(new ServletHolder(new LogFileServlet()), "/service/logfile"); - - final SessionManager sessionManager = root.getSessionHandler().getSessionManager(); - sessionManager.getSessionCookieConfig().setName(JSESSIONID_COOKIE_PREFIX + lastPort); - sessionManager.setMaxInactiveInterval((Integer)getAttribute(TIME_OUT)); - - return server; - } - - private Connector createSslConnector(final HttpPort<?> port) - { - final Connector connector; - KeyStore keyStore = port.getKeyStore(); - Collection<TrustStore> trustStores = port.getTrustStores(); - if (keyStore == null) - { - throw new IllegalConfigurationException("Key store is not configured. Cannot start management on HTTPS port without keystore"); - } - SslContextFactory factory = new SslContextFactory(); - factory.addExcludeProtocols(SSLUtil.SSLV3_PROTOCOL); - - if(port.getDisabledCipherSuites() != null) - { - factory.addExcludeCipherSuites(port.getDisabledCipherSuites().toArray(new String[port.getDisabledCipherSuites().size()])); - } - - if(port.getEnabledCipherSuites() != null && !port.getEnabledCipherSuites().isEmpty()) - { - factory.setIncludeCipherSuites(port.getEnabledCipherSuites().toArray(new String[port.getEnabledCipherSuites().size()])); - } - - boolean needClientCert = port.getNeedClientAuth() || port.getWantClientAuth(); - - if (needClientCert && trustStores.isEmpty()) - { - throw new IllegalConfigurationException("Client certificate authentication is enabled on AMQP port '" - + this.getName() + "' but no trust store defined"); - } - - try - { - SSLContext sslContext = SSLContext.getInstance("TLS"); - KeyManager[] keyManagers = keyStore.getKeyManagers(); - - TrustManager[] trustManagers; - if(trustStores == null || trustStores.isEmpty()) - { - trustManagers = null; - } - else if(trustStores.size() == 1) - { - trustManagers = trustStores.iterator().next().getTrustManagers(); - } - else - { - Collection<TrustManager> trustManagerList = new ArrayList<>(); - final QpidMultipleTrustManager mulTrustManager = new QpidMultipleTrustManager(); - - for(TrustStore ts : trustStores) - { - TrustManager[] managers = ts.getTrustManagers(); - if(managers != null) - { - for(TrustManager manager : managers) - { - if(manager instanceof X509TrustManager) - { - mulTrustManager.addTrustManager((X509TrustManager)manager); - } - else - { - trustManagerList.add(manager); - } - } - } - } - if(!mulTrustManager.isEmpty()) - { - trustManagerList.add(mulTrustManager); - } - trustManagers = trustManagerList.toArray(new TrustManager[trustManagerList.size()]); - } - sslContext.init(keyManagers, trustManagers, null); - - factory.setSslContext(sslContext); - if(port.getNeedClientAuth()) - { - factory.setNeedClientAuth(true); - } - else if(port.getWantClientAuth()) - { - factory.setWantClientAuth(true); - } - } - catch (GeneralSecurityException e) - { - throw new ServerScopedRuntimeException("Cannot configure port " + port.getName() + " for transport " + Transport.SSL, e); - } - connector = port.getTransports().contains(Transport.TCP) - ? new TcpAndSslSelectChannelConnector(factory) - { - @Override - public void customize(final EndPoint endpoint, final Request request) throws IOException - { - super.customize(endpoint, request); - request.setAttribute(PORT_SERVLET_ATTRIBUTE, port); - } - } - : new SslSelectChannelConnector(factory) - { - @Override - public void customize(final EndPoint endpoint, final Request request) throws IOException - { - super.customize(endpoint, request); - request.setAttribute(PORT_SERVLET_ATTRIBUTE, port); - } - }; - return connector; - } - - private void addRestServlet(ServletContextHandler root, String name, Class<? extends ConfiguredObject>... hierarchy) - { - ServletHolder servletHolder = new ServletHolder(name, new RestServlet(hierarchy)); - servletHolder.getRegistration().setMultipartConfig( - new MultipartConfigElement("", - getContextValue(Long.class, MAX_HTTP_FILE_UPLOAD_SIZE_CONTEXT_NAME), - -1l, - getContextValue(Integer.class, MAX_HTTP_FILE_UPLOAD_SIZE_CONTEXT_NAME))); - - List<String> paths = Arrays.asList("/api/latest/" + name , - "/api/v" + BrokerModel.MODEL_MAJOR_VERSION + "/" + name ); - - for(String path : paths) - { - root.addServlet(servletHolder, path + "/*"); - } - ServletHolder docServletHolder = new ServletHolder(name+"docs", new ApiDocsServlet(getModel(), - paths, - hierarchy)); - root.addServlet(docServletHolder, "/apidocs/latest/" + name + "/"); - root.addServlet(docServletHolder, "/apidocs/v" + BrokerModel.MODEL_MAJOR_VERSION + "/" + name +"/"); - root.addServlet(docServletHolder, "/apidocs/latest/" + name ); - root.addServlet(docServletHolder, "/apidocs/v" + BrokerModel.MODEL_MAJOR_VERSION + "/" + name); - - - } - - private void logOperationalListenMessages(Collection<Port<?>> ports) - { - for (Port port : ports) - { - Set<Transport> transports = port.getTransports(); - for (Transport transport: transports) - { - getBroker().getEventLogger().message(ManagementConsoleMessages.LISTENING(Protocol.HTTP.name(), transport.name(), port.getPort())); - } - } - } - - private void logOperationalShutdownMessage(Server server) - { - Connector[] connectors = server.getConnectors(); - for (Connector connector : connectors) - { - getBroker().getEventLogger().message(ManagementConsoleMessages.SHUTTING_DOWN(Protocol.HTTP.name(), connector.getPort())); - } - } - - - private Collection<Port<?>> getHttpPorts(Collection<Port<?>> ports) - { - Collection<Port<?>> httpPorts = new HashSet<>(); - for (Port<?> port : ports) - { - if (port.getProtocols().contains(Protocol.HTTP)) - { - httpPorts.add(port); - } - } - return httpPorts; - } - - @Override - public boolean isActivationAllowed(final Port<?> port) - { - return _allowPortActivation; - } - - @Override - public boolean isHttpsSaslAuthenticationEnabled() - { - return _httpsSaslAuthenticationEnabled; - } - - @Override - public boolean isHttpSaslAuthenticationEnabled() - { - return _httpSaslAuthenticationEnabled; - } - - @Override - public boolean isHttpsBasicAuthenticationEnabled() - { - return _httpsBasicAuthenticationEnabled; - } - - @Override - public boolean isHttpBasicAuthenticationEnabled() - { - return _httpBasicAuthenticationEnabled; - } - - @Override - public boolean isCompressResponses() - { - return _compressResponses; - } - - @Override - public AuthenticationProvider getAuthenticationProvider(HttpServletRequest request) - { - HttpPort<?> port = (HttpPort<?>)request.getAttribute(PORT_SERVLET_ATTRIBUTE); - return port == null ? null : port.getAuthenticationProvider(); - } - - @Override - protected void validateChange(final ConfiguredObject<?> proxyForValidation, final Set<String> changedAttributes) - { - super.validateChange(proxyForValidation, changedAttributes); - - HttpManagementConfiguration<?> updated = (HttpManagementConfiguration<?>)proxyForValidation; - if(changedAttributes.contains(HttpManagement.NAME)) - { - if(!getName().equals(updated.getName())) - { - throw new IllegalConfigurationException("Changing the name of http management plugin is not allowed"); - } - } - if (changedAttributes.contains(TIME_OUT)) - { - int value = updated.getSessionTimeout(); - if (value < 0) - { - throw new IllegalConfigurationException("Only positive integer value can be specified for the session time out attribute"); - } - } - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementConfiguration.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementConfiguration.java deleted file mode 100644 index d3d9770912..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementConfiguration.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin; - -import java.net.SocketAddress; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.model.ManagedContextDefault; -import org.apache.qpid.server.model.Plugin; - -public interface HttpManagementConfiguration<X extends HttpManagementConfiguration<X>> extends Plugin<X> -{ - - @ManagedAttribute( defaultValue = "true" ) - boolean isHttpsSaslAuthenticationEnabled(); - - @ManagedAttribute( defaultValue = "true" ) - boolean isHttpSaslAuthenticationEnabled(); - - @ManagedAttribute( defaultValue = "true" ) - boolean isHttpsBasicAuthenticationEnabled(); - - @ManagedAttribute( defaultValue = "false" ) - boolean isHttpBasicAuthenticationEnabled(); - - @ManagedAttribute( defaultValue = "600" ) - public int getSessionTimeout(); - - String QPID_HELP_URL = "qpid.helpURL"; - @ManagedContextDefault(name = QPID_HELP_URL) - String DEFAULT_HELP_URL = "http://qpid.apache.org/releases/qpid-${qpid.version}/java-broker/book"; - - String HTTP_MANAGEMENT_COMPRESS_RESPONSES = "httpManagement.compressResponses"; - @ManagedContextDefault(name = HTTP_MANAGEMENT_COMPRESS_RESPONSES) - boolean DEFAULT_COMPRESS_RESPONSES = false; - - @ManagedAttribute( defaultValue = "${"+HTTP_MANAGEMENT_COMPRESS_RESPONSES+"}" ) - public boolean isCompressResponses(); - - String MAX_HTTP_FILE_UPLOAD_SIZE_CONTEXT_NAME = "maxHttpFileUploadSize"; - @ManagedContextDefault( name = MAX_HTTP_FILE_UPLOAD_SIZE_CONTEXT_NAME) - static final long DEFAULT_MAX_UPLOAD_SIZE = 100 * 1024; - - - String JETTY_THREAD_POOL_MAX_QUEUED = "jetty.threadPool.maxQueued"; - @ManagedContextDefault( name = JETTY_THREAD_POOL_MAX_QUEUED) - static final long DEFAULT_JETTY_THREAD_POOL_MAX_QUEUED = 1000; - - String JETTY_THREAD_POOL_MAX_THREADS = "jetty.threadPool.maxThreads"; - @ManagedContextDefault( name = JETTY_THREAD_POOL_MAX_THREADS) - static final long DEFAULT_JETTY_THREAD_POOL_MAX_THREADS = 50; - - - String JETTY_THREAD_POOL_MIN_THREADS = "jetty.threadPool.minThreads"; - @ManagedContextDefault( name = JETTY_THREAD_POOL_MIN_THREADS) - static final long DEFAULT_JETTY_THREAD_POOL_MIN_THREADS = 5; - - - - AuthenticationProvider getAuthenticationProvider(HttpServletRequest request); -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementUtil.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementUtil.java deleted file mode 100644 index 90906538d2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementUtil.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.zip.GZIPOutputStream; - -import javax.security.auth.Subject; -import javax.security.auth.x500.X500Principal; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.codec.binary.Base64; - -import org.apache.qpid.server.management.plugin.servlet.ServletConnectionPrincipal; -import org.apache.qpid.server.management.plugin.session.LoginLogoutReporter; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; -import org.apache.qpid.server.security.auth.SubjectAuthenticationResult; -import org.apache.qpid.server.security.auth.UsernamePrincipal; -import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager; -import org.apache.qpid.server.security.auth.manager.ExternalAuthenticationManager; -import org.apache.qpid.transport.network.security.ssl.SSLUtil; - -public class HttpManagementUtil -{ - - /** - * Servlet context attribute holding a reference to a broker instance - */ - public static final String ATTR_BROKER = "Qpid.broker"; - - /** - * Servlet context attribute holding a reference to plugin configuration - */ - public static final String ATTR_MANAGEMENT_CONFIGURATION = "Qpid.managementConfiguration"; - - /** - * Default management entry URL - */ - public static final String ENTRY_POINT_PATH = "/management"; - - private static final String ATTR_LOGIN_LOGOUT_REPORTER = "Qpid.loginLogoutReporter"; - private static final String ATTR_SUBJECT = "Qpid.subject"; - private static final String ATTR_LOG_ACTOR = "Qpid.logActor"; - - private static final String ACCEPT_ENCODING_HEADER = "Accept-Encoding"; - private static final String CONTENT_ENCODING_HEADER = "Content-Encoding"; - private static final String GZIP_CONTENT_ENCODING = "gzip"; - - public static Broker<?> getBroker(ServletContext servletContext) - { - return (Broker<?>) servletContext.getAttribute(ATTR_BROKER); - } - - public static HttpManagementConfiguration getManagementConfiguration(ServletContext servletContext) - { - return (HttpManagementConfiguration) servletContext.getAttribute(ATTR_MANAGEMENT_CONFIGURATION); - } - - public static SocketAddress getSocketAddress(HttpServletRequest request) - { - return InetSocketAddress.createUnresolved(request.getServerName(), request.getServerPort()); - } - - public static Subject getAuthorisedSubject(HttpSession session) - { - return (Subject) session.getAttribute(ATTR_SUBJECT); - } - - public static void checkRequestAuthenticatedAndAccessAuthorized(HttpServletRequest request, Broker broker, - HttpManagementConfiguration managementConfig) - { - HttpSession session = request.getSession(); - Subject subject = getAuthorisedSubject(session); - if (subject == null) - { - subject = tryToAuthenticate(request, managementConfig); - if (subject == null) - { - throw new SecurityException("Only authenticated users can access the management interface"); - } - - Subject original = subject; - subject = new Subject(false, - original.getPrincipals(), - original.getPublicCredentials(), - original.getPrivateCredentials()); - subject.getPrincipals().add(new ServletConnectionPrincipal(request)); - subject.setReadOnly(); - - assertManagementAccess(broker.getSecurityManager(), subject); - - saveAuthorisedSubject(session, subject); - - - } - } - - public static void assertManagementAccess(final SecurityManager securityManager, Subject subject) - { - Subject.doAs(subject, new PrivilegedAction<Void>() - { - @Override - public Void run() - { - securityManager.accessManagement(); - return null; - } - }); - } - - public static void saveAuthorisedSubject(HttpSession session, Subject subject) - { - session.setAttribute(ATTR_SUBJECT, subject); - - // Cause the user logon to be logged. - session.setAttribute(ATTR_LOGIN_LOGOUT_REPORTER, - new LoginLogoutReporter(subject, getBroker(session.getServletContext()))); - } - - public static Subject tryToAuthenticate(HttpServletRequest request, HttpManagementConfiguration managementConfig) - { - Subject subject = null; - final AuthenticationProvider authenticationProvider = managementConfig.getAuthenticationProvider(request); - SubjectCreator subjectCreator = authenticationProvider.getSubjectCreator(request.isSecure()); - String remoteUser = request.getRemoteUser(); - - if (remoteUser != null || authenticationProvider instanceof AnonymousAuthenticationManager) - { - subject = authenticateUser(subjectCreator, remoteUser, null); - } - else if(authenticationProvider instanceof ExternalAuthenticationManager - && Collections.list(request.getAttributeNames()).contains("javax.servlet.request.X509Certificate")) - { - Principal principal = null; - X509Certificate[] certificates = - (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate"); - if(certificates != null && certificates.length != 0) - { - principal = certificates[0].getSubjectX500Principal(); - - if(!Boolean.valueOf(String.valueOf(authenticationProvider.getAttribute(ExternalAuthenticationManager.ATTRIBUTE_USE_FULL_DN)))) - { - String username; - String dn = ((X500Principal) principal).getName(X500Principal.RFC2253); - - - username = SSLUtil.getIdFromSubjectDN(dn); - principal = new UsernamePrincipal(username); - } - - subject = subjectCreator.createSubjectWithGroups(new AuthenticatedPrincipal(principal)); - } - } - else - { - String header = request.getHeader("Authorization"); - if (header != null) - { - String[] tokens = header.split("\\s"); - if (tokens.length >= 2 && "BASIC".equalsIgnoreCase(tokens[0])) - { - boolean isBasicAuthSupported = false; - if (request.isSecure()) - { - isBasicAuthSupported = managementConfig.isHttpsBasicAuthenticationEnabled(); - } - else - { - isBasicAuthSupported = managementConfig.isHttpBasicAuthenticationEnabled(); - } - if (isBasicAuthSupported) - { - String base64UsernameAndPassword = tokens[1]; - String[] credentials = (new String(Base64.decodeBase64(base64UsernameAndPassword.getBytes()))).split(":", 2); - if (credentials.length == 2) - { - subject = authenticateUser(subjectCreator, credentials[0], credentials[1]); - } - } - } - } - } - return subject; - } - - private static Subject authenticateUser(SubjectCreator subjectCreator, String username, String password) - { - SubjectAuthenticationResult authResult = subjectCreator.authenticate(username, password); - if (authResult.getStatus() == AuthenticationStatus.SUCCESS) - { - return authResult.getSubject(); - } - return null; - } - - public static Writer getOutputWriter(final HttpServletRequest request, final HttpServletResponse response) - throws IOException - { - return getOutputWriter(request, response, getManagementConfiguration(request.getServletContext())); - } - - public static Writer getOutputWriter(final HttpServletRequest request, final HttpServletResponse response, HttpManagementConfiguration managementConfiguration) - throws IOException - { - Writer writer; - writer = new BufferedWriter(new OutputStreamWriter(getOutputStream(request,response, managementConfiguration))); - - return writer; - } - - public static OutputStream getOutputStream(final HttpServletRequest request, final HttpServletResponse response) - throws IOException - { - return getOutputStream(request, response, getManagementConfiguration(request.getServletContext())); - } - - public static OutputStream getOutputStream(final HttpServletRequest request, final HttpServletResponse response, HttpManagementConfiguration managementConfiguration) - throws IOException - { - OutputStream outputStream; - if(managementConfiguration.isCompressResponses() - && Collections.list(request.getHeaderNames()).contains(ACCEPT_ENCODING_HEADER) - && request.getHeader(ACCEPT_ENCODING_HEADER).contains(GZIP_CONTENT_ENCODING)) - { - outputStream = new GZIPOutputStream(response.getOutputStream()); - response.setHeader(CONTENT_ENCODING_HEADER, GZIP_CONTENT_ENCODING); - } - else - { - outputStream = response.getOutputStream(); - } - return outputStream; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/connector/TcpAndSslSelectChannelConnector.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/connector/TcpAndSslSelectChannelConnector.java deleted file mode 100644 index 197032398e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/connector/TcpAndSslSelectChannelConnector.java +++ /dev/null @@ -1,378 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.connector; - -import java.io.IOException; -import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; - -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLSession; - -import org.eclipse.jetty.http.HttpSchemes; -import org.eclipse.jetty.io.AsyncEndPoint; -import org.eclipse.jetty.io.Buffer; -import org.eclipse.jetty.io.Connection; -import org.eclipse.jetty.io.EndPoint; -import org.eclipse.jetty.io.nio.AsyncConnection; -import org.eclipse.jetty.io.nio.IndirectNIOBuffer; -import org.eclipse.jetty.io.nio.SelectChannelEndPoint; -import org.eclipse.jetty.io.nio.SelectorManager; -import org.eclipse.jetty.io.nio.SslConnection; -import org.eclipse.jetty.server.AsyncHttpConnection; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.nio.SelectChannelConnector; -import org.eclipse.jetty.server.ssl.SslCertificates; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.util.ssl.SslContextFactory; - -public class TcpAndSslSelectChannelConnector extends SelectChannelConnector -{ - - private static final Logger LOG = Log.getLogger(TcpAndSslSelectChannelConnector.class); - - private final SslContextFactory _sslContextFactory; - - public TcpAndSslSelectChannelConnector(SslContextFactory factory) - { - _sslContextFactory = factory; - addBean(_sslContextFactory); - setUseDirectBuffers(false); - setSoLingerTime(30000); - } - - - @Override - public void customize(EndPoint endpoint, Request request) throws IOException - { - if(endpoint instanceof SslConnection.SslEndPoint) - { - request.setScheme(HttpSchemes.HTTPS); - } - - super.customize(endpoint,request); - - if(endpoint instanceof SslConnection.SslEndPoint) - { - SslConnection.SslEndPoint sslEndpoint = (SslConnection.SslEndPoint) endpoint; - SSLEngine sslEngine = sslEndpoint.getSslEngine(); - SSLSession sslSession = sslEngine.getSession(); - - SslCertificates.customize(sslSession, endpoint, request); - } - } - - @Override - protected AsyncConnection newConnection(SocketChannel channel, AsyncEndPoint endpoint) - { - return new ProtocolIdentifyingConnection((ProtocolIdentifyingEndpoint) endpoint); - } - - @Override - protected SelectChannelEndPoint newEndPoint(final SocketChannel channel, - final SelectorManager.SelectSet selectSet, - final SelectionKey key) throws IOException - { - - ProtocolIdentifyingEndpoint endpoint = new ProtocolIdentifyingEndpoint(channel,selectSet,key, getMaxIdleTime()); - endpoint.setConnection(selectSet.getManager().newConnection(channel, endpoint, key.attachment())); - return endpoint; - } - - protected SSLEngine createSSLEngine(SocketChannel channel) throws IOException - { - SSLEngine engine; - if (channel != null) - { - String peerHost = channel.socket().getInetAddress().getHostAddress(); - int peerPort = channel.socket().getPort(); - engine = _sslContextFactory.newSslEngine(peerHost, peerPort); - } - else - { - engine = _sslContextFactory.newSslEngine(); - } - - engine.setUseClientMode(false); - return engine; - } - - @Override - protected void doStart() throws Exception - { - _sslContextFactory.checkKeyStore(); - _sslContextFactory.start(); - - SSLEngine sslEngine = _sslContextFactory.newSslEngine(); - - sslEngine.setUseClientMode(false); - - SSLSession sslSession = sslEngine.getSession(); - - if (getRequestHeaderSize()<sslSession.getApplicationBufferSize()) - setRequestHeaderSize(sslSession.getApplicationBufferSize()); - if (getRequestBufferSize()<sslSession.getApplicationBufferSize()) - setRequestBufferSize(sslSession.getApplicationBufferSize()); - - super.doStart(); - } - - @Override - public boolean isConfidential(final Request request) - { - if(request.getScheme().equals(HttpSchemes.HTTPS)) - { - final int confidentialPort=getConfidentialPort(); - return confidentialPort==0||confidentialPort==request.getServerPort(); - } - return super.isConfidential(request); - } - - enum Protocol { UNKNOWN, TCP , SSL } - - private class ProtocolIdentifyingEndpoint extends SelectChannelEndPoint - { - - private Protocol _protocol = Protocol.UNKNOWN; - private Buffer _preBuffer = new IndirectNIOBuffer(6); - - public ProtocolIdentifyingEndpoint(final SocketChannel channel, - final SelectorManager.SelectSet selectSet, - final SelectionKey key, final int maxIdleTime) throws IOException - { - super(channel, selectSet, key, maxIdleTime); - } - - public Protocol getProtocol() throws IOException - { - if(_protocol == Protocol.UNKNOWN) - { - if(_preBuffer.space() != 0) - { - super.fill(_preBuffer); - _protocol = identifyFromPreBuffer(); - } - } - return _protocol; - } - - public SocketChannel getSocketChannel() - { - return (SocketChannel) getChannel(); - } - - private Protocol identifyFromPreBuffer() - { - if(_preBuffer.space() == 0) - { - byte[] helloBytes = _preBuffer.array(); - if (looksLikeSSLv2ClientHello(helloBytes) || looksLikeSSLv3ClientHello(helloBytes)) - { - return Protocol.SSL; - } - else - { - return Protocol.TCP; - } - } - return Protocol.UNKNOWN; - } - - private boolean looksLikeSSLv3ClientHello(byte[] headerBytes) - { - return headerBytes[0] == 22 && // SSL Handshake - (headerBytes[1] == 3 && // SSL 3.0 / TLS 1.x - (headerBytes[2] == 0 || // SSL 3.0 - headerBytes[2] == 1 || // TLS 1.0 - headerBytes[2] == 2 || // TLS 1.1 - headerBytes[2] == 3)) && // TLS1.2 - (headerBytes[5] == 1); // client_hello - } - - private boolean looksLikeSSLv2ClientHello(byte[] headerBytes) - { - return headerBytes[0] == -128 && - headerBytes[3] == 3 && // SSL 3.0 / TLS 1.x - (headerBytes[4] == 0 || // SSL 3.0 - headerBytes[4] == 1 || // TLS 1.0 - headerBytes[4] == 2 || // TLS 1.1 - headerBytes[4] == 3); - } - - @Override - public int fill(final Buffer buffer) throws IOException - { - int size = 0; - - if(getProtocol() != Protocol.UNKNOWN) - { - if (_preBuffer.hasContent()) - { - size = buffer.put(_preBuffer); - _preBuffer.skip(size); - } - if (buffer.space() != 0) - { - size += super.fill(buffer); - } - } - return size; - } - } - - private class ProtocolIdentifyingConnection implements AsyncConnection - { - private final ProtocolIdentifyingEndpoint _endpoint; - private AsyncConnection _delegate; - private final long _timestamp; - private IOException _exception; - - private ProtocolIdentifyingConnection(final ProtocolIdentifyingEndpoint endpoint) - { - _endpoint = endpoint; - _timestamp = System.currentTimeMillis(); - } - - @Override - public void onInputShutdown() throws IOException - { - if (_delegate == null) - { - createDelegate(true); - } - _delegate.onInputShutdown(); - } - - private boolean createDelegate(boolean createPlainWhenUnknown) throws IOException - { - if(_exception != null) - { - throw _exception; - } - Protocol protocol = _endpoint.getProtocol(); - if(protocol == Protocol.TCP || (createPlainWhenUnknown && protocol == Protocol.UNKNOWN)) - { - _delegate = new AsyncHttpConnection(TcpAndSslSelectChannelConnector.this, _endpoint, getServer()); - return true; - } - else if(protocol == Protocol.SSL) - { - SocketChannel channel = _endpoint.getSocketChannel(); - SSLEngine engine = createSSLEngine(channel); - SslConnection connection = new SslConnection(engine, _endpoint); - AsyncConnection delegate = new AsyncHttpConnection(TcpAndSslSelectChannelConnector.this, - connection.getSslEndPoint(), - getServer()); - connection.getSslEndPoint().setConnection(delegate); - connection.setAllowRenegotiate(_sslContextFactory.isAllowRenegotiate()); - - _delegate = connection; - return true; - } - return false; - } - - private boolean createDelegateNoException() - { - try - { - return createDelegate(false); - } - catch (IOException e) - { - _exception = e; - return false; - } - } - - @Override - public Connection handle() throws IOException - { - if(_delegate != null || createDelegate(false)) - { - return _delegate.handle(); - } - return this; - } - - @Override - public long getTimeStamp() - { - return _timestamp; - } - - @Override - public boolean isIdle() - { - if(_delegate != null || createDelegateNoException()) - { - return _delegate.isIdle(); - } - return false; - } - - @Override - public boolean isSuspended() - { - if(_delegate != null || createDelegateNoException()) - { - return _delegate.isSuspended(); - } - return false; - } - - @Override - public void onClose() - { - if(_delegate != null) - { - _delegate.onClose(); - } - } - - @Override - public void onIdleExpired(final long idleForMs) - { - try - { - if(_delegate != null || createDelegate(true)) - { - _delegate.onIdleExpired(idleForMs); - } - } - catch (IOException e) - { - LOG.ignore(e); - - try - { - _endpoint.close(); - } - catch(IOException e2) - { - LOG.ignore(e2); - } - } - } - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/ForbiddingAuthorisationFilter.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/ForbiddingAuthorisationFilter.java deleted file mode 100644 index 16f85ace2c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/ForbiddingAuthorisationFilter.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.filter; - -import java.io.IOException; -import java.security.AccessControlException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.qpid.server.management.plugin.HttpManagementConfiguration; -import org.apache.qpid.server.management.plugin.HttpManagementUtil; -import org.apache.qpid.server.model.Broker; - -public class ForbiddingAuthorisationFilter implements Filter -{ - public static String INIT_PARAM_ALLOWED = "allowed"; - private String _allowed = null; - - private Broker _broker; - private HttpManagementConfiguration _managementConfiguration; - - @Override - public void destroy() - { - } - - @Override - public void init(FilterConfig config) throws ServletException - { - String allowed = config.getInitParameter(INIT_PARAM_ALLOWED); - if (allowed != null) - { - _allowed = allowed; - } - ServletContext servletContext = config.getServletContext(); - _broker = HttpManagementUtil.getBroker(servletContext); - _managementConfiguration = HttpManagementUtil.getManagementConfiguration(servletContext); - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, - ServletException - { - HttpServletRequest httpRequest = (HttpServletRequest) request; - HttpServletResponse httpResponse = (HttpServletResponse) response; - String servletPath = httpRequest.getServletPath(); - if (_allowed == null || "".equals(_allowed) || servletPath.indexOf(_allowed) == -1) - { - try - { - HttpManagementUtil.checkRequestAuthenticatedAndAccessAuthorized(httpRequest, _broker, _managementConfiguration); - } - catch(AccessControlException e) - { - httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN); - return; - } - catch(SecurityException e) - { - httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); - return; - } - } - chain.doFilter(request, response); - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/ForbiddingTraceFilter.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/ForbiddingTraceFilter.java deleted file mode 100644 index c35b0df1a3..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/ForbiddingTraceFilter.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.filter; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * - * This {@link Filter} blocks HTTP TRACE commands from being - * processed. All TRACE requests are sent a 403 error. - * - */ -public class ForbiddingTraceFilter implements Filter -{ - private static final String METHOD_TRACE = "TRACE"; - - @Override - public void destroy() - { - } - - @Override - public void init(FilterConfig config) throws ServletException - { - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, - ServletException - { - HttpServletRequest httpRequest = (HttpServletRequest) request; - HttpServletResponse httpResponse = (HttpServletResponse) response; - if (httpRequest.getMethod().equals(METHOD_TRACE)) - { - httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN); - return; - } - chain.doFilter(request, response); - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/RedirectingAuthorisationFilter.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/RedirectingAuthorisationFilter.java deleted file mode 100644 index 184a653fa8..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/RedirectingAuthorisationFilter.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.filter; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.qpid.server.management.plugin.HttpManagementConfiguration; -import org.apache.qpid.server.management.plugin.HttpManagementUtil; -import org.apache.qpid.server.model.Broker; - -public class RedirectingAuthorisationFilter implements Filter -{ - public static String DEFAULT_LOGIN_URL = "login.html"; - public static String INIT_PARAM_LOGIN_URL = "login-url"; - - private String _loginUrl = DEFAULT_LOGIN_URL; - private Broker _broker; - private HttpManagementConfiguration _managementConfiguration; - - @Override - public void destroy() - { - } - - @Override - public void init(FilterConfig config) throws ServletException - { - String loginUrl = config.getInitParameter(INIT_PARAM_LOGIN_URL); - if (loginUrl != null) - { - _loginUrl = loginUrl; - } - ServletContext servletContext = config.getServletContext(); - _broker = HttpManagementUtil.getBroker(servletContext); - _managementConfiguration = HttpManagementUtil.getManagementConfiguration(servletContext); - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, - ServletException - { - HttpServletRequest httpRequest = (HttpServletRequest) request; - HttpServletResponse httpResponse = (HttpServletResponse) response; - try - { - HttpManagementUtil.checkRequestAuthenticatedAndAccessAuthorized(httpRequest, _broker, _managementConfiguration); - chain.doFilter(request, response); - } - catch(SecurityException e) - { - httpResponse.sendRedirect(_loginUrl); - } - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/log/LogFileDetails.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/log/LogFileDetails.java deleted file mode 100644 index 09dabd0e73..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/log/LogFileDetails.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.qpid.server.management.plugin.log; - -import java.io.File; - -public class LogFileDetails -{ - private String _name; - private File _location; - private String _mimeType; - private long _size; - private long _lastModified; - private String _appenderName; - - public LogFileDetails(String name, String appenderName, File location, String mimeType, long fileSize, long lastUpdateTime) - { - super(); - _name = name; - _location = location; - _mimeType = mimeType; - _size = fileSize; - _lastModified = lastUpdateTime; - _appenderName = appenderName; - } - - public String getName() - { - return _name; - } - - public File getLocation() - { - return _location; - } - - public String getMimeType() - { - return _mimeType; - } - - public long getSize() - { - return _size; - } - - public long getLastModified() - { - return _lastModified; - } - - public String getAppenderName() - { - return _appenderName; - } - - @Override - public String toString() - { - return "LogFileDetails [name=" + _name + "]"; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/log/LogFileHelper.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/log/LogFileHelper.java deleted file mode 100644 index 51256ab5fa..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/log/LogFileHelper.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.qpid.server.management.plugin.log; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import org.apache.log4j.Appender; -import org.apache.log4j.FileAppender; -import org.apache.log4j.QpidCompositeRollingAppender; - -public class LogFileHelper -{ - public static final String GZIP_MIME_TYPE = "application/x-gzip"; - public static final String TEXT_MIME_TYPE = "text/plain"; - public static final String ZIP_MIME_TYPE = "application/zip"; - public static final String GZIP_EXTENSION = ".gz"; - private static final int BUFFER_LENGTH = 1024 * 4; - private Collection<Appender> _appenders; - - public LogFileHelper(Collection<Appender> appenders) - { - super(); - _appenders = appenders; - } - - public List<LogFileDetails> findLogFileDetails(String[] requestedFiles) - { - List<LogFileDetails> logFiles = new ArrayList<LogFileDetails>(); - Map<String, List<LogFileDetails>> cache = new HashMap<String, List<LogFileDetails>>(); - for (int i = 0; i < requestedFiles.length; i++) - { - String logFile = requestedFiles[i]; - if ("".equals(logFile)) - { - throw new IllegalArgumentException("Log file parameter is empty"); - } - int pos = logFile.indexOf("/"); - if (pos == -1) - { - throw new IllegalArgumentException("Log file parameter '" + logFile + "' does not include an appender name"); - } - if (pos == logFile.length()) - { - throw new IllegalArgumentException("Log file parameter '" + logFile + "' does not include an file name"); - } - - String appenderName = logFile.substring(0, pos); - String fileName = logFile.substring(pos + 1); - - List<LogFileDetails> appenderFiles = cache.get(appenderName); - if (appenderFiles == null) - { - Appender fileAppender = null; - for (Appender appender : _appenders) - { - if (appenderName.equals(appender.getName())) - { - fileAppender = appender; - break; - } - } - if (fileAppender == null) - { - continue; - } - appenderFiles = getAppenderFiles(fileAppender, true); - if (appenderFiles == null) - { - continue; - } - cache.put(appenderName, appenderFiles); - } - for (LogFileDetails logFileDetails : appenderFiles) - { - if (logFileDetails.getName().equals(fileName)) - { - logFiles.add(logFileDetails); - break; - } - } - } - return logFiles; - } - - public List<LogFileDetails> getLogFileDetails(boolean includeLogFileLocation) - { - List<LogFileDetails> results = new ArrayList<LogFileDetails>(); - for (Appender appender : _appenders) - { - List<LogFileDetails> appenderFiles = getAppenderFiles(appender, includeLogFileLocation); - if (appenderFiles != null) - { - results.addAll(appenderFiles); - } - } - return results; - } - - public void writeLogFiles(List<LogFileDetails> logFiles, OutputStream os) throws IOException - { - ZipOutputStream out = new ZipOutputStream(os); - try - { - addLogFileEntries(logFiles, out); - } - finally - { - out.close(); - } - } - - public void writeLogFile(File file, OutputStream os) throws IOException - { - FileInputStream fis = new FileInputStream(file); - try - { - byte[] bytes = new byte[BUFFER_LENGTH]; - int length = 1; - while ((length = fis.read(bytes)) != -1) - { - os.write(bytes, 0, length); - } - } - finally - { - fis.close(); - } - } - - private List<LogFileDetails> getAppenderFiles(Appender appender, boolean includeLogFileLocation) - { - if (appender instanceof QpidCompositeRollingAppender) - { - return listQpidCompositeRollingAppenderFiles((QpidCompositeRollingAppender) appender, includeLogFileLocation); - } - else if (appender instanceof FileAppender) - { - return listFileAppenderFiles((FileAppender) appender, includeLogFileLocation); - } - return null; - } - - private List<LogFileDetails> listFileAppenderFiles(FileAppender appender, boolean includeLogFileLocation) - { - String appenderFilePath = appender.getFile(); - File appenderFile = new File(appenderFilePath); - if (appenderFile.exists()) - { - return listLogFiles(appenderFile.getParentFile(), appenderFile.getName(), appender.getName(), "", includeLogFileLocation); - } - return Collections.emptyList(); - } - - private List<LogFileDetails> listQpidCompositeRollingAppenderFiles(QpidCompositeRollingAppender appender, boolean includeLogFileLocation) - { - List<LogFileDetails> files = listFileAppenderFiles((FileAppender) appender, includeLogFileLocation); - String appenderFilePath = appender.getFile(); - File appenderFile = new File(appenderFilePath); - File backupFolder = new File(appender.getBackupFilesToPath()); - if (backupFolder.exists()) - { - String backupFolderName = backupFolder.getName() + "/"; - List<LogFileDetails> backedUpFiles = listLogFiles(backupFolder, appenderFile.getName(), appender.getName(), - backupFolderName, includeLogFileLocation); - files.addAll(backedUpFiles); - } - return files; - } - - private List<LogFileDetails> listLogFiles(File parent, String baseFileName, String appenderName, String relativePath, - boolean includeLogFileLocation) - { - List<LogFileDetails> files = new ArrayList<LogFileDetails>(); - for (File file : parent.listFiles()) - { - String name = file.getName(); - if (name.startsWith(baseFileName)) - { - String displayPath = name; - if (!relativePath.equals("")) - { - displayPath = relativePath + name; - } - files.add(new LogFileDetails(displayPath, appenderName, includeLogFileLocation ? file : null, getMimeType(name), file.length(), - file.lastModified())); - } - } - return files; - } - - private String getMimeType(String fileName) - { - if (fileName.endsWith(GZIP_EXTENSION)) - { - return GZIP_MIME_TYPE; - } - return TEXT_MIME_TYPE; - } - - private void addLogFileEntries(List<LogFileDetails> files, ZipOutputStream out) throws IOException - { - for (LogFileDetails logFileDetails : files) - { - File file = logFileDetails.getLocation(); - if (file.exists()) - { - ZipEntry entry = new ZipEntry(logFileDetails.getAppenderName() + "/" + logFileDetails.getName()); - entry.setSize(file.length()); - out.putNextEntry(entry); - writeLogFile(file, out); - out.closeEntry(); - } - out.flush(); - } - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueBinaryReport.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueBinaryReport.java deleted file mode 100644 index d842de3f1b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueBinaryReport.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.report; - -public abstract class QueueBinaryReport extends QueueReport<byte[]> -{ - public QueueBinaryReport() - { - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueReport.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueReport.java deleted file mode 100644 index 23b24aaf8d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueReport.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.report; - -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; - -/** - * <p> - * The QueueReport class provides an extension point for installations to provide custom management reporting on - * queues through the REST API. - * </p> - * - * <p> - * A custom QueueReport must extend either {@link org.apache.qpid.server.management.plugin.report.QueueTextReport} - * or {@link org.apache.qpid.server.management.plugin.report.QueueBinaryReport}. The report implementation must - * define a {@link #getName() name} which is unique amongst all installed reports. The report class must be present - * in the classpath of the broker, and a provider-configuration file named - * org.apache.qpid.server.management.plugin.report.QueueReport must be added in the resource directory - * META-INF/services directory with the binary name of the implementation (as described in - * {@link java.util.ServiceLoader ServiceLoader}). - * </p> - * - * <h3>Running reports</h3> - * <p> - * The report can be run using the URL: - * {@code http://<broker>/service/queuereport/<virtualhost name>/<queue name>/<report name>[?param1=x¶m2=y...]} - * </p> - * - * <h4>Report Parameters</h4> - * - * <p> - * Reports can take parameters from the query string of the HTTP request. For every parameter in the query string - * the system will look for a setter on the report object with either a String or String[] parameter. Thus if - * the query string contains {@code foo=bar}, then the system will look for a setter {@code setFoo(String value)} or - * {@code setFoo(String[] value)}. If the same parameter occurs multiple times in the query string then only the - * array variant of the setter will be called. - * </p> - * <p> - * Setters for the parameters are guaranteed to be called before the first message is added to the report. - * </p> - * - * <p> - * NOTE: In order to comply with the requirements of the {@link java.util.ServiceLoader ServiceLoader} api, all - * implementations of QueueReport MUST provide a public no-args constructor. - * </p> - * @param <T> - */ -public abstract class QueueReport<T> -{ - private Queue<?> _queue; - - QueueReport() - { - - } - - /** - * Gets the name of the report. - * <p> - * The name of the report must be unique amongst all installed implementations. The name of the report - * is examined by the Qpid immediately upon construction. The name should not change during - * the lifetime of the object (the value is only meaningful to the system at the time of initial construction) - * and all instances of the same concrete implementation should have the same name. - * </p> - * @return the name of the report - */ - public abstract String getName(); - - /** - * Get the name of the queue against which the report is being run. - * - * @return the name of the queue - */ - public final String getQueueName() - { - return _queue.getName(); - } - - final void setQueue(final Queue<?> queue) - { - _queue = queue; - } - - /** - * Get the name of the virtual host against which the report is being run. - * - * @return the name of the virtual host - */ - public final String getVirtualHostName() - { - return _queue.getParent(VirtualHost.class).getName(); - } - - /** - * - * The value returned by getContentType() will be used to set the Content-Type HTTP header field - * - * @return the value to use for the content-type HTTP header field - */ - public abstract String getContentType(); - - /** - * Called by the system to add a message to the report. - * - * <p> - * The method is called by the system for every message on the queue, or until {@link #isComplete()} returns true. - * </p> - * @param reportableMessage the message to add to the report - */ - public abstract void addMessage(final ReportableMessage reportableMessage); - - /** - * Informs the system if the report is complete (i.e. does not need to report on any more messages). - * - * <p> - * This method will be called by the system after each message is {@link #addMessage(ReportableMessage) added} - * to the report. If a report is only interested in some messages, and can determine that the addition of more - * messages will not vary the content of the report, then it can return true. - * </p> - * <p> - * If this method always returns false, then all messages from the queue will be added to the report. - * </p> - * <p> - * NOTE: Retrieving content or properties of the message may require it to be reloaded from disk, and so care - * should be taken by reports to only access properties/content of the message if it is going to be required - * for the report production. - * </p> - * - * @return true if the report does not want to report on any more messages in the queue - */ - public abstract boolean isComplete(); - - /** - * Called by the system to get the content of the report to retrun to the user. - * <p> - * The system guarantees to only call this method once - * </p> - * @return the report content. - */ - public abstract T getReport(); - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueTextReport.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueTextReport.java deleted file mode 100644 index 09bc5c4229..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueTextReport.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.report; - -public abstract class QueueTextReport extends QueueReport<String> -{ - public QueueTextReport() - { - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.java deleted file mode 100644 index 2a05cfc9a1..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.java +++ /dev/null @@ -1,408 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.report; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.ServiceLoader; -import java.util.Set; -import java.util.UUID; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.queue.QueueEntryVisitor; - -public class ReportRunner<T> -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ReportRunner.class); - - private static final Set<Class> IMMUTABLE_CLASSES = new HashSet<>(Arrays.<Class>asList( - Boolean.class, - Byte.class, - Short.class, - Character.class, - Integer.class, - Long.class, - Float.class, - Double.class, - UUID.class, - Date.class, - String.class - )); - - private ReportRunner(final QueueReport<T> report) - { - _report = report; - } - - public boolean isBinaryReport() - { - return _report instanceof QueueBinaryReport; - } - - public static ReportRunner<?> createRunner(final String reportName, final Map<String, String[]> parameterMap) - { - QueueReport<?> report = getReport(reportName); - setReportParameters(report, parameterMap); - return new ReportRunner<>(report); - } - - private static void setReportParameters(final QueueReport<?> report, final Map<String, String[]> parameterMap) - { - if(parameterMap != null && !parameterMap.isEmpty()) - { - Class<? extends QueueReport> clazz = report.getClass(); - for(Map.Entry<String,String[]> entry : parameterMap.entrySet()) - { - String key = entry.getKey(); - String[] value = entry.getValue(); - if(isValidName(key)) - { - - StringBuilder setterName = new StringBuilder("set"); - setterName.append(key.substring(0,1).toUpperCase()); - if(key.length()>1) - { - setterName.append(key.substring(1)); - } - Method method = null; - try - { - - if (value == null || value.length == 0 || value.length == 1) - { - try - { - method = clazz.getMethod(setterName.toString(), String.class); - method.invoke(report, value == null || value.length == 0 ? null : value[0]); - } - catch (NoSuchMethodException | IllegalAccessException e) - { - method = null; - } - } - if (method == null) - { - try - { - method = clazz.getMethod(setterName.toString(), String[].class); - method.invoke(report, new Object[] { value }); - } - catch (NoSuchMethodException | IllegalAccessException e) - { - LOGGER.info("Unknown parameter '" - + key - + "' (no setter) for report " - + report.getName()); - } - } - } - catch (InvocationTargetException e) - { - LOGGER.info("Error setting parameter '" + key + "' for report " + report.getName(), e); - } - } - else - { - LOGGER.info("Invalid parameter name '" + key + "' running report " + report.getName()); - } - } - } - } - - private static boolean isValidName(final String key) - { - if(key != null && key.length() != 0) - { - if(Character.isJavaIdentifierStart(key.charAt(0))) - { - for(int i = 1; i < key.length(); i++) - { - if(!Character.isJavaIdentifierPart(key.charAt(i))) - { - return false; - } - } - return true; - } - - } - return false; - - } - - private static QueueReport<?> getReport(final String reportName) - { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - for (final QueueReport report : ServiceLoader.load(QueueReport.class, classLoader)) - { - if (report.getName().equals(reportName)) - { - try - { - return report.getClass().newInstance(); - } - catch (InstantiationException | IllegalAccessException e) - { - // can't happen as by definition must have public noargs constructor - } - } - } - throw new IllegalArgumentException("Unknown report: " + reportName); - } - - public String getContentType() - { - return _report.getContentType(); - } - - - private static class ReportVisitor implements QueueEntryVisitor - { - - private final QueueReport _report; - - public ReportVisitor(final QueueReport report) - { - _report = report; - } - - @Override - public boolean visit(final QueueEntry entry) - { - _report.addMessage(convertMessage(entry.getMessage())); - return _report.isComplete(); - } - - - } - - - private static ReportableMessage convertMessage(final ServerMessage message) - { - return new ReportableMessage() - { - @Override - public String getInitialRoutingAddress() - { - return message.getInitialRoutingAddress(); - } - - @Override - public ReportableMessageHeader getMessageHeader() - { - return convertMessageHeader(message.getMessageHeader()); - } - - @Override - public ByteBuffer getContent() - { - ByteBuffer content = message.getContent(0, (int) getSize()); - - return content.asReadOnlyBuffer(); - } - - @Override - public boolean isPersistent() - { - return message.isPersistent(); - } - - @Override - public long getSize() - { - return message.getSize(); - } - - @Override - public long getExpiration() - { - return message.getExpiration(); - } - - @Override - public long getMessageNumber() - { - return message.getMessageNumber(); - } - - @Override - public long getArrivalTime() - { - return message.getArrivalTime(); - } - }; - } - - private static ReportableMessageHeader convertMessageHeader(final AMQMessageHeader messageHeader) - { - return new ReportableMessageHeader() - { - @Override - public String getCorrelationId() - { - return messageHeader.getCorrelationId(); - } - - @Override - public long getExpiration() - { - return messageHeader.getExpiration(); - } - - @Override - public String getUserId() - { - return messageHeader.getUserId(); - } - - @Override - public String getAppId() - { - return messageHeader.getAppId(); - } - - @Override - public String getMessageId() - { - return messageHeader.getMessageId(); - } - - @Override - public String getMimeType() - { - return messageHeader.getMimeType(); - } - - @Override - public String getEncoding() - { - return messageHeader.getEncoding(); - } - - @Override - public byte getPriority() - { - return messageHeader.getPriority(); - } - - @Override - public long getTimestamp() - { - return messageHeader.getTimestamp(); - } - - @Override - public String getType() - { - return messageHeader.getType(); - } - - @Override - public String getReplyTo() - { - return messageHeader.getReplyTo(); - } - - @Override - public Object getHeader(final String name) - { - return makeImmutable(messageHeader.getHeader(name)); - } - - @Override - public boolean containsHeaders(final Set<String> names) - { - return messageHeader.containsHeaders(names); - } - - @Override - public boolean containsHeader(final String name) - { - return messageHeader.containsHeader(name); - } - - @Override - public Collection<String> getHeaderNames() - { - return Collections.unmodifiableCollection(messageHeader.getHeaderNames()); - } - }; - } - - private static Object makeImmutable(final Object value) - { - if(value == null || IMMUTABLE_CLASSES.contains(value.getClass())) - { - return value; - } - else if(value instanceof byte[]) - { - return ByteBuffer.wrap((byte[])value).asReadOnlyBuffer(); - } - else if(value instanceof List) - { - List orig = (List) value; - List<Object> copy = new ArrayList<>(orig.size()); - for(Object element : orig) - { - copy.add(makeImmutable(element)); - } - return copy; - } - else if(value instanceof Map) - { - Map<?,?> orig = (Map<?,?>) value; - LinkedHashMap<Object,Object> copy = new LinkedHashMap<>(); - for(Map.Entry<?,?> entry : orig.entrySet()) - { - copy.put(makeImmutable(entry.getKey()),makeImmutable(entry.getValue())); - } - return copy; - } - else return null; - } - - private final QueueReport<T> _report; - - public final T runReport(Queue<?> queue) - { - _report.setQueue(queue); - ReportVisitor visitor = new ReportVisitor(_report); - queue.visit(visitor); - return _report.getReport(); - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessage.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessage.java deleted file mode 100644 index 00b6c4abeb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessage.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.report; - -import java.nio.ByteBuffer; - -public interface ReportableMessage -{ - String getInitialRoutingAddress(); - - ReportableMessageHeader getMessageHeader(); - - public ByteBuffer getContent(); - - boolean isPersistent(); - - long getSize(); - - long getExpiration(); - - long getMessageNumber(); - - long getArrivalTime(); -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessageHeader.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessageHeader.java deleted file mode 100644 index e78415f8d0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessageHeader.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.report; - -import java.util.Collection; -import java.util.Set; - -public interface ReportableMessageHeader -{ - String getCorrelationId(); - - long getExpiration(); - - String getUserId(); - - String getAppId(); - - String getMessageId(); - - String getMimeType(); - - String getEncoding(); - - byte getPriority(); - - long getTimestamp(); - - String getType(); - - String getReplyTo(); - - Object getHeader(String name); - - boolean containsHeaders(Set<String> names); - - boolean containsHeader(String name); - - Collection<String> getHeaderNames(); - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/DefinedFileServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/DefinedFileServlet.java deleted file mode 100644 index 2f6f55e042..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/DefinedFileServlet.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.management.plugin.servlet; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.qpid.server.management.plugin.HttpManagementUtil; - -public class DefinedFileServlet extends HttpServlet -{ - - private static final String FILENAME_INIT_PARAMETER = "filename"; - - private String _filename; - - public DefinedFileServlet() - { - super(); - } - - public DefinedFileServlet(String filename) - { - _filename = filename; - } - - @Override - public void init() throws ServletException - { - ServletConfig config = getServletConfig(); - String fileName = config.getInitParameter(FILENAME_INIT_PARAMETER); - if (fileName != null && !"".equals(fileName)) - { - _filename = fileName; - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - try (OutputStream output = HttpManagementUtil.getOutputStream(request, response)) - { - try(InputStream fileInput = getClass().getResourceAsStream("/resources/" + _filename)) - { - if (fileInput != null) - { - byte[] buffer = new byte[1024]; - response.setStatus(HttpServletResponse.SC_OK); - int read = 0; - - while ((read = fileInput.read(buffer)) > 0) - { - output.write(buffer, 0, read); - } - } - else - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "unknown file: " + _filename); - } - } - } - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/FileServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/FileServlet.java deleted file mode 100644 index 1c741d97e8..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/FileServlet.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.qpid.server.management.plugin.HttpManagementUtil; - -public class FileServlet extends HttpServlet -{ - private static final String RESOURCES_PREFIX = "/resources"; - private static final Map<String, String> CONTENT_TYPES; - - static - { - - Map<String, String> contentTypes = new HashMap<String, String>(); - contentTypes.put("js", "application/javascript"); - contentTypes.put("html", "text/html"); - contentTypes.put("css", "text/css"); - contentTypes.put("json", "application/json"); - contentTypes.put("jpg", "image/jpg"); - contentTypes.put("png", "image/png"); - contentTypes.put("gif", "image/gif"); - CONTENT_TYPES = Collections.unmodifiableMap(contentTypes); - } - - private final String _resourcePathPrefix; - private final boolean _usePathInfo; - - public FileServlet() - { - this(RESOURCES_PREFIX, false); - } - - public FileServlet(String resourcePathPrefix, boolean usePathInfo) - { - _resourcePathPrefix = resourcePathPrefix; - _usePathInfo = usePathInfo; - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - String filename = null; - if(_usePathInfo) - { - filename = request.getPathInfo(); - } - else - { - filename = request.getServletPath(); - } - - if(filename.contains(".")) - { - String suffix = filename.substring(filename.lastIndexOf('.')+1); - String contentType = CONTENT_TYPES.get(suffix); - if(contentType != null) - { - response.setContentType(contentType); - } - } - - URL resourceURL = getClass().getResource(_resourcePathPrefix + filename); - if(resourceURL != null) - { - response.setStatus(HttpServletResponse.SC_OK); - InputStream fileInput = resourceURL.openStream(); - try - { - byte[] buffer = new byte[1024]; - int read = 0; - OutputStream output = HttpManagementUtil.getOutputStream(request, response); - try - { - while((read = fileInput.read(buffer)) != -1) - { - output.write(buffer, 0, read); - } - } - finally - { - output.close(); - } - } - finally - { - fileInput.close(); - } - } - else - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "unknown file"); - } - - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/LogFileServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/LogFileServlet.java deleted file mode 100644 index 321cfae66c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/LogFileServlet.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.qpid.server.management.plugin.servlet; - -import java.io.IOException; -import java.io.OutputStream; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.log4j.LogManager; -import org.apache.qpid.server.management.plugin.log.LogFileDetails; -import org.apache.qpid.server.management.plugin.log.LogFileHelper; -import org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet; - -public class LogFileServlet extends AbstractServlet -{ - private static final String PARAMETER_LOG_FILE = "l"; - - private static final long serialVersionUID = 1L; - - public static final String LOGS_FILE_NAME = "qpid-logs-%s.zip"; - public static final String DATE_FORMAT = "yyyy-MM-dd-mmHHss"; - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, - ServletException - { - response.setHeader("Cache-Control", "no-cache"); - response.setHeader("Pragma", "no-cache"); - response.setDateHeader("Expires", 0); - - if (!getBroker().getSecurityManager().authoriseLogsAccess()) - { - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Log files download is denied"); - return; - } - - String[] requestedFiles = request.getParameterValues(PARAMETER_LOG_FILE); - - if (requestedFiles == null || requestedFiles.length == 0) - { - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - @SuppressWarnings("unchecked") - LogFileHelper helper = new LogFileHelper(Collections.list(LogManager.getRootLogger().getAllAppenders())); - - List<LogFileDetails> logFiles = null; - - try - { - logFiles = helper.findLogFileDetails(requestedFiles); - } - catch(IllegalArgumentException e) - { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - if (logFiles.size() == 0) - { - response.sendError(HttpServletResponse.SC_NOT_FOUND); - return; - } - - String fileName = String.format(LOGS_FILE_NAME, new SimpleDateFormat(DATE_FORMAT).format(new Date())); - response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("Content-Disposition", "attachment;filename=" + fileName); - response.setContentType(LogFileHelper.ZIP_MIME_TYPE); - - OutputStream os = response.getOutputStream(); - try - { - helper.writeLogFiles(logFiles, os); - } - finally - { - if (os != null) - { - os.close(); - } - } - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/ServletConnectionPrincipal.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/ServletConnectionPrincipal.java deleted file mode 100644 index 18a026ec93..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/ServletConnectionPrincipal.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet; - -import org.apache.qpid.server.security.auth.ManagementConnectionPrincipal; -import org.apache.qpid.server.security.auth.SocketConnectionPrincipal; - -import javax.servlet.ServletRequest; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -public class ServletConnectionPrincipal implements ManagementConnectionPrincipal -{ - private final InetSocketAddress _address; - - public ServletConnectionPrincipal(ServletRequest request) - { - _address = new InetSocketAddress(request.getRemoteHost(), request.getRemotePort()); - } - - @Override - public SocketAddress getRemoteAddress() - { - return _address; - } - - @Override - public String getName() - { - return _address.toString(); - } - - @Override - public boolean equals(final Object o) - { - if (this == o) - { - return true; - } - if (o == null || getClass() != o.getClass()) - { - return false; - } - - final ServletConnectionPrincipal that = (ServletConnectionPrincipal) o; - - if (!_address.equals(that._address)) - { - return false; - } - - return true; - } - - @Override - public int hashCode() - { - return _address.hashCode(); - } - - @Override - public String getType() - { - return "HTTP"; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/AbstractServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/AbstractServlet.java deleted file mode 100644 index ef32d352bb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/AbstractServlet.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.Writer; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; - -import javax.security.auth.Subject; -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.management.plugin.HttpManagementConfiguration; -import org.apache.qpid.server.management.plugin.HttpManagementUtil; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; - -public abstract class AbstractServlet extends HttpServlet -{ - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractServlet.class); - - private Broker<?> _broker; - private HttpManagementConfiguration _managementConfiguration; - - protected AbstractServlet() - { - super(); - } - - @Override - public void init() throws ServletException - { - ServletConfig servletConfig = getServletConfig(); - ServletContext servletContext = servletConfig.getServletContext(); - _broker = HttpManagementUtil.getBroker(servletContext); - _managementConfiguration = HttpManagementUtil.getManagementConfiguration(servletContext); - super.init(); - } - - @Override - protected final void doGet(final HttpServletRequest request, final HttpServletResponse resp) - { - doWithSubjectAndActor( - new PrivilegedExceptionAction<Void>() - { - @Override - public Void run() throws Exception - { - doGetWithSubjectAndActor(request, resp); - return null; - } - }, - request, - resp - ); - } - - /** - * Performs the GET action as the logged-in {@link Subject}. - * Subclasses commonly override this method - */ - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException - { - throw new UnsupportedOperationException("GET not supported by this servlet"); - } - - - @Override - protected final void doPost(final HttpServletRequest request, final HttpServletResponse resp) - { - doWithSubjectAndActor( - new PrivilegedExceptionAction<Void>() - { - @Override - public Void run() throws Exception - { - doPostWithSubjectAndActor(request, resp); - return null; - } - }, - request, - resp - ); - } - - /** - * Performs the POST action as the logged-in {@link Subject}. - * Subclasses commonly override this method - */ - protected void doPostWithSubjectAndActor(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException - { - throw new UnsupportedOperationException("POST not supported by this servlet"); - } - - @Override - protected final void doPut(final HttpServletRequest request, final HttpServletResponse resp) - { - doWithSubjectAndActor( - new PrivilegedExceptionAction<Void>() - { - @Override - public Void run() throws Exception - { - doPutWithSubjectAndActor(request, resp); - return null; - } - }, - request, - resp - ); - } - - public Writer getOutputWriter(final HttpServletRequest request, final HttpServletResponse response) - throws IOException - { - return HttpManagementUtil.getOutputWriter(request, response, _managementConfiguration); - } - - public OutputStream getOutputStream(final HttpServletRequest request, final HttpServletResponse response) - throws IOException - { - return HttpManagementUtil.getOutputStream(request, response, _managementConfiguration); - } - - /** - * Performs the PUT action as the logged-in {@link Subject}. - * Subclasses commonly override this method - */ - protected void doPutWithSubjectAndActor(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException - { - throw new UnsupportedOperationException("PUT not supported by this servlet"); - } - - @Override - protected final void doDelete(final HttpServletRequest request, final HttpServletResponse resp) - throws ServletException, IOException - { - doWithSubjectAndActor( - new PrivilegedExceptionAction<Void>() - { - @Override - public Void run() throws Exception - { - doDeleteWithSubjectAndActor(request, resp); - return null; - } - }, - request, - resp - ); - } - - /** - * Performs the PUT action as the logged-in {@link Subject}. - * Subclasses commonly override this method - */ - protected void doDeleteWithSubjectAndActor(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException - { - throw new UnsupportedOperationException("DELETE not supported by this servlet"); - } - - private void doWithSubjectAndActor( - PrivilegedExceptionAction<Void> privilegedExceptionAction, - final HttpServletRequest request, - final HttpServletResponse resp) - { - Subject subject; - try - { - subject = getAuthorisedSubject(request); - } - catch (SecurityException e) - { - sendError(resp, HttpServletResponse.SC_UNAUTHORIZED); - return; - } - - try - { - Subject.doAs(subject, privilegedExceptionAction); - } - catch(RuntimeException e) - { - LOGGER.error("Unable to perform action", e); - throw e; - } - catch (PrivilegedActionException e) - { - LOGGER.error("Unable to perform action", e); - Throwable cause = e.getCause(); - if(cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - if(cause instanceof Error) - { - throw (Error)cause; - } - throw new ConnectionScopedRuntimeException(e.getCause()); - } - } - - protected Subject getAuthorisedSubject(HttpServletRequest request) - { - Subject subject = HttpManagementUtil.getAuthorisedSubject(request.getSession()); - if (subject == null) - { - throw new SecurityException("Access to management rest interfaces is denied for un-authorised user"); - } - return subject; - } - - protected Broker<?> getBroker() - { - return _broker; - } - - protected HttpManagementConfiguration getManagementConfiguration() - { - return _managementConfiguration; - } - - protected void sendError(final HttpServletResponse resp, int errorCode) - { - try - { - resp.sendError(errorCode); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException("Failed to send error response code " + errorCode, e); - } - } - - protected void sendJsonResponse(Object object, HttpServletRequest request, HttpServletResponse response) throws IOException, - JsonGenerationException, JsonMappingException - { - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - response.setContentType("application/json"); - - final Writer writer = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, object); - } - - protected String[] getPathInfoElements(HttpServletRequest request) - { - String pathInfo = request.getPathInfo(); - if (pathInfo != null && pathInfo.length() > 0) - { - return pathInfo.substring(1).split("/"); - } - return null; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/Action.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/Action.java deleted file mode 100644 index 3241a7560e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/Action.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.util.Map; - -import org.apache.qpid.server.model.Broker; - - -public interface Action -{ - String getName(); - Object perform(Map<String, Object> request, Broker broker); -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ApiDocsServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ApiDocsServlet.java deleted file mode 100644 index 5c30378fc6..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ApiDocsServlet.java +++ /dev/null @@ -1,423 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * <p/> - * http://www.apache.org/licenses/LICENSE-2.0 - * <p/> - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.Writer; -import java.security.AccessControlException; -import java.util.*; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.Part; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.AbstractConfiguredObject; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredAutomatedAttribute; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ConfiguredObjectAttribute; -import org.apache.qpid.server.model.IllegalStateTransitionException; -import org.apache.qpid.server.model.IntegrityViolationException; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.Model; -import org.apache.qpid.server.util.urlstreamhandler.data.Handler; -import org.apache.qpid.server.virtualhost.ExchangeExistsException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.apache.qpid.util.DataUrlUtils; - -public class ApiDocsServlet extends AbstractServlet -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ApiDocsServlet.class); - private final Model _model; - private final List<Class<? extends ConfiguredObject>> _types; - - private Class<? extends ConfiguredObject>[] _hierarchy; - - private static final Set<Character> VOWELS = new HashSet<>(Arrays.asList('a','e','i','o','u')); - - public static final Comparator<Class<? extends ConfiguredObject>> CLASS_COMPARATOR = - new Comparator<Class<? extends ConfiguredObject>>() - { - @Override - public int compare(final Class<? extends ConfiguredObject> o1, - final Class<? extends ConfiguredObject> o2) - { - return o1.getSimpleName().compareTo(o2.getSimpleName()); - } - - }; - private static final Map<Class<? extends ConfiguredObject>, List<String>> REGISTERED_CLASSES = new TreeMap<>(CLASS_COMPARATOR); - - - public ApiDocsServlet(final Model model, final List<String> registeredPaths, Class<? extends ConfiguredObject>... hierarchy) - { - super(); - _model = model; - _hierarchy = hierarchy; - _types = hierarchy.length == 0 ? null : new ArrayList<>(_model.getTypeRegistry().getTypeSpecialisations(getConfiguredClass())); - if(_types != null) - { - Collections.sort(_types, CLASS_COMPARATOR); - } - if(_hierarchy.length != 0) - { - List<String> paths = REGISTERED_CLASSES.get(getConfiguredClass()); - if(paths == null) - { - paths = new ArrayList<>(); - REGISTERED_CLASSES.put(getConfiguredClass(), paths); - } - paths.addAll(registeredPaths); - - } - - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - response.setContentType("text/html"); - response.setStatus(HttpServletResponse.SC_OK); - - - PrintWriter writer = response.getWriter(); - - writePreamble(writer); - writeHead(writer); - - if(_hierarchy.length == 0) - { - writer.println("<table class=\"api\">"); - writer.println("<thead>"); - writer.println("<tr>"); - writer.println("<th class=\"type\">Type</th>"); - writer.println("<th class=\"path\">Path</th>"); - writer.println("<th class=\"description\">Description</th>"); - writer.println("</tr>"); - writer.println("</thead>"); - writer.println("<tbody>"); - for(Map.Entry<Class<? extends ConfiguredObject>, List<String>> entry : REGISTERED_CLASSES.entrySet()) - { - List<String> paths = entry.getValue(); - Class<? extends ConfiguredObject> objClass = entry.getKey(); - writer.println("<tr>"); - writer.println("<td class=\"type\" rowspan=\""+ paths.size()+"\"><a href=\"latest/"+ objClass.getSimpleName().toLowerCase()+"\">"+objClass.getSimpleName()+"</a></td>"); - writer.println("<td class=\"path\">" + paths.get(0) + "</td>"); - writer.println("<td class=\"description\" rowspan=\""+ paths.size()+"\">"+ - objClass.getAnnotation(ManagedObject.class).description()+"</td>"); - writer.println("</tr>"); - for(int i = 1; i < paths.size(); i++) - { - writer.println("<tr>"); - writer.println("<td class=\"path\">" + paths.get(i) + "</td>"); - writer.println("</tr>"); - } - - } - writer.println("</tbody>"); - writer.println("</table>"); - - } - else - { - writeCategoryDescription(writer); - writeUsage(writer, request); - writeTypes(writer); - writeAttributes(writer); - } - - writeFoot(writer); - } - - private void writePreamble(final PrintWriter writer) - { - writer.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\""); - writer.println("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"); - writer.println("<html>"); - - - } - - private void writeHead(final PrintWriter writer) - { - writer.println("<head>"); - writer.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/apidocs.css\">"); - writeTitle(writer); - - writer.println("</head>"); - writer.println("<body>"); - } - - private void writeTitle(final PrintWriter writer) - { - writer.print("<title>"); - if(_hierarchy.length == 0) - { - writer.print("Qpid API"); - } - else - { - writer.print("Qpid API: " + getConfiguredClass().getSimpleName()); - } - writer.println("</title>"); - } - - private void writeCategoryDescription(PrintWriter writer) - { - writer.println("<h1>"+getConfiguredClass().getSimpleName()+"</h1>"); - writer.println(getConfiguredClass().getAnnotation(ManagedObject.class).description()); - } - - private void writeUsage(final PrintWriter writer, final HttpServletRequest request) - { - writer.println("<a name=\"usage\"><h2>Usage</h2></a>"); - writer.println("<table class=\"usage\">"); - writer.println("<tbody>"); - writer.print("<tr><th class=\"operation\">Read</th><td class=\"method\">GET</td><td class=\"path\">" + request.getServletPath() - .replace("apidocs", "api")); - - for (final Class<? extends ConfiguredObject> category : _hierarchy) - { - writer.print("[/<" + category.getSimpleName().toLowerCase() + " name or id>"); - } - for(int i = 0; i < _hierarchy.length; i++) - { - writer.print("] "); - } - writer.println("</td></tr>"); - - writer.print("<tr><th class=\"operation\">Update</th><td class=\"method\">PUT or POST</td><td class=\"path\">" - + request.getServletPath().replace("apidocs", "api")); - for (final Class<? extends ConfiguredObject> category : _hierarchy) - { - writer.print("/<" + category.getSimpleName().toLowerCase() + " name or id>"); - } - - writer.print( - "<tr><th class=\"operation\">Create</th><td class=\"method\">PUT or POST</td><td class=\"path\">" - + request.getServletPath().replace("apidocs", "api")); - for (int i = 0; i < _hierarchy.length - 1; i++) - { - writer.print("/<" + _hierarchy[i].getSimpleName().toLowerCase() + " name or id>"); - } - - writer.print("<tr><th class=\"operation\">Delete</th><td class=\"method\">DELETE</td><td class=\"path\">" - + request.getServletPath().replace("apidocs", "api")); - for (final Class<? extends ConfiguredObject> category : _hierarchy) - { - writer.print("/<" + category.getSimpleName().toLowerCase() + " name or id>"); - } - - writer.println("</tbody>"); - writer.println("</table>"); - - } - - - private void writeTypes(final PrintWriter writer) - { - if(!_types.isEmpty() && !(_types.size() == 1 && getTypeName(_types.iterator().next()).trim().equals(""))) - { - writer.println("<a name=\"types\"><h2>Types</h2></a>"); - writer.println("<table class=\"types\">"); - writer.println("<thead>"); - writer.println("<tr><th class=\"type\">Type</th><th class=\"description\">Description</th></tr>"); - writer.println("</thead>"); - - writer.println("<tbody>"); - for (Class<? extends ConfiguredObject> type : _types) - { - writer.print("<tr><td class=\"type\">"); - writer.print(getTypeName(type)); - writer.print("</td><td class=\"description\">"); - writer.print(type.getAnnotation(ManagedObject.class).description()); - writer.println("</td></tr>"); - - } - writer.println("</tbody>"); - } - - writer.println("</table>"); - } - - private String getTypeName(final Class<? extends ConfiguredObject> type) - { - return type.getAnnotation(ManagedObject.class).type() == null - ? _model.getTypeRegistry().getTypeClass(type).getSimpleName() - : type.getAnnotation(ManagedObject.class).type(); - } - - private void writeAttributes(final PrintWriter writer) - { - writer.println("<a name=\"types\"><h2>Attributes</h2></a>"); - writer.println("<h2>Common Attributes</h2>"); - - writeAttributesTable(writer, _model.getTypeRegistry().getAttributeTypes(getConfiguredClass()).values()); - - for(Class<? extends ConfiguredObject> type : _types) - { - - ManagedObject typeAnnotation = type.getAnnotation(ManagedObject.class); - String typeName = typeAnnotation.type() == null ? _model.getTypeRegistry().getTypeClass(type).getSimpleName() : typeAnnotation.type(); - Collection<ConfiguredObjectAttribute<?, ?>> typeSpecificAttributes = - _model.getTypeRegistry().getTypeSpecificAttributes(type); - if(!typeSpecificAttributes.isEmpty()) - { - writer.println("<h2><span class=\"type\">"+typeName+"</span> Specific Attributes</h2>"); - writeAttributesTable(writer, typeSpecificAttributes); - } - - - } - - } - - private void writeAttributesTable(final PrintWriter writer, - final Collection<ConfiguredObjectAttribute<?, ?>> attributeTypes) - { - writer.println("<table class=\"attributes\">"); - writer.println("<thead>"); - writer.println("<tr><th class=\"name\">Attribute Name</th><th class=\"type\">Type</th><th class=\"description\">Description</th></tr>"); - writer.println("</thead>"); - writer.println("<tbody>"); - - for(ConfiguredObjectAttribute attribute : attributeTypes) - { - if(!attribute.isDerived()) - { - writer.println("<tr><td class=\"name\">" - + attribute.getName() - + "</td><td class=\"type\">" - + renderType(attribute) - + "</td class=\"description\"><td>" - + attribute.getDescription() - + "</td></tr>"); - } - } - writer.println("</tbody>"); - - writer.println("</table>"); - - } - - private String renderType(final ConfiguredObjectAttribute attribute) - { - final Class type = attribute.getType(); - if(Enum.class.isAssignableFrom(type)) - { - return "<div class=\"restriction\" title=\"enum: " + EnumSet.allOf(type) + "\">string</div>"; - } - else if(ConfiguredObject.class.isAssignableFrom(type)) - { - return "<div class=\"restriction\" title=\"name or id of a" + (VOWELS.contains(type.getSimpleName().toLowerCase().charAt(0)) ? "n " : " ") + type.getSimpleName() + "\">string</div>"; - } - else if(UUID.class == type) - { - return "<div class=\"restriction\" title=\"must be a UUID\">string</div>"; - } - else - { - boolean hasValuesRestriction = attribute instanceof ConfiguredAutomatedAttribute - && ((ConfiguredAutomatedAttribute)attribute).hasValidValues(); - - StringBuilder returnVal = new StringBuilder(); - if(hasValuesRestriction) - { - returnVal.append("<div class=\"restricted\" title=\"Valid values: " + ((ConfiguredAutomatedAttribute)attribute).validValues() + "\">"); - } - - if(Number.class.isAssignableFrom(type)) - { - returnVal.append("number"); - } - else if(Boolean.class == type) - { - returnVal.append("boolean"); - } - else if(String.class == type) - { - returnVal.append("string"); - } - else if(Collection.class.isAssignableFrom(type)) - { - // TODO - generate a description of the type in the array - returnVal.append("array"); - } - else if(Map.class.isAssignableFrom(type)) - { - // TODO - generate a description of the type in the object - returnVal.append("object"); - } - else - { - returnVal.append(type.getSimpleName()); - } - if(hasValuesRestriction) - { - returnVal.append("</div>"); - } - return returnVal.toString(); - } - } - - private void writeFoot(final PrintWriter writer) - { - writer.println("</body>"); - writer.println("</html>"); - } - private Class<? extends ConfiguredObject> getConfiguredClass() - { - return _hierarchy.length == 0 ? Broker.class : _hierarchy[_hierarchy.length-1]; - } - - - private int getIntParameterFromRequest(final HttpServletRequest request, - final String paramName, - final int defaultValue) - { - int intValue = defaultValue; - final String stringValue = request.getParameter(paramName); - if(stringValue!=null) - { - try - { - intValue = Integer.parseInt(stringValue); - } - catch (NumberFormatException e) - { - LOGGER.warn("Could not parse " + stringValue + " as integer for parameter " + paramName); - } - } - return intValue; - } - - private boolean getBooleanParameterFromRequest(HttpServletRequest request, final String paramName) - { - return Boolean.parseBoolean(request.getParameter(paramName)); - } - - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ConfiguredObjectToMapConverter.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ConfiguredObjectToMapConverter.java deleted file mode 100644 index 0f1b7d03e9..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ConfiguredObjectToMapConverter.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ConfiguredObjectAttribute; -import org.apache.qpid.server.model.Model; - -public class ConfiguredObjectToMapConverter -{ - /** Name of the key used for the statistics map */ - public static final String STATISTICS_MAP_KEY = "statistics"; - - private static Set<String> CONFIG_EXCLUDED_ATTRIBUTES = - new HashSet<>(Arrays.asList(ConfiguredObject.ID, - ConfiguredObject.DURABLE, - ConfiguredObject.CREATED_BY, - ConfiguredObject.CREATED_TIME, - ConfiguredObject.LAST_UPDATED_BY, - ConfiguredObject.LAST_UPDATED_TIME)); - - public Map<String, Object> convertObjectToMap(final ConfiguredObject<?> confObject, - Class<? extends ConfiguredObject> clazz, - int depth, - final boolean useActualValues, - final boolean inheritedActuals, - final boolean includeSystemContext, - final boolean extractAsConfig, - final int oversizeThreshold, - final boolean isSecureTransport - ) - { - Map<String, Object> object = new LinkedHashMap<>(); - - incorporateAttributesIntoMap(confObject, object, useActualValues, inheritedActuals, includeSystemContext, - extractAsConfig, oversizeThreshold, isSecureTransport); - if(!extractAsConfig) - { - incorporateStatisticsIntoMap(confObject, object); - } - - if(depth > 0) - { - incorporateChildrenIntoMap(confObject, clazz, depth, object, useActualValues, inheritedActuals, - includeSystemContext, extractAsConfig, oversizeThreshold, isSecureTransport); - } - return object; - } - - - private void incorporateAttributesIntoMap( - final ConfiguredObject<?> confObject, - Map<String, Object> object, - final boolean useActualValues, - final boolean inheritedActuals, - final boolean includeSystemContext, - final boolean extractAsConfig, - final int oversizeThreshold, - final boolean isSecureTransport) - { - // if extracting as config add a fake attribute for each secondary parent - if(extractAsConfig && confObject.getModel().getParentTypes(confObject.getCategoryClass()).size()>1) - { - Iterator<Class<? extends ConfiguredObject>> parentClasses = - confObject.getModel().getParentTypes(confObject.getCategoryClass()).iterator(); - - // ignore the first parent which is supplied by structure - parentClasses.next(); - - while(parentClasses.hasNext()) - { - Class<? extends ConfiguredObject> parentClass = parentClasses.next(); - ConfiguredObject parent = confObject.getParent(parentClass); - if(parent != null) - { - String categoryName = parentClass.getSimpleName(); - object.put(categoryName.substring(0,1).toLowerCase()+categoryName.substring(1), parent.getName()); - } - } - } - - for(String name : confObject.getAttributeNames()) - { - if (!(extractAsConfig && CONFIG_EXCLUDED_ATTRIBUTES.contains(name))) - { - Object value = - useActualValues ? confObject.getActualAttributes().get(name) : confObject.getAttribute(name); - if (value instanceof ConfiguredObject) - { - object.put(name, ((ConfiguredObject) value).getName()); - } - else if (ConfiguredObject.CONTEXT.equals(name)) - { - Map<String, Object> contextValues = new HashMap<>(); - if (useActualValues) - { - collectContext(contextValues, confObject.getModel(), confObject, inheritedActuals); - } - else - { - for (String contextName : confObject.getContextKeys(!includeSystemContext)) - { - contextValues.put(contextName, confObject.getContextValue(String.class, contextName)); - } - } - if (!contextValues.isEmpty()) - { - object.put(ConfiguredObject.CONTEXT, contextValues); - } - } - else if (value instanceof Collection) - { - List<Object> converted = new ArrayList<>(); - for (Object member : (Collection) value) - { - if (member instanceof ConfiguredObject) - { - converted.add(((ConfiguredObject) member).getName()); - } - else - { - converted.add(member); - } - } - object.put(name, converted); - } - else if (value != null) - { - ConfiguredObjectAttribute<?, ?> attribute = confObject.getModel() - .getTypeRegistry() - .getAttributeTypes(confObject.getClass()) - .get(name); - - if (attribute.isSecureValue(value) && !(isSecureTransport && extractAsConfig)) - { - // do not expose actual secure attribute value - // getAttribute() returns encoded value - value = confObject.getAttribute(name); - } - - if(attribute.isOversized() && !extractAsConfig && !useActualValues) - { - String valueString = String.valueOf(value); - if(valueString.length() > oversizeThreshold) - { - - String replacementValue = "".equals(attribute.getOversizedAltText()) - ? String.valueOf(value).substring(0, oversizeThreshold - 4) + "..." - : attribute.getOversizedAltText(); - - object.put(name, replacementValue); - } - else - { - object.put(name, value); - } - } - else - { - object.put(name, value); - } - } - else if (extractAsConfig) - { - ConfiguredObjectAttribute<?, ?> attribute = confObject.getModel() - .getTypeRegistry() - .getAttributeTypes(confObject.getClass()) - .get(name); - - if(attribute.isPersisted() && attribute.isDerived()) - { - object.put(name, confObject.getAttribute(name)); - } - } - } - } - } - - private void collectContext(Map<String, Object> contextValues, Model model, ConfiguredObject<?> confObject, boolean inheritedContext) - { - Object value = confObject.getActualAttributes().get(ConfiguredObject.CONTEXT); - if (inheritedContext) - { - Collection<Class<? extends ConfiguredObject>> parents = model.getParentTypes(confObject.getCategoryClass()); - if(parents != null && !parents.isEmpty()) - { - ConfiguredObject parent = confObject.getParent(parents.iterator().next()); - if(parent != null) - { - collectContext(contextValues, model, parent, inheritedContext); - } - } - } - if (value instanceof Map) - { - contextValues.putAll((Map<String,String>)value); - } - } - - private void incorporateStatisticsIntoMap( - final ConfiguredObject<?> confObject, Map<String, Object> object) - { - - Map<String, Object> statMap = new TreeMap<String,Object>(confObject.getStatistics()); - - if(!statMap.isEmpty()) - { - object.put(STATISTICS_MAP_KEY, statMap); - } - - } - - private void incorporateChildrenIntoMap( - final ConfiguredObject confObject, - Class<? extends ConfiguredObject> clazz, - int depth, - Map<String, Object> object, - final boolean useActualValues, - final boolean inheritedActuals, - final boolean includeSystemContext, - final boolean extractAsConfig, - final int oversizeThreshold, - final boolean isSecure) - { - List<Class<? extends ConfiguredObject>> childTypes = new ArrayList<>(confObject.getModel().getChildTypes(clazz)); - - Collections.sort(childTypes, new Comparator<Class<? extends ConfiguredObject>>() - { - @Override - public int compare(final Class<? extends ConfiguredObject> o1, final Class<? extends ConfiguredObject> o2) - { - return o1.getSimpleName().compareTo(o2.getSimpleName()); - } - }); - for(Class<? extends ConfiguredObject> childClass : childTypes) - { - if(!(extractAsConfig && confObject.getModel().getParentTypes(childClass).iterator().next() != confObject.getCategoryClass())) - { - - Collection children = confObject.getChildren(childClass); - if(children != null) - { - List<? extends ConfiguredObject> sortedChildren = new ArrayList<ConfiguredObject>(children); - Collections.sort(sortedChildren, new Comparator<ConfiguredObject>() - { - @Override - public int compare(final ConfiguredObject o1, final ConfiguredObject o2) - { - return o1.getName().compareTo(o2.getName()); - } - }); - - List<Map<String, Object>> childObjects = new ArrayList<>(); - - for (ConfiguredObject child : sortedChildren) - { - if (!(extractAsConfig && !child.isDurable())) - { - childObjects.add(convertObjectToMap(child, - childClass, - depth - 1, - useActualValues, - inheritedActuals, - includeSystemContext, - extractAsConfig, - oversizeThreshold, - isSecure)); - } - } - - if (!childObjects.isEmpty()) - { - String childTypeSingular = childClass.getSimpleName().toLowerCase(); - object.put(childTypeSingular + (childTypeSingular.endsWith("s") ? "es" : "s"), childObjects); - } - } - } - } - } - - - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/HelperServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/HelperServlet.java deleted file mode 100644 index cafde3b7f9..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/HelperServlet.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -import org.apache.qpid.server.management.plugin.servlet.rest.action.ListAccessControlProviderAttributes; -import org.apache.qpid.server.management.plugin.servlet.rest.action.ListBrokerAttribute; -import org.apache.qpid.server.management.plugin.servlet.rest.action.ListGroupProviderAttributes; -import org.apache.qpid.server.management.plugin.servlet.rest.action.ListTimeZones; -import org.apache.qpid.server.model.Broker; - -public class HelperServlet extends AbstractServlet -{ - private static final long serialVersionUID = 1L; - - private static final String PARAM_ACTION = "action"; - - private Map<String, Action> _actions; - private ObjectMapper _mapper; - - public HelperServlet() - { - _mapper = new ObjectMapper(); - _mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - - Action[] supportedActions = { - new ListBrokerAttribute(Broker.PRODUCT_VERSION, "version"), - new ListGroupProviderAttributes(), - new ListAccessControlProviderAttributes(), - new PluginClassProviderAction(), - new ListTimeZones() - }; - - _actions = new HashMap<String, Action>(); - - for(Action action : supportedActions) - { - _actions.put(action.getName(), action); - } - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, - IOException - { - perform(request, response); - } - - @Override - protected void doPostWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, - IOException - { - perform(request, response); - } - - private void perform(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - String actionName = request.getParameter(PARAM_ACTION); - Action action = _actions.get(actionName); - if (action == null) - { - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - - Map<String, Object> parameters = new HashMap<String, Object>(); - @SuppressWarnings("unchecked") - Enumeration<String> names = request.getParameterNames(); - while (names.hasMoreElements()) - { - String name = (String) names.nextElement(); - String[] values = request.getParameterValues(name); - if (values.length == 1) - { - parameters.put(name, values[0]); - } - else - { - parameters.put(name, values); - } - } - - Object output = action.perform(parameters, getBroker()); - if (output == null) - { - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - response.setContentType("application/json"); - final Writer writer = getOutputWriter(request, response); - _mapper.writeValue(writer, output); - - response.setStatus(HttpServletResponse.SC_OK); - - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/KeyComparator.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/KeyComparator.java deleted file mode 100644 index 3d862ce321..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/KeyComparator.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.util.Comparator; -import java.util.Map; - -class KeyComparator implements Comparator<Map> -{ - private String _key; - - public KeyComparator(final String key) - { - _key = key; - } - - public int compare(final Map o1, final Map o2) - { - Comparable left = (Comparable) o1.get(_key); - Comparable right = (Comparable) o2.get(_key); - - int result; - if(left == null) - { - result = right == null ? 0 : -1; - } - else - { - result = left.compareTo(right); - } - - return result; - - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogFileListingServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogFileListingServlet.java deleted file mode 100644 index a7889e4890..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogFileListingServlet.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.util.Collections; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.log4j.LogManager; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -import org.apache.qpid.server.management.plugin.log.LogFileDetails; -import org.apache.qpid.server.management.plugin.log.LogFileHelper; - -public class LogFileListingServlet extends AbstractServlet -{ - private static final long serialVersionUID = 1L; - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, - ServletException - { - response.setHeader("Cache-Control", "no-cache"); - response.setHeader("Pragma", "no-cache"); - response.setDateHeader("Expires", 0); - - if (!getBroker().getSecurityManager().authoriseLogsAccess()) - { - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Log files access is denied"); - return; - } - - @SuppressWarnings("unchecked") - LogFileHelper helper = new LogFileHelper(Collections.list(LogManager.getRootLogger().getAllAppenders())); - List<LogFileDetails> logFiles = helper.getLogFileDetails(false); - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - final Writer writer = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, logFiles); - - response.setStatus(HttpServletResponse.SC_OK); - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogRecordsServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogRecordsServlet.java deleted file mode 100644 index b9d58c8868..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogRecordsServlet.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -import org.apache.qpid.server.logging.LogRecorder; - -public class LogRecordsServlet extends AbstractServlet -{ - private static final long serialVersionUID = 2L; - - public static final String PARAM_LAST_LOG_ID = "lastLogId"; - - public LogRecordsServlet() - { - super(); - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - - if (!getBroker().getSecurityManager().authoriseLogsAccess()) - { - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Broker logs access is denied"); - return; - } - - long lastLogId = 0; - try - { - lastLogId = Long.parseLong(request.getParameter(PARAM_LAST_LOG_ID)); - } - catch(Exception e) - { - // ignore null and incorrect parameter values - } - - List<Map<String,Object>> logRecords = new ArrayList<Map<String, Object>>(); - - LogRecorder logRecorder = getBroker().getLogRecorder(); - for(LogRecorder.Record record : logRecorder) - { - if (record.getId() > lastLogId) - { - logRecords.add(logRecordToObject(record)); - } - } - - final Writer writer = getOutputWriter(request,response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, logRecords); - - response.setStatus(HttpServletResponse.SC_OK); - - } - - private Map<String, Object> logRecordToObject(LogRecorder.Record record) - { - Map<String, Object> recordMap = new LinkedHashMap<String, Object>(); - recordMap.put("id",record.getId()); - recordMap.put("timestamp", record.getTimestamp()); - recordMap.put("level", record.getLevel()); - recordMap.put("thread", record.getThreadName()); - recordMap.put("logger", record.getLogger()); - recordMap.put("message", record.getMessage()); - return recordMap; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LoggedOnUserPreferencesServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LoggedOnUserPreferencesServlet.java deleted file mode 100644 index 6984a32e09..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LoggedOnUserPreferencesServlet.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.net.SocketAddress; -import java.security.Principal; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.security.auth.Subject; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; - -import org.apache.qpid.server.management.plugin.HttpManagementUtil; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; - -public class LoggedOnUserPreferencesServlet extends AbstractServlet -{ - private static final long serialVersionUID = 1L; - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, - ServletException - { - PreferencesProvider preferencesProvider = getPreferencesProvider(request); - if (preferencesProvider == null) - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Preferences provider is not configured"); - return; - } - String userName = getAuthenticatedUserName(request); - Map<String, Object> preferences = preferencesProvider.getPreferences(userName); - if (preferences == null) - { - preferences = Collections.<String, Object>emptyMap(); - } - sendJsonResponse(preferences, request, response); - } - - /* - * replace preferences - */ - @Override - protected void doPutWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException - { - PreferencesProvider preferencesProvider = getPreferencesProvider(request); - if (preferencesProvider == null) - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Preferences provider is not configured"); - return; - } - String userName = getAuthenticatedUserName(request); - - ObjectMapper mapper = new ObjectMapper(); - - @SuppressWarnings("unchecked") - Map<String, Object> newPreferences = mapper.readValue(request.getInputStream(), LinkedHashMap.class); - - preferencesProvider.deletePreferences(userName); - Map<String, Object> preferences = preferencesProvider.setPreferences(userName, newPreferences); - if (preferences == null) - { - preferences = Collections.<String, Object>emptyMap(); - } - sendJsonResponse(preferences, request, response); - } - - /* - * update preferences - */ - @Override - protected void doPostWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException - { - PreferencesProvider preferencesProvider = getPreferencesProvider(request); - if (preferencesProvider == null) - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Preferences provider is not configured"); - return; - } - String userName = getAuthenticatedUserName(request); - - ObjectMapper mapper = new ObjectMapper(); - - @SuppressWarnings("unchecked") - Map<String, Object> newPreferences = mapper.readValue(request.getInputStream(), LinkedHashMap.class); - Map<String, Object> preferences = preferencesProvider.setPreferences(userName, newPreferences); - if (preferences == null) - { - preferences = Collections.<String, Object>emptyMap(); - } - sendJsonResponse(preferences, request, response); - } - - private String getAuthenticatedUserName(HttpServletRequest request) - { - Subject subject = getAuthorisedSubject(request); - Principal principal = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); - return principal.getName(); - } - - private PreferencesProvider getPreferencesProvider(HttpServletRequest request) - { - AuthenticationProvider authenticationProvider = getManagementConfiguration().getAuthenticationProvider(request); - if (authenticationProvider == null) - { - throw new IllegalStateException("Authentication provider is not found"); - } - return authenticationProvider.getPreferencesProvider(); - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogoutServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogoutServlet.java deleted file mode 100644 index 34b115ed13..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogoutServlet.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.qpid.server.management.plugin.HttpManagementUtil; - -@SuppressWarnings("serial") -public class LogoutServlet extends HttpServlet -{ - public static final String RETURN_URL_INIT_PARAM = "qpid.webui_logout_redirect"; - private String _returnUrl = HttpManagementUtil.ENTRY_POINT_PATH; - - @Override - public void init(ServletConfig config) throws ServletException - { - super.init(config); - - String initValue = config.getServletContext().getInitParameter(RETURN_URL_INIT_PARAM); - if(initValue != null) - { - _returnUrl = initValue; - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException - { - HttpSession session = request.getSession(false); - if(session != null) - { - // Invalidating the session will cause LoginLogoutReporter to log the user logoff. - session.invalidate(); - } - - resp.sendRedirect(_returnUrl); - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MapComparator.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MapComparator.java deleted file mode 100644 index 84d987813b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MapComparator.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.util.Collections; -import java.util.Comparator; -import java.util.Map; - -class MapComparator implements Comparator<Map> -{ - private Comparator<Map>[] _sortKeys; - - public MapComparator(final String[] sortKeys) - { - _sortKeys = parseKeys(sortKeys); - } - - private static Comparator<Map>[] parseKeys(final String[] sortKeys) - { - Comparator<Map>[] comparators = new Comparator[sortKeys.length]; - for(int i = 0; i < sortKeys.length; i++) - { - String key = sortKeys[i]; - - if(key.startsWith("+") || key.startsWith(" ")) - { - comparators[i] = new KeyComparator(key.substring(1)); - } - else if(key.startsWith("-")) - { - comparators[i] = Collections.reverseOrder(new KeyComparator(key.substring(1))); - } - else - { - comparators[i] = new KeyComparator(key); - } - } - return comparators; - } - - - public int compare(final Map o1, final Map o2) - { - int result = 0; - for(int i = 0; i < _sortKeys.length; i++) - { - result = _sortKeys[i].compare(o1, o2); - if(result != 0) - { - return result; - } - } - return 0; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageContentServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageContentServlet.java deleted file mode 100644 index db58e49eeb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageContentServlet.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.nio.ByteBuffer; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.qpid.server.message.MessageDeletedException; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.queue.QueueEntryVisitor; - -public class MessageContentServlet extends AbstractServlet -{ - public MessageContentServlet() - { - super(); - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements != null && pathInfoElements.length > 2) - { - getMessageContent(request, response); - } - - } - - private void getMessageContent(HttpServletRequest request, HttpServletResponse response) throws IOException - { - Queue queue = getQueueFromRequest(request); - String path[] = getPathInfoElements(request); - MessageFinder finder = new MessageFinder(Long.parseLong(path[2])); - queue.visit(finder); - if(finder.isFound()) - { - response.setContentType(finder.getMimeType()); - response.setContentLength((int) finder.getSize()); - getOutputStream(request, response).write(finder.getContent()); - - } - - } - - private Queue getQueueFromRequest(HttpServletRequest request) - { - // TODO - validation that there is a vhost and queue and only those in the path - - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements == null || pathInfoElements.length < 2) - { - throw new IllegalArgumentException("Invalid path is specified"); - } - String vhostName = pathInfoElements[0]; - String queueName = pathInfoElements[1]; - - VirtualHost<?,?,?> vhost = getBroker().findVirtualHostByName(vhostName); - if (vhost == null) - { - throw new IllegalArgumentException("Could not find virtual host with name '" + vhostName + "'"); - } - return getQueueFromVirtualHost(queueName, vhost); - } - - private Queue getQueueFromVirtualHost(String queueName, VirtualHost<?,?,?> vhost) - { - Queue queue = null; - - for(Queue q : vhost.getQueues()) - { - if(q.getName().equals(queueName)) - { - queue = q; - break; - } - } - return queue; - } - - private class MessageFinder implements QueueEntryVisitor - { - private final long _messageNumber; - private String _mimeType; - private long _size; - private byte[] _content; - private boolean _found; - - private MessageFinder(long messageNumber) - { - _messageNumber = messageNumber; - } - - - public boolean visit(QueueEntry entry) - { - ServerMessage message = entry.getMessage(); - if(message != null) - { - if(_messageNumber == message.getMessageNumber()) - { - try - { - MessageReference reference = message.newReference(); - try - { - _mimeType = message.getMessageHeader().getMimeType(); - _size = message.getSize(); - _content = new byte[(int) _size]; - _found = true; - message.getContent(ByteBuffer.wrap(_content), 0); - } - finally - { - reference.release(); - } - return true; - } - catch (MessageDeletedException e) - { - // ignore - the message was deleted as we tried too look at it, treat as if no message found - } - } - - } - return false; - } - - public String getMimeType() - { - return _mimeType; - } - - public long getSize() - { - return _size; - } - - public byte[] getContent() - { - return _content; - } - - public boolean isFound() - { - return _found; - } - } - - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageServlet.java deleted file mode 100644 index 38f7ef06bc..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageServlet.java +++ /dev/null @@ -1,568 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.security.AccessControlException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.MessageDeletedException; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.queue.QueueEntryVisitor; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.store.TransactionLogResource; - -public class MessageServlet extends AbstractServlet -{ - private static final Logger LOGGER = LoggerFactory.getLogger(MessageServlet.class); - - public MessageServlet() - { - super(); - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements != null && pathInfoElements.length > 2) - { - getMessageContent(request, response); - } - else - { - getMessageList(request, response); - } - - } - - private void getMessageContent(HttpServletRequest request, HttpServletResponse response) throws IOException - { - Queue queue = getQueueFromRequest(request); - String path[] = getPathInfoElements(request); - MessageFinder messageFinder = new MessageFinder(Long.parseLong(path[2])); - queue.visit(messageFinder); - - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - response.setContentType("application/json"); - - final Writer writer = getOutputWriter(request,response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, messageFinder.getMessageObject()); - } - - private void getMessageList(HttpServletRequest request, HttpServletResponse response) throws IOException - { - Queue queue = getQueueFromRequest(request); - - int first = -1; - int last = -1; - String range = request.getHeader("Range"); - if(range != null) - { - String[] boundaries = range.split("=")[1].split("-"); - first = Integer.parseInt(boundaries[0]); - last = Integer.parseInt(boundaries[1]); - } - final MessageCollector messageCollector = new MessageCollector(first, last); - queue.visit(messageCollector); - - response.setContentType("application/json"); - final List<Map<String, Object>> messages = messageCollector.getMessages(); - int queueSize = (int) queue.getQueueDepthMessages(); - String min = messages.isEmpty() ? "0" : messages.get(0).get("position").toString(); - String max = messages.isEmpty() ? "0" : messages.get(messages.size()-1).get("position").toString(); - response.setHeader("Content-Range", (min + "-" + max + "/" + queueSize)); - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - - final Writer writer = getOutputWriter(request,response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, messages); - } - - private Queue<?> getQueueFromRequest(HttpServletRequest request) - { - // TODO - validation that there is a vhost and queue and only those in the path - - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements == null || pathInfoElements.length < 2) - { - throw new IllegalArgumentException("Invalid path is specified"); - } - String vhostName = pathInfoElements[0]; - String queueName = pathInfoElements[1]; - - VirtualHost<?,?,?> vhost = getBroker().findVirtualHostByName(vhostName); - if (vhost == null) - { - throw new IllegalArgumentException("Could not find virtual host with name '" + vhostName + "'"); - } - - Queue queueFromVirtualHost = getQueueFromVirtualHost(queueName, vhost); - if (queueFromVirtualHost == null) - { - throw new IllegalArgumentException("Could not find queue with name '" + queueName + "' on virtual host '" + vhost.getName() + "'"); - } - return queueFromVirtualHost; - } - - private Queue getQueueFromVirtualHost(String queueName, VirtualHost<?,?,?> vhost) - { - Queue queue = null; - - for(Queue<?> q : vhost.getQueues()) - { - - if(q.getName().equals(queueName)) - { - queue = q; - break; - } - } - return queue; - } - - private abstract static class QueueEntryTransaction implements VirtualHost.TransactionalOperation - { - private final Queue _sourceQueue; - private final List _messageIds; - - protected QueueEntryTransaction(Queue sourceQueue, List messageIds) - { - _sourceQueue = sourceQueue; - _messageIds = messageIds; - } - - @Override - public void withinTransaction(final VirtualHost.Transaction txn) - { - - _sourceQueue.visit(new QueueEntryVisitor() - { - - public boolean visit(final QueueEntry entry) - { - final ServerMessage message = entry.getMessage(); - if(message != null) - { - final long messageId = message.getMessageNumber(); - if (_messageIds.remove(messageId) || (messageId <= (long) Integer.MAX_VALUE - && _messageIds.remove(Integer.valueOf((int)messageId)))) - { - updateEntry(entry, txn); - } - } - return _messageIds.isEmpty(); - } - }); - } - - - protected abstract void updateEntry(QueueEntry entry, VirtualHost.Transaction txn); - } - - private static class MoveTransaction extends QueueEntryTransaction - { - private final Queue _destinationQueue; - - public MoveTransaction(Queue sourceQueue, List<Long> messageIds, Queue destinationQueue) - { - super(sourceQueue, messageIds); - _destinationQueue = destinationQueue; - } - - @Override - protected void updateEntry(QueueEntry entry, VirtualHost.Transaction txn) - { - ServerMessage msg = entry.getMessage(); - if(msg != null && !msg.isReferenced((TransactionLogResource)_destinationQueue)) - { - txn.move(entry, _destinationQueue); - } - } - } - - private static class CopyTransaction extends QueueEntryTransaction - { - private final Queue _destinationQueue; - - public CopyTransaction(Queue sourceQueue, List<Long> messageIds, Queue destinationQueue) - { - super(sourceQueue, messageIds); - _destinationQueue = destinationQueue; - } - - @Override - protected void updateEntry(QueueEntry entry, VirtualHost.Transaction txn) - { - ServerMessage msg = entry.getMessage(); - if(msg != null && !msg.isReferenced((TransactionLogResource)_destinationQueue)) - { - txn.copy(entry, _destinationQueue); - } - } - } - - private static class DeleteTransaction extends QueueEntryTransaction - { - public DeleteTransaction(Queue sourceQueue, List<Long> messageIds) - { - super(sourceQueue, messageIds); - } - - @Override - protected void updateEntry(QueueEntry entry, VirtualHost.Transaction txn) - { - txn.dequeue(entry); - } - } - - - private static class ClearQueueTransaction implements VirtualHost.TransactionalOperation - { - private final Queue _queue; - - protected ClearQueueTransaction(Queue queue) - { - _queue = queue; - } - - @Override - public void withinTransaction(final VirtualHost.Transaction txn) - { - _queue.visit(new QueueEntryVisitor() - { - - public boolean visit(final QueueEntry entry) - { - final ServerMessage message = entry.getMessage(); - if(message != null) - { - txn.dequeue(entry); - } - return false; - } - }); - - } - } - - private class MessageCollector implements QueueEntryVisitor - { - private final int _first; - private final int _last; - private int _position = -1; - private final List<Map<String, Object>> _messages = new ArrayList<Map<String, Object>>(); - - private MessageCollector(int first, int last) - { - _first = first; - _last = last; - } - - - public boolean visit(QueueEntry entry) - { - - _position++; - if((_first == -1 || _position >= _first) && (_last == -1 || _position <= _last)) - { - final Map<String, Object> messageObject = convertToObject(entry, false); - messageObject.put("position", _position); - _messages.add(messageObject); - } - return _last != -1 && _position > _last; - } - - public List<Map<String, Object>> getMessages() - { - return _messages; - } - } - - - private class MessageFinder implements QueueEntryVisitor - { - private final long _messageNumber; - private Map<String, Object> _messageObject; - - private MessageFinder(long messageNumber) - { - _messageNumber = messageNumber; - } - - - public boolean visit(QueueEntry entry) - { - ServerMessage message = entry.getMessage(); - if(message != null) - { - if(_messageNumber == message.getMessageNumber()) - { - try - { - MessageReference reference = message.newReference(); - try - { - _messageObject = convertToObject(entry, true); - } - finally - { - reference.release(); - } - return true; - } - catch (MessageDeletedException e) - { - // ignore - the message has been deleted before we got a chance to look at it - } - } - } - return false; - } - - public Map<String, Object> getMessageObject() - { - return _messageObject; - } - } - - private Map<String, Object> convertToObject(QueueEntry entry, boolean includeContent) - { - Map<String, Object> object = new LinkedHashMap<String, Object>(); - object.put("size", entry.getSize()); - object.put("deliveryCount", entry.getDeliveryCount()); - object.put("state",entry.isAvailable() - ? "Available" - : entry.isAcquired() - ? "Acquired" - : ""); - final ConsumerImpl deliveredConsumer = entry.getDeliveredConsumer(); - object.put("deliveredTo", deliveredConsumer == null ? null : deliveredConsumer.getConsumerNumber()); - ServerMessage message = entry.getMessage(); - - if(message != null) - { - convertMessageProperties(object, message); - if(includeContent) - { - convertMessageHeaders(object, message); - } - } - - return object; - } - - private void convertMessageProperties(Map<String, Object> object, ServerMessage message) - { - object.put("id", message.getMessageNumber()); - object.put("arrivalTime",message.getArrivalTime()); - object.put("persistent", message.isPersistent()); - - final AMQMessageHeader messageHeader = message.getMessageHeader(); - if(messageHeader != null) - { - addIfPresent(object, "messageId", messageHeader.getMessageId()); - addIfPresentAndNotZero(object, "expirationTime", messageHeader.getExpiration()); - addIfPresent(object, "applicationId", messageHeader.getAppId()); - addIfPresent(object, "correlationId", messageHeader.getCorrelationId()); - addIfPresent(object, "encoding", messageHeader.getEncoding()); - addIfPresent(object, "mimeType", messageHeader.getMimeType()); - addIfPresent(object, "priority", messageHeader.getPriority()); - addIfPresent(object, "replyTo", messageHeader.getReplyTo()); - addIfPresentAndNotZero(object, "timestamp", messageHeader.getTimestamp()); - addIfPresent(object, "type", messageHeader.getType()); - addIfPresent(object, "userId", messageHeader.getUserId()); - } - - } - - private void addIfPresentAndNotZero(Map<String, Object> object, String name, Object property) - { - if(property instanceof Number) - { - Number value = (Number)property; - if (value.longValue() != 0) - { - object.put(name, property); - } - } - } - - private void addIfPresent(Map<String, Object> object, String name, Object property) - { - if(property != null) - { - object.put(name, property); - } - } - - private void convertMessageHeaders(Map<String, Object> object, ServerMessage message) - { - final AMQMessageHeader messageHeader = message.getMessageHeader(); - if(messageHeader != null) - { - Map<String, Object> headers = new HashMap<String,Object>(); - for(String headerName : messageHeader.getHeaderNames()) - { - headers.put(headerName, messageHeader.getHeader(headerName)); - } - object.put("headers", headers); - } - } - - /* - * POST moves or copies messages to the given queue from a queue specified in the posted JSON data - */ - @Override - protected void doPostWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - - try - { - final Queue<?> sourceQueue = getQueueFromRequest(request); - - ObjectMapper mapper = new ObjectMapper(); - - @SuppressWarnings("unchecked") - Map<String,Object> providedObject = mapper.readValue(request.getInputStream(), LinkedHashMap.class); - - String destQueueName = (String) providedObject.get("destinationQueue"); - Boolean move = (Boolean) providedObject.get("move"); - - final VirtualHost<?,?,?> vhost = sourceQueue.getParent(VirtualHost.class); - - boolean isMoveTransaction = move != null && Boolean.valueOf(move); - - // FIXME: added temporary authorization check until we introduce management layer - // and review current ACL rules to have common rules for all management interfaces - String methodName = isMoveTransaction? "moveMessages":"copyMessages"; - authorizeMethod(methodName, vhost); - - - final Queue destinationQueue = getQueueFromVirtualHost(destQueueName, vhost); - final List<Long> messageIds = new ArrayList<Long>((List<Long>) providedObject.get("messages")); - QueueEntryTransaction txn = - isMoveTransaction - ? new MoveTransaction(sourceQueue, messageIds, destinationQueue) - : new CopyTransaction(sourceQueue, messageIds, destinationQueue); - vhost.executeTransaction(txn); - response.setStatus(HttpServletResponse.SC_OK); - - } - catch(AccessControlException e) - { - response.setStatus(HttpServletResponse.SC_FORBIDDEN); - } - catch(RuntimeException e) - { - LOGGER.error("Failure to perform message operation", e); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } - - /* - * DELETE removes specified messages from, or clears the queue - */ - @Override - protected void doDeleteWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - final Queue<?> queue = getQueueFromRequest(request); - - final VirtualHost<?,?,?> vhost = queue.getParent(VirtualHost.class); - boolean clearQueue = Boolean.parseBoolean(request.getParameter("clear")); - - try - { - if (clearQueue) - { - clearQueue(queue, vhost); - } - else - { - final List<Long> messageIds = new ArrayList<>(); - for(String idStr : request.getParameterValues("id")) - { - messageIds.add(Long.valueOf(idStr)); - } - - deleteMessages(queue, vhost, messageIds); - } - response.setStatus(HttpServletResponse.SC_OK); - } - catch (AccessControlException e) - { - response.setStatus(HttpServletResponse.SC_FORBIDDEN); - } - - } - - private void deleteMessages(final Queue<?> queue, final VirtualHost<?, ?, ?> vhost, final List<Long> messageIds) - { - // FIXME: added temporary authorization check until we introduce management layer - // and review current ACL rules to have common rules for all management interfaces - authorizeMethod("deleteMessages", vhost); - vhost.executeTransaction(new DeleteTransaction(queue, messageIds)); - } - - private void clearQueue(final Queue<?> queue, final VirtualHost<?, ?, ?> vhost) - { - // FIXME: added temporary authorization check until we introduce management layer - // and review current ACL rules to have common rules for all management interfaces - authorizeMethod("clearQueue", vhost); - vhost.executeTransaction(new ClearQueueTransaction(queue)); - } - - private void authorizeMethod(String methodName, VirtualHost<?,?,?> vhost) - { - SecurityManager securityManager = getBroker().getSecurityManager(); - securityManager.authoriseMethod(Operation.UPDATE, "VirtualHost.Queue", methodName, vhost.getName()); - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MetaDataServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MetaDataServlet.java deleted file mode 100644 index 88705563af..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MetaDataServlet.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.ConfiguredAutomatedAttribute; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ConfiguredObjectAttribute; -import org.apache.qpid.server.model.ConfiguredObjectTypeRegistry; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.Model; - -public class MetaDataServlet extends AbstractServlet -{ - - private Model _instance; - - public MetaDataServlet(final Model model) - { - _instance = model; - } - - @Override - public void init() throws ServletException - { - super.init(); - } - - - - @Override - protected void doGetWithSubjectAndActor(final HttpServletRequest request, final HttpServletResponse response) - throws ServletException, IOException - { - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - Map<String,Map> classToDataMap = new TreeMap<>(); - - for(Class<? extends ConfiguredObject> clazz : _instance.getSupportedCategories()) - { - classToDataMap.put(clazz.getSimpleName(), processCategory(clazz)); - } - - final Writer writer = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, classToDataMap); - - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - } - - private Map<String,Map> processCategory(final Class<? extends ConfiguredObject> clazz) - { - Map<String, Map> typeToDataMap = new TreeMap<>(); - ConfiguredObjectTypeRegistry typeRegistry = _instance.getTypeRegistry(); - for(Class<? extends ConfiguredObject> type : typeRegistry.getTypeSpecialisations(clazz)) - { - typeToDataMap.put(ConfiguredObjectTypeRegistry.getType(type), processType(type)); - } - return typeToDataMap; - } - - private Map<String,Object> processType(final Class<? extends ConfiguredObject> type) - { - Map<String,Object> typeDetails = new LinkedHashMap<>(); - typeDetails.put("attributes", processAttributes(type)); - typeDetails.put("managedInterfaces", getManagedInterfaces(type)); - typeDetails.put("validChildTypes", getValidChildTypes(type)); - ManagedObject annotation = type.getAnnotation(ManagedObject.class); - if(annotation != null) - { - if(annotation.deprecated()) - { - typeDetails.put("deprecated",true); - } - if(!"".equals(annotation.description() ) ) - { - typeDetails.put("description", annotation.description()); - } - } - return typeDetails; - } - - private Map<String, Collection<String>> getValidChildTypes(final Class<? extends ConfiguredObject> type) - { - Map<String, Collection<String>> validChildTypes = new HashMap<>(); - for(Class<? extends ConfiguredObject> childType : _instance.getChildTypes(ConfiguredObjectTypeRegistry.getCategory(type))) - { - Collection<String> validValues = _instance.getTypeRegistry().getValidChildTypes(type, childType); - if(validValues != null) - { - validChildTypes.put(childType.getSimpleName(), validValues); - } - } - return validChildTypes; - } - - private Set<String> getManagedInterfaces(Class<? extends ConfiguredObject> type) - { - Set<String> interfaces = new HashSet<>(); - for(Class<?> classObject: _instance.getTypeRegistry().getManagedInterfaces(type)) - { - interfaces.add(classObject.getSimpleName()); - } - return interfaces; - } - - private Map<String,Map> processAttributes(final Class<? extends ConfiguredObject> type) - { - Collection<ConfiguredObjectAttribute<?, ?>> attributes = - _instance.getTypeRegistry().getAttributeTypes(type).values(); - - Map<String,Map> attributeDetails = new LinkedHashMap<>(); - for(ConfiguredObjectAttribute<?, ?> attribute : attributes) - { - Map<String,Object> attrDetails = new LinkedHashMap<>(); - attrDetails.put("type",attribute.getType().getSimpleName()); - if(!"".equals(attribute.getDescription())) - { - attrDetails.put("description",attribute.getDescription()); - } - if(attribute.isDerived()) - { - attrDetails.put("derived",attribute.isDerived()); - } - if(attribute.isAutomated()) - { - if(!"".equals(((ConfiguredAutomatedAttribute)attribute).defaultValue())) - { - attrDetails.put("defaultValue",((ConfiguredAutomatedAttribute)attribute).defaultValue()); - } - if(((ConfiguredAutomatedAttribute)attribute).isMandatory()) - { - attrDetails.put("mandatory",((ConfiguredAutomatedAttribute)attribute).isMandatory()); - } - if(!(((ConfiguredAutomatedAttribute)attribute).validValues()).isEmpty()) - { - Collection<String> validValues = ((ConfiguredAutomatedAttribute<?,?>) attribute).validValues(); - - Collection<Object> convertedValues = new ArrayList<>(validValues.size()); - for(String value : validValues) - { - convertedValues.add(attribute.convert(value,null)); - } - attrDetails.put("validValues", convertedValues); - } - - } - if(attribute.isSecure()) - { - attrDetails.put("secure",attribute.isSecure()); - } - if(attribute.isOversized()) - { - attrDetails.put("oversize", attribute.isOversized()); - } - attributeDetails.put(attribute.getName(), attrDetails); - } - return attributeDetails; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/PluginClassProviderAction.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/PluginClassProviderAction.java deleted file mode 100644 index cd14abc582..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/PluginClassProviderAction.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.apache.qpid.server.management.plugin.servlet.rest;/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.plugin.Pluggable; -import org.apache.qpid.server.plugin.QpidServiceLoader; - -public class PluginClassProviderAction implements Action -{ - @Override - public String getName() - { - return "pluginList"; - } - - @Override - public Object perform(Map<String, Object> request, Broker broker) - { - try - { - String className = (String) request.get("plugin"); - QpidServiceLoader serviceLoader = new QpidServiceLoader(); - final Class<Pluggable> clazz = (Class<Pluggable>) Class.forName("org.apache.qpid.server.plugin."+className); - List<String> values = new ArrayList<String>(); - for(Pluggable instance : serviceLoader.instancesOf(clazz)) - { - values.add(instance.getType()); - } - return values; - } - catch (ClassNotFoundException e) - { - return Collections.emptyList(); - } - - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/QueueReportServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/QueueReportServlet.java deleted file mode 100644 index 2b3def2dab..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/QueueReportServlet.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.qpid.server.management.plugin.report.ReportRunner; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; - -public class QueueReportServlet extends AbstractServlet -{ - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws - IOException, - ServletException - { - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements != null && pathInfoElements.length == 3) - { - Queue<?> queue = getQueueFromRequest(request); - ReportRunner<?> reportRunner = ReportRunner.createRunner(pathInfoElements[2],request.getParameterMap()); - Object output = reportRunner.runReport(queue); - response.setContentType(reportRunner.getContentType()); - if(reportRunner.isBinaryReport()) - { - response.getOutputStream().write((byte[])output); - } - else - { - response.getWriter().write((String)output); - } - } - else - { - throw new IllegalArgumentException("Invalid path is specified"); - } - - } - - private Queue<?> getQueueFromRequest(HttpServletRequest request) - { - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements == null || pathInfoElements.length < 2) - { - throw new IllegalArgumentException("Invalid path is specified"); - } - String vhostName = pathInfoElements[0]; - String queueName = pathInfoElements[1]; - - VirtualHost<?,?,?> vhost = getBroker().findVirtualHostByName(vhostName); - if (vhost == null) - { - throw new IllegalArgumentException("Could not find virtual host with name '" + vhostName + "'"); - } - - Queue queueFromVirtualHost = getQueueFromVirtualHost(queueName, vhost); - if (queueFromVirtualHost == null) - { - throw new IllegalArgumentException("Could not find queue with name '" + queueName + "' on virtual host '" + vhost.getName() + "'"); - } - return queueFromVirtualHost; - } - - private Queue getQueueFromVirtualHost(String queueName, VirtualHost<?,?,?> vhost) - { - Queue queue = null; - - for(Queue<?> q : vhost.getQueues()) - { - - if(q.getName().equals(queueName)) - { - queue = q; - break; - } - } - return queue; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/RestServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/RestServlet.java deleted file mode 100644 index 275d7f6794..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/RestServlet.java +++ /dev/null @@ -1,774 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * <p/> - * http://www.apache.org/licenses/LICENSE-2.0 - * <p/> - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.security.AccessControlException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.Part; - -import org.apache.qpid.server.model.AbstractConfiguredObject; -import org.apache.qpid.server.model.IllegalStateTransitionException; -import org.apache.qpid.server.model.IntegrityViolationException; -import org.apache.qpid.server.virtualhost.ExchangeExistsException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.util.urlstreamhandler.data.Handler; -import org.apache.qpid.util.DataUrlUtils; - -public class RestServlet extends AbstractServlet -{ - private static final Logger LOGGER = LoggerFactory.getLogger(RestServlet.class); - /** - * An initialization parameter to specify hierarchy - */ - private static final String HIERARCHY_INIT_PARAMETER = "hierarchy"; - - public static final String DEPTH_PARAM = "depth"; - public static final String OVERSIZE_PARAM = "oversize"; - public static final String ACTUALS_PARAM = "actuals"; - public static final String SORT_PARAM = "sort"; - public static final String INCLUDE_SYS_CONTEXT_PARAM = "includeSysContext"; - public static final String INHERITED_ACTUALS_PARAM = "inheritedActuals"; - public static final String EXTRACT_INITIAL_CONFIG_PARAM = "extractInitialConfig"; - public static final int SC_UNPROCESSABLE_ENTITY = 422; - - /** - * Signifies that the agent wishes the servlet to set the Content-Disposition on the - * response with the value attachment. This filename will be derived from the parameter value. - */ - public static final String CONTENT_DISPOSITION_ATTACHMENT_FILENAME_PARAM = "contentDispositionAttachmentFilename"; - - public static final Set<String> RESERVED_PARAMS = - new HashSet<>(Arrays.asList(DEPTH_PARAM, - SORT_PARAM, - OVERSIZE_PARAM, - ACTUALS_PARAM, - INCLUDE_SYS_CONTEXT_PARAM, - EXTRACT_INITIAL_CONFIG_PARAM, - INHERITED_ACTUALS_PARAM, - CONTENT_DISPOSITION_ATTACHMENT_FILENAME_PARAM)); - - private Class<? extends ConfiguredObject>[] _hierarchy; - - private final ConfiguredObjectToMapConverter _objectConverter = new ConfiguredObjectToMapConverter(); - private final boolean _hierarchyInitializationRequired; - - public RestServlet() - { - super(); - _hierarchyInitializationRequired = true; - } - - public RestServlet(Class<? extends ConfiguredObject>... hierarchy) - { - super(); - _hierarchy = hierarchy; - _hierarchyInitializationRequired = false; - } - - @Override - public void init() throws ServletException - { - super.init(); - if (_hierarchyInitializationRequired) - { - doInitialization(); - } - Handler.register(); - } - - @SuppressWarnings("unchecked") - private void doInitialization() throws ServletException - { - ServletConfig config = getServletConfig(); - String hierarchy = config.getInitParameter(HIERARCHY_INIT_PARAMETER); - if (hierarchy != null && !"".equals(hierarchy)) - { - List<Class<? extends ConfiguredObject>> classes = new ArrayList<Class<? extends ConfiguredObject>>(); - String[] hierarchyItems = hierarchy.split(","); - for (String item : hierarchyItems) - { - Class<?> itemClass = null; - try - { - itemClass = Class.forName(item); - } - catch (ClassNotFoundException e) - { - try - { - itemClass = Class.forName("org.apache.qpid.server.model." + item); - } - catch (ClassNotFoundException e1) - { - throw new ServletException("Unknown configured object class '" + item - + "' is specified in hierarchy for " + config.getServletName()); - } - } - Class<? extends ConfiguredObject> clazz = (Class<? extends ConfiguredObject>)itemClass; - classes.add(clazz); - } - Class<? extends ConfiguredObject>[] hierarchyClasses = (Class<? extends ConfiguredObject>[])new Class[classes.size()]; - _hierarchy = classes.toArray(hierarchyClasses); - } - else - { - _hierarchy = (Class<? extends ConfiguredObject>[])new Class[0]; - } - } - - protected Collection<ConfiguredObject<?>> getObjects(HttpServletRequest request) - { - String[] pathInfoElements = getPathInfoElements(request); - List<String> names = new ArrayList<String>(); - if(pathInfoElements != null) - { - if(pathInfoElements.length > _hierarchy.length) - { - throw new IllegalArgumentException("Too many entries in path for REST servlet " - + getServletName() + ". Expected hierarchy length: " + _hierarchy.length - + "; Request hierarchy length: " + pathInfoElements.length - + "; Path Elements: " + Arrays.toString(pathInfoElements)); - } - names.addAll(Arrays.asList(pathInfoElements)); - } - - Collection<ConfiguredObject<?>> parents = new ArrayList<ConfiguredObject<?>>(); - parents.add(getBroker()); - Collection<ConfiguredObject<?>> children = new ArrayList<ConfiguredObject<?>>(); - - Map<Class<? extends ConfiguredObject>, String> filters = - new HashMap<Class<? extends ConfiguredObject>, String>(); - - for(int i = 0; i < _hierarchy.length; i++) - { - if(i == 0 || getBroker().getModel().getChildTypes(_hierarchy[i - 1]).contains(_hierarchy[i])) - { - - for(ConfiguredObject<?> parent : parents) - { - if(names.size() > i - && names.get(i) != null - && !names.get(i).equals("*") - && names.get(i).trim().length() != 0) - { - for(ConfiguredObject<?> child : parent.getChildren(_hierarchy[i])) - { - if(child.getName().equals(names.get(i))) - { - children.add(child); - } - } - } - else - { - children.addAll((Collection<? extends ConfiguredObject<?>>) parent.getChildren(_hierarchy[i])); - } - } - } - else - { - children = parents; - if(names.size() > i - && names.get(i) != null - && !names.get(i).equals("*") - && names.get(i).trim().length() != 0) - { - filters.put(_hierarchy[i], names.get(i)); - } - } - - parents = children; - children = new ArrayList<ConfiguredObject<?>>(); - } - - if(!filters.isEmpty()) - { - Collection<ConfiguredObject<?>> potentials = parents; - parents = new ArrayList<ConfiguredObject<?>>(); - - for(ConfiguredObject o : potentials) - { - - boolean match = true; - - for(Map.Entry<Class<? extends ConfiguredObject>, String> entry : filters.entrySet()) - { - Collection<? extends ConfiguredObject> ancestors = - getAncestors(getConfiguredClass(),entry.getKey(), o); - match = false; - for(ConfiguredObject ancestor : ancestors) - { - if(ancestor.getName().equals(entry.getValue())) - { - match = true; - break; - } - } - if(!match) - { - break; - } - } - if(match) - { - parents.add(o); - } - - } - } - - return filter(parents, request); - } - - private Collection<ConfiguredObject<?>> filter(Collection<ConfiguredObject<?>> objects, HttpServletRequest request) - { - - - Map<String, Collection<String>> filters = new HashMap<String, Collection<String>>(); - - for(String param : (Collection<String>) Collections.list(request.getParameterNames())) - { - if(!RESERVED_PARAMS.contains(param)) - { - filters.put(param, Arrays.asList(request.getParameterValues(param))); - } - } - - if(filters.isEmpty()) - { - return objects; - } - - Collection<ConfiguredObject<?>> filteredObj = new ArrayList<ConfiguredObject<?>>(objects); - - Iterator<ConfiguredObject<?>> iter = filteredObj.iterator(); - - while(iter.hasNext()) - { - ConfiguredObject obj = iter.next(); - for(Map.Entry<String, Collection<String>> entry : filters.entrySet()) - { - Object value = obj.getAttribute(entry.getKey()); - if(!entry.getValue().contains(String.valueOf(value))) - { - iter.remove(); - } - } - - } - - return filteredObj; - } - - private Collection<? extends ConfiguredObject> getAncestors(Class<? extends ConfiguredObject> childType, - Class<? extends ConfiguredObject> ancestorType, - ConfiguredObject child) - { - Collection<ConfiguredObject> ancestors = new HashSet<ConfiguredObject>(); - Collection<Class<? extends ConfiguredObject>> parentTypes = child.getModel().getParentTypes(childType); - - for(Class<? extends ConfiguredObject> parentClazz : parentTypes) - { - if(parentClazz == ancestorType) - { - ConfiguredObject parent = child.getParent(parentClazz); - if(parent != null) - { - ancestors.add(parent); - } - } - else - { - ConfiguredObject parent = child.getParent(parentClazz); - if(parent != null) - { - ancestors.addAll(getAncestors(parentClazz, ancestorType, parent)); - } - } - } - - return ancestors; - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - // TODO - sort special params, everything else should act as a filter - String attachmentFilename = request.getParameter(CONTENT_DISPOSITION_ATTACHMENT_FILENAME_PARAM); - boolean extractInitialConfig = getBooleanParameterFromRequest(request, EXTRACT_INITIAL_CONFIG_PARAM); - - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - if (attachmentFilename == null) - { - setCachingHeadersOnResponse(response); - } - else - { - setContentDispositionHeaderIfNecessary(response, attachmentFilename); - } - - Collection<ConfiguredObject<?>> allObjects = getObjects(request); - - int depth; - boolean actuals; - boolean includeSystemContext; - boolean inheritedActuals; - int oversizeThreshold; - - if(extractInitialConfig) - { - depth = Integer.MAX_VALUE; - oversizeThreshold = Integer.MAX_VALUE; - actuals = true; - includeSystemContext = false; - inheritedActuals = false; - } - else - { - depth = getIntParameterFromRequest(request, DEPTH_PARAM, 1); - oversizeThreshold = getIntParameterFromRequest(request, OVERSIZE_PARAM, 120); - actuals = getBooleanParameterFromRequest(request, ACTUALS_PARAM); - includeSystemContext = getBooleanParameterFromRequest(request, INCLUDE_SYS_CONTEXT_PARAM); - inheritedActuals = getBooleanParameterFromRequest(request, INHERITED_ACTUALS_PARAM); - } - - List<Map<String, Object>> output = new ArrayList<>(); - for(ConfiguredObject configuredObject : allObjects) - { - - output.add(_objectConverter.convertObjectToMap(configuredObject, getConfiguredClass(), - depth, actuals, inheritedActuals, includeSystemContext, extractInitialConfig, oversizeThreshold, request.isSecure())); - } - - - Writer writer = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, extractInitialConfig && output.size() == 1 ? output.get(0) : output); - } - - private void setContentDispositionHeaderIfNecessary(final HttpServletResponse response, - final String attachmentFilename) - { - if (attachmentFilename != null) - { - String filenameRfc2183 = ensureFilenameIsRfc2183(attachmentFilename); - if (filenameRfc2183.length() > 0) - { - response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filenameRfc2183)); - } - else - { - response.setHeader("Content-disposition", String.format("attachment")); // Agent will allow user to choose a name - } - } - } - - private Class<? extends ConfiguredObject> getConfiguredClass() - { - return _hierarchy.length == 0 ? Broker.class : _hierarchy[_hierarchy.length-1]; - } - - @Override - protected void doPutWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - performCreateOrUpdate(request, response); - } - - private void performCreateOrUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - response.setContentType("application/json"); - - List<String> names = getParentNamesFromServletPath(request); - Map<String, Object> providedObject = getRequestProvidedObject(request); - boolean isFullObjectURL = names.size() == _hierarchy.length; - boolean updateOnlyAllowed = isFullObjectURL && "POST".equalsIgnoreCase(request.getMethod()); - try - { - if (names.isEmpty() && _hierarchy.length == 0) - { - getBroker().setAttributes(providedObject); - response.setStatus(HttpServletResponse.SC_OK); - return; - } - - ConfiguredObject theParent = getBroker(); - ConfiguredObject[] otherParents = null; - Class<? extends ConfiguredObject> objClass = getConfiguredClass(); - if (_hierarchy.length > 1) - { - List<ConfiguredObject> parents = findAllObjectParents(names); - theParent = parents.remove(0); - otherParents = parents.toArray(new ConfiguredObject[parents.size()]); - } - - if (isFullObjectURL) - { - providedObject.put("name", names.get(names.size() - 1)); - ConfiguredObject<?> configuredObject = findObjectToUpdateInParent(objClass, providedObject, theParent, otherParents); - - if (configuredObject != null) - { - configuredObject.setAttributes(providedObject); - response.setStatus(HttpServletResponse.SC_OK); - return; - } - else if (updateOnlyAllowed) - { - sendErrorResponse(request, response, HttpServletResponse.SC_NOT_FOUND, "Object with " - + (providedObject.containsKey("id") ? " id '" + providedObject.get("id") : " name '" + providedObject.get("name")) - + "' does not exist!"); - return; - } - } - - ConfiguredObject<?> configuredObject = theParent.createChild(objClass, providedObject, otherParents); - StringBuffer requestURL = request.getRequestURL(); - if (!isFullObjectURL) - { - requestURL.append("/").append(configuredObject.getName()); - } - response.setHeader("Location", requestURL.toString()); - response.setStatus(HttpServletResponse.SC_CREATED); - } - catch (RuntimeException e) - { - setResponseStatus(request, response, e); - } - - } - - private List<ConfiguredObject> findAllObjectParents(List<String> names) - { - Collection<ConfiguredObject>[] objects = new Collection[_hierarchy.length]; - for (int i = 0; i < _hierarchy.length - 1; i++) - { - objects[i] = new HashSet<>(); - if (i == 0) - { - for (ConfiguredObject object : getBroker().getChildren(_hierarchy[0])) - { - if (object.getName().equals(names.get(0))) - { - objects[0].add(object); - break; - } - } - } - else - { - for (int j = i - 1; j >= 0; j--) - { - if (getBroker().getModel().getChildTypes(_hierarchy[j]).contains(_hierarchy[i])) - { - for (ConfiguredObject<?> parent : objects[j]) - { - for (ConfiguredObject<?> object : parent.getChildren(_hierarchy[i])) - { - if (object.getName().equals(names.get(i))) - { - objects[i].add(object); - } - } - } - break; - } - } - } - - } - List<ConfiguredObject> parents = new ArrayList<>(); - Class<? extends ConfiguredObject> objClass = getConfiguredClass(); - Collection<Class<? extends ConfiguredObject>> parentClasses = - getBroker().getModel().getParentTypes(objClass); - for (int i = _hierarchy.length - 2; i >= 0; i--) - { - if (parentClasses.contains(_hierarchy[i])) - { - if (objects[i].size() == 1) - { - parents.add(objects[i].iterator().next()); - } - else - { - throw new IllegalArgumentException("Cannot deduce parent of class " - + _hierarchy[i].getSimpleName()); - } - } - - } - return parents; - } - - private List<String> getParentNamesFromServletPath(HttpServletRequest request) - { - List<String> names = new ArrayList<>(); - String[] pathInfoElements = getPathInfoElements(request); - if (pathInfoElements != null) - { - if (!(pathInfoElements.length == _hierarchy.length || - (_hierarchy.length > 0 && pathInfoElements.length == _hierarchy.length - 1))) - { - throw new IllegalArgumentException("Either parent path or full object path must be specified on object creation." - + " Full object path must be specified on object update. " - + "Found " - + names - + " of size " - + names.size() - + " expecting " - + _hierarchy.length); - } - names.addAll(Arrays.asList(pathInfoElements)); - } - return names; - } - - private Map<String, Object> getRequestProvidedObject(HttpServletRequest request) throws IOException, ServletException - { - Map<String, Object> providedObject; - - ArrayList<String> headers = Collections.list(request.getHeaderNames()); - ObjectMapper mapper = new ObjectMapper(); - - if(headers.contains("Content-Type") && request.getHeader("Content-Type").startsWith("multipart/form-data")) - { - providedObject = new HashMap<>(); - Map<String,String> fileUploads = new HashMap<>(); - Collection<Part> parts = request.getParts(); - for(Part part : parts) - { - if("data".equals(part.getName()) && "application/json".equals(part.getContentType())) - { - providedObject = mapper.readValue(part.getInputStream(), LinkedHashMap.class); - } - else - { - byte[] data = new byte[(int) part.getSize()]; - part.getInputStream().read(data); - String inlineURL = DataUrlUtils.getDataUrlForBytes(data); - fileUploads.put(part.getName(),inlineURL.toString()); - } - } - providedObject.putAll(fileUploads); - } - else - { - - providedObject = mapper.readValue(request.getInputStream(), LinkedHashMap.class); - } - return providedObject; - } - - private ConfiguredObject<?> findObjectToUpdateInParent(Class<? extends ConfiguredObject> objClass, Map<String, Object> providedObject, ConfiguredObject theParent, ConfiguredObject[] otherParents) - { - Collection<? extends ConfiguredObject> existingChildren = theParent.getChildren(objClass); - - for (ConfiguredObject obj : existingChildren) - { - if ((providedObject.containsKey("id") && String.valueOf(providedObject.get("id")).equals(obj.getId().toString())) - || (obj.getName().equals(providedObject.get("name")) && sameOtherParents(obj, otherParents, objClass))) - { - return obj; - } - } - return null; - } - - private boolean sameOtherParents(ConfiguredObject obj, ConfiguredObject[] otherParents, Class<? extends ConfiguredObject> objClass) - { - Collection<Class<? extends ConfiguredObject>> parentClasses = obj.getModel().getParentTypes(objClass); - - if(otherParents == null || otherParents.length == 0) - { - return parentClasses.size() == 1; - } - - - for (ConfiguredObject parent : otherParents) - { - boolean found = false; - for (Class<? extends ConfiguredObject> parentClass : parentClasses) - { - if (parent == obj.getParent(parentClass)) - { - found = true; - break; - } - } - - if (!found) - { - return false; - } - } - - return true; - } - - private void setResponseStatus(HttpServletRequest request, HttpServletResponse response, RuntimeException e) throws IOException - { - if (e instanceof AccessControlException) - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("AccessControlException, sending " + HttpServletResponse.SC_FORBIDDEN, e); - } - response.setStatus(HttpServletResponse.SC_FORBIDDEN); - } - else - { - int responseCode = HttpServletResponse.SC_BAD_REQUEST; - String message = e.getMessage(); - if (e instanceof ExchangeExistsException || e instanceof QueueExistsException - || e instanceof AbstractConfiguredObject.DuplicateIdException - || e instanceof AbstractConfiguredObject.DuplicateNameException - || e instanceof IntegrityViolationException - || e instanceof IllegalStateTransitionException) - { - responseCode = HttpServletResponse.SC_CONFLICT; - } - else if (e instanceof IllegalConfigurationException || e instanceof IllegalArgumentException) - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug(e.getClass().getSimpleName() + " processing request : " + message); - } - else if (LOGGER.isTraceEnabled()) - { - LOGGER.trace(e.getClass().getSimpleName() + " processing request", e); - } - responseCode = SC_UNPROCESSABLE_ENTITY; - } - else - { - LOGGER.warn("Unexpected exception processing request ", e); - } - - - sendErrorResponse(request, response, responseCode, message); - - } - } - - private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, int responseCode, String message) throws IOException - { - response.setStatus(responseCode); - - response.setContentType("application/json"); - response.setCharacterEncoding("UTF-8"); - - Writer out = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(out, Collections.singletonMap("errorMessage", message)); - } - - @Override - protected void doDeleteWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - setCachingHeadersOnResponse(response); - try - { - Collection<ConfiguredObject<?>> allObjects = getObjects(request); - for(ConfiguredObject o : allObjects) - { - o.delete(); - } - - response.setStatus(HttpServletResponse.SC_OK); - } - catch(RuntimeException e) - { - setResponseStatus(request, response, e); - } - } - - @Override - protected void doPostWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - performCreateOrUpdate(request, response); - } - - private void setCachingHeadersOnResponse(HttpServletResponse response) - { - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - } - - private int getIntParameterFromRequest(final HttpServletRequest request, - final String paramName, - final int defaultValue) - { - int intValue = defaultValue; - final String stringValue = request.getParameter(paramName); - if(stringValue!=null) - { - try - { - intValue = Integer.parseInt(stringValue); - } - catch (NumberFormatException e) - { - LOGGER.warn("Could not parse " + stringValue + " as integer for parameter " + paramName); - } - } - return intValue; - } - - private boolean getBooleanParameterFromRequest(HttpServletRequest request, final String paramName) - { - return Boolean.parseBoolean(request.getParameter(paramName)); - } - - private String ensureFilenameIsRfc2183(final String requestedFilename) - { - String fileNameRfc2183 = requestedFilename.replaceAll("[\\P{InBasic_Latin}\\\\:/]", ""); - return fileNameRfc2183; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/SaslServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/SaslServlet.java deleted file mode 100644 index 5bff0e22e5..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/SaslServlet.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.net.SocketAddress; -import java.security.Principal; -import java.security.SecureRandom; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import javax.security.auth.Subject; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.codec.binary.Base64; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.management.plugin.HttpManagementConfiguration; -import org.apache.qpid.server.management.plugin.HttpManagementUtil; -import org.apache.qpid.server.management.plugin.servlet.ServletConnectionPrincipal; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; - -public class SaslServlet extends AbstractServlet -{ - - private static final Logger LOGGER = LoggerFactory.getLogger(SaslServlet.class); - - private static final SecureRandom SECURE_RANDOM = new SecureRandom(); - private static final String ATTR_RANDOM = "SaslServlet.Random"; - private static final String ATTR_ID = "SaslServlet.ID"; - private static final String ATTR_SASL_SERVER = "SaslServlet.SaslServer"; - private static final String ATTR_EXPIRY = "SaslServlet.Expiry"; - private static final long SASL_EXCHANGE_EXPIRY = 3000L; - - public SaslServlet() - { - super(); - } - - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws - ServletException, - IOException - { - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - - HttpSession session = request.getSession(); - getRandom(session); - - SubjectCreator subjectCreator = getSubjectCreator(request); - List<String> mechanismsList = subjectCreator.getMechanisms(); - String[] mechanisms = mechanismsList.toArray(new String[mechanismsList.size()]); - Map<String, Object> outputObject = new LinkedHashMap<String, Object>(); - - final Subject subject = getAuthorisedSubject(request); - if(subject != null) - { - Principal principal = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); - outputObject.put("user", principal.getName()); - } - else if (request.getRemoteUser() != null) - { - outputObject.put("user", request.getRemoteUser()); - } - - outputObject.put("mechanisms", (Object) mechanisms); - - final Writer writer = getOutputWriter(request, response); - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, outputObject); - - } - - private Random getRandom(final HttpSession session) - { - Random rand = (Random) session.getAttribute(ATTR_RANDOM); - if(rand == null) - { - synchronized (SECURE_RANDOM) - { - rand = new Random(SECURE_RANDOM.nextLong()); - } - session.setAttribute(ATTR_RANDOM, rand); - } - return rand; - } - - - @Override - protected void doPostWithSubjectAndActor(final HttpServletRequest request, final HttpServletResponse response) throws IOException - { - checkSaslAuthEnabled(request); - - try - { - response.setContentType("application/json"); - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader("Expires", 0); - - HttpSession session = request.getSession(); - - String mechanism = request.getParameter("mechanism"); - String id = request.getParameter("id"); - String saslResponse = request.getParameter("response"); - - SubjectCreator subjectCreator = getSubjectCreator(request); - - if(mechanism != null) - { - if(id == null) - { - if(LOGGER.isDebugEnabled()) - { - LOGGER.debug("Creating SaslServer for mechanism: " + mechanism); - } - SaslServer saslServer = subjectCreator.createSaslServer(mechanism, request.getServerName(), null/*TODO*/); - evaluateSaslResponse(request, response, session, saslResponse, saslServer, subjectCreator); - } - else - { - response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED); - session.removeAttribute(ATTR_ID); - session.removeAttribute(ATTR_SASL_SERVER); - session.removeAttribute(ATTR_EXPIRY); - } - } - else - { - if(id != null) - { - if(id.equals(session.getAttribute(ATTR_ID)) && System.currentTimeMillis() < (Long) session.getAttribute(ATTR_EXPIRY)) - { - SaslServer saslServer = (SaslServer) session.getAttribute(ATTR_SASL_SERVER); - evaluateSaslResponse(request, response, session, saslResponse, saslServer, subjectCreator); - } - else - { - response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED); - session.removeAttribute(ATTR_ID); - session.removeAttribute(ATTR_SASL_SERVER); - session.removeAttribute(ATTR_EXPIRY); - } - } - else - { - response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED); - session.removeAttribute(ATTR_ID); - session.removeAttribute(ATTR_SASL_SERVER); - session.removeAttribute(ATTR_EXPIRY); - } - } - } - catch(IOException e) - { - LOGGER.error("Error processing SASL request", e); - throw e; - } - catch(RuntimeException e) - { - LOGGER.error("Error processing SASL request", e); - throw e; - } - } - - private void checkSaslAuthEnabled(HttpServletRequest request) - { - boolean saslAuthEnabled = false; - HttpManagementConfiguration management = getManagementConfiguration(); - if (request.isSecure()) - { - saslAuthEnabled = management.isHttpsSaslAuthenticationEnabled(); - } - else - { - saslAuthEnabled = management.isHttpSaslAuthenticationEnabled(); - } - if (!saslAuthEnabled) - { - throw new ConnectionScopedRuntimeException("Sasl authentication disabled."); - } - } - - private void evaluateSaslResponse(final HttpServletRequest request, - final HttpServletResponse response, - final HttpSession session, final String saslResponse, final SaslServer saslServer, SubjectCreator subjectCreator) throws IOException - { - final String id; - byte[] challenge; - try - { - challenge = saslServer.evaluateResponse(saslResponse == null ? new byte[0] : Base64.decodeBase64(saslResponse.getBytes())); - } - catch(SaslException e) - { - session.removeAttribute(ATTR_ID); - session.removeAttribute(ATTR_SASL_SERVER); - session.removeAttribute(ATTR_EXPIRY); - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - - return; - } - - if(saslServer.isComplete()) - { - Subject originalSubject = subjectCreator.createSubjectWithGroups(new AuthenticatedPrincipal(saslServer.getAuthorizationID())); - Subject subject = new Subject(false, - originalSubject.getPrincipals(), - originalSubject.getPublicCredentials(), - originalSubject.getPrivateCredentials()); - subject.getPrincipals().add(new ServletConnectionPrincipal(request)); - subject.setReadOnly(); - - Broker broker = getBroker(); - try - { - HttpManagementUtil.assertManagementAccess(broker.getSecurityManager(), subject); - } - catch(SecurityException e) - { - sendError(response, HttpServletResponse.SC_FORBIDDEN); - return; - } - - HttpManagementUtil.saveAuthorisedSubject(request.getSession(), subject); - session.removeAttribute(ATTR_ID); - session.removeAttribute(ATTR_SASL_SERVER); - session.removeAttribute(ATTR_EXPIRY); - if(challenge != null && challenge.length != 0) - { - Map<String, Object> outputObject = new LinkedHashMap<String, Object>(); - outputObject.put("challenge", new String(Base64.encodeBase64(challenge))); - - final Writer writer = getOutputWriter(request, response); - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, outputObject); - } - response.setStatus(HttpServletResponse.SC_OK); - } - else - { - Random rand = getRandom(session); - id = String.valueOf(rand.nextLong()); - session.setAttribute(ATTR_ID, id); - session.setAttribute(ATTR_SASL_SERVER, saslServer); - session.setAttribute(ATTR_EXPIRY, System.currentTimeMillis() + SASL_EXCHANGE_EXPIRY); - - response.setStatus(HttpServletResponse.SC_OK); - - Map<String, Object> outputObject = new LinkedHashMap<String, Object>(); - outputObject.put("id", id); - outputObject.put("challenge", new String(Base64.encodeBase64(challenge))); - - final Writer writer = getOutputWriter(request, response); - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, outputObject); - } - } - - private SubjectCreator getSubjectCreator(HttpServletRequest request) - { - return HttpManagementUtil.getManagementConfiguration(getServletContext()).getAuthenticationProvider(request).getSubjectCreator( - request.isSecure()); - } - - @Override - protected Subject getAuthorisedSubject(HttpServletRequest request) - { - Subject subject = HttpManagementUtil.getAuthorisedSubject(request.getSession()); - if(subject == null) - { - subject = HttpManagementUtil.tryToAuthenticate(request, HttpManagementUtil.getManagementConfiguration(getServletContext())); - } - return subject; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/StructureServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/StructureServlet.java deleted file mode 100644 index 7508aa2d0b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/StructureServlet.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * <p/> - * http://www.apache.org/licenses/LICENSE-2.0 - * <p/> - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; - -public class StructureServlet extends AbstractServlet -{ - public StructureServlet() - { - super(); - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - - // TODO filtering??? request.getParameter("filter"); // filter=1,2,3 /groups/*/* - - Map<String,Object> structure = generateStructure(getBroker(), Broker.class); - - final Writer writer = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, structure); - - response.setStatus(HttpServletResponse.SC_OK); - - } - - private Map<String, Object> generateStructure(ConfiguredObject object, Class<? extends ConfiguredObject> clazz) - { - Map<String, Object> structure = new LinkedHashMap<String, Object>(); - structure.put("id", object.getId()); - structure.put("name", object.getName()); - - for(Class<? extends ConfiguredObject> childClass : object.getModel().getChildTypes(clazz)) - { - Collection<? extends ConfiguredObject> children = object.getChildren(childClass); - if(children != null) - { - List<Map<String, Object>> childObjects = new ArrayList<Map<String, Object>>(); - - for(ConfiguredObject child : children) - { - childObjects.add(generateStructure(child, childClass)); - } - - if(!childObjects.isEmpty()) - { - structure.put(pluralize(childClass),childObjects); - } - } - } - - return structure; - } - - private String pluralize(Class<? extends ConfiguredObject> childClass) - { - String name = childClass.getSimpleName().toLowerCase(); - return name + (name.endsWith("s") ? "es" : "s"); - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/UserPreferencesServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/UserPreferencesServlet.java deleted file mode 100644 index bbaecca017..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/UserPreferencesServlet.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.model.User; -import org.apache.qpid.server.security.access.Operation; - -public class UserPreferencesServlet extends AbstractServlet -{ - private static final Logger LOGGER = LoggerFactory.getLogger(UserPreferencesServlet.class); - private static final long serialVersionUID = 1L; - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, - ServletException - { - String[] pathElements = getPathInfoElements(request); - if (pathElements != null && pathElements.length > 1) - { - getUserPreferences(pathElements[0], pathElements[1], request, response); - } - else - { - getUserList(pathElements, request, response); - } - } - - private void getUserPreferences(String authenticationProviderName, String userId, HttpServletRequest request, HttpServletResponse response) - throws IOException - { - Map<String, Object> preferences = null; - PreferencesProvider preferencesProvider = getPreferencesProvider(authenticationProviderName); - if (preferencesProvider == null) - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Preferences provider is not configured"); - return; - } - try - { - preferences = preferencesProvider.getPreferences(userId); - - sendJsonResponse(preferences, request, response); - } - catch (SecurityException e) - { - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Viewing of preferences is not allowed"); - return; - } - } - - private void getUserList(String[] pathElements, HttpServletRequest request, HttpServletResponse response) throws IOException - { - List<Map<String, Object>> users = null; - try - { - users = getUsers(pathElements); - } - catch (Exception e) - { - LOGGER.debug("Bad preferences request", e); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); - } - sendJsonResponse(users, request, response); - } - - private PreferencesProvider getPreferencesProvider(String authenticationProviderName) - { - AuthenticationProvider authenticationProvider = getAuthenticationProvider(authenticationProviderName); - if (authenticationProvider == null) - { - throw new IllegalArgumentException(String.format("Authentication provider '%s' is not found", - authenticationProviderName)); - } - PreferencesProvider preferencesProvider = authenticationProvider.getPreferencesProvider(); - return preferencesProvider; - } - - private AuthenticationProvider getAuthenticationProvider(String authenticationProviderName) - { - Broker broker = getBroker(); - Collection<AuthenticationProvider> authenticationProviders = broker.getAuthenticationProviders(); - for (AuthenticationProvider authenticationProvider : authenticationProviders) - { - if (authenticationProviderName.equals(authenticationProvider.getName())) - { - return authenticationProvider; - } - } - return null; - } - - private List<Map<String, Object>> getUsers(String[] pathElements) - { - List<Map<String, Object>> users = new ArrayList<Map<String, Object>>(); - String authenticationProviderName = pathElements != null && pathElements.length > 0 ? pathElements[0] : null; - - Broker broker = getBroker(); - Collection<AuthenticationProvider> authenticationProviders = broker.getAuthenticationProviders(); - for (AuthenticationProvider authenticationProvider : authenticationProviders) - { - if (authenticationProviderName != null && !authenticationProvider.getName().equals(authenticationProviderName)) - { - continue; - } - PreferencesProvider preferencesProvider = authenticationProvider.getPreferencesProvider(); - if (preferencesProvider != null) - { - Set<String> usernames = preferencesProvider.listUserIDs(); - for (String name : usernames) - { - Map<String, Object> userMap = new HashMap<String, Object>(); - userMap.put(User.NAME, name); - userMap.put("authenticationProvider", authenticationProvider.getName()); - users.add(userMap); - } - } - } - return users; - } - - /* - * removes preferences - */ - @Override - protected void doDeleteWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException - { - Broker broker = getBroker(); - Collection<AuthenticationProvider> authenticationProviders = broker.getAuthenticationProviders(); - Map<String, Set<String>> providerUsers = new HashMap<String, Set<String>>(); - Map<String, AuthenticationProvider> requestProviders = new HashMap<String, AuthenticationProvider>(); - for (String path : request.getParameterValues("user")) - { - String[] elements = path.split("/"); - if (elements.length != 2) - { - throw new IllegalArgumentException("Illegal user parameter " + path); - } - - String userId = elements[1]; - - String providerName = elements[0]; - Set<String> users = providerUsers.get(providerName); - - if (users == null) - { - AuthenticationProvider provider = findAuthenticationProviderByName(providerName, authenticationProviders); - if (provider == null) - { - throw new IllegalArgumentException("Cannot find provider with name '" + providerName + "'"); - } - users = new HashSet<String>(); - providerUsers.put(providerName, users); - requestProviders.put(providerName, provider); - } - users.add(userId); - } - - if (!providerUsers.isEmpty()) - { - for (Map.Entry<String, Set<String>> entry : providerUsers.entrySet()) - { - String providerName = entry.getKey(); - AuthenticationProvider provider = requestProviders.get(providerName); - Set<String> usersToDelete = entry.getValue(); - PreferencesProvider preferencesProvider = provider.getPreferencesProvider(); - - if (preferencesProvider != null && !usersToDelete.isEmpty()) - { - String[] users = usersToDelete.toArray(new String[usersToDelete.size()]); - try - { - preferencesProvider.deletePreferences(users); - } - catch (SecurityException e) - { - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Deletion of preferences is not allowed"); - return; - } - } - } - } - - } - - protected AuthenticationProvider findAuthenticationProviderByName(String providerName, Collection<AuthenticationProvider> authenticationProviders) - { - AuthenticationProvider provider = null; - for (AuthenticationProvider authenticationProvider : authenticationProviders) - { - if(authenticationProvider.getName().equals(providerName)) - { - provider = authenticationProvider; - break; - } - } - return provider; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/AbstractSpecialisedAttributeLister.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/AbstractSpecialisedAttributeLister.java deleted file mode 100644 index c697603c6c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/AbstractSpecialisedAttributeLister.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest.action; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; -import java.util.TreeSet; - -import org.apache.qpid.server.management.plugin.servlet.rest.Action; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ConfiguredObjectAttribute; -import org.apache.qpid.server.model.ConfiguredObjectTypeRegistry; - -abstract class AbstractSpecialisedAttributeLister<T extends ConfiguredObject> implements Action -{ - - - private static final String ATTRIBUTES = "attributes"; - private static final String DESCRIPTIONS = "descriptions"; - - @Override - final public Object perform(Map<String, Object> request, Broker broker) - { - ConfiguredObjectTypeRegistry typeRegistry = broker.getModel().getTypeRegistry(); - Collection<Class<? extends ConfiguredObject>> groupProviderTypes = - typeRegistry.getTypeSpecialisations(getCategoryClass()); - - Map<String, Object> attributes = new TreeMap<String, Object>(); - - for (Class<? extends ConfiguredObject> groupProviderType : groupProviderTypes) - { - Collection<ConfiguredObjectAttribute<?, ?>> typeSpecificAttributes = - typeRegistry.getTypeSpecificAttributes(groupProviderType); - - Map<String, Object> data = new HashMap<String, Object>(); - - Collection<String> attributeNames = new TreeSet<>(); - Map<String,String> descriptions = new HashMap<>(); - for(ConfiguredObjectAttribute<?, ?> attr : typeSpecificAttributes) - { - attributeNames.add(attr.getName()); - if(!"".equals(attr.getDescription())) - { - descriptions.put(attr.getName(), attr.getDescription()); - } - } - data.put(ATTRIBUTES, attributeNames); - data.put(DESCRIPTIONS, descriptions); - - attributes.put(ConfiguredObjectTypeRegistry.getType(groupProviderType), data); - } - return attributes; - } - - abstract Class<T> getCategoryClass(); - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListAccessControlProviderAttributes.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListAccessControlProviderAttributes.java deleted file mode 100644 index 1eb3f9a9ac..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListAccessControlProviderAttributes.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest.action; - -import org.apache.qpid.server.model.AccessControlProvider; - -public class ListAccessControlProviderAttributes extends AbstractSpecialisedAttributeLister<AccessControlProvider> -{ - @Override - public String getName() - { - return ListAccessControlProviderAttributes.class.getSimpleName(); - } - - @Override - Class<AccessControlProvider> getCategoryClass() - { - return AccessControlProvider.class; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListBrokerAttribute.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListBrokerAttribute.java deleted file mode 100644 index dc414e6a64..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListBrokerAttribute.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest.action; - -import java.util.Map; - -import org.apache.qpid.server.management.plugin.servlet.rest.Action; -import org.apache.qpid.server.model.Broker; - -public class ListBrokerAttribute implements Action -{ - - private final String _attributeName; - private final String _name; - - public ListBrokerAttribute(String attributeName, String name) - { - _attributeName = attributeName; - _name = name; - } - - @Override - public String getName() - { - return _name; - } - - @Override - public Object perform(Map<String, Object> request, Broker broker) - { - return broker.getAttribute(_attributeName); - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListGroupProviderAttributes.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListGroupProviderAttributes.java deleted file mode 100644 index ecb4320f1f..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListGroupProviderAttributes.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest.action; - -import org.apache.qpid.server.model.GroupProvider; - -public class ListGroupProviderAttributes extends AbstractSpecialisedAttributeLister<GroupProvider> -{ - @Override - public String getName() - { - return ListGroupProviderAttributes.class.getSimpleName(); - } - - @Override - Class<GroupProvider> getCategoryClass() - { - return GroupProvider.class; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListTimeZones.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListTimeZones.java deleted file mode 100644 index 56bc7b1bf7..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListTimeZones.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.management.plugin.servlet.rest.action; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - -import org.apache.qpid.server.management.plugin.servlet.rest.Action; -import org.apache.qpid.server.model.Broker; - -public class ListTimeZones implements Action -{ - - private static final String[] TIMEZONE_REGIONS = { "Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Australia", - "Europe", "Indian", "Pacific" }; - - @Override - public String getName() - { - return ListTimeZones.class.getSimpleName(); - } - - @Override - public Object perform(Map<String, Object> request, Broker broker) - { - List<TimeZoneDetails> timeZoneDetails = new ArrayList<TimeZoneDetails>(); - String[] ids = TimeZone.getAvailableIDs(); - long currentTime = System.currentTimeMillis(); - Date currentDate = new Date(currentTime); - for (String id : ids) - { - int cityPos = id.indexOf("/"); - if (cityPos > 0 && cityPos < id.length() - 1) - { - String region = id.substring(0, cityPos); - for (int i = 0; i < TIMEZONE_REGIONS.length; i++) - { - if (region.equals(TIMEZONE_REGIONS[i])) - { - TimeZone tz = TimeZone.getTimeZone(id); - int offset = tz.getOffset(currentTime)/60000; - String city = id.substring(cityPos + 1).replace('_', ' '); - timeZoneDetails.add(new TimeZoneDetails(id, tz.getDisplayName(tz.inDaylightTime(currentDate), TimeZone.SHORT), offset, city, region)); - break; - } - } - } - } - return timeZoneDetails; - } - - public static class TimeZoneDetails - { - private String id; - private String name; - private int offset; - private String city; - private String region; - - public TimeZoneDetails(String id, String name, int offset, String city, String region) - { - super(); - this.id = id; - this.name = name; - this.offset = offset; - this.city = city; - this.region = region; - } - - public String getId() - { - return id; - } - - public String getName() - { - return name; - } - - public int getOffset() - { - return offset; - } - - public String getCity() - { - return city; - } - - public String getRegion() - { - return region; - } - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/session/LoginLogoutReporter.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/session/LoginLogoutReporter.java deleted file mode 100644 index 7e0d13fddb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/session/LoginLogoutReporter.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.session; - -import java.security.Principal; -import java.security.PrivilegedAction; - -import javax.security.auth.Subject; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionBindingListener; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; - -/** - * Logs {@link ManagementConsoleMessages#OPEN(String)} and {@link ManagementConsoleMessages#CLOSE(String)} - * messages. A single instance of this class must be placed in the {@link HttpSession} immediately after - * the user has successfully logged-in, and removed (or the whole session invalidated) as the user logs out. - */ -public class LoginLogoutReporter implements HttpSessionBindingListener -{ - private static final Logger LOGGER = LoggerFactory.getLogger(LoginLogoutReporter.class); - private final Subject _subject; - private final Principal _principal; - private final EventLoggerProvider _eventLoggerProvider; - - public LoginLogoutReporter(Subject subject, EventLoggerProvider eventLoggerProvider) - { - super(); - _subject = subject; - _principal = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(_subject); - _eventLoggerProvider = eventLoggerProvider; - } - - @Override - public void valueBound(HttpSessionBindingEvent arg0) - { - reportLogin(); - } - - @Override - public void valueUnbound(HttpSessionBindingEvent arg0) - { - reportLogout(); - } - - private void reportLogin() - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("User logging in : " + _principal); - } - - Subject.doAs(_subject, new PrivilegedAction<Void>() - { - @Override - public Void run() - { - getEventLogger().message(ManagementConsoleMessages.OPEN(_principal.getName())); - return null; - } - }); - } - - private void reportLogout() - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("User logging out : " + _principal); - } - - Subject.doAs(_subject, new PrivilegedAction<Void>() - { - @Override - public Void run() - { - getEventLogger().message(ManagementConsoleMessages.CLOSE(_principal.getName())); - return null; - } - }); - } - - public EventLogger getEventLogger() - { - return _eventLoggerProvider.getEventLogger(); - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/aclfile/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/aclfile/add.html deleted file mode 100644 index 796988c410..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/aclfile/add.html +++ /dev/null @@ -1,64 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div id="addAccessControlProvider.oldBrowserWarning" class="infoMessage hidden clear"></div> - <div class="clear"> - <div id="addAccessControlProvider.serverPathLabel" class="formLabel-labelCell tableContainer-labelCell">Server path or upload*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addAccessControlProvider.serverPath" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'serverPath', - placeHolder: 'access control provider file server path', - required: true, - excluded: true, - promptMessage: 'Location of the access control provider file on the server', - title: 'Enter the access control provider file path'" /> - - <!-- Hidden and used purely for form submission --> - <input type="hidden" id="addAccessControlProvider.path" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'path', - required: true" /> - </div> - - <div id="addAccessControlProvider.uploadFields"> - <div id="addAccessControlProvider.fileLabel" class="formLabel-labelCell tableContainer-labelCell"></div> - <div class="fileUpload clear"> - <span id="addAccessControlProvider.selectedFile" class="infoMessage"></span> - <span id="addAccessControlProvider.selectedFileStatus"></span> - </div> - - <div class="fileUpload clear"> - <input type="file" id="addAccessControlProvider.file" - multiple="false" - data-dojo-type="dojox/form/Uploader" - data-dojo-props="label: 'Upload'"/> - <button id="addAccessControlProvider.fileClearButton" - data-dojo-type="dijit/form/Button" - data-dojo-props="label: 'Clear', - disabled: true"> - </button> - </div> - </div> - - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/showAclFile.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/showAclFile.html deleted file mode 100644 index 24cef75737..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/showAclFile.html +++ /dev/null @@ -1,27 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="AclFileProvider"> - <div class="clear"> - <div class="formLabel-labelCell">Path:</div> - <div class="path"></div> - </div> - <div class="clear"></div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addAccessControlProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addAccessControlProvider.html deleted file mode 100644 index 64f8078314..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addAccessControlProvider.html +++ /dev/null @@ -1,66 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit/Dialog" data-dojo-props="title:'Access Control Provider'" id="addAccessControlProvider"> - <div id="addAccessControlProvider.contentPane"> - <form id="addAccessControlProvider.form" method="post" data-dojo-type="dijit/form/Form"> - <div class="formBox"> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Name*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addAccessControlProvider.name" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'access control provider name', - required: true, - promptMessage: 'Name of access control provider, must be unique', - title: 'Enter a unique access control provider name per broker'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Type*:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <select id="addAccessControlProvider.type" data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'type', - required: true, - placeHolder: 'select access control provider type', - promptMessage: 'Type of access control provider', - title: 'Select access control provider type', - searchAttr: 'name'"> - </select> - </div> - </div> - - <div class="clear"> - <div id="addAccessControlProvider.typeFields"></div> - </div> - </div> - </form> - <div class="clear"> - </div> - </div> - - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button data-dojo-type="dijit/form/Button" id="addAccessControlProvider.addButton" data-dojo-props="label: 'Save'" type="submit"></button> - <button data-dojo-type="dijit/form/Button" id="addAccessControlProvider.cancelButton" data-dojo-props="label: 'Cancel'" ></button> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addAuthenticationProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addAuthenticationProvider.html deleted file mode 100644 index 5a565e72e3..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addAuthenticationProvider.html +++ /dev/null @@ -1,64 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit/Dialog" data-dojo-props="title:'Authentication Provider'" id="addAuthenticationProvider"> - <div id="addAuthenticationProvider.contentPane"> - <form id="addAuthenticationProvider.form" method="post" data-dojo-type="dijit/form/Form"> - <div class="formBox"> - <fieldset> - <legend>Authentication Provider</legend> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Name*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addAuthenticationProvider.name" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'authentication provider name', - required: true, - promptMessage: 'Name of authentication provider, must be unique', - title: 'Enter a unique authentication provider name per broker'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Type*:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <select id="addAuthenticationProvider.type" data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'type', - required: true, - placeHolder: 'select authentication provider type', - promptMessage: 'Type of authentication provider', - title: 'Select authentication provider type', - searchAttr: 'name'"> - </select> - </div> - </div> - <div class="clear"></div> - <div id="addAuthenticationProvider.typeFields"></div> - </fieldset> - </div> - </form> - - <div id="addPreferencesProvider.form"></div> - </div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button data-dojo-type="dijit/form/Button" id="addAuthenticationProvider.addButton" data-dojo-props="label: 'Save'" type="submit"></button> - <button data-dojo-type="dijit/form/Button" id="addAuthenticationProvider.cancelButton" data-dojo-props="label: 'Cancel'" ></button> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addBinding.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addBinding.html deleted file mode 100644 index d4ac5877cb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addBinding.html +++ /dev/null @@ -1,64 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit/Dialog" style="width:600px;" data-dojo-props="title:'Add Binding'" id="addBinding"> - <form id="formAddBinding" method="post" data-dojo-type="dijit/form/Form"> - - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Exchange Name*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <div id="addBinding.selectExchangeDiv"></div> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Queue Name*: </div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <div id="addBinding.selectQueueDiv"></div> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Binding Key*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="formAddbinding.bindingKey" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'Binding Key', - required: true, - promptMessage: 'Binding key', - title: 'Enter binding key'" /> - </div> - </div> - - <div class="clear formBox"> - <fieldset> - <legend>Binding Arguments</legend> - <div class="editNoteBanner">NOTE: Only arguments with name and value will be submitted. To edit, please, click on a grid cell.</div> - <div id="formAddbinding.bindingArguments"></div> - <div> - <button data-dojo-type="dijit/form/Button" id="formAddbinding.addArgumentButton" type="button" data-dojo-props="title:'Add new binding argument'">+</button> - <button data-dojo-type="dijit/form/Button" id="formAddbinding.deleteArgumentButton" type="button" data-dojo-props="title:'Remove selected binding argument(s)'">-</button> - </div> - </fieldset> - </div> - - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <input type="submit" value="Create Binding" label="Create Binding" data-dojo-type="dijit/form/Button" /> - </div> - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addExchange.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addExchange.html deleted file mode 100644 index 25e9752392..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addExchange.html +++ /dev/null @@ -1,74 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" style="width:600px;" data-dojo-props="title:'Add Exchange'" id="addExchange"> - <form id="formAddExchange" method="post" dojoType="dijit.form.Form"> - <div class="clear"> - <div class="formLabel-labelCell">Name*:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddExchange.name" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'exchange name', - required: true, - promptMessage: 'Name of exchange', - title: 'Enter an exchange name', - regExp:'^(?!qpid\.|amq\.|\<\<default\>\>)[\x20-\x2e\x30-\x7F]{1,255}$', - invalidMessage:'Illegal or reserved exchange name!'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Exchange Type:</div> - <div class="formLabel-controlCell"> - <select id="formAddExchange.type" - dojoType="dijit.form.FilteringSelect" - data-dojo-props=" - name: 'type', - promptMessage: 'Type of exchange - responsible for routing messages to queues'"> - <option value="direct">direct</option> - <option value="topic">topic</option> - <option value="headers">headers</option> - <option value="fanout">fanout</option> - </select> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Durable?</div> - <div class="formLabel-controlCell"> - <input type="checkbox" id="formAddExchange.durable" - dojoType="dijit.form.CheckBox" - data-dojo-props=" - name: 'durable', - value: 'durable', - checked: true"/> - </div> - </div> - - - <div class="clear"></div> - - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <input type="submit" value="Create Exchange" label="Create Exchange" dojoType="dijit.form.Button" /> - </div> - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addGroupProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addGroupProvider.html deleted file mode 100644 index b622fe94d2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addGroupProvider.html +++ /dev/null @@ -1,66 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div class="dijitHidden"> - <div data-dojo-type="dijit/Dialog" data-dojo-props="title:'Add Store'" id="addGroupProvider"> - <div id="addGroupProvider.contentPane"> - <form id="addGroupProvider.form" method="post" data-dojo-type="dijit/form/Form"> - <div class="formBox"> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Name*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addGroupProvider.name" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'group provider name', - required: true, - promptMessage: 'Name of group provider, must be unique', - title: 'Enter a unique group provider name per broker'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Type*:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <select id="addGroupProvider.type" data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'type', - required: true, - placeHolder: 'group provider type', - promptMessage: 'Type of group provider', - title: 'Select type', - searchAttr: 'name'"> - </select> - </div> - </div> - <div class="clear"> - <div id="addGroupProvider.typeFields"></div> - </div> - </div> - </form> - <div class="clear"> - </div> - </div> - - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button data-dojo-type="dijit/form/Button" id="addGroupProvider.addButton" data-dojo-props="label: 'Save'" type="submit"></button> - <button data-dojo-type="dijit/form/Button" id="addGroupProvider.cancelButton" data-dojo-props="label: 'Cancel'" ></button> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addPort.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addPort.html deleted file mode 100644 index 10b79987a5..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addPort.html +++ /dev/null @@ -1,260 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" data-dojo-props="title:'Port'" id="addPort"> - <form id="formAddPort" method="post" data-dojo-type="dijit.form.Form"> - <div class="hidden infoMessage" id="portEditWarning">NOTE: changes will only take effect after Broker restart.</div> - <div id="formAddPort:fields"> - - <div class="clear"> - <div class="formLabel-labelCell"> - <label for="formAddPort.name">Name*:</label> - </div> - <div class="formLabel-controlCell"> - <input id="formAddPort.name" type="text" - data-dojo-type="dijit.form.ValidationTextBox" - data-dojo-props=" - name: 'name', - required: 'true', - placeHolder: 'name', - promptMessage: 'Name of port, must be unique', - title: 'Enter name of port'"/> - </div> - </div> - - <div class="clear"> - <div class="formLabel-labelCell"> - <label for="formAddPort.type">Port Type*:</label> - </div> - <div class="formLabel-controlCell"> - <select id="formAddPort.type" - data-dojo-type="dijit.form.FilteringSelect" - data-dojo-props=" - name: 'type', - label: 'Port Type*:', - value: '', - placeHolder: 'port type', - promptMessage: 'Port type', - title: 'Enter port type'"> - </select> - </div> - </div> - - <div class="clear"> - <div class="formLabel-labelCell"> - <label for="formAddPort.port">Port Number*:</label> - </div> - <div class="formLabel-controlCell"> - <input id="formAddPort.port" type="text" - data-dojo-type="dijit.form.ValidationTextBox" - data-dojo-props=" - name: 'port', - required: 'true', - placeHolder: 'port number', - promptMessage: 'Port number to be bound', - title: 'Enter port number'"/> - </div> - </div> - </div> - - <div id="formAddPort:fieldsProtocols"> - <div class="clear"> - <div class="formLabel-labelCell"> - <label for="formAddPort.protocols">Protocols:</label> - </div> - <div class="formLabel-controlCell"> - <select id="formAddPort.protocols" - data-dojo-type="dijit.form.MultiSelect" - data-dojo-props=" - name: 'protocols', - value: '', - title: 'Select protocol(s) to be associated with this port'"> - </select> - </div> - <div id="formAddPort.protocols.tooltip" - data-dojo-type="dijit.Tooltip" - data-dojo-props="connectId: 'formAddPort.protocols', - label: 'Protocol(s) to be associated with the port'"> - </div> - - </div> - </div> - - <div id="formAddPort:fieldsAuthenticationProvider"> - <div class="clear"> - <div class="formLabel-labelCell"> - <label for="formAddPort.authenticationProvider">Authentication Provider*:</label> - </div> - <div class="formLabel-controlCell"> - <select id="formAddPort.authenticationProvider" - data-dojo-type="dijit.form.FilteringSelect" - data-dojo-props=" - name: 'authenticationProvider', - searchAttr: 'name', - required: true, - placeHolder: 'provider', - promptMessage: 'Authentication provider to authenticate users connecting to the port', - title: 'Associate the port with an authentication provider'"> - </select> - </div> - </div> - </div> - - <div id="formAddPort:fieldsBindingAddress"> - <div class="clear"> - <div class="formLabel-labelCell"> - <label for="formAddPort.bindingAddress">Binding address:</label> - </div> - <div class="formLabel-controlCell"> - <input id="formAddPort.bindingAddress" type="text" - data-dojo-type="dijit.form.ValidationTextBox" - data-dojo-props=" - name: 'bindingAddress', - placeHolder: 'binding address', - promptMessage: 'Restricts the port to listen on the specified address only. The <code>*</code> wildcard signifies all addresses', - title: 'Enter a binding address'"/> - </div> - </div> - </div> - - <div id="formAddPort:transport" > - <div class="clear"> - <div class="formLabel-labelCell"> - <label for="formAddPort.transports">Transport:</label> - </div> - <div class="formLabel-controlCell"> - <select id="formAddPort.transports" - data-dojo-type="dijit.form.MultiSelect" - data-dojo-props=" - name: 'transports', - placeHolder: 'TCP', - value: '', - multiple: true, - title: 'Select transport(s) to be associated with the port'"> - </select> - <div id="formAddPort.transports.tooltip" - data-dojo-type="dijit.Tooltip" - data-dojo-props="connectId: 'formAddPort.transports', - label: 'Transport(s) to be associated with the port'"> - </div> - </div> - </div> - </div> - - <div id="formAddPort:maxOpenConnections" > - <div class="clear"> - <div class="formLabel-labelCell"> - <label for="formAddPort.transports">Maximum number of connections:</label> - </div> - <div class="formLabel-controlCell"> - <input id="formAddPort.maxOpenConnections" type="text" - data-dojo-type="dijit.form.ValidationTextBox" - data-dojo-props=" - name: 'maxOpenConnections', - placeHolder: 'maximum number of connections', - promptMessage: 'Maximum number of concurrent connections permitted by this port. The <code>-1</code> signifies no limit is imposed.', - title: 'Enter a maximum number of connections'"/> - </div> - </div> - </div> - - <div id="formAddPort:fieldsTransportSSL"> - <div class="clear"> - <div class="formLabel-labelCell"> - <label for="formAddPort.keyStore">Key Store*:</label> - </div> - <div class="formLabel-controlCell"> - <select id="formAddPort.keyStore" - data-dojo-type="dijit.form.FilteringSelect" - data-dojo-props=" - name: 'keyStore', - label: 'Key Store*:', - searchAttr: 'name', - placeHolder: 'keystore', - value: '', - required: true, - promptMessage: 'Keystore that provides the SSL certificate', - title: 'Select the keystore that provides the SSL certificate'"> - </select> - </div> - </div> - </div> - - <div id="formAddPort:fieldsClientAuth"> - <div id="formAddPort:fieldsClientAuthCheckboxes"> - <div class="clear"> - <div class="formLabel-labelCell"> - <label for="formAddPort.needClientAuth">Need SSL Client Certificate:</label> - </div> - <div class="formLabel-controlCell"> - <input id="formAddPort.needClientAuth" type="checkbox" - data-dojo-type="dijit.form.CheckBox" - data-dojo-props=" - name: 'needClientAuth'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell"> - <label for="formAddPort.wantClientAuth">Want SSL Client Certificate:</label> - </div> - <div class="formLabel-controlCell"> - <input id="formAddPort.wantClientAuth" type="checkbox" - data-dojo-type="dijit.form.CheckBox" - data-dojo-props=" - name: 'wantClientAuth'" /> - </div> - </div> - </div> - - <div class="clear"> - <div class="formLabel-labelCell"> - Trust Stores: - </div> - </div> - - <div class="clear"> - <div class="formLabel-controlCell"> - <table id="formAddPort.trustStores" - data-dojo-type="dojox.grid.EnhancedGrid" - data-dojo-props=" - plugins: {indirectSelection: true}, - rowSelector:'0px'" - style="height: 100px; width:400px"> <!--todo remove --> - <thead> - <tr> - <th field="name">Name</th> - <th field="peersOnly">Peers Only</th> - </tr> - </thead> - </table> - </div> - </div> - </div> - - <input type="hidden" id="formAddPort.id" name="id"/> - <div class="clear"></div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <!-- submit buttons --> - <input type="submit" value="Save Port" label="Save Port" dojoType="dijit.form.Button" /> - </div> - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addPreferencesProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addPreferencesProvider.html deleted file mode 100644 index e3984e1ae2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addPreferencesProvider.html +++ /dev/null @@ -1,28 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit/Dialog" data-dojo-props="title:'Preferences Provider'" id="addPreferencesProvider"> - - <div id="addPreferencesProvider.preferencesProvider" data-dojo-type="qpid/management/preferencesprovider/PreferencesProviderForm"></div> - - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <!-- submit buttons --> - <input type="button" value="Save" data-dojo-props="label: 'Save'" data-dojo-type="dijit/form/Button" id="addPreferencesProvider.saveButton"/> - <input type="button" value="Cancel" data-dojo-props="label: 'Cancel'" data-dojo-type="dijit/form/Button" id="addPreferencesProvider.cancelButton"/> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addQueue.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addQueue.html deleted file mode 100644 index 61f0de22d8..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addQueue.html +++ /dev/null @@ -1,344 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" data-dojo-props="title:'Add Queue'" id="addQueue"> - <form id="formAddQueue" method="post" dojoType="dijit.form.Form"> - - <div class="clear"> - <div class="formLabel-labelCell">Queue Name*:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.name" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'queue name', - required: true, - promptMessage: 'Name of queue', - title: 'Enter a queue name', - regExp:'^[\x20-\x2e\x30-\x7F]{1,255}$'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Queue Type:</div> - <div class="formLabel-controlCell"> - <select id="formAddQueue.type" - dojoType="dijit.form.FilteringSelect" - data-dojo-props=" - name: 'type', - value: 'standard', - searchAttr: 'name', - required: true, - promptMessage: 'Type of Queue', - title: 'Enter the queue type'"> - <option value="standard">Standard</option> - <option value="priority">Priority</option> - <option value="lvq">LVQ</option> - <option value="sorted">Sorted</option> - </select> - </div> - </div> - <div class="clear"></div> - - <div id="formAddQueueType:priority" class="hidden typeSpecificDiv"> - <div class="clear"> - <div class="formLabel-labelCell">Priorities:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.priorities" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'priorities', - placeHolder: 'number of priorities', - promptMessage: 'Number of priorities supported by the queue', - title: 'Enter the number of priorities supported by the queue', - trim: true"/> - </div> - </div> - <div class="clear"></div> - </div> - - <div id="formAddQueueType:lvq" class="hidden typeSpecificDiv"> - <div class="clear"> - <div class="formLabel-labelCell">LVQ Message Property:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.lvqKey" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'lvqKey', - placeHolder: 'lvq key', - promptMessage: 'Name of the message property used to perform the conflation', - title: 'Enter the name of the message property used to perform the conflation', - trim: true"/> - </div> - </div> - <div class="clear"></div> - </div> - - <div id="formAddQueueType:sorted" class="hidden typeSpecificDiv"> - <div class="clear"> - <div class="formLabel-labelCell">Sort Message Property*:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.sortKey" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'sortKey', - placeHolder: 'sort key', - promptMessage: 'Name of the message property used for sorting the messages on the queue', - title: 'Enter the name of the message property used for sorting the messages on the queue', - trim: true"/> - </div> - </div> - <div class="clear"></div> - </div> - - <div class="clear"> - <div class="formLabel-labelCell">Durable?</div> - <div class="formLabel-controlCell"> - <input type="checkbox" id="formAddQueue.durable" - dojoType="dijit.form.CheckBox" - data-dojo-props=" - name: 'durable', - value: 'durable', - checked: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Persist Messages?</div> - <div class="formLabel-controlCell"> - <select id="formAddQueue.messageDurability" - dojoType="dijit.form.FilteringSelect" - data-dojo-props=" - name: 'messageDurability', - value: '', - searchAttr: 'name', - required: false, - promptMessage: 'Message persistence override. If not default, messages arriving will have persistence setting overridden', - title: 'Enter message persistence override'"> - <option value="ALWAYS">Always</option> - <option value="DEFAULT">Default</option> - <option value="NEVER">Never</option> - </select> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Maximum Ttl:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.maximumMessageTtl" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'maximumMessageTtl', - placeHolder: 'ttl in ms', - promptMessage: 'Maximum message time to live (ttl) in ms. Messages arriving with larger ttl values will be overridden by this value', - title: 'Enter the maximum message time to live in milliseconds', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Minimum Ttl:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.minimumMessageTtl" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'minimumMessageTtl', - placeHolder: 'ttl in ms', - promptMessage: 'Minimum message time to live (ttl) in ms. Messages arriving with smaller ttl values will be overridden by this value', - title: 'Enter the minimum message time to live in milliseconds', - trim: true"/> - </div> - </div> - - <div class="clear formBox"> - <fieldset> - <legend>Flow Control Settings</legend> - <div class="clear"> - <div class="formLabel-labelCell">Capacity:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.capacity" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'queueFlowControlSizeBytes', - placeHolder: 'size in bytes', - promptMessage: 'Ceiling (in bytes) at which queue will begin to throttle sessions producing messages', - title: 'Enter the ceiling (in bytes) at which queue will begin to throttle sessions producing messages', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Resume Capacity:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.flowResumeCapacity" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'queueFlowResumeSizeBytes', - placeHolder: 'size in bytes', - promptMessage: 'Floor (in bytes) at which queue will cease to throttle sessions producing messages', - title: 'Enter the floor (in bytes) at which queue will cease to throttle sessions producing messages', - trim: true"/> - </div> - </div> - </fieldset> - <div class="clear"></div> - </div> - - <div class="clear formBox"> - <fieldset> - <legend>Alerting Settings</legend> - <div class="clear"> - <div class="formLabel-labelCell">Queue Depth:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.maximumMessageCount" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'alertThresholdQueueDepthMessages', - placeHolder: 'number of messages', - promptMessage: 'Ceiling value for number of messages on queue before alerts will be generated', - title: 'Enter the ceiling value for number of messages on queue before alerts will be generated', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Queue Depth:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.maximumQueueDepth" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'alertThresholdQueueDepthBytes', - placeHolder: 'total message size in bytes', - promptMessage: 'Ceiling value (in bytes) for total size of all messages on the queue before alerts will be generated', - title: 'Enter the ceiling value (in bytes) for total size of all messages on the queue before alerts will be generated', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Message Age:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.maximumMessageAge" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'alertThresholdMessageAge', - placeHolder: 'time in ms', - promptMessage: 'Message age (in milliseconds) above which alerts will be generated', - title: 'Enter the message age (in milliseconds) above which alerts will be generated', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Message Size:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.maximumMessageSize" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'alertThresholdMessageSize', - placeHolder: 'message size in bytes', - promptMessage: 'Message size (in bytes) above which alerts will be generated', - title: 'Enter the message size (in bytes) above which alerts will be generated', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Gap between alerts:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.alertRepeatGap" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'alertRepeatGap', - placeHolder: 'time in ms', - promptMessage: 'Minimum time (in milliseconds) between each alert', - title: 'Enter the minimum time (in milliseconds) between each alert.', - trim: true"/> - </div> - </div> - </fieldset> - <div class="clear"></div> - </div> - - <div class="clear formBox"> - <fieldset> - <legend>Other Settings</legend> - <div class="clear"> - <div class="formLabel-labelCell">Maximum Delivery Retries:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.maximumDeliveryAttempts" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'maximumDeliveryAttempts', - placeHolder: 'number of retries', - promptMessage: 'Maximum number of delivery attempts before the message will be sent to the alternate exchange', - title: 'Enter the maximum number of delivery attempts before the message will be sent to the alternate exchange', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Create DLQ?</div> - <div class="formLabel-controlCell"> - <input type="checkbox" id="formAddQueue.dlqEnabled" - dojoType="dijit.form.CheckBox" - data-dojo-props=" - name: 'dlqEnabled', - value: 'dlqEnabled', - title: 'Controls where a dead letter queue is automatically created', - checked: false"/> - </div> - </div> - - <div class="clear"></div> - <div class="infoMessage">Configuring maximum delivery retries on a queue which has no DLQ or alternate <br/>exchange will result in messages being discarded after the limit is reached.</div> - - <div class="clear"> - <div class="formLabel-labelCell">Message Group Key:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formAddQueue.messageGroupKey" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'messageGroupKey', - placeHolder: 'message group key', - promptMessage: 'Name of the message property used for message grouping', - title: 'Enter the name of the message property used for message grouping', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Shared Message Groups?</div> - <div class="formLabel-controlCell"> - <input type="checkbox" id="formAddQueue.messageGroupSharedGroups" - dojoType="dijit.form.CheckBox" - data-dojo-props=" - name: 'messageGroupSharedGroups', - value: 'messageGroupSharedGroups', - checked: false, - title: 'Controls where a shared groups feature is enabled'"/> - </div> - </div> - </fieldset> - <div class="clear"></div> - </div> - - <div class="clear" data-dojo-type="dijit/TitlePane" data-dojo-props="title: 'Context variables', open: false"> - <div id="formAddQueue.context" ></div> - </div> - - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <!-- submit buttons --> - <input type="submit" value="Create Queue" label="Create Queue" dojoType="dijit.form.Button" /> - </div> - - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addStore.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addStore.html deleted file mode 100644 index a1903d456e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addStore.html +++ /dev/null @@ -1,66 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div class="dijitHidden"> - <div data-dojo-type="dijit/Dialog" data-dojo-props="title:'Add Store'" id="addStore"> - <div id="addStore.contentPane"> - <form id="addStore.form" method="post" data-dojo-type="dijit/form/Form"> - <div class="formBox"> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Name*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.name" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'store name', - required: true, - promptMessage: 'Name of store, must be unique', - title: 'Enter a unique store name per broker'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Type*:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <select id="addStore.type" data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'type', - required: true, - placeHolder: 'store type', - promptMessage: 'Type of store', - title: 'Select type', - searchAttr: 'name'"> - </select> - </div> - </div> - <div class="clear"> - <div id="addStore.typeFields"></div> - </div> - </div> - </form> - <div class="clear"> - </div> - </div> - - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button data-dojo-type="dijit/form/Button" id="addStore.addButton" data-dojo-props="label: 'Save'" type="submit"></button> - <button data-dojo-type="dijit/form/Button" id="addStore.cancelButton" data-dojo-props="label: 'Cancel'" ></button> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addVirtualHostNodeAndVirtualHost.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addVirtualHostNodeAndVirtualHost.html deleted file mode 100644 index a2ee2c1b4b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addVirtualHostNodeAndVirtualHost.html +++ /dev/null @@ -1,136 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" style="width:600px;" data-dojo-props="title:'Add'" id="addVirtualHostNodeAndVirtualHost"> - <div id="addVirtualHostNodeAndVirtualHost.contentPane"> - - <!-- VHN Form --> - <form id="addVirtualHostNode.form" method="post" data-dojo-type="dijit/form/Form"> - <div class="formBox"> - <fieldset> - <legend>Virtual Host Node</legend> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Name*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHostNode.nodeName" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'node name', - required: true, - promptMessage: 'Name of node, must be unique', - title: 'Enter a unique node name per broker'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Type*:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <select id="addVirtualHostNode.type" data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'type', - required: true, - disabled: true, - placeHolder: 'select virtual host node type', - promptMessage: 'Type of virtual host node', - title: 'Select virtual host node type', - searchAttr: 'name'"> - </select> - </div> - </div> - <div class="clear"></div> - - <div id="addVirtualHostNode.typeFields"></div> - - <div id="addVirtualHostNode.uploadFields" class="clear"> - <div class="formLabel-labelCell"> - <label for="addVirtualHostNode.upload">Upload virtualhost configuration from file:</label> - </div> - <div class="formLabel-controlCell"> - <input id="addVirtualHostNode.upload" type="checkbox" - data-dojo-type="dijit.form.CheckBox" - data-dojo-props=" - name: 'upload'" /> - </div> - <div id="addVirtualHostNode.fileFields" class="clear"> - <div class="formLabel-labelCell"> - <label for="addVirtualHostNode.file">Select JSON file*:</label> - </div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input type="file" id="addVirtualHostNode.file" - multiple="false" - data-dojo-type="dojox.form.Uploader" - data-dojo-props=" - label: 'Select'"/> - <span id="addVirtualHostNode.selectedFile" class="infoMessage"></span> - <span id="addVirtualHostNode.selectedFileStatus"></span> - </div> - </div> - </div> - - <div class="clear"></div> - - <div data-dojo-type="dijit/TitlePane" data-dojo-props="title: 'Context variables', open: false"> - <div id="addVirtualHostNode.context"></div> - </div> - - - </fieldset> - </div> - </form> - - <!-- VH Form --> - <form id="addVirtualHost.form" method="post" data-dojo-type="dijit/form/Form"> - <div class="formBox"> - <fieldset> - <legend>Virtual Host</legend> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Type*:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <select id="addVirtualHost.type" data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'type', - required: true, - disabled: true, - placeHolder: 'select virtual host type', - promptMessage: 'Type of virtual host', - title: 'Select virtual host type', - searchAttr: 'name'"> - </select> - </div> - </div> - <div class="clear"></div> - - <div id="addVirtualHost.typeFields"></div> - - <div data-dojo-type="dijit/TitlePane" data-dojo-props="title: 'Context variables', open: false"> - <div id="addVirtualHost.context"></div> - </div> - - </fieldset> - </div> - </form> - </div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button data-dojo-type="dijit/form/Button" id="addVirtualHostNodeAndVirtualHost.addButton" data-dojo-props="label: 'Add'" type="submit"></button> - <button data-dojo-type="dijit/form/Button" id="addVirtualHostNodeAndVirtualHost.cancelButton" data-dojo-props="label: 'Cancel'" ></button> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/addUser.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/addUser.html deleted file mode 100644 index 785605f694..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/addUser.html +++ /dev/null @@ -1,42 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" style="width:600px;" data-dojo-props="title:'Add User'" id="addUser"> - <form id="formAddUser" method="post" dojoType="dijit.form.Form"> - <table cellpadding="0" cellspacing="2"> - <tr> - <td valign="top"><strong>User Name*: </strong></td> - <td><input type="text" required="true" name="name" id="formAddUser.name" placeholder="User Name" - dojoType="dijit.form.ValidationTextBox" missingMessage="A name must be supplied" /></td> - </tr> - <tr> - <td valign="top"><strong>Password*</strong></td> - <td><input type="password" required="true" name="password" id="formAddUser.password" dojoType="dijit.form.ValidationTextBox"/></td> - </tr> - </table> - <br/> - - <!-- submit buttons --> - <input type="submit" value="Create User" label="Create User" dojoType="dijit.form.Button" /> - - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/add.html deleted file mode 100644 index 11a9bf8ea0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/add.html +++ /dev/null @@ -1,30 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Use full DN:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" class="useFullDN" id="external.useFullDN" - data-dojo-type="dijit/form/CheckBox" - data-dojo-props=" name: 'useFullDN' " /> - </div> - <div data-dojo-type="dijit/Tooltip" - data-dojo-props="connectId: ['external.useFullDN'], - label: 'If selected, full distinguished name will be used as principal name'"> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/show.html deleted file mode 100644 index ac065c723c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/show.html +++ /dev/null @@ -1,26 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell">Use full DN:</div> - <div ><span class="useFullDN" ></span></div> - </div> - <div class="clear"></div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/add.html deleted file mode 100644 index 53eb786722..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/add.html +++ /dev/null @@ -1,31 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Path*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" class="path" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'path', - required: true, - placeHolder: 'path/to/store', - title: 'Enter path to user store', - promptMessage: 'File system location for the users store.'"/> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/show.html deleted file mode 100644 index 5060656964..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/show.html +++ /dev/null @@ -1,26 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell">Path to file:</div> - <div ><span class="path" ></span></div> - </div> - <div class="clear"></div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/setPassword.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/setPassword.html deleted file mode 100644 index 3d67463abd..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/setPassword.html +++ /dev/null @@ -1,42 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" style="width:600px;" data-dojo-props="title:'Set Password'" id="setPassword"> - <form id="formSetPassword" method="post" dojoType="dijit.form.Form"> - <table cellpadding="0" cellspacing="2"> - <tr> - <td valign="top"><strong>User Name: </strong></td> - <td><input type="text" required="true" name="name" id="formSetPassword.name" placeholder="User Name" - dojoType="dijit.form.TextBox" enabled="false" /></td> - </tr> - <tr> - <td valign="top"><strong>Password*</strong></td> - <td><input type="password" required="true" name="password" id="formSetPassword.password" dojoType="dijit.form.ValidationTextBox"/></td> - </tr> - </table> - <br/> - - <!-- submit buttons --> - <input type="submit" value="Set Password" label="Set Password" dojoType="dijit.form.Button" /> - - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/showPrincipalDatabaseAuthenticationManager.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/showPrincipalDatabaseAuthenticationManager.html deleted file mode 100644 index e6c067fddf..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/showPrincipalDatabaseAuthenticationManager.html +++ /dev/null @@ -1,27 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="PrincipalDatabaseAuthenticationManager"> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Users'"> - <div class="users"></div> - <button data-dojo-type="dijit.form.Button" class="addUserButton">Add User</button> - <button data-dojo-type="dijit.form.Button" class="deleteUserButton">Delete Users</button> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/add.html deleted file mode 100644 index 3a3b613564..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/add.html +++ /dev/null @@ -1,133 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">LDAP server URL*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" class="providerUrl" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'providerUrl', - required: true, - placeHolder: 'ldap://host:port', - title: 'Enter LDAP server URL', - promptMessage: 'LDAP server URL'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">LDAP authentication URL</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" class="providerAuthUrl" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'providerAuthUrl', - placeHolder: 'ldap://host:port', - title: 'Enter optional LDAP authentication URL', - promptMessage: 'URL of LDAP server for performing \'ldap bind\'. If not specified, the LDAP server URL will be used for both searches and authentications'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Trust Store:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <select class="trustStore" data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - required: false, - name: 'trustStore', - placeHolder: 'Select trust store', - promptMessage: 'Select the trust store containing the certificate of the CA that signs to LDAP servers certificate', - title: 'Select trust store for secure connection', - searchAttr: 'name'"> - </select> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Search context*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" class="searchContext" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'searchContext', - required: true, - placeHolder: 'dc=users,dc=example,dc=com', - title: 'Enter search context', - promptMessage: 'Identifies the entry that is the base of the subtree containing users'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Search filter*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" class="searchFilter" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'searchFilter', - required: true, - placeHolder: '(uid={0})', - title: 'Enter user search filter ', - promptMessage: 'Filter expression used to locate users within the subtree. {0} will be replaced by the user id.'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Search username:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" class="searchUsername" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'searchUsername', - placeHolder: 'username', - title: 'Enter username for authenticated search', - promptMessage: 'The username used to authenticate to the directory in order to perform the search. If not specified, an anonymous bind is used to perform the search'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Search password:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="password" class="searchPassword" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'searchPassword', - placeHolder: '****', - title: 'Enter password for authenticated search', - promptMessage: 'The password to be used with the search username'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Authenticate without search:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" class="bindWithoutSearch" id="addAuthenticationProvider.simpleldap.bindWithoutSearch" - data-dojo-type="dijit/form/CheckBox" - data-dojo-props=" name: 'bindWithoutSearch' " /> - </div> - </div> - <div data-dojo-type="dijit/Tooltip" - data-dojo-props="connectId: ['addAuthenticationProvider.simpleldap.bindWithoutSearch'], - label: 'If selected, the provider will not search the directory'"> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">LDAP Context Factory:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" class="ldapContextFactory" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'ldapContextFactory', - placeHolder: 'com.sun.jndi.ldap.LdapCtxFactory', - title: 'Enter fully qualified class name for LDAP Context Factory', - promptMessage: 'Fully qualified class name for LDAP Context Factory'"/> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/show.html deleted file mode 100644 index e2f1da32af..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/show.html +++ /dev/null @@ -1,58 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell">LDAP server URL:</div> - <div ><span class="providerUrl" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Search context:</div> - <div><span class="searchContext" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Search filter:</div> - <div><span class="searchFilter" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Search user name:</div> - <div><span class="searchUsername" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Search password:</div> - <div><span class="searchPassword" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Trust Store:</div> - <div><span class="trustStore" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Bind without search:</div> - <div><span class="bindWithoutSearch" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">LDAP Context Factory:</div> - <div><span class="ldapContextFactory" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">LDAP authentication URL:</div> - <div><span class="providerAuthUrl" ></span></div> - </div> - <div class="clear"></div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ContextVariablesEditor.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ContextVariablesEditor.html deleted file mode 100644 index 60fc0843eb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ContextVariablesEditor.html +++ /dev/null @@ -1,35 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div class="contextEditor"> - <div class="contextGrid"> - <div class="grid"></div> - </div> - <div> - <button data-dojo-type="dijit/form/Button" class="addButton" type="button" data-dojo-props="title:'Add new entry'">+</button> - <button data-dojo-type="dijit/form/Button" class="deleteButton" type="button" data-dojo-props="title:'Remove selected entry'">-</button> - <span class="dijit dijitReset dijitInline"> - <label>Show</label> - <select class="filter" name="filter" data-dojo-type="dijit/form/Select"> - <option value="*" selected="selected">All</option> - <option value="false">Local</option> - <option value="true" >Inherited</option> - </select> - </span> - </div> -</div>
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ResourceWidget.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ResourceWidget.html deleted file mode 100644 index e47fa6ca6d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ResourceWidget.html +++ /dev/null @@ -1,48 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> - -<div class="dijit dijitReset dijitInline dijitLeft" id="widget_${id}" role="presentation"> - <input type="text" name="${name}_resourceLocation" - data-dojo-attach-point="resourceLocation,textbox,focusNode" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props="required:true,disabled:false"/> - - <div data-dojo-attach-point="uploadFields"> - <div data-dojo-attach-point="uploadData" style="width:auto;overflow:hidden;text-align:right"> - <span data-dojo-attach-point="selectedFile" class="infoMessage"></span> - <span data-dojo-attach-point="selectedFileStatus"></span> - </div> - <div style="text-align:right"> - <span data-dojo-attach-point="blah"></span> - <input name="${name}_uploadedFile" multiple="false" type="file" id="uploader_${id}" - data-dojo-attach-point="uploader" - data-dojo-type="dojox/form/Uploader" - data-dojo-props="label: 'Upload'"/> - <button data-dojo-attach-point="clearButton" data-dojo-type="dijit/form/Button" - data-dojo-props="label: 'Clear', disabled: true"/>Clear</button> - - </div> - <div class="clear"></div> - </div> - <div data-dojo-attach-point="unsupportedWarning" class="infoMessage hidden clear" style="overflow:scroll;"> - File upload requires a more recent browser with HTML5 support - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/TimeZoneSelector.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/common/TimeZoneSelector.html deleted file mode 100644 index 2b2fca7d8a..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/TimeZoneSelector.html +++ /dev/null @@ -1,66 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<table cellpadding="0" cellspacing="2"> - <tr> - <td class="labelClass"><strong>Use UTC time:</strong></td> - <td> - <input type="checkbox" class='utcSelector' name="utc" data-dojo-type="dijit/form/CheckBox" value="UTC"></input> - </td> - </tr> - <tr> - <td class="labelClass"><strong>Time Zone:</strong></td> - <td> - <table cellpadding="0" cellspacing="2"> - <tr> - <td>Region</td> - <td><select class='timezoneRegion' name="region" data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - placeholder: 'Select region', - required: true, - missingMessage: 'A region must be supplied', - title: 'Select region', - autoComplete: true, - value:'undefined'"> - <option value="undefined">Undefined</option> - <option value="Africa">Africa</option> - <option value="America">America</option> - <option value="Antarctica">Antarctica</option> - <option value="Arctic">Arctic</option> - <option value="Asia">Asia</option> - <option value="Atlantic">Atlantic</option> - <option value="Australia">Australia</option> - <option value="Europe">Europe</option> - <option value="Indian">Indian</option> - <option value="Pacific">Pacific</option> - </select></td> - <td>City</td> - <td><select class='timezoneCity' name="city" data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - placeholder: 'Select city', - required: true, - missingMessage: 'A city must be supplied', - title: 'Select city'"> - </select></td> - </tr> - </table> - </td> - </tr> -</table>
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/css/apidocs.css b/qpid/java/broker-plugins/management-http/src/main/java/resources/css/apidocs.css deleted file mode 100644 index 5baecf7c02..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/css/apidocs.css +++ /dev/null @@ -1,86 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -html, body { - margin-top: 20px; - margin-left: 40px; - margin-right: 40px; - padding: 0; - font-family: Lucida Sans,Lucida Grande,Arial,sans-serif !important; - font-size: 13px !important; - background: white; - color: #333; -} - -th, td { - text-align: left; -} - -.type { - font-family: "Courier New", courier, monospace; -} - -table.types td.name { - width: 20em; -} - -table.attributes td.name { - font-family: "Courier New", courier, monospace; - width: 20em; -} - -table.attributes td.type { - width: 7em; -} - -table.api td,th { - vertical-align: top; -} - - -table.api td.type { - width: 12em; -} - - -table.api td.path { - width: 20em; -} - - -table.api td.description { - width: 25em; -} - -table.api a:link { - color: #333; - text-decoration: none; -} - -table.api a:visited { - color: #666; - text-decoration: none; -} - - -div.restriction { - border-bottom: 1px dotted #666; - display: inline; -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/css/common.css b/qpid/java/broker-plugins/management-http/src/main/java/resources/css/common.css deleted file mode 100644 index ec31709987..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/css/common.css +++ /dev/null @@ -1,339 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -* { - outline: none !important; -} - -html, body { - height: 100%; - margin: 0; - margin-right: 40px; - padding: 0; - overflow: hidden; - font-family: Lucida Sans,Lucida Grande,Arial !important; - font-size: 13px !important; - background: white; - color: #333; -} - -.clear { - clear: both; -} - -.hidden { - display: none; -} - -#pageLayout { - height: 100%; -} -button { - -webkit-transition: background-color 0.2s linear; - border-radius:4px; - -moz-border-radius: 4px 4px 4px 4px; - -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15); - background-color: #E4F2FF; - background-position: center top; - background-repeat: repeat-x; - border: 1px solid #769DC0; - padding: 2px 8px 4px; - font-size:1em; -} - -button:hover { - background-color: #AFD9FF; - color: #000000; -} - -h1 { - font-size:1.5em; -} - -.header { - height:100px; - background:url("../images/qpid-logo.png") left center no-repeat -} - -.logo { - text-align:left; - vertical-align: top; - font-weight:600; - height: 90px; - padding-left: 200px; - padding-top: 1px; - padding-bottom: 10px; - font-size:14px; - font-family:"Verdana", cursive; -} - -.footer { - color:#000000; - clear:both; - text-align:center; - font-size:11px; - line-height:17px; - -} - -div .messages { - width: 100%; - height: 350px; -} - -.formBox { - margin: 10px 5px; -} - -.formBox legend { - font-weight: bold; - margin-left: 5px; - background-color: white; -} - -.formBox fieldset { - padding: 5px; - border: .1em solid lightgrey; - border-radius: 5px; -} - -.formLabel-labelCell, .tableContainer-labelCell { - width: 300px; - font-weight: bold; -} - -.tableContainer-labelCell { - float: none; -} - -.formLabel-labelCell { - margin-left: 5px; - float: left; - } - -.formValue-valueCell { - float: left; -} - -.formBox .addPermittedNodeList { - width: 15em; -} - -.formBox .addPermittedNodeList select { - width: 100%; -} - -.formLabel-controlCell { - padding: 1px; - float: left; -} - -.columnDefDialogButtonIcon { - background: url("../dojo/dojox/grid/enhanced/resources/images/sprite_icons.png") no-repeat; - background-position: -260px 2px; - width: 14px; - height: 14px; -} - -.logViewerIcon { - background: url("../images/log-viewer.png") no-repeat; - width: 14px; - height: 16px; -} - -.downloadLogsIcon { - background: url("../images/download.png") no-repeat; - width: 14px; - height: 14px; -} - -.dojoxGridFBarClearFilterButtontnIcon -{ - background: url("../dojo/dojox/grid/enhanced/resources/images/sprite_icons.png") no-repeat; - background-position: -120px -18px; - width: 14px; - height: 14px; -} - -.rowNumberLimitIcon -{ - background: url("../dojo/dojox/grid/enhanced/resources/images/sprite_icons.png") no-repeat; - background-position: -240px -18px; - width: 14px; - height: 14px; -} - -.gridRefreshIcon -{ - background: url("../images/refresh.png") no-repeat; - width: 16px; - height: 16px; -} - -.gridAutoRefreshIcon -{ - background: url("../images/auto-refresh.png") no-repeat; - width: 16px; - height: 16px; -} - -.redBackground tr{ background-color:#ffdcd7 !important; background-image: none !important;} -.yellowBackground tr{background-color:#fbfddf !important; background-image: none !important;} -.grayBackground tr{background-color:#eeeeee !important; background-image: none !important;} -.dojoxGridRowOdd.grayBackground tr{ background-color:#e9e9e9 !important; background-image: none !important;} -.dojoxGridRowOdd.yellowBackground tr{background-color:#fafdd5 !important; background-image: none !important;} -.dojoxGridRowOdd.redBackground tr{background-color:#f4c1c1 !important; background-image: none !important;} - -.preferencesIcon -{ - background: url("../images/gear.png") no-repeat; - width: 16px; - height: 16px; -} - -.helpIcon -{ - background: url("../images/help.png") no-repeat; - width: 16px; - height: 16px; -} - -.loadingIcon -{ - background: url("../dojo/dojox/image/resources/images/loading.gif") no-repeat; - width: 16px; - height: 16px; - background-size: contain; - display: inline-block; -} - -.loadedIcon -{ - background: url("../dojo/dijit/icons/images/commonIconsObjActEnabled_rtl.png") no-repeat; - background-position: -352px -0px; - width: 16px; - height: 16px; - display: inline-block; -} - -.fileUpload -{ - float: right; - padding: 5px; -} - -.infoMessage -{ - padding: 5px; - font-style: italic; -} - -.alignLeft { - float: left; - display: inline-block; -} - -.alignRight { - float: right; - display: inline-block; -} - -.multiLineValue { - display: inline-block; -} - -.haOptionLabel { - font-weight: bold; - margin-left: 5px; -} - -.editNoteBanner { - font-style: italic; - margin: 0px 0px 10px 5px; -} - -#errorDialog { - overflow: auto; - width: 400px; -} - -.errorDialogErrorPrimary { - font-weight: bold; - margin-bottom: 10px; - max-width: 350px; -} - -.errorDialogErrorSecondary { - font-style: italic; -} - -/* Required to keep queue type radio buttons on one line when dialog adds scrollbar */ -#addQueue { - overflow: auto; - width: 630px; -} - -#authenticatedUserControls { - max-width: 300px; -} - -.claro .dojoxCheckedMultiSelectWrapper { - height: auto; -} - -.claro .dojoxCheckedMultiSelect .dojoxCheckedMultiSelectWrapper { - border: none; - background-color: transparent; -} - -.dijitMultiSelect { - width : 14.75em; -} - -.highlightedText -{ - font-weight: bold; -} - -.normalText -{ - font-weight: normal; -} - -.contextEditor -{ - margin-left:5px; - margin-right:5px; -} - -.contextGrid -{ - width:100%; - max-height: 140px; - overflow: auto; -} - -.qpidDialogPaneActionBar -{ - margin-left:-10px; - margin-right:-10px; - margin-bottom:-10px; - margin-top:5px; -}
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/editBroker.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/editBroker.html deleted file mode 100644 index 993a2c7505..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/editBroker.html +++ /dev/null @@ -1,119 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit/Dialog" data-dojo-props="title:'Edit Broker'" id="editBrokerDialog"> - <form id="editBrokerForm" method="post" data-dojo-type="dijit/form/Form"> - <div id="editBroker.allFields"> - <div id="editBroker.contentPane"> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Name*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editBroker.name" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'name', - required: true, - disabled: false, - trim: true, - promptMessage: 'Identifies the broker instance.', - title: 'Enter broker name'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Default Virtual Host*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editBroker.defaultVirtualHost" - data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'defaultVirtualHost', - required: true, - promptMessage: 'Default virtual host used for clients that do not specify one when connecting.', - title: 'Select default virtual host' " /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Statistics reporting period (ms):</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editBroker.statisticsReportingPeriod" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'statisticsReportingPeriod', - trim: true, - placeholder: 'Time in ms', - label: 'Statistics reporting period (ms):', - promptMessage: 'Frequency with which statistics are reported to broker log.'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Statistics reporting period enabled:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editBroker.statisticsReportingResetEnabled" - data-dojo-type="dijit/form/CheckBox" - data-dojo-props=" name: 'statisticsReportingResetEnabled' " /> - </div> - </div> - - <div class="clear formBox"> - <fieldset> - <legend>Global Connection Defaults</legend> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Maximum number of sessions:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editBroker.connection.sessionCountLimit" - data-dojo-props=" - name: 'connection.sessionCountLimit', - placeHolder: 'Number of sessions', - trim: true, - promptMessage: 'Maximum number of sessions per connection' "/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Heart beat delay (ms)::</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editBroker.connection.heartBeatDelay" - data-dojo-props=" - name: 'connection.heartBeatDelay', - trim: true, - invalidMessage: 'Invalid value', - placeHolder: 'Time in ms', - promptMessage: 'Interval between heart beat messages exchanged between broker and clients'"/> - </div> - </div> - </fieldset> - </div> - - <div data-dojo-type="dijit/TitlePane" data-dojo-props="title: 'Context variables', open: false"> - <div id="editBroker.context" - data-dojo-type="qpid/common/ContextVariablesEditor" - data-dojo-props="name: 'context', title: 'Context variables'" ></div> - </div> - - <div class="clear"></div> - </div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button data-dojo-type="dijit/form/Button" id="editBroker.saveButton" data-dojo-props="label: 'Save'">Save</button> - <button data-dojo-type="dijit/form/Button" id="editBroker.cancelButton" data-dojo-props="label: 'Cancel'" ></button> - </div> - </div> - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/editQueue.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/editQueue.html deleted file mode 100644 index e7b33ed6f9..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/editQueue.html +++ /dev/null @@ -1,300 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" data-dojo-props="title:'Edit Queue'" id="editQueue"> - <form id="formEditQueue" method="post" dojoType="dijit.form.Form"> - <div id="formEditQueue.allFields"> - <div id="formEditQueue.contentPane"> - <div class="editNoteBanner">NOTE: All changes will only take effect after Virtual Host restart.</div> - <div class="clear"> - <div class="formLabel-labelCell">Queue Name:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.name" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'queue name', - required: true, - promptMessage: 'Name of queue', - disabled: 'true'"/> - </div> - </div> - - <div class="clear"> - <div class="formLabel-labelCell">Queue Type:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.type" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'type', - placeHolder: 'queue type', - required: true, - promptMessage: 'Type of queue', - disabled: 'true'"/> - </div> - </div> - <div class="clear"></div> - - <div id="formEditQueueType:priority" class="hidden typeSpecificDiv"> - <div class="clear"> - <div class="formLabel-labelCell">Priorities:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.priorities" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'priorities', - disabled: 'true', - promptMessage: 'Number of priorities supported by the queue', - title: 'Enter the number of priorities supported by the queue', - trim: true"/> - </div> - </div> - <div class="clear"></div> - </div> - - <div id="formEditQueueType:lvq" class="hidden typeSpecificDiv"> - <div class="clear"> - <div class="formLabel-labelCell">LVQ Message Property:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.lvqKey" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'lvqKey', - disabled: 'true', - promptMessage: 'Name of the message property used to perform the conflation', - title: 'Enter the name of the message property used to perform the conflation', - trim: true"/> - </div> - </div> - <div class="clear"></div> - </div> - - <div id="formEditQueueType:sorted" class="hidden typeSpecificDiv"> - <div class="clear"> - <div class="formLabel-labelCell">Sort Message Property*:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.sortKey" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'sortKey', - disabled: 'true', - promptMessage: 'Name of the message property used for sorting the messages on the queue', - title: 'Enter the name of the message property used for sorting the messages on the queue', - trim: true"/> - </div> - </div> - <div class="clear"></div> - </div> - - <div class="clear"> - <div class="formLabel-labelCell">Durable?</div> - <div class="formLabel-controlCell"> - <input type="checkbox" id="formEditQueue.durable" - dojoType="dijit.form.CheckBox" - data-dojo-props=" - name: 'durable', - value: 'durable', - disabled: 'true'"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Persist Messages?</div> - <div class="formLabel-controlCell"> - <select id="formEditQueue.messageDurability" - dojoType="dijit.form.FilteringSelect" - data-dojo-props=" - name: 'messageDurability', - value: '', - searchAttr: 'name', - required: false, - promptMessage: 'Message persistence override. If not default, messages arriving will have persistence setting overridden', - title: 'Enter message persistence override'"> - <option value="ALWAYS">Always</option> - <option value="DEFAULT">Default</option> - <option value="NEVER">Never</option> - </select> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Maximum Ttl:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.maximumMessageTtl" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'maximumMessageTtl', - placeHolder: 'ttl in ms', - promptMessage: 'Maximum message time to live (ttl) in ms. Messages arriving with larger ttl values will be overridden by this value', - title: 'Enter the maximum message time to live in milliseconds', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Minimum Ttl:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.minimumMessageTtl" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'minimumMessageTtl', - placeHolder: 'ttl in ms', - promptMessage: 'Minimum message time to live (ttl) in ms. Messages arriving with smaller ttl values will be overridden by this value', - title: 'Enter the minimum message time to live in milliseconds', - trim: true"/> - </div> - </div> - - <div class="clear"></div> - - <div class="clear formBox"> - <fieldset> - <legend>Flow Control Settings</legend> - <div class="clear"> - <div class="formLabel-labelCell">Capacity:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.queueFlowControlSizeBytes" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'queueFlowControlSizeBytes', - placeHolder: 'size in bytes', - promptMessage: 'Ceiling (in bytes) at which queue will begin to throttle sessions producing messages', - title: 'Enter the ceiling (in bytes) at which queue will begin to throttle sessions producing messages', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Resume Capacity:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.queueFlowResumeSizeBytes" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'queueFlowResumeSizeBytes', - placeHolder: 'size in bytes', - promptMessage: 'Floor (in bytes) at which queue will cease to throttle sessions producing messages', - title: 'Enter the floor (in bytes) at which queue will cease to throttle sessions producing messages', - trim: true"/> - </div> - </div> - </fieldset> - <div class="clear"></div> - </div> - - <div class="clear formBox"> - <fieldset> - <legend>Alerting Settings</legend> - <div class="clear"> - <div class="formLabel-labelCell">Queue Depth:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.alertThresholdQueueDepthMessages" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'alertThresholdQueueDepthMessages', - placeHolder: 'number of messages', - promptMessage: 'Ceiling value for number of messages on queue before alerts will be generated', - title: 'Enter the ceiling value for number of messages on queue before alerts will be generated', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Queue Depth:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.alertThresholdQueueDepthBytes" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'alertThresholdQueueDepthBytes', - placeHolder: 'total message size in bytes', - promptMessage: 'Ceiling value (in bytes) for total size of all messages on the queue before alerts will be generated', - title: 'Enter the ceiling value (in bytes) for total size of all messages on the queue before alerts will be generated', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Message Age:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.alertThresholdMessageAge" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'alertThresholdMessageAge', - placeHolder: 'time in ms', - promptMessage: 'Message age (in milliseconds) above which alerts will be generated', - title: 'Enter the message age (in milliseconds) above which alerts will be generated', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Message Size:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.alertThresholdMessageSize" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'alertThresholdMessageSize', - placeHolder: 'message size in bytes', - promptMessage: 'Message size (in bytes) above which alerts will be generated', - title: 'Enter the message size (in bytes) above which alerts will be generated', - trim: true"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Gap between alerts:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.alertRepeatGap" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'alertRepeatGap', - placeHolder: 'time in ms', - promptMessage: 'Minimum time (in milliseconds) between each alert', - title: 'Enter the minimum time (in milliseconds) between each alert.', - trim: true"/> - </div> - </div> - </fieldset> - <div class="clear"></div> - </div> - - <div class="clear formBox"> - <fieldset> - <legend>Other Settings</legend> - <div class="clear"> - <div class="formLabel-labelCell">Maximum Delivery Retries:</div> - <div class="formLabel-controlCell"> - <input type="text" id="formEditQueue.maximumDeliveryAttempts" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'maximumDeliveryAttempts', - placeHolder: 'number of retries', - promptMessage: 'Maximum number of delivery attempts before the message will be sent to the alternate exchange', - title: 'Enter the maximum number of delivery attempts before the message will be sent to the alternate exchange', - trim: true"/> - </div> - </div> - </fieldset> - <div class="clear"></div> - </div> - - <div data-dojo-type="dijit/TitlePane" data-dojo-props="title: 'Context variables', open: false"> - <div id="formEditQueue.context" ></div> - </div> - </div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button data-dojo-type="dijit/form/Button" id="formEditQueue.saveButton" data-dojo-props="label: 'Save'">Save</button> - <button data-dojo-type="dijit/form/Button" id="formEditQueue.cancelButton" data-dojo-props="label: 'Cancel'" ></button> - </div> - </div> - - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHost.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHost.html deleted file mode 100644 index 8e03dfdd17..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHost.html +++ /dev/null @@ -1,137 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit/Dialog" data-dojo-props="title:'Edit Virtual Host'" id="editVirtualHostDialog"> - <form id="editVirtualHostForm" method="post" data-dojo-type="dijit/form/Form"> - <div id="editVirtualHost.allFields"> - <div id="editVirtualHost.contentPane"> - <div class="editNoteBanner">NOTE: All changes will only take effect after Virtual Host restart.</div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Name*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editVirtualHost.name" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'name', - required: true, - disabled: true, - title: 'Enter virtual host name'" /> - </div> - </div> - - <div id="editVirtualHost.typeFields"></div> - - <div class="clear formBox"> - <fieldset> - <legend>Store transaction settings</legend> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Idle Timeout Warn:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editVirtualHost.storeTransactionIdleTimeoutWarn" - name="storeTransactionIdleTimeoutWarn" - placeHolder="idle timeout warn time in ms" - promptMessage="Length of time a transaction must be idle before warnings produced"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Idle Timeout Close:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editVirtualHost.storeTransactionIdleTimeoutClose" - name="storeTransactionIdleTimeoutClose" - placeHolder="idle timeout close time in ms" - promptMessage="Length of time a transaction must be idle before the connection is closed"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Open Timeout Warn:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editVirtualHost.storeTransactionOpenTimeoutWarn" - name="storeTransactionOpenTimeoutWarn" - placeHolder="open timeout warn time in ms" - promptMessage="Length of time a transaction must be open before warnings produced"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Open Timeout Close:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editVirtualHost.storeTransactionOpenTimeoutClose" - name="storeTransactionOpenTimeoutClose" - placeHolder="open timeout close time in ms" - promptMessage="Length of time a transaction must be open before the connection is closed"/> - </div> - </div> - </fieldset> - </div> - - <div class="clear formBox"> - <fieldset> - <legend>House keeping settings</legend> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Check period (ms):</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editVirtualHost.housekeepingCheckPeriod" - name="housekeepingCheckPeriod" - placeHolder="house keeping check period in ms" - promptMessage="Frequency with which the housekeeper runs"/> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Thread count:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editVirtualHost.housekeepingThreadCount" - name="housekeepingThreadCount" - placeHolder="house keeping thread count" - promptMessage="Number of threads used to perform housekeeping"/> - </div> - </div> - </fieldset> - </div> - <div class="clear"></div> - - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Dead letter queue enabled:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input type="checkbox" id="editVirtualHost.queue.deadLetterQueueEnabled" - data-dojo-type="dijit/form/CheckBox" - data-dojo-props="name: 'queue.deadLetterQueueEnabled'"> - </input> - </div> - </div> - - <div class="clear"></div> - - <div data-dojo-type="dijit/TitlePane" data-dojo-props="title: 'Context variables', open: false"> - <div id="editVirtualHost.context" ></div> - </div> - </div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button data-dojo-type="dijit/form/Button" id="editVirtualHost.saveButton" data-dojo-props="label: 'Save'">Save</button> - <button data-dojo-type="dijit/form/Button" id="editVirtualHost.cancelButton" data-dojo-props="label: 'Cancel'" ></button> - </div> - </div> - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHostNode.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHostNode.html deleted file mode 100644 index 59597845a2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHostNode.html +++ /dev/null @@ -1,56 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit/Dialog" data-dojo-props="title:'Edit Virtual Host'" id="editVirtualHostNodeDialog"> - <form id="editVirtualHostNodeForm" method="post" data-dojo-type="dijit/form/Form"> - <div id="editVirtualHostNode.allFields"> - <div id="editVirtualHostNode.contentPane"> - <div class="editNoteBanner">NOTE: All changes will only take effect after Virtual Host Node restart.</div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Name*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editVirtualHostNode.name" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - placeHolder: 'name', - required: true, - missingMessage: 'Name must be supplied', - disabled: true, - title: 'Enter virtual host name'" /> - </div> - </div> - - <div id="editVirtualHostNode.typeFields"></div> - - <div class="clear"></div> - - <div data-dojo-type="dijit/TitlePane" data-dojo-props="title: 'Context variables', open: false"> - <div id="editVirtualHostNode.context" ></div> - </div> - </div> - </div> - - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button data-dojo-type="dijit/form/Button" id="editVirtualHostNode.saveButton" data-dojo-props="label: 'Save'">Save</button> - <button data-dojo-type="dijit/form/Button" id="editVirtualHostNode.cancelButton" data-dojo-props="label: 'Cancel'" ></button> - </div> - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/footer.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/footer.html deleted file mode 100644 index 44fa4fda36..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/footer.html +++ /dev/null @@ -1,28 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> - -<div class="footer"><p>© 2004-<span class="currentYear">2015</span> The Apache Software Foundation. - <br/> - Apache Qpid, Qpid, Apache, the Apache feather logo, and the Apache Qpid project logo are trademarks of - The Apache Software Foundation. - <br/> - All other marks mentioned may be trademarks or registered trademarks of their respective owners. -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showColumnDefDialog.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showColumnDefDialog.html deleted file mode 100644 index 535b9a1fe5..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showColumnDefDialog.html +++ /dev/null @@ -1,32 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div> - <div>Select columns to display:</div> - <div class="columnList"></div> - </div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button value="Display" data-dojo-type="dijit.form.Button" - class="displayButton" data-dojo-props="label: 'Display' "></button> - <button value="Cancel" data-dojo-type="dijit.form.Button" data-dojo-props="label: 'Cancel'" - class="cancelButton"></button> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showRowNumberLimitDialog.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showRowNumberLimitDialog.html deleted file mode 100644 index cacdf49e66..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showRowNumberLimitDialog.html +++ /dev/null @@ -1,33 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div> - <div>Set the maximum number of rows to cache and display:</div> - <input class="rowNumberLimit" data-dojo-type="dijit.form.NumberSpinner" - data-dojo-props="invalidMessage: 'Invalid value', required: true, smallDelta: 1,mconstraints: {min:1,max:65535,places:0, pattern: '#####'}, label: 'Maximum number of rows:', name: 'rowNumberLimit'"></input> - </div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button value="Submit" data-dojo-type="dijit.form.Button" - class="submitButton" data-dojo-props="label: 'Submit' "></button> - <button value="Cancel" data-dojo-type="dijit.form.Button" data-dojo-props="label: 'Cancel'" - class="cancelButton"></button> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/group/addGroupMember.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/group/addGroupMember.html deleted file mode 100644 index e479e8cb74..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/group/addGroupMember.html +++ /dev/null @@ -1,38 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" style="width:600px;" data-dojo-props="title:'Add Group Member'" id="addGroupMember"> - <form id="formAddGroupMember" method="post" dojoType="dijit.form.Form"> - <table cellpadding="0" cellspacing="2"> - <tr> - <td valign="top"><strong>Name*: </strong></td> - <td><input type="text" required="true" name="name" id="formAddGroupMember.name" placeholder="Name" - dojoType="dijit.form.ValidationTextBox" missingMessage="A name must be supplied" /></td> - </tr> - </table> - <br/> - - <div class="dijitDialogPaneActionBar"> - <input type="submit" value="Add Group Member" label="Add Group Member" dojoType="dijit.form.Button" /> - </div> - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/group/showGroup.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/group/showGroup.html deleted file mode 100644 index c84e794ac1..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/group/showGroup.html +++ /dev/null @@ -1,32 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="group"> - <span style="">Name:</span><span class="name" style="position:absolute; left:6em"></span> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Group Members'"> - <div class="groupMembers"></div> - <div class="dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="addGroupMemberButton" type="button">Add Group Member</button> - <button data-dojo-type="dijit.form.Button" class="removeGroupMemberButton" type="button">Remove Group Members</button> - </div> - </div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/addGroup.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/addGroup.html deleted file mode 100644 index 29ce2ebe6c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/addGroup.html +++ /dev/null @@ -1,39 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" style="width:600px;" data-dojo-props="title:'Add Group'" id="addGroup"> - <form id="formAddGroup" method="post" dojoType="dijit.form.Form"> - <table cellpadding="0" cellspacing="2"> - <tr> - <td valign="top"><strong>Group Name*: </strong></td> - <td><input type="text" required="true" name="name" id="formAddGroup.name" placeholder="Group Name" - dojoType="dijit.form.ValidationTextBox" missingMessage="A name must be supplied" /></td> - </tr> - </table> - <br/> - - <div class="dijitDialogPaneActionBar"> - <input type="submit" value="Create Group" label="Create Group" dojoType="dijit.form.Button" /> - </div> - - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/add.html deleted file mode 100644 index 7fc458cd4f..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/add.html +++ /dev/null @@ -1,37 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Path*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" class="addGroupProviderPath" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'path', - required: true, - placeHolder: 'path/to/group/file', - title: 'Enter path to file with groups', - promptMessage: 'Enter path to file with groups'"/> - </div> - </div> - - <div class="clear"></div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/show.html deleted file mode 100644 index 740c65fd38..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/show.html +++ /dev/null @@ -1,25 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell">Path to file:</div> - <div ><span class="path" ></span></div> - </div> - <div class="clear"></div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/showGroupManagingGroupProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/showGroupManagingGroupProvider.html deleted file mode 100644 index 62a6c7537c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/showGroupManagingGroupProvider.html +++ /dev/null @@ -1,30 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="FileGroupManager"> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Groups'"> - <div class="groups"></div> - <div class="dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="addGroupButton">Add Group</button> - <button data-dojo-type="dijit.form.Button" class="deleteGroupButton">Delete Groups</button> - </div> - </div> - -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/auto-refresh.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/auto-refresh.png Binary files differdeleted file mode 100644 index 493636f467..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/auto-refresh.png +++ /dev/null diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/download.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/download.png Binary files differdeleted file mode 100644 index b64b41d476..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/download.png +++ /dev/null diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/gear.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/gear.png Binary files differdeleted file mode 100644 index 0bb4394b46..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/gear.png +++ /dev/null diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/help.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/help.png Binary files differdeleted file mode 100644 index f7d3698d25..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/help.png +++ /dev/null diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/log-viewer.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/log-viewer.png Binary files differdeleted file mode 100644 index 858fd48beb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/log-viewer.png +++ /dev/null diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/qpid-logo.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/qpid-logo.png Binary files differdeleted file mode 100644 index ae0fbb462f..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/qpid-logo.png +++ /dev/null diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/refresh.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/refresh.png Binary files differdeleted file mode 100644 index 083044979b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/refresh.png +++ /dev/null diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/index.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/index.html deleted file mode 100644 index 896640fd67..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/index.html +++ /dev/null @@ -1,137 +0,0 @@ -<!DOCTYPE HTML> -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> -<html lang="en"> -<head> - <meta charset="utf-8"> - <title>Qpid Management</title> - <link rel="stylesheet" href="dojo/dojo/resources/dojo.css"> - <link rel="stylesheet" href="dojo/dijit/themes/claro/claro.css"> - <link rel="stylesheet" href="dojo/dojox/grid/resources/claroGrid.css"> - <link rel="stylesheet" href="dojo/dojox/grid/enhanced/resources/claro/EnhancedGrid.css"> - <link rel="stylesheet" href="dojo/dojox/grid/enhanced/resources/EnhancedGrid_rtl.css"> - <link rel="stylesheet" href="dojo/dojox/form/resources/CheckedMultiSelect.css"> - <link rel="stylesheet" href="dojo/dojox/form/resources/FileInput.css" /> - <link rel="stylesheet" href="css/common.css" media="screen"> - <script> - function getContextPath() - { - var contextPath = "/"; - var documentURL = document.URL; - var managementPageStart = documentURL.lastIndexOf("/"); - var firstSlashPos = documentURL.indexOf("/", documentURL.indexOf("//") + 2); - if (managementPageStart > firstSlashPos) - { - contextPath = documentURL.substring(firstSlashPos, managementPageStart); - } - return contextPath; - } - - var dojoConfig = { - tlmSiblingOfDojo:false, - async:true, - baseUrl: getContextPath(), - packages:[ - { name:"dojo", location:"dojo/dojo" }, - { name:"dijit", location:"dojo/dijit" }, - { name:"dojox", location:"dojo/dojox" }, - { name:"qpid", location:"js/qpid" } - ] - }; - - </script> - <script src="dojo/dojo/dojo.js"> - </script> - - <script> - var qpidManagementHelper = null; - require([ - "dojo/parser", - "qpid/authorization/checkUser", - "qpid/common/ConsoleHelper", - "dijit/layout/BorderContainer", - "dijit/layout/TabContainer", - "dijit/layout/ContentPane", - "dijit/TitlePane", - "dijit/Menu", - "dijit/MenuItem", - "qpid/management/treeView", - "qpid/management/controller", - "qpid/common/footer" - ], function(parser, User, ConsoleHelper){ - parser.parse(); - qpidManagementHelper = ConsoleHelper; - User.getUserAndUpdateUI(); - dijit.Tooltip.defaultPosition = ["after-centered", "below-centered"]; - }); - </script> - -</head> -<body class="claro"> - -<div id="pageLayout" data-dojo-type="dijit.layout.BorderContainer" data-dojo-props="design: 'headline', gutters: false"> - <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'top'"> - <div id="header" class="header" style="float: left; width: 300px"></div> - <div style="float: right;"> - <div id="login" class="hidden"><span id="authenticatedUser" class="hidden"></span> - <div id="authenticatedUserControls" data-dojo-type="dijit.form.DropDownButton" data-dojo-props="iconClass: 'preferencesIcon'"> - <div data-dojo-type="dijit.Menu"> - <div data-dojo-type="dijit.MenuItem" data-dojo-props="onClick: function(){window.location='logout';}" >Log out</div> - <div data-dojo-type="dijit.MenuItem" - data-dojo-props="iconClass:'dijitIconFunction',onClick: function(){qpidManagementHelper.showPreferencesDialog();}">Preferences</div> - <div data-dojo-type="dijit.MenuItem" - data-dojo-props="iconClass: 'helpIcon', onClick: function(){qpidManagementHelper.showHelp();}">Help</div> - </div> - </div> - </div> - </div> - </div> - <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'leading', splitter: true" style="width:20%"> - <div qpid-type="treeView" qpid-props="query: 'service/structure'" ></div> - </div> - <div id="managedViews" data-dojo-type="dijit.layout.TabContainer" data-dojo-props="region:'center', tabPosition: 'top'"> - </div> - <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'bottom'"> - <div qpid-type="footer"></div> - </div> - - <div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" data-dojo-props="title: 'Error'" id="errorDialog"> - <div> - <div class="errorDialogErrorPrimary"> - <span id="errorDialog.statusCode">000</span> - <span id="errorDialog.errorMessage">error</span> - </div> - - <div class="clear" class="errorDialogErrorSecondary"> - <div id="errorDialog.advice.reconnect"> - Please login again and retry your operation. - </div> - <div id="errorDialog.advice.retry"> - Please correct the problem and retry your operation. - </div> - </div> - </div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <input type="button" id="errorDialog.button.cancel" value="Cancel" label="Cancel" dojoType="dijit.form.Button" onClick="dijit.byId('errorDialog').hide();"/> - <input type="button" id="errorDialog.button.relogin" value="Login" label="Login" dojoType="dijit.form.Button" onClick="dijit.byId('errorDialog').hide(); window.location='logout';"/> - </div> - </div> - </div> -</div> - -</body> -</html> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/README.txt b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/README.txt deleted file mode 100644 index 6ef692ce31..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/README.txt +++ /dev/null @@ -1,8 +0,0 @@ -Crypto-JS -========= - -Version: 3.1.2 - -These files are from Crypto-JS (https://code.google.com/p/crypto-js/) by Jeff Mott. - - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/enc-base64-min.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/enc-base64-min.js deleted file mode 100644 index 7ab054d94b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/enc-base64-min.js +++ /dev/null @@ -1,8 +0,0 @@ -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -(function(){var h=CryptoJS,j=h.lib.WordArray;h.enc.Base64={stringify:function(b){var e=b.words,f=b.sigBytes,c=this._map;b.clamp();b=[];for(var a=0;a<f;a+=3)for(var d=(e[a>>>2]>>>24-8*(a%4)&255)<<16|(e[a+1>>>2]>>>24-8*((a+1)%4)&255)<<8|e[a+2>>>2]>>>24-8*((a+2)%4)&255,g=0;4>g&&a+0.75*g<f;g++)b.push(c.charAt(d>>>6*(3-g)&63));if(e=c.charAt(64))for(;b.length%4;)b.push(e);return b.join("")},parse:function(b){var e=b.length,f=this._map,c=f.charAt(64);c&&(c=b.indexOf(c),-1!=c&&(e=c));for(var c=[],a=0,d=0;d< -e;d++)if(d%4){var g=f.indexOf(b.charAt(d-1))<<2*(d%4),h=f.indexOf(b.charAt(d))>>>6-2*(d%4);c[a>>>2]|=(g|h)<<24-8*(a%4);a++}return j.create(c,a)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})(); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/hmac-sha1.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/hmac-sha1.js deleted file mode 100644 index 0d50d81a1e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/hmac-sha1.js +++ /dev/null @@ -1,17 +0,0 @@ -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -var CryptoJS=CryptoJS||function(g,l){var e={},d=e.lib={},m=function(){},k=d.Base={extend:function(a){m.prototype=this;var c=new m;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}, -p=d.WordArray=k.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=l?c:4*a.length},toString:function(a){return(a||n).stringify(this)},concat:function(a){var c=this.words,q=a.words,f=this.sigBytes;a=a.sigBytes;this.clamp();if(f%4)for(var b=0;b<a;b++)c[f+b>>>2]|=(q[b>>>2]>>>24-8*(b%4)&255)<<24-8*((f+b)%4);else if(65535<q.length)for(b=0;b<a;b+=4)c[f+b>>>2]=q[b>>>2];else c.push.apply(c,q);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< -32-8*(c%4);a.length=g.ceil(c/4)},clone:function(){var a=k.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],b=0;b<a;b+=4)c.push(4294967296*g.random()|0);return new p.init(c,a)}}),b=e.enc={},n=b.Hex={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],f=0;f<a;f++){var d=c[f>>>2]>>>24-8*(f%4)&255;b.push((d>>>4).toString(16));b.push((d&15).toString(16))}return b.join("")},parse:function(a){for(var c=a.length,b=[],f=0;f<c;f+=2)b[f>>>3]|=parseInt(a.substr(f, -2),16)<<24-4*(f%8);return new p.init(b,c/2)}},j=b.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],f=0;f<a;f++)b.push(String.fromCharCode(c[f>>>2]>>>24-8*(f%4)&255));return b.join("")},parse:function(a){for(var c=a.length,b=[],f=0;f<c;f++)b[f>>>2]|=(a.charCodeAt(f)&255)<<24-8*(f%4);return new p.init(b,c)}},h=b.Utf8={stringify:function(a){try{return decodeURIComponent(escape(j.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return j.parse(unescape(encodeURIComponent(a)))}}, -r=d.BufferedBlockAlgorithm=k.extend({reset:function(){this._data=new p.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=h.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,b=c.words,f=c.sigBytes,d=this.blockSize,e=f/(4*d),e=a?g.ceil(e):g.max((e|0)-this._minBufferSize,0);a=e*d;f=g.min(4*a,f);if(a){for(var k=0;k<a;k+=d)this._doProcessBlock(b,k);k=b.splice(0,a);c.sigBytes-=f}return new p.init(k,f)},clone:function(){var a=k.clone.call(this); -a._data=this._data.clone();return a},_minBufferSize:0});d.Hasher=r.extend({cfg:k.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){r.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(b,d){return(new a.init(d)).finalize(b)}},_createHmacHelper:function(a){return function(b,d){return(new s.HMAC.init(a, -d)).finalize(b)}}});var s=e.algo={};return e}(Math); -(function(){var g=CryptoJS,l=g.lib,e=l.WordArray,d=l.Hasher,m=[],l=g.algo.SHA1=d.extend({_doReset:function(){this._hash=new e.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(d,e){for(var b=this._hash.words,n=b[0],j=b[1],h=b[2],g=b[3],l=b[4],a=0;80>a;a++){if(16>a)m[a]=d[e+a]|0;else{var c=m[a-3]^m[a-8]^m[a-14]^m[a-16];m[a]=c<<1|c>>>31}c=(n<<5|n>>>27)+l+m[a];c=20>a?c+((j&h|~j&g)+1518500249):40>a?c+((j^h^g)+1859775393):60>a?c+((j&h|j&g|h&g)-1894007588):c+((j^h^ -g)-899497514);l=g;g=h;h=j<<30|j>>>2;j=n;n=c}b[0]=b[0]+n|0;b[1]=b[1]+j|0;b[2]=b[2]+h|0;b[3]=b[3]+g|0;b[4]=b[4]+l|0},_doFinalize:function(){var d=this._data,e=d.words,b=8*this._nDataBytes,g=8*d.sigBytes;e[g>>>5]|=128<<24-g%32;e[(g+64>>>9<<4)+14]=Math.floor(b/4294967296);e[(g+64>>>9<<4)+15]=b;d.sigBytes=4*e.length;this._process();return this._hash},clone:function(){var e=d.clone.call(this);e._hash=this._hash.clone();return e}});g.SHA1=d._createHelper(l);g.HmacSHA1=d._createHmacHelper(l)})(); -(function(){var g=CryptoJS,l=g.enc.Utf8;g.algo.HMAC=g.lib.Base.extend({init:function(e,d){e=this._hasher=new e.init;"string"==typeof d&&(d=l.parse(d));var g=e.blockSize,k=4*g;d.sigBytes>k&&(d=e.finalize(d));d.clamp();for(var p=this._oKey=d.clone(),b=this._iKey=d.clone(),n=p.words,j=b.words,h=0;h<g;h++)n[h]^=1549556828,j[h]^=909522486;p.sigBytes=b.sigBytes=k;this.reset()},reset:function(){var e=this._hasher;e.reset();e.update(this._iKey)},update:function(e){this._hasher.update(e);return this},finalize:function(e){var d= -this._hasher;e=d.finalize(e);d.reset();return d.finalize(this._oKey.clone().concat(e))}})})(); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/hmac-sha256.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/hmac-sha256.js deleted file mode 100644 index c822cfb1f4..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/hmac-sha256.js +++ /dev/null @@ -1,18 +0,0 @@ -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -var CryptoJS=CryptoJS||function(h,s){var f={},g=f.lib={},q=function(){},m=g.Base={extend:function(a){q.prototype=this;var c=new q;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}, -r=g.WordArray=m.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=s?c:4*a.length},toString:function(a){return(a||k).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%4)for(var e=0;e<a;e++)c[b+e>>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535<d.length)for(e=0;e<a;e+=4)c[b+e>>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< -32-8*(c%4);a.length=h.ceil(c/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d<a;d+=4)c.push(4294967296*h.random()|0);return new r.init(c,a)}}),l=f.enc={},k=l.Hex={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b<a;b++){var e=c[b>>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b<c;b+=2)d[b>>>3]|=parseInt(a.substr(b, -2),16)<<24-4*(b%8);return new r.init(d,c/2)}},n=l.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b<a;b++)d.push(String.fromCharCode(c[b>>>2]>>>24-8*(b%4)&255));return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b<c;b++)d[b>>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new r.init(d,c)}},j=l.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}}, -u=g.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new r.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?h.ceil(f):h.max((f|0)-this._minBufferSize,0);a=f*e;b=h.min(4*a,b);if(a){for(var g=0;g<a;g+=e)this._doProcessBlock(d,g);g=d.splice(0,a);c.sigBytes-=b}return new r.init(g,b)},clone:function(){var a=m.clone.call(this); -a._data=this._data.clone();return a},_minBufferSize:0});g.Hasher=u.extend({cfg:m.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){u.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(c,d){return(new a.init(d)).finalize(c)}},_createHmacHelper:function(a){return function(c,d){return(new t.HMAC.init(a, -d)).finalize(c)}}});var t=f.algo={};return f}(Math); -(function(h){for(var s=CryptoJS,f=s.lib,g=f.WordArray,q=f.Hasher,f=s.algo,m=[],r=[],l=function(a){return 4294967296*(a-(a|0))|0},k=2,n=0;64>n;){var j;a:{j=k;for(var u=h.sqrt(j),t=2;t<=u;t++)if(!(j%t)){j=!1;break a}j=!0}j&&(8>n&&(m[n]=l(h.pow(k,0.5))),r[n]=l(h.pow(k,1/3)),n++);k++}var a=[],f=f.SHA256=q.extend({_doReset:function(){this._hash=new g.init(m.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],g=b[2],j=b[3],h=b[4],m=b[5],n=b[6],q=b[7],p=0;64>p;p++){if(16>p)a[p]= -c[d+p]|0;else{var k=a[p-15],l=a[p-2];a[p]=((k<<25|k>>>7)^(k<<14|k>>>18)^k>>>3)+a[p-7]+((l<<15|l>>>17)^(l<<13|l>>>19)^l>>>10)+a[p-16]}k=q+((h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25))+(h&m^~h&n)+r[p]+a[p];l=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&g^f&g);q=n;n=m;m=h;h=j+k|0;j=g;g=f;f=e;e=k+l|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+g|0;b[3]=b[3]+j|0;b[4]=b[4]+h|0;b[5]=b[5]+m|0;b[6]=b[6]+n|0;b[7]=b[7]+q|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes; -d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=h.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=q.clone.call(this);a._hash=this._hash.clone();return a}});s.SHA256=q._createHelper(f);s.HmacSHA256=q._createHmacHelper(f)})(Math); -(function(){var h=CryptoJS,s=h.enc.Utf8;h.algo.HMAC=h.lib.Base.extend({init:function(f,g){f=this._hasher=new f.init;"string"==typeof g&&(g=s.parse(g));var h=f.blockSize,m=4*h;g.sigBytes>m&&(g=f.finalize(g));g.clamp();for(var r=this._oKey=g.clone(),l=this._iKey=g.clone(),k=r.words,n=l.words,j=0;j<h;j++)k[j]^=1549556828,n[j]^=909522486;r.sigBytes=l.sigBytes=m;this.reset()},reset:function(){var f=this._hasher;f.reset();f.update(this._iKey)},update:function(f){this._hasher.update(f);return this},finalize:function(f){var g= -this._hasher;f=g.finalize(f);g.reset();return g.finalize(this._oKey.clone().concat(f))}})})(); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/authorization/checkUser.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/authorization/checkUser.js deleted file mode 100644 index be9bef3519..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/authorization/checkUser.js +++ /dev/null @@ -1,45 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -define(["dojo/dom", - "qpid/authorization/sasl", - "dijit/registry", - "dojox/html/entities", - "dojo/domReady!"], function(dom, sasl, registry, entities){ - -var updateUI = function updateUI(data) -{ - if(data.user) - { - var userName = entities.encode(String(data.user)); - var controlButton = registry.byId("authenticatedUserControls"); - if (controlButton) - { - controlButton.set("label", userName); - } - dom.byId("authenticatedUser").innerHTML = userName; - dom.byId("login").style.display = "inline"; - } -}; - -return {getUserAndUpdateUI: function(){sasl.getUser(updateUI);}} - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/authorization/sasl.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/authorization/sasl.js deleted file mode 100644 index fc972f3c7e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/authorization/sasl.js +++ /dev/null @@ -1,351 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", "dojox/encoding/base64", "dojox/encoding/digests/_base", "dojox/encoding/digests/MD5", "dojox/uuid/generateRandomUuid", "dojo/request/script"], - function (xhr, base64, digestsBase, MD5, uuid, script) { - -var encodeUTF8 = function encodeUTF8(str) { - var byteArray = []; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) <= 0x7F) { - byteArray.push(str.charCodeAt(i)); - } - else { - var h = encodeURIComponent(str.charAt(i)).substr(1).split('%'); - for (var j = 0; j < h.length; j++) - byteArray.push(parseInt(h[j], 16)); - } - } - return byteArray; -}; - -var decodeUTF8 = function decodeUTF8(byteArray) -{ - var str = ''; - for (var i = 0; i < byteArray.length; i++) - str += byteArray[i] <= 0x7F? - byteArray[i] === 0x25 ? "%25" : - String.fromCharCode(byteArray[i]) : - "%" + byteArray[i].toString(16).toUpperCase(); - return decodeURIComponent(str); -}; - -var errorHandler = function errorHandler(error) -{ - if(error.status == 401) - { - alert("Authentication Failed"); - } - else if(error.status == 403) - { - alert("Authorization Failed"); - } - else - { - alert(error); - } -} - -var saslServiceUrl="service/sasl"; - -var saslPlain = function saslPlain(user, password, callbackFunction) -{ - var responseArray = [ 0 ].concat(encodeUTF8( user )).concat( [ 0 ] ).concat( encodeUTF8( password ) ); - var plainResponse = base64.encode(responseArray); - - // Using dojo.xhrGet, as very little information is being sent - dojo.xhrPost({ - // The URL of the request - url: saslServiceUrl, - content: { - mechanism: "PLAIN", - response: plainResponse - }, - handleAs: "json", - failOk: true - }).then(callbackFunction, errorHandler); -}; - -var saslCramMD5 = function saslCramMD5(user, password, saslMechanism, callbackFunction) -{ - dojo.xhrPost({ - // The URL of the request - url: saslServiceUrl, - content: { - mechanism: saslMechanism - }, - handleAs: "json", - failOk: true - }).then(function(data) - { - - var challengeBytes = base64.decode(data.challenge); - var wa=[]; - var bitLength = challengeBytes.length*8; - for(var i=0; i<bitLength; i+=8) - { - wa[i>>5] |= (challengeBytes[i/8] & 0xFF)<<(i%32); - } - var challengeStr = digestsBase.wordToString(wa).substring(0,challengeBytes.length); - - var digest = user + " " + MD5._hmac(challengeStr, password, digestsBase.outputTypes.Hex); - var id = data.id; - - var response = base64.encode(encodeUTF8( digest )); - - dojo.xhrPost({ - // The URL of the request - url: saslServiceUrl, - content: { - id: id, - response: response - }, - handleAs: "json", - failOk: true - }).then(callbackFunction, errorHandler); - - }, - function(error) - { - if(error.status == 403) - { - alert("Authentication Failed"); - } - else - { - alert(error); - } - }); - - - -}; - - var saslScramSha1 = function saslScramSha1(user, password, saslMechanism, callbackFunction) { - saslScram("sha1",user,password,saslMechanism,callbackFunction); - }; - - var saslScramSha256 = function saslScramSha1(user, password, saslMechanism, callbackFunction) { - saslScram("sha256",user,password,saslMechanism,callbackFunction); - }; - - var saslScram = function saslScramSha1(mechanism, user, password, saslMechanism, callbackFunction) { - - var DIGEST = mechanism.toUpperCase(); - var HMAC = "Hmac"+DIGEST; - - script.get("js/crypto-js/hmac-"+mechanism+".js").then( function() - { - script.get("js/crypto-js/enc-base64-min.js").then ( function() - { - - var toBase64 = function toBase64( input ) - { - var result = []; - for(var i = 0; i < input.length; i++) - { - result[i] = input.charCodeAt(i); - } - return base64.encode( result ) - }; - - var fromBase64 = function fromBase64( input ) - { - var decoded = base64.decode( input ); - var result = ""; - for(var i = 0; i < decoded.length; i++) - { - result+= String.fromCharCode(decoded[i]); - } - return result; - }; - - var xor = function xor(lhs, rhs) { - var words = []; - for(var i = 0; i < lhs.words.length; i++) - { - words.push(lhs.words[i]^rhs.words[i]); - } - return CryptoJS.lib.WordArray.create(words); - }; - - var hasNonAscii = function hasNonAscii(name) { - for(var i = 0; i < name.length; i++) { - if(name.charCodeAt(i) > 127) { - return true; - } - } - return false; - }; - - var generateSaltedPassword = function generateSaltedPassword(salt, password, iterationCount) - { - var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo[DIGEST], password); - - hmac.update(salt); - hmac.update(CryptoJS.enc.Hex.parse("00000001")); - - var result = hmac.finalize(); - var previous = null; - for(var i = 1 ;i < iterationCount; i++) - { - hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo[DIGEST], password); - hmac.update( previous != null ? previous : result ); - previous = hmac.finalize(); - result = xor(result, previous); - } - return result; - - }; - - GS2_HEADER = "n,,"; - - if(!hasNonAscii(user)) { - - user = user.replace(/=/g, "=3D"); - user = user.replace(/,/g, "=2C"); - - clientNonce = uuid(); - clientFirstMessageBare = "n=" + user + ",r=" + clientNonce; - dojo.xhrPost({ - // The URL of the request - url: saslServiceUrl, - content: { - mechanism: saslMechanism, - response: toBase64(GS2_HEADER + clientFirstMessageBare) - }, - handleAs: "json", - failOk: true - }).then(function (data) { - var serverFirstMessage = fromBase64(data.challenge); - var id = data.id; - - var parts = serverFirstMessage.split(","); - nonce = parts[0].substring(2); - if (!nonce.substr(0, clientNonce.length) == clientNonce) { - alert("Authentication error - server nonce does not start with client nonce") - } - else { - var salt = CryptoJS.enc.Base64.parse(parts[1].substring(2)); - var iterationCount = parts[2].substring(2); - var saltedPassword = generateSaltedPassword(salt, password, iterationCount) - var clientFinalMessageWithoutProof = "c=" + toBase64(GS2_HEADER) + ",r=" + nonce; - var authMessage = clientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalMessageWithoutProof; - var clientKey = CryptoJS[HMAC]("Client Key", saltedPassword); - var storedKey = CryptoJS[DIGEST](clientKey); - var clientSignature = CryptoJS[HMAC](authMessage, storedKey); - var clientProof = xor(clientKey, clientSignature); - var serverKey = CryptoJS[HMAC]("Server Key", saltedPassword); - serverSignature = CryptoJS[HMAC](authMessage, serverKey); - dojo.xhrPost({ - // The URL of the request - url: saslServiceUrl, - content: { - id: id, - response: toBase64(clientFinalMessageWithoutProof - + ",p=" + clientProof.toString(CryptoJS.enc.Base64)) - }, - handleAs: "json", - failOk: true - }).then(function (data) { - var serverFinalMessage = fromBase64(data.challenge); - if (serverSignature.toString(CryptoJS.enc.Base64) == serverFinalMessage.substring(2)) { - callbackFunction(); - } - else { - errorHandler("Server signature did not match"); - } - - - }, errorHandler); - } - - }, errorHandler); - } - else - { - alert("Username '"+name+"' is invalid"); - } - - }, errorHandler); - }, errorHandler); - }; - -var containsMechanism = function containsMechanism(mechanisms, mech) -{ - for (var i = 0; i < mechanisms.length; i++) { - if (mechanisms[i] == mech) { - return true; - } - } - - return false; -}; - -var SaslClient = {}; - -SaslClient.authenticate = function(username, password, callbackFunction) -{ - dojo.xhrGet({ - url: saslServiceUrl, - handleAs: "json", - failOk: true - }).then(function(data) - { - var mechMap = data.mechanisms; - if(containsMechanism(mechMap, "SCRAM-SHA-256")) - { - saslScramSha256(username, password, "SCRAM-SHA-256", callbackFunction) - } - else if(containsMechanism(mechMap, "SCRAM-SHA-1")) - { - saslScramSha1(username, password, "SCRAM-SHA-1", callbackFunction) - } - else if (containsMechanism(mechMap, "CRAM-MD5")) - { - saslCramMD5(username, password, "CRAM-MD5", callbackFunction); - } - else if (containsMechanism(mechMap, "CRAM-MD5-HEX")) - { - var hashedPassword = MD5(password, digestsBase.outputTypes.Hex); - saslCramMD5(username, hashedPassword, "CRAM-MD5-HEX", callbackFunction); - } - else if (containsMechanism(mechMap, "PLAIN")) - { - saslPlain(username, password, callbackFunction); - } - else - { - alert("No supported SASL mechanism offered: " + mechMap); - } - }, errorHandler); -}; - -SaslClient.getUser = function(callbackFunction) -{ - dojo.xhrGet({ - url: saslServiceUrl, - handleAs: "json", - failOk: true - }).then(callbackFunction, errorHandler); -}; - -return SaslClient; -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ConsoleHelper.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ConsoleHelper.js deleted file mode 100644 index 9cebf48ce6..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ConsoleHelper.js +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", "dojo/domReady!"], function (xhr) { - - var preferencesDialog = null; - var helpURL = null; - - return { - showPreferencesDialog: function () { - if (preferencesDialog == null) - { - require(["qpid/management/Preferences", "dojo/ready"], function(PreferencesDialog, ready){ - ready(function(){ - preferencesDialog = new PreferencesDialog(); - preferencesDialog.showDialog(); - }); - }); - } - else - { - preferencesDialog.showDialog(); - } - }, - getHelpUrl: function() - { - if (!helpURL) - { - xhr.get({ - sync: true, - url: "api/latest/broker", - content: { "depth" : 1, "includeSysContext" : true }, - handleAs: "json" - }).then(function(data) { - var broker = data[0]; - if ("context" in broker && "qpid.helpURL" in broker["context"] ) - { - helpURL = broker["context"]["qpid.helpURL"]; - } - else - { - helpURL = "http://qpid.apache.org/"; - } - }); - } - return helpURL; - }, - showHelp: function() - { - var newWindow = window.open(this.getHelpUrl(),'QpidHelp','height=600,width=600,scrollbars=1,location=1,resizable=1,status=0,toolbar=0,titlebar=1,menubar=0', true); - newWindow.focus(); - } - }; - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ContextVariablesEditor.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ContextVariablesEditor.js deleted file mode 100644 index a3e4023273..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ContextVariablesEditor.js +++ /dev/null @@ -1,558 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([ - "qpid/common/util", - "dojo/_base/xhr", - "dojo/_base/declare", - "dojo/_base/array", - "dojo/_base/connect", - "dojo/_base/lang", - "dojo/dom-construct", - "dojo/parser", - "dojo/query", - "dojo/store/Memory", - "dojo/data/ObjectStore", - "dijit/_WidgetBase", - "dijit/registry", - "dojo/text!common/ContextVariablesEditor.html", - "dijit/form/Button", - "dojox/grid/EnhancedGrid", - "dojox/grid/enhanced/_Plugin", - "dijit/form/Select", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], -function (util, xhr, declare, array, connect, lang, domConstruct, parser, query, Memory, ObjectStore, _WidgetBase, registry, template) - { - - return declare("qpid.common.ContextVariablesEditor", [_WidgetBase], { - - value: null, - effectiveValues: null, - inheritedActualValues: null, - domNode: null, - _grid: null, - _addButton: null, - _deleteButton: null, - _filterBox: null, - _nextGridItemId: 0, - _dynamicInheritedContext: {}, - - constructor: function(args) - { - this._args = args; - }, - - buildRendering: function() - { - this.domNode = domConstruct.create("div", {innerHTML: template}); - parser.parse(this.domNode); - }, - - postCreate: function() - { - this.inherited(arguments); - var that = this; - var gridNode = query(".grid", this.domNode)[0]; - var addButtonNode = query(".addButton", this.domNode)[0]; - var deleteButtonNode = query(".deleteButton", this.domNode)[0]; - var addButton = registry.byNode(addButtonNode); - var deleteButton = registry.byNode(deleteButtonNode); - var layout = [[ - { name: "Name", field: "name", width: "40%", editable: true}, - { name: 'Actual Value', field: 'actualValue', width: '30%', editable: true}, - { name: 'Effective Value', field: 'effectiveValue', width: '30%', editable: false} - ]]; - var data = []; - var objectStore = new dojo.data.ObjectStore({objectStore: new Memory({data:data, idProperty: "id"})}); - var grid = new dojox.grid.EnhancedGrid({ - selectionMode: "multiple", - store: objectStore, - singleClickEdit: true, - structure: layout, - autoHeight: true, - sortFields: [{attribute: 'name', descending: false}], - plugins: {indirectSelection: true} - }, gridNode); - grid.canEdit = function(inCell, inRowIndex) - { - var item = grid.getItem(inRowIndex); - return inCell.field == "actualValue" || (inCell.field=="name" && item && item["inherited"] == false); - }; - - this._grid = grid; - this._deleteButton = deleteButton; - this._addButtonNode = addButtonNode; - - var toggleGridButtons = function(index) - { - var data = grid.selection.getSelected(); - deleteButton.set("disabled", !data || data.length==0); - }; - - connect.connect(grid.selection, 'onSelected', toggleGridButtons); - connect.connect(grid.selection, 'onDeselected', toggleGridButtons); - connect.connect(grid, 'onStyleRow' , this, function(row) { that._onStyleRow(row); }); - - deleteButton.set("disabled", true); - addButton.on("click", function(event) { that._newItem(); }); - deleteButton.on("click", function(event) { that._deleteSelected(); }); - grid.on("applyEdit", function(inRowIndex) { that._onEdit(inRowIndex); }); - grid.startup(); - this._filterBox = registry.byNode(query(".filter", this.domNode)[0]); - this._filterBox.on("change", function(value) { if (value) { that._filter(value); } }); - }, - resize: function() - { - this._grid.render(); - }, - load: function(restUrl, data) - { - data = data || {}; - var actualValues = data.actualValues; - var allEffectiveValues = data.effectiveValues; - var inheritedActualValues = data.inheritedActualValues; - if (!actualValues) - { - xhr.get( - { - url: restUrl, - sync: true, - content: { actuals: true }, - handleAs: "json", - load: function(data) - { - actualValues = data[0].context; - } - } - ); - } - if (!allEffectiveValues) - { - xhr.get( - { - url: restUrl, - sync: true, - content: { actuals: false }, - handleAs: "json", - load: function(data) - { - allEffectiveValues = data[0].context; - } - } - ); - } - if (!inheritedActualValues) - { - xhr.get( - { - url: restUrl, - sync: true, - content: { actuals: true, inheritedActuals: true}, - handleAs: "json", - load: function(data) - { - inheritedActualValues = data[0].context; - } - } - ); - } - this.setData(actualValues, allEffectiveValues, inheritedActualValues); - }, - loadInheritedData: function(restUrl) - { - var allEffectiveValues = null; - xhr.get( - { - url: restUrl, - sync: true, - content: { actuals: false }, - handleAs: "json", - load: function(data) - { - allEffectiveValues = data[0].context; - } - } - ); - - var inheritedActualValues = null; - xhr.get( - { - url: restUrl, - sync: true, - content: { actuals: true, inheritedActuals: true}, - handleAs: "json", - load: function(data) - { - inheritedActualValues = data[0].context; - } - } - ); - - this.setData({}, allEffectiveValues, inheritedActualValues); - }, - setData: function(actualValues, allEffectiveValues, inheritedActualValues) - { - this.value = actualValues; - this.effectiveValues = allEffectiveValues; - this.inheritedActualValues = inheritedActualValues; - - var values = this._mergeValues(actualValues, allEffectiveValues, inheritedActualValues); - this._originalValues = values; - - var grid = this._grid; - if (grid) - { - // delete previous store data - grid.store.fetch({ - onComplete:function(items,request) - { - if(items.length) - { - array.forEach(items, function(item) - { - grid.store.deleteItem(item); - }); - } - } - }); - - // add new data into grid store - this._nextGridItemId = 0; - for(var i=0; i<values.length; i++) - { - var item = values[i]; - var storeItem = { - id: this._nextId(), - name: item.name, - actualValue: item.actualValue, - effectiveValue: item.effectiveValue, - "inherited": item["inherited"], - changed: false - }; - grid.store.newItem(storeItem); - } - grid.store.save(); - } - this._filter(this._filterBox.value); - this._handleOnChange(actualValues); - }, - addInheritedContext: function(object) - { - if (object) - { - var grid = this._grid; - for(key in object) - { - for(var i=0;i< this._originalValues.length;i++) - { - var varExists = false; - if (this._originalValues[i].name == key) - { - varExists = true; - break; - } - } - if (!varExists && !(key in this._dynamicInheritedContext)) - { - this._dynamicInheritedContext[key] = object[key]; - var storeItem = { - id: this._nextId(), - name: key, - actualValue: object[key], - effectiveValue: "", - "inherited": true, - changed: false - }; - grid.store.newItem(storeItem); - this._originalValues.push({name: key, - actualValue: object[key], - effectiveValue: "", - "inherited": true, - changed: false}); - } - } - grid.store.save(); - this._filter(this._filterBox.value); - } - }, - removeDynamicallyAddedInheritedContext: function() - { - if (this._dynamicInheritedContext) - { - var that = this; - var grid = this._grid; - grid.store.fetch({ - onComplete:function(items,request) - { - if(items.length) - { - for(key in that._dynamicInheritedContext) - { - var item = null; - for(var i=0;i<items.length;i++) - { - if (items[i].name == key) - { - item = items[i]; - break; - } - } - if (item && !item.changed) - { - grid.store.deleteItem(item); - that._deleteOriginalItem(item); - } - } - grid.store.save(); - that._dynamicInheritedContext = {}; - } - } - }); - } - }, - destroy: function() - { - if (this.domNode) - { - this.domNode.destroy(); - this.domNode = null; - } - if (this._grid != null) - { - this._grid.destroyRecursively(); - this._grid = null; - } - if (this._addButton != null) - { - this._addButton.destroyRecursively(); - this._addButton = null; - } - if (this._deleteButton != null) - { - this._deleteButton.destroyRecursively(); - this._deleteButton = null; - } - }, - onChange: function(newValue){}, - _newItem: function() - { - var newItem = { id: this._nextId(), name: "", actualValue: "", effectiveValue: "", "inherited": false, changed: true}; - var grid = this._grid; - grid.store.newItem(newItem); - grid.store.save(); - grid.store.fetch( - { - onComplete:function(items,request) - { - var rowIndex = items.length - 1; - window.setTimeout(function() - { - grid.focus.setFocusIndex(rowIndex, 1 ); - },10); - } - }); - }, - _deleteSelected: function() - { - var that = this; - var grid = this._grid; - var data = grid.selection.getSelected(); - if(data.length > 0) - { - array.forEach(data, function(selectedItem) { - if (selectedItem !== null && !selectedItem["inherited"]) - { - grid.store.deleteItem(selectedItem); - that._deleteOriginalItem(selectedItem.name); - } - }); - grid.store.save(); - grid.selection.deselectAll(); - this._valueChanged(); - } - }, - _deleteOriginalItem: function(key) - { - for(var i=0;i< this._originalValues.length;i++) - { - if (this._originalValues[i].name == key) - { - this._originalValues = this._originalValues.splice(i, 1); - break; - } - } - }, - _onEdit:function(inRowIndex) - { - var grid = this._grid; - var item = grid.getItem(inRowIndex); - var previousItems = this._originalValues; - var previousItemActualValue = null; - for(var i=0;i<previousItems.length;i++) - { - if (previousItems[i].name == item.name) - { - previousItemActualValue = previousItems[i].actualValue; - break; - } - } - - if (item.actualValue != previousItemActualValue) - { - if (!item.changed) - { - grid.store.setValue(item, "changed", true); - grid.store.save(); - } - } - else - { - if (item["inherited"]== true && item.changed) - { - grid.store.setValue(item, "changed", false); - grid.store.save(); - } - } - this._valueChanged(); - }, - _onStyleRow: function(row) - { - var grid = this._grid; - var inRowIndex = row.index; - var item = grid.getItem(inRowIndex); - if (item && (item["inherited"] == false || item.changed)) - { - row.customClasses += " highlightedText"; - } - else - { - row.customClasses += " normalText"; - } - grid.focus.styleRow(row); - grid.edit.styleRow(row); - }, - _filter: function(value) - { - this._grid.filter({"inherited": value}); - }, - _nextId: function() - { - this._nextGridItemId = this._nextGridItemId + 1; - return this._nextGridItemId; - }, - _valueChanged: function() - { - if (this._grid) - { - var value ={}; - var grid = this._grid; - grid.store.fetch({ - onComplete:function(items,request) - { - if(items.length > 0) - { - array.forEach(items, function(item) - { - if (item !== null && item.name && ((item["inherited"] && item.changed) || !item["inherited"])) - { - value[item.name]=item.actualValue; - } - }); - } - } - }); - if (!util.equals(this.value, value)) - { - this.value = value; - this._handleOnChange(value); - } - } - }, - _setValueAttr: function(actualValues) - { - this.value = actualValues; - if (this.inheritedActualValues!=null && this.effectiveValues != null) - { - this.setData(this.value, this.effectiveValues, this.inheritedActualValues); - } - }, - _setEffectiveValuesAttr: function(effectiveValues) - { - this.effectiveValues = effectiveValues; - if (this.value != null && this.inheritedActualValues !=null) - { - this.setData(this.value, this.effectiveValues, this.inheritedActualValues); - } - }, - _setInheritedActualValues: function(inheritedActualValues) - { - this.inheritedActualValues = inheritedActualValues; - if (this.value!= null && this.effectiveValues != null) - { - this.setData(this.value, this.effectiveValues, this.inheritedActualValues); - } - }, - _mergeValues: function(actualValues, allEffectiveValues, inheritedActualValues) - { - var fields = []; - - if (allEffectiveValues) - { - for(var key in allEffectiveValues) - { - if (!actualValues || !(key in actualValues)) - { - var actualValue = inheritedActualValues && key in inheritedActualValues ? inheritedActualValues[key] : allEffectiveValues[key]; - fields.push({name: key, actualValue: actualValue, effectiveValue: allEffectiveValues[key], "inherited": true}); - } - } - } - - if (actualValues) - { - for(var key in actualValues) - { - var effectiveValue = allEffectiveValues && key in allEffectiveValues ? allEffectiveValues[key]: actualValues[key]; - fields.push({name: key, actualValue: actualValues[key], effectiveValue: effectiveValue, "inherited": false}); - } - } - return fields; - }, - _handleOnChange: function(newValue) - { - if (!util.equals(this._lastValueReported, newValue)) - { - this._lastValueReported = newValue; - if(this._onChangeHandle) - { - this._onChangeHandle.remove(); - } - this._onChangeHandle = this.defer(function() - { - this._onChangeHandle = null; - this.onChange(newValue); - }); - } - } - - }); -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/FormWidgetMixin.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/FormWidgetMixin.js deleted file mode 100644 index 11160e9608..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/FormWidgetMixin.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/declare"], function(declare) -{ - return declare("qpid.common.FormWidgetMixin", null, - { - name: "", - value: "", - _onChangeActive: false, - - compare: function(val1, val2) - { - if(typeof val1 == "number" && typeof val2 == "number") - { - return (isNaN(val1) && isNaN(val2)) ? 0 : val1 - val2; - } - else if(val1 > val2) - { - return 1; - } - else if(val1 < val2) - { - return -1; - } - else - { - return 0; - } - }, - onChange: function() - { - }, - _setValueAttr: function(newValue, priorityChange) - { - this._handleOnChange(newValue, priorityChange); - }, - _handleOnChange: function(newValue, priorityChange) - { - this._set("value", newValue); - if(this._lastValueReported == undefined && (priorityChange === null || !this._onChangeActive)) - { - this._resetValue = this._lastValueReported = newValue; - } - this._pendingOnChange = this._pendingOnChange || (typeof newValue != typeof this._lastValueReported) - || (this.compare(newValue, this._lastValueReported) != 0); - if(( priorityChange || priorityChange === undefined) && this._pendingOnChange) - { - this._lastValueReported = newValue; - this._pendingOnChange = false; - if(this._onChangeActive) - { - if(this._onChangeHandle) - { - this._onChangeHandle.remove(); - } - this._onChangeHandle = this.defer(function() { this._onChangeHandle = null; this.onChange(newValue); }); - } - } - }, - create: function() - { - this.inherited(arguments); - this._onChangeActive = true; - }, - destroy: function() - { - if(this._onChangeHandle) - { - this._onChangeHandle.remove(); - this.onChange(this._lastValueReported); - } - this.inherited(arguments); - }, - undo: function() - { - this._setValueAttr(this._lastValueReported, false); - }, - reset: function() - { - this._hasBeenBlurred = false; - this._setValueAttr(this._resetValue, true); - } - }); -});
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ResourceWidget.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ResourceWidget.js deleted file mode 100644 index bee38149da..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ResourceWidget.js +++ /dev/null @@ -1,196 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([ - "dojo/_base/declare", - "dojo/_base/array", - "dojo/_base/lang", - "qpid/common/util", - "dijit/_Widget", - "dijit/_TemplatedMixin", - "dijit/_WidgetsInTemplateMixin", - "qpid/common/FormWidgetMixin", - "dojo/text!common/ResourceWidget.html", - "dojox/html/entities", - "dojox/form/Uploader", - "dijit/form/Button", - "dijit/form/ValidationTextBox", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], -function (declare, array, lang, util, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, FormWidgetMixin, template, entities) -{ - - return declare("qpid.common.ResourceWidget", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, FormWidgetMixin], - { - templateString: template, - fileReaderSupported: window.FileReader ? true : false, - displayWarningWhenFileReaderUnsupported: false, - isDebug: false, - uploaded: false, - - buildRendering: function() - { - //Strip out the apache comment header from the template html as comments unsupported. - this.templateString = this.templateString.replace(/<!--[\s\S]*?-->/g, ""); - this.inherited(arguments); - }, - postCreate: function() - { - this.inherited(arguments); - - if(this._resetValue === undefined) - { - this._lastValueReported = this._resetValue = this.value; - } - - var that = this; - - if (this.fileReaderSupported) - { - this.fileReader= new FileReader(); - this.fileReader.onload = function(evt) {that._uploadFileComplete(evt);}; - this.fileReader.onerror = function(ex) {console.error("Failed to load file for " + this.name, ex);}; - this.uploader.on("change", function(selected){that._fileChanged(selected)}); - this.clearButton.on("click", function(event){that._fileClearButtonClicked(event)}); - } - else - { - // Fall back for IE8/9 which do not support FileReader - this.uploadFields.style.display = "none"; - if (this.displayWarningWhenFileReaderUnsupported) - { - this.unsupportedWarning.className = this.unsupportedWarning.className.replace("hidden", ""); - } - } - this.resourceLocation.on("blur", function(){that._pathChanged()}); - this._originalValue = arguments.value; - if (this.placeHolder) - { - this.resourceLocation.set("placeHolder", this.placeHolder); - } - if (this.promptMessage) - { - this.resourceLocation.set("promptMessage", this.promptMessage); - } - if (this.title) - { - this.resourceLocation.set("title", this.title); - } - this.resourceLocation.set("required", this.required ? true : false); - this.uploadData.style.display = "none"; - }, - startup: function() - { - if (this.fileReaderSupported) - { - this.uploader.startup(); - } - }, - _fileChanged: function (evt) - { - var file = this.uploader.domNode.children[0].files[0]; - this.selectedFileName = file.name; - this.selectedFile.innerHTML = file.name; - this.selectedFileStatus.className = "loadingIcon"; - if (this.isDebug) - { - this._log("Beginning to read file " + file.name + " for " + this.name); - } - this.fileReader.readAsDataURL(file); - }, - _uploadFileComplete: function(evt) - { - var reader = evt.target; - var result = reader.result; - if (this.isDebug) - { - this._log(this.name + " file read complete, contents " + result); - } - this.set("value", result); - }, - _fileClearButtonClicked: function(event) - { - this.uploaded = false; - this.uploader.reset(); - this.set("value", this._resetValue); - }, - _pathChanged: function() - { - var serverPathValue = this.resourceLocation.get("value") || this._resetValue; - this.set("value", serverPathValue); - if (this.uploaded ) - { - this.uploaded = !serverPathValue; - } - }, - _setValueAttr: function(newValue, priorityChange) - { - var isDataUrl = this.uploaded || ( newValue && newValue.indexOf("data:") == 0 ); - if (isDataUrl) - { - this._initUploaded(true); - } - else - { - this.resourceLocation.set("value", newValue); - this.selectedFileName = null; - this.selectedFileStatus.className = ""; - this.selectedFile.innerHTML = ""; - this.resourceLocation.set("required", this.required ? true : false); - this.resourceLocation.setDisabled(false); - this.clearButton.setDisabled(true); - this.uploadData.style.display = "none"; - } - this.inherited(arguments); - }, - _log: function(message) - { - if (this.isDebug) - { - console.log(message); - } - }, - _setPlaceHolderAttr: function(newValue) - { - this.resourceLocation.set("placeHolder", newValue); - }, - _setUploadedAttr: function(uploaded) - { - this.uploaded = uploaded; - this._initUploaded(uploaded); - }, - _initUploaded: function(uploaded) - { - if (uploaded) - { - this.uploadData.style.display = "block"; - this.selectedFileStatus.className = "loadedIcon"; - this.selectedFile.innerHTML = this.selectedFileName || "uploaded data"; - this.resourceLocation.set("value", ""); - this.resourceLocation.setDisabled(true); - this.resourceLocation.set("required", false); - this.clearButton.setDisabled(false); - this.selectedFileStatus.className = "loadedIcon"; - } - } - } - ); -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/TimeZoneSelector.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/TimeZoneSelector.js deleted file mode 100644 index fa4bd8c873..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/TimeZoneSelector.js +++ /dev/null @@ -1,217 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([ - "dojo/_base/declare", - "dojo/_base/array", - "dojo/dom-construct", - "dojo/parser", - "dojo/query", - "dojo/dom-style", - "dojo/store/Memory", - "dijit/_WidgetBase", - "dijit/registry", - "dojo/text!common/TimeZoneSelector.html", - "qpid/common/timezone", - "dijit/form/ComboBox", - "dijit/form/FilteringSelect", - "dijit/form/CheckBox", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], -function (declare, array, domConstruct, parser, query, domStyle, Memory, _WidgetBase, registry, template, timezone) { - - var preferencesRegions = ["Africa","America","Antarctica","Arctic","Asia","Atlantic","Australia","Europe","Indian","Pacific"]; - - function initSupportedRegions() - { - var supportedRegions = [{"id": "undefined", "name": "Undefined"}]; - for(var j = 0; j<preferencesRegions.length; j++) - { - supportedRegions.push({id: preferencesRegions[j], name: preferencesRegions[j] }); - } - return supportedRegions; - } - - return declare("qpid.common.TimeZoneSelector", [_WidgetBase], { - - value: null, - domNode: null, - _regionSelector: null, - _citySelector: null, - _utcSelector: null, - - constructor: function(args) - { - this._args = args; - }, - - buildRendering: function(){ - this.domNode = domConstruct.create("div", {innerHTML: template}); - parser.parse(this.domNode); - }, - - postCreate: function(){ - this.inherited(arguments); - - var self = this; - if (this._args.labelStyle) - { - var nl = query(".labelClass", this.domNode); - array.forEach(nl, function(entry, i){ - domStyle.set(entry, self._args.labelStyle) - }); - } - var supportedTimeZones = timezone.getAllTimeZones(); - - this._utcSelector = registry.byNode(query(".utcSelector", this.domNode)[0]); - this._citySelector = registry.byNode(query(".timezoneCity", this.domNode)[0]); - this._citySelector.set("searchAttr", "city"); - this._citySelector.set("query", {region: /.*/}); - this._citySelector.set("labelAttr", "city"); - this._citySelector.set("store", new Memory({ data: supportedTimeZones })); - if (this._args.name) - { - this._citySelector.set("name", this._args.name); - } - this._regionSelector = registry.byNode(query(".timezoneRegion", this.domNode)[0]); - var supportedRegions = initSupportedRegions(); - this._regionSelector.set("store", new Memory({ data: supportedRegions })); - - this._utcSelector.on("change", function(value){ - var checked = this.get("checked"); - if (checked) - { - self.value ="UTC"; - } - else - { - if (self._citySelector.value && self._regionSelector.value) - { - self.value = self._citySelector.value; - } - else - { - self.value = null; - } - } - self._citySelector.set("disabled", checked); - self._regionSelector.set("disabled", checked); - self._handleOnChange(self.value); - }); - this._regionSelector.on("change", function(value){ - if (value=="undefined") - { - self._citySelector.set("disabled", true); - self._citySelector.query.region = /.*/; - self.value = null; - self._citySelector.set("value", null); - self._handleOnChange(self.value); - } - else - { - self._citySelector.set("disabled", false); - self._citySelector.query.region = value || /.*/; - if (this.timeZone) - { - self._citySelector.set("value", this.timeZone); - this.timeZone = null; - } - else - { - self._citySelector.set("value", null); - } - } - }); - - this._citySelector.on("change", function(value){ - self.value = value; - self._handleOnChange(value); - }); - - this._setValueAttr(this._args.value); - }, - - _setValueAttr: function(value) - { - if (value) - { - if (value == "UTC") - { - this._utcSelector.set("checked", true); - } - else - { - this._utcSelector.set("checked", false); - var elements = value.split("/"); - if (elements.length > 1) - { - this._regionSelector.timeZone = value; - this._regionSelector.set("value", elements[0]); - this._citySelector.set("value", value); - } - else - { - this._regionSelector.set("value", "undefined"); - } - } - } - else - { - this._utcSelector.set("checked", false); - this._regionSelector.set("value", "undefined"); - } - this.value = value; - this._handleOnChange(value); - }, - - destroy: function() - { - if (this.domNode) - { - this.domNode.destroy(); - this.domNode = null; - } - _regionSelector: null; - _citySelector: null; - _utcSelector: null; - }, - - onChange: function(newValue){}, - - _handleOnChange: function(newValue) - { - if (this._lastValueReported != newValue) - { - this._lastValueReported = newValue; - if(this._onChangeHandle) - { - this._onChangeHandle.remove(); - } - this._onChangeHandle = this.defer(function() - { - this._onChangeHandle = null; - this.onChange(newValue); - }); - } - } - - }); -});
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/UpdatableStore.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/UpdatableStore.js deleted file mode 100644 index 64d557c242..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/UpdatableStore.js +++ /dev/null @@ -1,189 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/json", - "qpid/common/util", - "dojo/store/Memory", - "dojox/grid/DataGrid", - "dojo/data/ObjectStore", - "dojo/store/Observable"], function (json, util, Memory, DataGrid, ObjectStore, Observable) { - - function UpdatableStore( data, divName, structure, func, props, Grid, notObservable ) { - - var that = this; - var GridType = DataGrid; - - that.memoryStore = new Memory({data: data, idProperty: "id"}); - that.store = notObservable ? that.memoryStore : new Observable(that.memoryStore); - that.dataStore = ObjectStore({objectStore: that.store}); - - var gridProperties = { store: that.dataStore, - structure: structure, - autoHeight: true - }; - if(props) { - for(var prop in props) { - if(props.hasOwnProperty(prop)) - { - gridProperties[ prop ] = props[ prop ]; - } - } - } - - if(Grid) - { - GridType = Grid; - } - - that.grid = new GridType(gridProperties, divName); - - // since we created this grid programmatically, call startup to render it - that.grid.startup(); - - if( func ) - { - func(that); - } - - } - - UpdatableStore.prototype.update = function(data) - { - var changed = false; - var store = this.store; - var theItem; - - // handle deletes - // iterate over existing store... if not in new data then remove - store.query({ }).forEach(function(object) { - if(data) { - for(var i=0; i < data.length; i++) { - if(data[i].id == object.id) { - return; - } - } - } - store.remove(object.id); - changed = true; - }); - - // iterate over data... - if(data) { - for(var i=0; i < data.length; i++) - { - if(theItem = store.get(data[i].id)) - { - var modified = !util.equals(theItem, data[i]); - if(modified) - { - if (store.notify) - { - // Seems that we are required to update the item that the store already holds - for(var propName in data[i]) - { - if(data[i].hasOwnProperty(propName)) - { - if(theItem[ propName ] != data[i][ propName ]) - { - theItem[ propName ] = data[i][ propName ]; - } - } - } - // and tell it we have done so - store.notify(theItem, data[i].id); - } - else - { - store.put(data[i], {overwrite: true}); - } - changed = true; - } - } else { - // if not in the store then add - store.put(data[i]); - changed = true; - } - } - } - - return changed; - }; - - function removeItemsFromArray(items, numberToRemove) - { - if (items) - { - if (numberToRemove > 0 && items.length > 0) - { - if (numberToRemove >= items.length) - { - numberToRemove = numberToRemove - items.length; - items.length = 0 - } - else - { - items.splice(0, numberToRemove); - numberToRemove = 0; - } - } - } - return numberToRemove; - }; - - UpdatableStore.prototype.append = function(data, limit) - { - var changed = false; - var items = this.memoryStore.data; - - if (limit) - { - var totalSize = items.length + (data ? data.length : 0); - var numberToRemove = totalSize - limit; - - if (numberToRemove > 0) - { - changed = true; - numberToRemove = removeItemsFromArray(items, numberToRemove); - if (numberToRemove > 0) - { - removeItemsFromArray(data, numberToRemove); - } - } - } - - if (data && data.length > 0) - { - changed = true; - items.push.apply(items, data); - } - - this.memoryStore.setData(items); - return changed; - }; - - UpdatableStore.prototype.close = function() - { - this.dataStore.close(); - this.dataStore = null; - this.store = null; - this.memoryStore = null; - }; - return UpdatableStore; -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/footer.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/footer.js deleted file mode 100644 index ea13b1fc53..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/footer.js +++ /dev/null @@ -1,30 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", "dojo/query", "dojo/domReady!"], function (xhr, query) { - query('div[qpid-type="footer"]').forEach(function(node, index, arr) { - xhr.get({url: "footer.html", - sync: true, - load: function(data) { - node.innerHTML = data; - } }); - }); -}); - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/formatter.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/formatter.js deleted file mode 100644 index 2f8683ee1c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/formatter.js +++ /dev/null @@ -1,99 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -define(function () { - return { - - formatBytes: function formatBytes(amount) - { - var returnVal = { units: "B", - value: "0"}; - - - if(amount < 1000) - { - returnVal.value = amount.toPrecision(3);; - } - else if(amount < 1000 * 1024) - { - returnVal.units = "KB"; - returnVal.value = (amount / 1024).toPrecision(3); - } - else if(amount < 1000 * 1024 * 1024) - { - returnVal.units = "MB"; - returnVal.value = (amount / (1024 * 1024)).toPrecision(3); - } - else if(amount < 1000 * 1024 * 1024 * 1024) - { - returnVal.units = "GB"; - returnVal.value = (amount / (1024 * 1024 * 1024)).toPrecision(3); - } - - return returnVal; - - }, - - formatTime: function formatTime(amount) - { - var returnVal = { units: "ms", - value: "0"}; - - if(amount < 1000) - { - returnVal.units = "ms"; - returnVal.value = amount.toString(); - } - else if(amount < 1000 * 60) - { - returnVal.units = "s"; - returnVal.value = (amount / 1000).toPrecision(3); - } - else if(amount < 1000 * 60 * 60) - { - returnVal.units = "min"; - returnVal.value = (amount / (1000 * 60)).toPrecision(3); - } - else if(amount < 1000 * 60 * 60 * 24) - { - returnVal.units = "hr"; - returnVal.value = (amount / (1000 * 60 * 60)).toPrecision(3); - } - else if(amount < 1000 * 60 * 60 * 24 * 7) - { - returnVal.units = "d"; - returnVal.value = (amount / (1000 * 60 * 60 * 24)).toPrecision(3); - } - else if(amount < 1000 * 60 * 60 * 24 * 365) - { - returnVal.units = "wk"; - returnVal.value = (amount / (1000 * 60 * 60 * 24 * 7)).toPrecision(3); - } - else - { - returnVal.units = "yr"; - returnVal.value = (amount / (1000 * 60 * 60 * 24 * 365)).toPrecision(3); - } - - return returnVal; - } - }; -});
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/ColumnDefDialog.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/ColumnDefDialog.js deleted file mode 100644 index a0b62082cb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/ColumnDefDialog.js +++ /dev/null @@ -1,145 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -define([ - "dojo/_base/declare", - "dojo/_base/event", - "dojo/_base/array", - "dojo/_base/lang", - "dojo/parser", - "dojo/dom-construct", - "dojo/query", - "dijit/registry", - "dijit/form/Button", - "dijit/form/CheckBox", - "dojox/grid/enhanced/plugins/Dialog", - "dojo/text!../../../grid/showColumnDefDialog.html", - "dojo/domReady!" -], function(declare, event, array, lang, parser, dom, query, registry, Button, CheckBox, Dialog, template ){ - - -return declare("qpid.common.grid.ColumnDefDialog", null, { - - grid: null, - containerNode: null, - _columns: [], - _dialog: null, - - constructor: function(args){ - var grid = this.grid = args.grid; - var that = this; - this.containerNode = dom.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances) - { - that._postParse(); - }); - }, - _postParse: function() - { - var submitButton = registry.byNode(query(".displayButton", this.containerNode)[0]); - this.closeButton = registry.byNode(query(".cancelButton", this.containerNode)[0]); - var columnsContainer = query(".columnList", this.containerNode)[0]; - - this._buildColumnWidgets(columnsContainer); - - this._dialog = new Dialog({ - "refNode": this.grid.domNode, - "title": "Grid Columns", - "content": this.containerNode - }); - - var self = this; - submitButton.on("click", function(e){self._onColumnsSelect(e); }); - this.closeButton.on("click", function(e){self._dialog.hide(); }); - - this._dialog.startup(); - }, - - destroy: function(){ - this._dialog.destroyRecursive(); - this._dialog = null; - this.grid = null; - this.containerNode = null; - this._columns = null; - }, - - showDialog: function(){ - this._initColumnWidgets(); - this._dialog.show(); - }, - - _initColumnWidgets: function() - { - var cells = this.grid.layout.cells; - for(var i in cells) - { - var cell = cells[i]; - this._columns[cell.name].checked = !cell.hidden; - } - }, - - _onColumnsSelect: function(evt){ - event.stop(evt); - var grid = this.grid; - grid.beginUpdate(); - var cells = grid.layout.cells; - try - { - for(var i in cells) - { - var cell = cells[i]; - var widget = this._columns[cell.name]; - grid.layout.setColumnVisibility(i, widget.checked); - } - } - finally - { - grid.endUpdate(); - this._dialog.hide(); - } - }, - - _buildColumnWidgets: function(columnsContainer) - { - var cells = this.grid.layout.cells; - for(var i in cells) - { - var cell = cells[i]; - var widget = new dijit.form.CheckBox({ - required: false, - checked: !cell.hidden, - label: cell.name, - name: this.grid.id + "_cchb_ " + i - }); - - this._columns[cell.name] = widget; - - var div = dom.create("div"); - div.appendChild(widget.domNode); - div.appendChild(dom.create("span", {innerHTML: cell.name})); - - columnsContainer.appendChild(div); - } - } - - }); - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilter.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilter.js deleted file mode 100644 index 262210f879..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilter.js +++ /dev/null @@ -1,230 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -define([ - "dojo/_base/declare", - "dojo/_base/lang", - "dojo/_base/array", - "dijit/Toolbar", - "dojox/grid/enhanced/_Plugin", - "dojox/grid/enhanced/plugins/Dialog", - "dojox/grid/enhanced/plugins/filter/FilterLayer", - "dojox/grid/enhanced/plugins/filter/FilterDefDialog", - "dojox/grid/enhanced/plugins/filter/FilterStatusTip", - "dojox/grid/enhanced/plugins/filter/ClearFilterConfirm", - "dojox/grid/EnhancedGrid", - "dojo/i18n!dojox/grid/enhanced/nls/Filter", - "qpid/common/grid/EnhancedFilterTools" -], function(declare, lang, array, Toolbar, _Plugin, - Dialog, FilterLayer, FilterDefDialog, FilterStatusTip, ClearFilterConfirm, EnhancedGrid, nls, EnhancedFilterTools){ - - // override CriteriaBox#_getColumnOptions to show criteria for hidden columns with EnhancedFilter - dojo.extend(dojox.grid.enhanced.plugins.filter.CriteriaBox, { - _getColumnOptions: function(){ - var colIdx = this.dlg.curColIdx >= 0 ? String(this.dlg.curColIdx) : "anycolumn"; - var filterHidden = this.plugin.filterHidden; - return array.map(array.filter(this.plugin.grid.layout.cells, function(cell){ - return !(cell.filterable === false || (!filterHidden && cell.hidden)); - }), function(cell){ - return { - label: cell.name || cell.field, - value: String(cell.index), - selected: colIdx == String(cell.index) - }; - }); - } - }); - - // Enhanced filter has extra functionality for refreshing, limiting rows, displaying/hiding columns in the grid - var EnhancedFilter = declare("qpid.common.grid.EnhancedFilter", _Plugin, { - // summary: - // Accept the same plugin parameters as dojox.grid.enhanced.plugins.Filter and the following: - // - // filterHidden: boolean: - // Whether to display filtering criteria for hidden columns. Default to true. - // - // defaulGridRowLimit: int: - // Default limit for numbers of items to cache in the gris dtore - // - // disableFiltering: boolean: - // Whether to disable a filtering including filter button, clear filter button and filter summary. - // - // toolbar: dijit.Toolbar: - // An instance of toolbar to add the enhanced filter widgets. - - - // name: String - // plugin name - name: "enhancedFilter", - - // filterHidden: Boolean - // whether to filter hidden columns - filterHidden: true, - - constructor: function(grid, args){ - // summary: - // See constructor of dojox.grid.enhanced._Plugin. - this.grid = grid; - this.nls = nls; - - args = this.args = lang.isObject(args) ? args : {}; - if(typeof args.ruleCount != 'number' || args.ruleCount < 0){ - args.ruleCount = 0; - } - this.ruleCountToConfirmClearFilter = args.ruleCountToConfirmClearFilter || 5; - - if (args.filterHidden){ - this.filterHidden = args.filterHidden; - } - this.defaulGridRowLimit = args.defaulGridRowLimit; - this.disableFiltering = args.disableFiltering; - this.displayLastUpdateTime = args.displayLastUpdateTime; - - //Install UI components - var obj = { "plugin": this }; - - this.filterBar = ( args.toolbar && args.toolbar instanceof dijit.Toolbar) ? args.toolbar: new Toolbar(); - - if (!this.disableFiltering) - { - //Install filter layer - this._wrapStore(); - - this.clearFilterDialog = new Dialog({ - refNode: this.grid.domNode, - title: this.nls["clearFilterDialogTitle"], - content: new ClearFilterConfirm(obj) - }); - - this.filterDefDialog = new FilterDefDialog(obj); - this.filterDefDialog.filterDefPane._clearFilterBtn.set("label", "Clear Filter"); - - nls["statusTipTitleNoFilter"] = "Filter is not set"; - nls["statusTipMsg"] = "Click on 'Set Filter' button to specify filtering conditions"; - this.filterStatusTip = new FilterStatusTip(obj); - - var self = this; - var toggleClearFilterBtn = function (arg){ self.enhancedFilterTools.toggleClearFilterBtn(arg); }; - - this.filterBar.toggleClearFilterBtn = toggleClearFilterBtn; - - this.grid.isFilterBarShown = function (){return true}; - - this.connect(this.grid.layer("filter"), "onFilterDefined", function(filter){ - toggleClearFilterBtn(true); - }); - - //Expose the layer event to grid. - grid.onFilterDefined = function(){}; - this.connect(grid.layer("filter"), "onFilterDefined", function(filter){ - grid.onFilterDefined(grid.getFilter(), grid.getFilterRelation()); - }); - } - - // add extra buttons into toolbar - this.enhancedFilterTools = new EnhancedFilterTools({ - grid: grid, - toolbar: this.filterBar, - filterStatusTip: this.filterStatusTip, - clearFilterDialog: this.clearFilterDialog, - filterDefDialog: this.filterDefDialog, - defaulGridRowLimit: this.defaulGridRowLimit, - disableFiltering: this.disableFiltering, - displayLastUpdateTime: this.displayLastUpdateTime, - nls: nls, - ruleCountToConfirmClearFilter: this.ruleCountToConfirmClearFilter - }); - - this.filterBar.placeAt(this.grid.viewsHeaderNode, "before"); - this.filterBar.startup(); - - }, - - destroy: function(){ - this.inherited(arguments); - try - { - if (this.filterDefDialog) - { - this.filterDefDialog.destroy(); - this.filterDefDialog = null; - } - if (this.grid) - { - this.grid.unwrap("filter"); - this.grid = null; - } - if (this.filterBar) - { - this.filterBar.destroyRecursive(); - this.filterBar = null; - } - if (this.enhancedFilterTools) - { - this.enhancedFilterTools.destroy(); - this.enhancedFilterTools = null; - } - if (this.clearFilterDialog) - { - this.clearFilterDialog.destroyRecursive(); - this.clearFilterDialog = null; - } - if (this.filterStatusTip) - { - this.filterStatusTip.destroy(); - this.filterStatusTip = null; - } - this.args = null; - - }catch(e){ - console.warn("Filter.destroy() error:",e); - } - }, - - _wrapStore: function(){ - var g = this.grid; - var args = this.args; - var filterLayer = args.isServerSide ? new FilterLayer.ServerSideFilterLayer(args) : - new FilterLayer.ClientSideFilterLayer({ - cacheSize: args.filterCacheSize, - fetchAll: args.fetchAllOnFirstFilter, - getter: this._clientFilterGetter - }); - FilterLayer.wrap(g, "_storeLayerFetch", filterLayer); - - this.connect(g, "_onDelete", lang.hitch(filterLayer, "invalidate")); - }, - - onSetStore: function(store){ - this.filterDefDialog.clearFilter(true); - }, - - _clientFilterGetter: function(/* data item */ datarow,/* cell */cell, /* int */rowIndex){ - return cell.get(rowIndex, datarow); - } - - }); - - EnhancedGrid.registerPlugin(EnhancedFilter); - - return EnhancedFilter; - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilterTools.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilterTools.js deleted file mode 100644 index 187ed8cfc6..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilterTools.js +++ /dev/null @@ -1,310 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -define([ - "dojo/_base/declare", - "dojo/_base/event", - "dojo/dom-construct", - "dojo/date/locale", - "dijit/form/Button", - "dijit/form/ToggleButton", - "qpid/common/grid/RowNumberLimitDialog", - "qpid/common/grid/ColumnDefDialog", - "qpid/common/grid/FilterSummary", - "qpid/management/UserPreferences" -], function(declare, event, domConstruct, locale, Button, ToggleButton, RowNumberLimitDialog, ColumnDefDialog, FilterSummary, UserPreferences){ - - var _stopEvent = function (evt){ - try{ - if(evt && evt.preventDefault){ - event.stop(evt); - } - }catch(e){} - }; - - return declare("qpid.common.grid.EnhancedFilterTools", null, { - - grid: null, - filterBar: null, - filterStatusTip: null, - clearFilterDialog: null, - filterDefDialog: null, - - columnDefDialog: null, - columnDefButton: null, - filterDefButton: null, - clearFilterButton: null, - filterSummary: null, - setRowNumberLimitButton: null, - setRowNumberLimitDialog: null, - refreshButton: null, - autoRefreshButton: null, - - constructor: function(params) - { - this.inherited(arguments); - - this.filterBar = params.toolbar; - this.grid = params.grid; - this.filterStatusTip= params.filterStatusTip; - this.clearFilterDialog = params.clearFilterDialog; - this.filterDefDialog = params.filterDefDialog; - this.ruleCountToConfirmClearFilter = params.ruleCountToConfirmClearFilter; - this.displayLastUpdateTime = params.hasOwnProperty("displayLastUpdateTime")?params.displayLastUpdateTime:true; - - this._addRefreshButtons(); - this._addRowLimitButton(params.defaulGridRowLimit); - this._addColumnsButton(); - - if (!params.disableFiltering) - { - this._addFilteringTools(params.nls); - } - }, - - toggleClearFilterBtn: function(clearFlag) - { - var filterLayer = this.grid.layer("filter"); - var filterSet = filterLayer && filterLayer.filterDef && filterLayer.filterDef(); - this.clearFilterButton.set("disabled", !filterSet); - }, - - destroy: function() - { - this.inherited(arguments); - - if (this.columnDefDialog) - { - this.columnDefDialog.destroy(); - this.columnDefDialog = null; - } - if (this.columnDefButton) - { - this.columnDefButton.destroy(); - this.columnDefButton = null; - } - if (this.filterDefButton) - { - this.filterDefButton.destroy(); - this.filterDefButton = null; - } - if (this.clearFilterButton) - { - this.clearFilterButton.destroy(); - this.clearFilterButton = null; - } - if (this.filterSummary) - { - this.filterSummary.destroy(); - this.filterSummary = null; - } - if (this.setRowNumberLimitButton) - { - this.setRowNumberLimitButton.destroy(); - this.setRowNumberLimitButton = null; - } - if (this.setRowNumberLimitDialog) - { - this.setRowNumberLimitDialog.destroy(); - this.setRowNumberLimitDialog = null; - } - if (this.refreshButton) - { - this.refreshButton.destroy(); - this.refreshButton = null; - } - if (this.autoRefreshButton) - { - this.autoRefreshButton.destroy(); - this.autoRefreshButton = null; - } - - this.grid = null; - this.filterBar = null; - this.filterStatusTip = null; - this.clearFilterDialog = null; - this.filterDefDialog = null; - }, - - _addRefreshButtons: function() - { - var self = this; - this.refreshButton = new dijit.form.Button({ - label: "Refresh", - type: "button", - iconClass: "gridRefreshIcon", - title: "Manual Refresh" - }); - - this.autoRefreshButton = new dijit.form.ToggleButton({ - label: "Auto Refresh", - type: "button", - iconClass: "gridAutoRefreshIcon", - title: "Auto Refresh" - }); - - this.autoRefreshButton.on("change", function(value){ - self.grid.updater.updatable=value; - self.refreshButton.set("disabled", value); - }); - - this.refreshButton.on("click", function(value){ - self.grid.updater.performUpdate(); - }); - - this.filterBar.addChild(this.autoRefreshButton); - this.filterBar.addChild(this.refreshButton); - - if (this.displayLastUpdateTime) - { - var updateStatusPanel = domConstruct.create("div"); - var updateTimeLabel = domConstruct.create("span", {innerHTML: "Update time: ", "class": "formLabel-labelCell", "style": "padding-right: 5px;padding-left: 5px"}, updateStatusPanel); - var updateTimeLabelPreferredTZ = domConstruct.create("span", {innerHTML: "Preferred timezone:", "style": "padding-right: 5px"}, updateStatusPanel); - var updateTimePreferredTZ = domConstruct.create("span", {"style": "padding-right: 5px"}, updateStatusPanel); - var updateTimeLabelBrowserTZ = domConstruct.create("span", {innerHTML: "Browser timezone:", "style": "padding-right: 5px"}, updateStatusPanel); - var updateTimeBrowserTZ = domConstruct.create("span", {"style": "padding-right: 5px"}, updateStatusPanel); - - var lastUpdateTimeUpdater = function(data) - { - var userTimeZone = UserPreferences.timeZone; - var displayStyle = userTimeZone? "inline" : "none"; - updateTimeLabelPreferredTZ.style.display = displayStyle; - updateTimePreferredTZ.style.display = displayStyle; - var formatOptions = {selector: "time", timePattern: "HH:mm:ss.SSS", appendTimeZone: true, addOffset: true}; - var updateTime = new Date(); - updateTimePreferredTZ.innerHTML = UserPreferences.formatDateTime(updateTime.getTime(), formatOptions); - updateTimeBrowserTZ.innerHTML = locale.format(updateTime, formatOptions); - }; - - if (self.grid.updater.store) - { - // data have been already provided/or fetched - // set last update time to current time - lastUpdateTimeUpdater(); - } - - self.grid.updater.addOnUpdate(lastUpdateTimeUpdater); - domConstruct.place(updateStatusPanel, this.grid.viewsHeaderNode, "before"); - } - }, - - _addRowLimitButton: function(defaulGridRowLimit) - { - var self = this; - this.setRowNumberLimitButton = new dijit.form.Button({ - label: "Set Row Limit", - type: "button", - iconClass: "rowNumberLimitIcon", - title: "Set Row Number Limit" - }); - this.setRowNumberLimitButton.set("title", "Set Row Number Limit (Current: " + defaulGridRowLimit +")"); - - this.setRowNumberLimitDialog = new RowNumberLimitDialog(this.grid.domNode, function(newLimit){ - if (newLimit > 0 && self.grid.updater.appendLimit != newLimit ) - { - self.grid.updater.appendLimit = newLimit; - self.grid.updater.performRefresh([]); - self.setRowNumberLimitButton.set("title", "Set Row Number Limit (Current: " + newLimit +")"); - } - }); - - this.setRowNumberLimitButton.on("click", function(evt){ - self.setRowNumberLimitDialog.showDialog(self.grid.updater.appendLimit); - }); - - this.filterBar.addChild(this.setRowNumberLimitButton); - }, - - _addColumnsButton: function() - { - var self = this; - this.columnDefDialog = new ColumnDefDialog({grid: this.grid}); - - this.columnDefButton = new dijit.form.Button({ - label: "Display Columns", - type: "button", - iconClass: "columnDefDialogButtonIcon", - title: "Show/Hide Columns" - }); - - this.columnDefButton.on("click", function(e){ - _stopEvent(e); - self.columnDefDialog.showDialog(); - }); - - this.filterBar.addChild(this.columnDefButton); - }, - - _addFilteringTools: function(nls) - { - var self = this; - - this.filterDefButton = new dijit.form.Button({ - "class": "dojoxGridFBarBtn", - label: "Set Filter", - iconClass: "dojoxGridFBarDefFilterBtnIcon", - showLabel: "true", - title: "Define filter" - }); - - this.clearFilterButton = new dijit.form.Button({ - "class": "dojoxGridFBarBtn", - label: "Clear filter", - iconClass: "dojoxGridFBarClearFilterButtontnIcon", - showLabel: "true", - title: "Clear filter", - disabled: true - }); - - - this.filterDefButton.on("click", function(e){ - _stopEvent(e); - - // a bit of a hack to force dialog to rebuild the criteria controls in order to get rid from empty rule controls - self.filterDefDialog._criteriasChanged = true; - self.filterDefDialog.showDialog(); - }); - - this.clearFilterButton.on("click", function(e){ - _stopEvent(e); - if (self.ruleCountToConfirmClearFilter && self.filterDefDialog.getCriteria() >= self.ruleCountToConfirmClearFilter) - { - self.clearFilterDialog.show(); - } - else - { - self.grid.layer("filter").filterDef(null); - self.toggleClearFilterBtn(true) - } - }); - - this.filterSummary = new FilterSummary({grid: this.grid, filterStatusTip: this.filterStatusTip, nls: nls}); - - this.filterBar.addChild(this.filterDefButton); - this.filterBar.addChild(this.clearFilterButton); - - this.filterBar.addChild(new dijit.ToolbarSeparator()); - this.filterBar.addChild(this.filterSummary, "last"); - this.filterBar.getColumnIdx = function(coordX){return self.filterSummary._getColumnIdx(coordX);}; - - } - }); -});
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/FilterSummary.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/FilterSummary.js deleted file mode 100644 index d29e4027df..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/FilterSummary.js +++ /dev/null @@ -1,173 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -define([ - "dojo/_base/declare", - "dojo/_base/lang", - "dojo/_base/html", - "dojo/query", - "dojo/dom-construct", - "dojo/string", - "dojo/on", - "dijit/_WidgetBase" -], function(declare, lang, html, query, domConstruct, string, on, _WidgetBase){ - -return declare("qpid.common.grid.FilterSummary", [_WidgetBase], { - - domNode: null, - itemName: null, - filterStatusTip: null, - grid: null, - _handle_statusTooltip: null, - _timeout_statusTooltip: 300, - _nls: null, - - constructor: function(params) - { - this.inherited(arguments); - this.itemName = params.itemsName; - this.initialize(params.filterStatusTip, params.grid); - this._nls = params.nls; - }, - - buildRendering: function(){ - this.inherited(arguments); - var itemsName = this.itemName || this._nls["defaultItemsName"]; - var message = string.substitute(this._nls["filterBarMsgNoFilterTemplate"], [0, itemsName ]); - this.domNode = domConstruct.create("span", {innerHTML: message, "class": "dijit dijitReset dijitInline dijitButtonInline", role: "presentation" }); - }, - - postCreate: function(){ - this.inherited(arguments); - on(this.domNode, "mouseenter", lang.hitch(this, this._onMouseEnter)); - on(this.domNode, "mouseleave", lang.hitch(this, this._onMouseLeave)); - on(this.domNode, "mousemove", lang.hitch(this, this._onMouseMove)); - }, - - destroy: function() - { - this.inherited(arguments); - this.itemName = null; - this.filterStatusTip = null; - this.grid = null; - this._handle_statusTooltip = null; - this._filteredClass = null; - this._nls = null; - }, - - initialize: function(filterStatusTip, grid) - { - this.filterStatusTip = filterStatusTip; - this.grid = grid; - if (this.grid) - { - var filterLayer = grid.layer("filter"); - this.connect(filterLayer, "onFiltered", this.onFiltered); - } - }, - - onFiltered: function(filteredSize, originSize) - { - try - { - var itemsName = this.itemName || this._nls["defaultItemsName"], - msg = "", g = this.grid, - filterLayer = g.layer("filter"); - if(filterLayer.filterDef()){ - msg = string.substitute(this._nls["filterBarMsgHasFilterTemplate"], [filteredSize, originSize, itemsName]); - }else{ - msg = string.substitute(this._nls["filterBarMsgNoFilterTemplate"], [originSize, itemsName]); - } - this.domNode.innerHTML = msg; - } - catch(e) - { - // swallow and log exception - // otherwise grid rendering is screwed - console.error(e); - } - }, - - _getColumnIdx: function(coordX){ - var headers = query("[role='columnheader']", this.grid.viewsHeaderNode); - var idx = -1; - for(var i = headers.length - 1; i >= 0; --i){ - var coord = html.position(headers[i]); - if(coordX >= coord.x && coordX < coord.x + coord.w){ - idx = i; - break; - } - } - if(idx >= 0 && this.grid.layout.cells[idx].filterable !== false){ - return idx; - }else{ - return -1; - } - }, - - _setStatusTipTimeout: function(){ - this._clearStatusTipTimeout(); - this._handle_statusTooltip = setTimeout(lang.hitch(this,this._showStatusTooltip),this._timeout_statusTooltip); - }, - - _clearStatusTipTimeout: function(){ - if (this._handle_statusTooltip){ - clearTimeout(this._handle_statusTooltip); - } - this._handle_statusTooltip = null; - }, - - _showStatusTooltip: function(){ - this._handle_statusTooltip = null; - if(this.filterStatusTip){ - this.filterStatusTip.showDialog(this._tippos.x, this._tippos.y, this._getColumnIdx(this._tippos.x)); - } - }, - - _updateTipPosition: function(evt){ - this._tippos = { - x: evt.pageX, - y: evt.pageY - }; - }, - - _onMouseEnter: function(e){ - this._updateTipPosition(e); - if(this.filterStatusTip){ - this._setStatusTipTimeout(); - } - }, - - _onMouseMove: function(e){ - if(this.filterStatusTip){ - this._setStatusTipTimeout(); - if(this._handle_statusTooltip){ - this._updateTipPosition(e); - } - } - }, - - _onMouseLeave: function(e){ - this._clearStatusTipTimeout(); - } - }); - -});
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/GridUpdater.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/GridUpdater.js deleted file mode 100644 index e5d96d44e7..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/GridUpdater.js +++ /dev/null @@ -1,297 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/lang", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/UpdatableStore", - "qpid/common/util", - "dojo/store/Memory", - "dojo/data/ObjectStore", - "qpid/common/grid/EnhancedFilter", - "dojox/grid/enhanced/plugins/NestedSorting", - "dojo/domReady!"], - function (xhr, parser, array, lang, properties, updater, UpdatableStore, util, Memory, ObjectStore) { - - function GridUpdater(args, store) { - this.updatable = args.hasOwnProperty("updatable") ? args.updatable : true ; - this.serviceUrl = args.serviceUrl; - - this.onUpdate = []; - if (args.onUpdate) - { - this.onUpdate.push(args.onUpdate); - } - this.dataTransformer = args.dataTransformer; - - this.appendData = args.append; - this.appendLimit = args.appendLimit; - this.initialData = args.data; - this.initializeStore(store); - }; - - GridUpdater.prototype.buildUpdatableGridArguments = function(args) - { - var filterPluginFound = args && args.hasOwnProperty("plugins") && args.plugins.filter ? true: false; - - var gridProperties = { - autoHeight: true, - plugins: { - pagination: { - defaultPageSize: 25, - pageSizes: [10, 25, 50, 100], - description: true, - sizeSwitch: true, - pageStepper: true, - gotoButton: true, - maxPageStep: 4, - position: "bottom" - }, - enhancedFilter: { - disableFiltering: filterPluginFound - } - } - }; - - if(args) - { - for(var argProperty in args) - { - if(args.hasOwnProperty(argProperty)) - { - if (argProperty == "plugins") - { - var argPlugins = args[ argProperty ]; - for(var argPlugin in argPlugins) - { - if(argPlugins.hasOwnProperty(argPlugin)) - { - var argPluginProperties = argPlugins[ argPlugin ]; - if (argPluginProperties && gridProperties.plugins.hasOwnProperty(argPlugin)) - { - var gridPlugin = gridProperties.plugins[ argPlugin ]; - for(var pluginProperty in argPluginProperties) - { - if(argPluginProperties.hasOwnProperty(pluginProperty)) - { - gridPlugin[pluginProperty] = argPluginProperties[pluginProperty]; - } - } - } - else - { - gridProperties.plugins[ argPlugin ] = argPlugins[ argPlugin ]; - } - } - } - } - else - { - gridProperties[ argProperty ] = args[ argProperty ]; - } - } - } - } - - gridProperties.updater = this; - gridProperties.store = this.dataStore; - - return gridProperties; - }; - - GridUpdater.prototype.initializeStore = function(store) - { - var self = this; - - function processData(data) - { - if (self.dataTransformer) - { - data = self.dataTransformer(data); - } - var dataSet = false; - if (!store) - { - store = new ObjectStore({objectStore: new Memory({data: data, idProperty: "id"})}); - dataSet = true; - } - self.dataStore = store - self.store = store; - if (store instanceof ObjectStore) - { - if( store.objectStore instanceof Memory) - { - self.memoryStore = store.objectStore; - } - self.store = store.objectStore - } - - if (data) - { - if ((dataSet || self.updateOrAppend(data)) && self.onUpdate.length > 0) - { - self.fireUpdate(data); - } - } - }; - - if (this.serviceUrl) - { - var requestUrl = lang.isFunction(this.serviceUrl) ? this.serviceUrl() : this.serviceUrl; - xhr.get({url: requestUrl, sync: true, handleAs: "json"}).then(processData, util.xhrErrorHandler); - } - else - { - processData(this.initialData); - } - }; - - GridUpdater.prototype.start = function(grid) - { - this.grid = grid; - if (this.serviceUrl) - { - updater.add(this); - } - }; - - GridUpdater.prototype.destroy = function() - { - updater.remove(this); - if (this.dataStore) - { - this.dataStore.close(); - this.dataStore = null; - } - this.store = null; - this.memoryStore = null; - this.grid = null; - this.onUpdate = null; - }; - - GridUpdater.prototype.updateOrAppend = function(data) - { - return this.appendData ? - UpdatableStore.prototype.append.call(this, data, this.appendLimit): - UpdatableStore.prototype.update.call(this, data); - }; - - GridUpdater.prototype.refresh = function(data) - { - if (this.dataTransformer && data) - { - data = this.dataTransformer(data); - } - this.updating = true; - try - { - if (this.updateOrAppend(data)) - { - // EnhancedGrid with Filter plugin has "filter" layer. - // The filter expression needs to be re-applied after the data update - var filterLayer = this.grid.layer("filter"); - if ( filterLayer && filterLayer.filterDef) - { - var currentFilter = filterLayer.filterDef(); - - if (currentFilter) - { - // re-apply filter in the filter layer - filterLayer.filterDef(currentFilter); - } - } - - // refresh grid to render updates - this.grid._refresh(); - } - } - finally - { - this.updating = false; - this.fireUpdate(data); - } - } - - GridUpdater.prototype.update = function() - { - if (this.updatable) - { - this.performUpdate(); - } - }; - - GridUpdater.prototype.performUpdate = function() - { - var self = this; - var requestUrl = lang.isFunction(this.serviceUrl) ? this.serviceUrl() : this.serviceUrl; - var requestArguments = {url: requestUrl, sync: properties.useSyncGet, handleAs: "json"}; - xhr.get(requestArguments).then(function(data){self.refresh(data);}); - }; - - GridUpdater.prototype.performRefresh = function(data) - { - if (!this.updating) - { - this.refresh(data); - } - }; - - GridUpdater.prototype.fireUpdate=function(data) - { - if (this.onUpdate.length > 0) - { - for(var i=0; i<this.onUpdate.length;i++) - { - var onUpdate= this.onUpdate[i]; - try - { - onUpdate(data); - } - catch(e) - { - if (console && console.error) - { - console.error(e); - } - } - } - } - }; - - GridUpdater.prototype.addOnUpdate = function(obj) { - this.onUpdate.push(obj); - }; - - GridUpdater.prototype.removeOnUpdate = function(obj) { - for(var i = 0; i < this.onUpdate.length; i++) { - if(this.onUpdate[i] === obj) { - this.onUpdate.splice(i,1); - return; - } - } - }; - - return GridUpdater; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/RowNumberLimitDialog.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/RowNumberLimitDialog.js deleted file mode 100644 index e78670bf57..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/RowNumberLimitDialog.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -define([ - "dojo/_base/declare", - "dojo/_base/event", - "dojo/_base/array", - "dojo/_base/lang", - "dojo/parser", - "dojo/dom-construct", - "dojo/query", - "dijit/registry", - "dijit/form/Button", - "dijit/form/CheckBox", - "dojox/grid/enhanced/plugins/Dialog", - "dojo/text!../../../grid/showRowNumberLimitDialog.html", - "dojo/domReady!" -], function(declare, event, array, lang, parser, dom, query, registry, Button, CheckBox, Dialog, template ){ - - -return declare("qpid.management.logs.RowNumberLimitDialog", null, { - - grid: null, - dialog: null, - - constructor: function(domNode, limitChangedCallback) - { - var that = this; - this.containerNode = dom.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances) - { - that._postParse(domNode, limitChangedCallback); - }); - }, - _postParse: function(domNode, limitChangedCallback) - { - this.rowNumberLimit = registry.byNode(query(".rowNumberLimit", this.containerNode)[0]) - this.submitButton = registry.byNode(query(".submitButton", this.containerNode)[0]); - this.closeButton = registry.byNode(query(".cancelButton", this.containerNode)[0]); - - this.dialog = new Dialog({ - "refNode": domNode, - "title": "Grid Rows Number", - "content": this.containerNode - }); - - var self = this; - this.submitButton.on("click", function(e){ - if (self.rowNumberLimit.value > 0) - { - try - { - limitChangedCallback(self.rowNumberLimit.value); - } - catch(e) - { - console.error(e); - } - finally - { - self.dialog.hide(); - } - } - }); - - this.closeButton.on("click", function(e){self.dialog.hide(); }); - this.dialog.startup(); - }, - - destroy: function(){ - this.submitButton.destroy(); - this.closeButton.destroy(); - this.dialog.destroy(); - this.dialog = null; - }, - - showDialog: function(currentLimit){ - this.rowNumberLimit.set("value", currentLimit); - this.dialog.show(); - } - - }); - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/UpdatableGrid.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/UpdatableGrid.js deleted file mode 100644 index 04041388bd..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/UpdatableGrid.js +++ /dev/null @@ -1,56 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -define([ - "dojo/_base/declare", - "dojox/grid/EnhancedGrid", - "dojo/domReady!"], function(declare, EnhancedGrid){ - - return declare("qpid.common.grid.UpdatableGrid", [EnhancedGrid], { - - updater: null, - - postCreate: function(){ - this.inherited(arguments); - if (this.updater) - { - this.updater.start(this); - } - }, - - destroy: function(){ - if (this.updater) - { - try - { - this.updater.destroy(); - } - catch(e) - { - console.error(e) - } - this.updater = null; - } - this.inherited(arguments); - } - }); - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/metadata.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/metadata.js deleted file mode 100644 index 1a9ceb7419..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/metadata.js +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -define(["dojo/_base/xhr", - "dojo/_base/array", - "dojox/lang/functional/object", - "qpid/common/properties", - "dojo/domReady!" - ], - function (xhr, array, fobject, properties) - { - var metadata = - { - _init: function () - { - var that = this; - xhr.get({sync: true, handleAs: "json", url: "service/metadata", load: function(data){that._onMetadata(data)}}); - }, - _onMetadata: function (metadata) - { - this.metadata = metadata; - }, - getMetaData: function (category, type) - { - return this.metadata[category][type]; - }, - getDefaultValueForAttribute: function (category, type, attributeName) - { - var metaDataForInstance = this.getMetaData(category, type); - var attributesForType = metaDataForInstance["attributes"]; - var attributesForName = attributesForType[attributeName]; - return attributesForName ? attributesForName["defaultValue"] : undefined; - }, - getTypesForCategory: function (category) - { - return fobject.keys(this.metadata[category]); - }, - extractUniqueListOfValues : function(data) - { - var values = []; - for (i = 0; i < data.length; i++) - { - for (j = 0; j < data[i].length; j++) - { - var current = data[i][j]; - if (array.indexOf(values, current) == -1) - { - values.push(current); - } - } - } - return values; - }, - implementsManagedInterface: function (category, type, managedInterfaceName) - { - var md = this.getMetaData(category, type); - if (md && md.managedInterfaces) - { - return array.indexOf(md.managedInterfaces, managedInterfaceName) >= 0 ; - } - return false; - }, - validChildTypes: function (category, type, childCategory) - { - var metaData = this.getMetaData(category, type); - return metaData ? metaData.validChildTypes[childCategory] : []; - } - - }; - - metadata._init(); - - return metadata; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/properties.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/properties.js deleted file mode 100644 index 8d85345b74..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/properties.js +++ /dev/null @@ -1,26 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/has", "dojo/_base/sniff", "dojo/domReady!"], - function (has) { - var properties = {}; - properties.useSyncGet = (has("ie") <= 8); - return properties; - });
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/timezone.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/timezone.js deleted file mode 100644 index f886a72daa..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/timezone.js +++ /dev/null @@ -1,95 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -define(["dojo/_base/xhr"], function (xhr) { - - var timezones = {}; - - var timeZoneSortFunction = function(a, b){ - if (a.region == b.region) - { - if (a.city == b.city) - { - return 0; - } - return a.city < b.city ? -1 : 1; - } - return a.region < b.region ? -1 : 1; - } - - function loadTimezones() - { - xhr.get({ - url: "service/helper?action=ListTimeZones", - sync: true, - handleAs: "json", - load: function(zones) - { - zones.sort(timeZoneSortFunction); - timezones.data = zones; - }, - error: function(error) - { - if (console && console.error) - { - console.error(error); - } - } - }); - } - - return { - getAllTimeZones: function() - { - if (!timezones.data) - { - loadTimezones(); - } - return timezones.data; - }, - getTimeZoneInfo: function(timeZone) { - if (timeZone == "UTC") - { - return { - "id" : "UTC", - "name" : "UTC", - "offset" : 0 - } - } - var tzi = timezones[timeZone]; - if (!tzi) - { - var data = this.getAllTimeZones(); - for(var i = 0; i < data.length; i++) - { - var zone = data[i]; - if (zone.id == timeZone) - { - tzi = zone; - timezones[timeZone] = zone; - break; - } - } - } - return tzi; - } - }; -});
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/updater.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/updater.js deleted file mode 100644 index f31fd1aa1f..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/updater.js +++ /dev/null @@ -1,65 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["qpid/management/UserPreferences"], function (UserPreferences) { - var updateList = new Array(); - - function invokeUpdates() - { - for(var i = 0; i < updateList.length; i++) - { - var obj = updateList[i]; - obj.update(); - } - } - - var updatePeriod = UserPreferences.updatePeriod ? UserPreferences.updatePeriod: 5; - - var timer = setInterval(invokeUpdates, updatePeriod * 1000); - - var updateIntervalListener = { - onPreferencesChange: function(preferences) - { - if (preferences.updatePeriod && preferences.updatePeriod != updatePeriod) - { - updatePeriod = preferences.updatePeriod; - clearInterval(timer); - timer = setInterval(invokeUpdates, updatePeriod * 1000); - } - } - }; - - UserPreferences.addListener(updateIntervalListener); - - return { - add: function(obj) { - updateList.push(obj); - }, - - remove: function(obj) { - for(var i = 0; i < updateList.length; i++) { - if(updateList[i] === obj) { - updateList.splice(i,1); - return; - } - } - } - }; -});
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/util.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/util.js deleted file mode 100644 index 5bf5574347..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/util.js +++ /dev/null @@ -1,842 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/lang", - "dojo/json", - "dojo/dom-construct", - "dojo/dom-geometry", - "dojo/dom-style", - "dojo/_base/window", - "dojo/query", - "dojo/parser", - "dojo/store/Memory", - "dojo/window", - "dojo/on", - "dojox/html/entities", - "qpid/common/metadata", - "qpid/common/widgetconfigurer", - "dijit/registry", - "dijit/TitlePane", - "dijit/Dialog", - "dijit/form/Form", - "dijit/form/Button", - "dijit/form/RadioButton", - "dijit/form/CheckBox", - "dijit/form/FilteringSelect", - "dijit/form/ValidationTextBox", - "dojox/layout/TableContainer", - "dijit/layout/ContentPane", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!" - ], - function (xhr, array, event, lang, json, dom, geometry, domStyle, win, query, parser, Memory, w, on, entities, metadata, widgetconfigurer, registry) { - var util = {}; - if (Array.isArray) { - util.isArray = function (object) { - return Array.isArray(object); - }; - } else { - util.isArray = function (object) { - return object instanceof Array; - }; - } - - util.flattenStatistics = function (data) { - var attrName, stats, propName, theList; - for(attrName in data) { - if(data.hasOwnProperty(attrName)) { - if(attrName == "statistics") { - stats = data.statistics; - for(propName in stats) { - if(stats.hasOwnProperty( propName )) { - data[ propName ] = stats[ propName ]; - } - } - } else if(data[ attrName ] instanceof Array) { - theList = data[ attrName ]; - - for(var i=0; i < theList.length; i++) { - util.flattenStatistics( theList[i] ); - } - } - } - } - }; - - util.isReservedExchangeName = function(exchangeName) - { - return exchangeName == null || exchangeName == "" || "<<default>>" == exchangeName || exchangeName.indexOf("amq.") == 0 || exchangeName.indexOf("qpid.") == 0; - }; - - util.deleteGridSelections = function(updater, grid, url, confirmationMessageStart, idParam) - { - var data = grid.selection.getSelected(); - var success = false; - if(data.length) - { - var confirmationMessage = null; - if (data.length == 1) - { - confirmationMessage = confirmationMessageStart + " '" + data[0].name + "'?"; - } - else - { - var names = ''; - for(var i = 0; i<data.length; i++) - { - if (names) - { - names += ', '; - } - names += "\""+ data[i].name + "\""; - } - confirmationMessage = confirmationMessageStart + "s " + names + "?"; - } - if(confirm(confirmationMessage)) - { - var i, queryParam; - for(i = 0; i<data.length; i++) - { - if(queryParam) - { - queryParam += "&"; - } - else - { - queryParam = "?"; - } - queryParam += ( idParam || "id" ) + "=" + encodeURIComponent(data[i].id); - } - var query = url + queryParam; - var failureReason = ""; - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) - { - success = true; - grid.selection.deselectAll(); - if (updater) - { - updater.update(); - } - }, - function(error) {success = false; failureReason = error;}); - if(!success ) - { - util.xhrErrorHandler(failureReason); - } - } - } - return success; - } - - util.isProviderManagingUsers = function(type) - { - return metadata.implementsManagedInterface("AuthenticationProvider", type, "PasswordCredentialManagingAuthenticationProvider"); - }; - - util.supportsPreferencesProvider = function(type) - { - return metadata.implementsManagedInterface("AuthenticationProvider", type, "PreferencesSupportingAuthenticationProvider"); - }; - - util.showSetAttributesDialog = function(attributeWidgetFactories, data, putURL, dialogTitle, category, type, appendNameToUrl) - { - var layout = new dojox.layout.TableContainer({ - cols: 1, - "labelWidth": "300", - showLabels: true, - orientation: "horiz", - customClass: "formLabel" - }); - var submitButton = new dijit.form.Button({label: "Submit", type: "submit"}); - var form = new dijit.form.Form(); - - var dialogContent = dom.create("div"); - var dialogContentArea = dom.create("div", {"style": {width: 600}}); - var dialogActionBar = dom.create("div", { "class": "dijitDialogPaneActionBar"} ); - dialogContent.appendChild(dialogContentArea); - dialogContent.appendChild(dialogActionBar); - dialogContentArea.appendChild(layout.domNode) - dialogActionBar.appendChild(submitButton.domNode); - form.domNode.appendChild(dialogContent); - - var widgets = {}; - var requiredFor ={}; - var groups = {}; - for(var i in attributeWidgetFactories) - { - var attributeWidgetFactory = attributeWidgetFactories[i]; - var widget = attributeWidgetFactory.createWidget(data); - var name = attributeWidgetFactory.name ? attributeWidgetFactory.name : widget.name; - widgets[name] = widget; - var dotPos = name.indexOf("."); - if (dotPos == -1) - { - if (widget instanceof dijit.layout.ContentPane) - { - dialogContentArea.appendChild(widget.domNode); - } - else - { - layout.addChild(widget); - } - } - else - { - var groupName = name.substring(0, dotPos); - var groupFieldContainer = null; - if (groups.hasOwnProperty(groupName)) - { - groupFieldContainer = groups[groupName]; - } - else - { - groupFieldContainer = new dojox.layout.TableContainer({ - cols: 1, - "labelWidth": "300", - showLabels: true, - orientation: "horiz", - customClass: "formLabel" - }); - groups[groupName] = groupFieldContainer; - var groupTitle = attributeWidgetFactory.groupName ? attributeWidgetFactory.groupName : - groupName.charAt(0).toUpperCase() + groupName.slice(1); - var panel = new dijit.TitlePane({title: groupTitle, content: groupFieldContainer.domNode}); - dialogContentArea.appendChild(dom.create("br")); - dialogContentArea.appendChild(panel.domNode); - } - groupFieldContainer.addChild(widget); - } - if (attributeWidgetFactory.hasOwnProperty("requiredFor") && !data[name]) - { - requiredFor[attributeWidgetFactory.requiredFor] = widget; - } - } - - this.applyMetadataToWidgets(dialogContent, category, type); - - // add onchange handler to set required property for dependent widget - for(var widgetName in requiredFor) - { - var dependent = requiredFor[widgetName]; - var widget = widgets[widgetName]; - if (widget) - { - widget.dependent = dependent; - widget.on("change", function(newValue){ - this.dependent.set("required", newValue != ""); - }); - } - } - var setAttributesDialog = new dijit.Dialog({ - title: dialogTitle, - content: form - }); - form.on("submit", function(e) - { - event.stop(e); - try - { - if(form.validate()) - { - var values = {}; - var formWidgets = form.getDescendants(); - for(var i in formWidgets) - { - var widget = formWidgets[i]; - var value = widget.value; - var propName = widget.name; - if (propName && !widget.disabled){ - if ((widget instanceof dijit.form.CheckBox || widget instanceof dijit.form.RadioButton)) { - if (widget.checked != widget.initialValue) { - values[ propName ] = widget.checked; - } - } else if (value != widget.initialValue) { - values[ propName ] = value ? value: null; - } - } - } - - var that = this; - var url = putURL; - if (appendNameToUrl){ - url = url + "/" + encodeURIComponent(values["name"]); - } - xhr.put({url: url , sync: true, handleAs: "json", - headers: { "Content-Type": "application/json"}, - putData: json.stringify(values), - load: function(x) {that.success = true; }, - error: function(error) {that.success = false; that.failureReason = error;}}); - if(this.success === true) - { - setAttributesDialog.destroy(); - } - else - { - util.xhrErrorHandler(this.failureReason); - - } - return false; - } - else - { - alert('Form contains invalid data. Please correct first'); - return false; - } - } - catch(e) - { - alert("Unexpected exception:" + e.message); - return false; - } - }); - form.connectChildren(true); - setAttributesDialog.startup(); - var formWidgets = form.getDescendants(); - var aproximateHeight = 0; - for(var i in formWidgets){ - var widget = formWidgets[i]; - var propName = widget.name; - if (propName) { - if ((widget instanceof dijit.form.CheckBox || widget instanceof dijit.form.RadioButton)) { - widget.initialValue = widget.checked; - } else { - widget.initialValue = widget.value; - } - aproximateHeight += 30; - } - } - dialogContentArea.style.overflow= "auto"; - dialogContentArea.style.height = "300"; - setAttributesDialog.on("hide", function(e){setAttributesDialog.destroy();}); - setAttributesDialog.show(); - }; - - util.findAllWidgets = function(root) - { - return query("[widgetid]", root).map(registry.byNode).filter(function(w){ return w;}); - }; - - util.xhrErrorHandler = function(error) - { - var fallback = "Unexpected error - see server logs"; - var statusCodeNode = dojo.byId("errorDialog.statusCode"); - var errorMessageNode = dojo.byId("errorDialog.errorMessage"); - var userMustReauth = false; - - if (error) - { - if (error.hasOwnProperty("status")) - { - var hasMessage = error.hasOwnProperty("message"); - var message; - - if (error.status == 0) - { - message = "Unable to contact the Broker"; - } - else if (error.status == 401) - { - message = "Authentication required"; - userMustReauth = true; - } - else if (error.status == 403) - { - message = "Access Forbidden"; - } - else - { - message = hasMessage ? error.message : fallback; - - // Try for a more detail error sent by the Broker as json - if (error.hasOwnProperty("responseText")) - { - try - { - var errorObj = json.parse(error.responseText); - message = errorObj.hasOwnProperty("errorMessage") ? errorObj.errorMessage : errorMessageNode; - } - catch (e) - { - // Ignore - } - } - } - - errorMessageNode.innerHTML = entities.encode(message ? message : fallback); - statusCodeNode.innerHTML = entities.encode(String(error.status)); - - dojo.byId("errorDialog.advice.retry").style.display = userMustReauth ? "none" : "block"; - dojo.byId("errorDialog.advice.reconnect").style.display = userMustReauth ? "block" : "none"; - - domStyle.set(registry.byId("errorDialog.button.cancel").domNode, 'display', userMustReauth ? "none" : "block"); - domStyle.set(registry.byId("errorDialog.button.relogin").domNode, 'display', userMustReauth ? "block" : "none"); - - } - else - { - statusCodeNode.innerHTML = ""; - errorMessageNode.innerHTML = fallback; - } - - var dialog = dijit.byId("errorDialog"); - if (!dialog.open) - { - dialog.show(); - } - } - }; - - util.sendRequest = function (url, method, attributes, sync) - { - var success = false; - var failureReason = ""; - var syncRequired = sync == undefined ? true : sync; - if (method == "POST" || method == "PUT") - { - xhr.put({ - url: url, - sync: syncRequired, - handleAs: "json", - headers: { "Content-Type": "application/json"}, - putData: json.stringify(attributes), - load: function(x) {success = true; }, - error: function(error) {success = false; failureReason = error;} - }); - } - else if (method == "DELETE") - { - xhr.del({url: url, sync: syncRequired, handleAs: "json"}).then( - function(data) { success = true; }, - function(error) {success = false; failureReason = error;} - ); - } - - if (syncRequired && !success) - { - util.xhrErrorHandler(failureReason); - } - return success; - } - - util.equals = function(object1, object2) - { - if (object1 && object2) - { - if (typeof object1 != typeof object2) - { - return false; - } - else - { - if (object1 instanceof Array || typeof object1 == "array") - { - if (object1.length != object2.length) - { - return false; - } - - for (var i = 0, l=object1.length; i < l; i++) - { - var item = object1[i]; - if (item && (item instanceof Array || typeof item == "array" || item instanceof Object)) - { - if (!this.equals(item, object2[i])) - { - return false; - } - } - else if (item != object2[i]) - { - return false; - } - } - - return true; - } - else if (object1 instanceof Object) - { - for (propName in object1) - { - if (object1.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) - { - return false; - } - else if (typeof object1[propName] != typeof object2[propName]) - { - return false; - } - } - - for(propName in object2) - { - var object1Prop = object1[propName]; - var object2Prop = object2[propName]; - - if (object2.hasOwnProperty(propName) != object1.hasOwnProperty(propName)) - { - return false; - } - else if (typeof object1Prop != typeof object2Prop) - { - return false; - } - - if(!object2.hasOwnProperty(propName)) - { - // skip functions - continue; - } - - if (object1Prop && (object1Prop instanceof Array || typeof object1Prop == "array" || object1Prop instanceof Object)) - { - if (!this.equals(object1Prop, object2Prop)) - { - return false; - } - } - else if(object1Prop != object2Prop) - { - return false; - } - } - return true; - } - } - } - return object1 === object2; - } - - util.parseHtmlIntoDiv = function(containerNode, htmlTemplateLocation, postParseCallback) - { - xhr.get({url: htmlTemplateLocation, - sync: true, - load: function(template) { - containerNode.innerHTML = template; - parser.parse(containerNode).then(function(instances) - { - if (postParseCallback && typeof postParseCallback == "function") - { - postParseCallback(); - } - }); - }}); - } - util.buildUI = function(containerNode, parent, htmlTemplateLocation, fieldNames, obj, postParseCallback) - { - this.parseHtmlIntoDiv(containerNode, htmlTemplateLocation, - function() - { - if (fieldNames && obj) - { - for(var i=0; i<fieldNames.length;i++) - { - var fieldName = fieldNames[i]; - obj[fieldName]= query("." + fieldName, containerNode)[0]; - } - } - - if (postParseCallback && typeof postParseCallback == "function") - { - postParseCallback(); - } - }); - - } - - util.updateUI = function(data, fieldNames, obj) - { - for(var i=0; i<fieldNames.length;i++) - { - var fieldName = fieldNames[i]; - var value = data[fieldName]; - var fieldNode = obj[fieldName]; - if (fieldNode) - { - fieldNode.innerHTML= (value == undefined || value == null) ? "" : entities.encode(String(value)); - } - } - } - - util.applyMetadataToWidgets = function(domRoot, category, type) - { - this.applyToWidgets(domRoot, category, type, null); - } - - util.applyToWidgets = function(domRoot, category, type, data) - { - var widgets = util.findAllWidgets(domRoot); - array.forEach(widgets, - function (widget) - { - widgetconfigurer.config(widget, category, type, data); - }); - } - - util.getFormWidgetValues = function (form, initialData) - { - var values = {}; - var formWidgets = form.getChildren(); - for(var i in formWidgets) - { - var widget = formWidgets[i]; - var value = widget.value; - var propName = widget.name; - if (propName && (widget.required || value )) - { - if (widget.excluded) - { - continue; - } - if (widget.contextvar) - { - var context = values["context"]; - if (!context) - { - context = {}; - values["context"] = context; - } - context[propName]=String(value); - } - else if (widget instanceof dijit.form.RadioButton) - { - if (widget.checked) - { - var currentValue = values[propName]; - if (currentValue) - { - if (lang.isArray(currentValue)) - { - currentValue.push(value) - } - else - { - values[ propName ] = [currentValue, value]; - } - } - else - { - values[ propName ] = value; - } - } - } - else if (widget instanceof dijit.form.CheckBox) - { - values[ propName ] = widget.checked; - } - else - { - if (widget.get("type") == "password") - { - if (value) - { - values[ propName ] = value; - } - } - else - { - values[ propName ] = value ? value: null; - } - } - } - } - if (initialData) - { - for(var propName in values) - { - if (values[propName] == initialData[propName]) - { - delete values[propName]; - } - } - } - return values; - } - - util.updateUpdatableStore = function(updatableStore, data) - { - var currentRowCount = updatableStore.grid.rowCount; - updatableStore.grid.domNode.style.display = data ? "block" : "none"; - updatableStore.update(data || []); - if (data) - { - if (currentRowCount == 0 && data.length == 1) - { - // grid with a single row is not rendering properly after being hidden - // force rendering - updatableStore.grid.render(); - } - } - } - - util.makeTypeStore = function (types) - { - var typeData = []; - for (var i = 0; i < types.length; i++) { - var type = types[i]; - typeData.push({id: type, name: type}); - } - return new Memory({ data: typeData }); - } - - util.setMultiSelectOptions = function(multiSelectWidget, options) - { - util.addMultiSelectOptions(multiSelectWidget, options, true); - } - - util.addMultiSelectOptions = function(multiSelectWidget, options, clearExistingOptions) - { - if (clearExistingOptions) - { - var children = multiSelectWidget.children; - var initialLength = children.length; - for (var i = initialLength - 1; i >= 0 ; i--) - { - var child = children.item(i); - multiSelectWidget.removeChild(child); - } - } - for (var i = 0; i < options.length; i++) - { - // construct new option for list - var newOption = win.doc.createElement('option'); - var value = options[i]; - newOption.innerHTML = value; - newOption.value = value; - - // add new option to list - multiSelectWidget.appendChild(newOption); - } - } - - var singleContextVarRegexp = "(\\${[\\w+\\.\\-:]+})"; - - util.numericOrContextVarRegexp = function(constraints) - { - return "^(\\d+)|" + singleContextVarRegexp + "$"; - } - - util.signedOrContextVarRegexp = function(constraints) - { - return "^(-?\\d+)|" + singleContextVarRegexp + "$"; - } - - util.nameOrContextVarRegexp = function(constraints) - { - return "^(\\w+)|" + singleContextVarRegexp + "$"; - } - - util.jdbcUrlOrContextVarRegexp = function(constraints) - { - return "^(jdbc:.*:.*)|" + singleContextVarRegexp + "$"; - } - - util.nodeAddressOrContextVarRegexp = function(constraints) - { - return "^(([0-9a-zA-Z.-_]|::)+:[0-9]{1,5})|" + singleContextVarRegexp + "$"; - } - - util.resizeContentAreaAndRepositionDialog = function(contentNode, dialog) - { - var viewport = w.getBox(); - var contentDimension =dojo.position(contentNode); - var dialogDimension = dojo.position(dialog.domNode); - var dialogTitleAndFooterHeight = dialogDimension.h - contentDimension.h; - var dialogLeftRightSpaces = dialogDimension.w - contentDimension.w; - - var resize = function() - { - var viewport = w.getBox(); - var width = viewport.w * dialog.maxRatio; - var height = viewport.h * dialog.maxRatio; - var dialogDimension = dojo.position(dialog.domNode); - - var maxContentHeight = height - dialogTitleAndFooterHeight; - - // if width style is set on a dialog node, use dialog width - if (dialog.domNode.style && dialog.domNode.style.width) - { - width = dialogDimension.w; - } - var maxContentWidth = width - dialogLeftRightSpaces; - domStyle.set(contentNode, {"overflow": "auto", maxHeight: maxContentHeight + "px", maxWidth: maxContentWidth + "px"}); - - var dialogX = viewport.w/2 - dialogDimension.w/2; - var dialogY = viewport.h/2 - dialogDimension.h/2; - domStyle.set(dialog.domNode, {top: dialogY + "px", left: dialogX + "px"}); - dialog.resize(); - }; - resize(); - on(window, "resize", resize); - } - - util.submit = function(method, resourceUrl, data, successAction, failureAction) - { - var result = {success: true, failureReason: null}; - var xhrArguments = { - url: resourceUrl, - sync: true, - handleAs: "json", - headers: { "Content-Type": "application/json"}, - load: function(x) { - result.success = true; - result.data = x; - if (successAction) - { - successAction(x); - } - }, - error: function(error) { - result.success = false; - result.failureReason = error; - if (failureAction) - { - failureAction(error); - } - else - { - util.xhrErrorHandler(error); - } - } - } - if (data && method != "del") - { - xhrArguments[method + "Data"] = json.stringify(data); - } - xhr[method](xhrArguments); - return result; - } - - util.post = function(resourceUrl, data, successAction, failureAction) - { - return util.submit("post", resourceUrl, data, successAction, failureAction) - } - - util.put = function(resourceUrl, data, successAction, failureAction) - { - return util.submit("put", resourceUrl, data, successAction, failureAction) - } - - return util; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/widgetconfigurer.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/widgetconfigurer.js deleted file mode 100644 index baafc6f71d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/widgetconfigurer.js +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["dojo/_base/xhr", - "dojo/string", - "dojo/query", - "dojo/dom", - "dojo/dom-construct", - "dojo/dom-attr", - "dijit/registry", - "qpid/common/properties", - "qpid/common/metadata", - "dojo/text!strings.html", - "dojo/domReady!" - ], - function (xhr, string, query, dom, domConstruct, domAttr, registry, properties, metadata, template) - { - var widgetconfigurer = - { - _init: function () - { - var stringsTemplate = domConstruct.create("div", {innerHTML: template}); - var promptTemplateWithDefaultNode = query("[id='promptTemplateWithDefault']", stringsTemplate)[0]; - - // The following will contain ${prompt} and ${default} formatted with html elements - this.promptTemplateWithDefault = promptTemplateWithDefaultNode.innerHTML; - - domConstruct.destroy(stringsTemplate); - }, - _processWidgetPrompt: function (widget, category, type) - { - var widgetName = widget.name; - if (widgetName && (widget instanceof dijit.form.ValidationTextBox || widget instanceof dijit.form.FilteringSelect)) - { - // If not done so already, save the prompt text specified on the widget. We do this so if we - // config the same widget again, we can apply the default again (which may be different if the user - // has selected a different type within the category). - if (typeof widget.get("qpid.originalPromptMessage") == "undefined") - { - widget.set("qpid.originalPromptMessage", widget.get("promptMessage")); - } - - var promptMessage = widget.get("qpid.originalPromptMessage"); - var defaultValue = metadata.getDefaultValueForAttribute(category, type, widgetName); - if (defaultValue) - { - var newPromptMessage = string.substitute(this.promptTemplateWithDefault, { 'default': defaultValue, 'prompt': promptMessage }); - - if (promptMessage != newPromptMessage) - { - widget.set("promptMessage", newPromptMessage); - } - } - } - else if (widget instanceof dijit.Tooltip) - { - // If it is a tooltop, find the connected widget and use its name to lookup the default from the metadata. - if (typeof widget.get("qpid.originalLabel") == "undefined") - { - widget.set("qpid.originalLabel", widget.get("label")); - } - - var message = widget.get("qpid.originalLabel"); - var connectId = widget.get("connectId")[0]; - var connectWidget = registry.byId(connectId); - if (connectWidget) - { - var connectWidgetName = connectWidget.get("name"); - var defaultValue = metadata.getDefaultValueForAttribute(category, type, connectWidgetName); - if (defaultValue) - { - var newMessage = string.substitute(this.promptTemplateWithDefault, { 'default': defaultValue, 'prompt': message }); - - if (message != newMessage) - { - widget.set("label", newMessage); - } - } - } - } - }, - _processWidgetValue: function (widget, category, type, data) - { - var widgetName = widget.name; - - if (widgetName) - { - var defaultValue = metadata.getDefaultValueForAttribute(category, type, widgetName); - var dataValue = data && widgetName in data ? data[widgetName] : null; - - // Stash the default value and initial value so we can later differentiate - // when sending updates to the server - - if (defaultValue) - { - widget.defaultValue = defaultValue; - } - - if (dataValue) - { - widget.initialValue = dataValue; - } - - if (widget instanceof dijit.form.FilteringSelect || widget instanceof dojox.form.CheckedMultiSelect) - { - var widgetValue = dataValue == null ? defaultValue : dataValue; - if (widgetValue) - { - widget.set("value", widgetValue); - } - } - else if (widget instanceof dijit.form.CheckBox) - { - var widgetValue = dataValue == null ? (defaultValue == "true") : dataValue; - widget.set("checked", widgetValue ? true : false); - } - else - { - if (dataValue) - { - widget.set("value", dataValue); - } - } - } - }, - config: function (widget, category, type, data) - { - this._processWidgetPrompt(widget, category, type); - this._processWidgetValue(widget, category, type, data); - } - }; - - widgetconfigurer._init(); - - return widgetconfigurer; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/AccessControlProvider.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/AccessControlProvider.js deleted file mode 100644 index cf95a23819..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/AccessControlProvider.js +++ /dev/null @@ -1,132 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/_base/connect", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/UpdatableStore", - "dojox/grid/EnhancedGrid", - "dijit/registry", - "dojo/_base/event", - "dojox/html/entities", - "dojox/grid/enhanced/plugins/Pagination", - "dojox/grid/enhanced/plugins/IndirectSelection", - "dojo/domReady!"], - function (xhr, parser, query, connect, properties, updater, util, UpdatableStore, EnhancedGrid, registry, event, entities) { - - function AccessControlProvider(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "accesscontrolprovider", name: name, parent: parent}; - } - - AccessControlProvider.prototype.getTitle = function() { - return "AccessControlProvider: " + this.name ; - }; - - AccessControlProvider.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showAccessControlProvider.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - - that.accessControlProviderUpdater = new AccessControlProviderUpdater(contentPane.containerNode, that.modelObj, that.controller); - - var deleteButton = query(".deleteAccessControlProviderButton", contentPane.containerNode)[0]; - var deleteWidget = registry.byNode(deleteButton); - connect.connect(deleteWidget, "onClick", - function(evt){ - event.stop(evt); - that.deleteAccessControlProvider(); - }); - }); - }}); - }; - - AccessControlProvider.prototype.close = function() { - if (this.accessControlProviderUpdater.details) - { - this.accessControlProviderUpdater.details.close(); - } - }; - - AccessControlProvider.prototype.deleteAccessControlProvider = function() { - if(confirm("Are you sure you want to delete access control provider '" + this.name + "'?")) { - var query = "api/latest/accesscontrolprovider/" +encodeURIComponent(this.name); - this.success = true - var that = this; - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.close(); - that.contentPane.onClose() - that.controller.tabContainer.removeChild(that.contentPane); - that.contentPane.destroyRecursive(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!this.success ) { - util.xhrErrorHandler(this.failureReason); - } - } - }; - - function AccessControlProviderUpdater(node, groupProviderObj, controller) - { - this.controller = controller; - this.name = query(".name", node)[0]; - this.type = query(".type", node)[0]; - this.state = query(".state", node)[0]; - this.query = "api/latest/accesscontrolprovider/"+encodeURIComponent(groupProviderObj.name); - - var that = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}) - .then(function(data) - { - that.accessControlProviderData = data[0]; - - util.flattenStatistics( that.accessControlProviderData ); - - that.updateHeader(); - - var ui = that.accessControlProviderData.type; - require(["qpid/management/accesscontrolprovider/"+ ui], - function(SpecificProvider) { - that.details = new SpecificProvider(query(".providerDetails", node)[0], groupProviderObj, controller); - }); - }); - } - - AccessControlProviderUpdater.prototype.updateHeader = function() - { - this.name.innerHTML = entities.encode(String(this.accessControlProviderData[ "name" ])); - this.type.innerHTML = entities.encode(String(this.accessControlProviderData[ "type" ])); - this.state.innerHTML = entities.encode(String(this.accessControlProviderData[ "state" ])); - }; - - return AccessControlProvider; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/AuthenticationProvider.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/AuthenticationProvider.js deleted file mode 100644 index cf9c32496a..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/AuthenticationProvider.js +++ /dev/null @@ -1,243 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/_base/connect", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/UpdatableStore", - "dojox/grid/EnhancedGrid", - "qpid/management/addAuthenticationProvider", - "dojo/_base/event", - "dijit/registry", - "dojo/dom-style", - "dojox/html/entities", - "dojo/dom", - "qpid/management/PreferencesProvider", - "qpid/management/authenticationprovider/PrincipalDatabaseAuthenticationManager", - "dojo/domReady!"], - function (xhr, parser, query, connect, properties, updater, util, UpdatableStore, EnhancedGrid, - addAuthenticationProvider, event, registry, domStyle, entities, dom, PreferencesProvider, PrincipalDatabaseAuthenticationManager) { - - function AuthenticationProvider(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "authenticationprovider", name: name, parent: parent}; - } - - AuthenticationProvider.prototype.getTitle = function() { - return "AuthenticationProvider:" + this.name; - }; - - AuthenticationProvider.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showAuthProvider.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - - var authProviderUpdater = new AuthProviderUpdater(contentPane.containerNode, that.modelObj, that.controller, that); - that.authProviderUpdater = authProviderUpdater; - - var editButtonNode = query(".editAuthenticationProviderButton", contentPane.containerNode)[0]; - var editButtonWidget = registry.byNode(editButtonNode); - editButtonWidget.on("click", - function(evt){ - event.stop(evt); - addAuthenticationProvider.show(authProviderUpdater.authProviderData); - }); - authProviderUpdater.editButton = editButtonWidget; - - var deleteButton = query(".deleteAuthenticationProviderButton", contentPane.containerNode)[0]; - var deleteWidget = registry.byNode(deleteButton); - connect.connect(deleteWidget, "onClick", - function(evt){ - event.stop(evt); - that.deleteAuthenticationProvider(); - }); - - authProviderUpdater.update(); - if (util.isProviderManagingUsers(authProviderUpdater.authProviderData.type)) - { - authProviderUpdater.managingUsersUI = new PrincipalDatabaseAuthenticationManager(contentPane.containerNode, authProviderUpdater.authProviderData, that.controller); - authProviderUpdater.managingUsersUI.update(authProviderUpdater.authProviderData); - } - - if (!util.supportsPreferencesProvider(authProviderUpdater.authProviderData.type)) - { - var authenticationProviderPanel = registry.byNode( query(".preferencesPanel", contentPane.containerNode)[0]); - domStyle.set(authenticationProviderPanel.domNode, "display","none"); - } - else - { - var preferencesProviderData = authProviderUpdater.authProviderData.preferencesproviders? authProviderUpdater.authProviderData.preferencesproviders[0]: null; - authProviderUpdater.updatePreferencesProvider(preferencesProviderData); - } - - updater.add( that.authProviderUpdater ); - }); - }}); - }; - - AuthenticationProvider.prototype.close = function() { - updater.remove( this.authProviderUpdater); - if (this.authProviderUpdater.details) - { - updater.remove(this.authProviderUpdater.details.authDatabaseUpdater); - } - }; - - AuthenticationProvider.prototype.deleteAuthenticationProvider = function() { - if(confirm("Are you sure you want to delete authentication provider '" + this.name + "'?")) { - var query = "api/latest/authenticationprovider/" +encodeURIComponent(this.name); - this.success = true - var that = this; - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.close(); - that.contentPane.onClose() - that.controller.tabContainer.removeChild(that.contentPane); - that.contentPane.destroyRecursive(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!this.success ) { - util.xhrErrorHandler(this.failureReason); - } - } - }; - - function AuthProviderUpdater(node, authProviderObj, controller, authenticationProvider) - { - this.controller = controller; - this.name = query(".name", node)[0]; - this.type = query(".type", node)[0]; - this.state = query(".state", node)[0]; - this.authenticationProvider = authenticationProvider; - this.preferencesProviderType=dom.byId("preferencesProviderType"); - this.preferencesProviderName=dom.byId("preferencesProviderName"); - this.preferencesProviderState=dom.byId("preferencesProviderState"); - this.editPreferencesProviderButton = query(".editPreferencesProviderButton", node)[0]; - this.deletePreferencesProviderButton = query(".deletePreferencesProviderButton", node)[0]; - this.preferencesProviderAttributes = dom.byId("preferencesProviderAttributes") - this.preferencesNode = query(".preferencesProviderDetails", node)[0]; - -this.authenticationProviderDetailsContainer = query(".authenticationProviderDetails", node)[0]; - this.query = "api/latest/authenticationprovider/" + encodeURIComponent(authProviderObj.name); - - } - - AuthProviderUpdater.prototype.updatePreferencesProvider = function(preferencesProviderData) - { - if (preferencesProviderData) - { - if (!this.preferencesProvider) - { - var preferencesProvider =new PreferencesProvider(preferencesProviderData.name, this.authProviderData); - preferencesProvider.init(this.preferencesNode, this); - this.preferencesProvider = preferencesProvider; - } - this.preferencesProvider.update(preferencesProviderData); - } - else - { - if (this.preferencesProvider) - { - this.preferencesProvider.update(null); - } - } - }; - - AuthProviderUpdater.prototype.onPreferencesProviderDeleted = function() - { - this.preferencesProvider = null; - } - - AuthProviderUpdater.prototype.updateHeader = function() - { - this.authenticationProvider.name = this.authProviderData[ "name" ] - this.name.innerHTML = entities.encode(String(this.authProviderData[ "name" ])); - this.type.innerHTML = entities.encode(String(this.authProviderData[ "type" ])); - this.state.innerHTML = entities.encode(String(this.authProviderData[ "state" ])); - }; - - AuthProviderUpdater.prototype.update = function() - { - var that = this; - xhr.get({url: this.query, sync: true, handleAs: "json"}).then(function(data) {that._update(data[0]);}); - }; - - AuthProviderUpdater.prototype._update = function(data) - { - var that = this; - this.authProviderData = data; - util.flattenStatistics(data ); - this.updateHeader(); - - if (this.details) - { - this.details.update(data); - } - else - { - require(["qpid/management/authenticationprovider/" + encodeURIComponent(data.type.toLowerCase()) + "/show"], - function(DetailsUI) - { - that.details = new DetailsUI({containerNode:that.authenticationProviderDetailsContainer, parent: that}); - that.details.update(data); - } - ); - } - - if (this.managingUsersUI) - { - try - { - this.managingUsersUI.update(data); - } - catch(e) - { - if (console) - { - console.error(e); - } - } - } - var preferencesProviderData = data.preferencesproviders? data.preferencesproviders[0]: null; - try - { - this.updatePreferencesProvider(preferencesProviderData); - } - catch(e) - { - if (console) - { - console.error(e); - } - } - } - - return AuthenticationProvider; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Broker.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Broker.js deleted file mode 100644 index 9720bc988b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Broker.js +++ /dev/null @@ -1,715 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/json", - "dojo/_base/connect", - "dojo/store/Memory", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/UpdatableStore", - "dojox/grid/EnhancedGrid", - "dijit/registry", - "dojox/html/entities", - "qpid/management/addAuthenticationProvider", - "qpid/management/addVirtualHostNodeAndVirtualHost", - "qpid/management/addPort", - "qpid/management/addStore", - "qpid/management/addGroupProvider", - "qpid/management/addAccessControlProvider", - "qpid/management/editBroker", - "dojox/grid/enhanced/plugins/Pagination", - "dojox/grid/enhanced/plugins/IndirectSelection", - "dijit/layout/AccordionContainer", - "dijit/layout/AccordionPane", - "dijit/form/FilteringSelect", - "dijit/form/NumberSpinner", - "dijit/form/ValidationTextBox", - "dijit/form/CheckBox", - "dojo/store/Memory", - "dijit/form/DropDownButton", - "dijit/Menu", - "dijit/MenuItem", - "dojo/domReady!"], - function (xhr, parser, query, json, connect, memory, properties, updater, util, UpdatableStore, EnhancedGrid, registry, entities, - addAuthenticationProvider, addVirtualHostNodeAndVirtualHost, addPort, addStore, addGroupProvider, addAccessControlProvider, editBroker) { - - var brokerAttributeNames = ["name", "operatingSystem", "platform", "productVersion", "modelVersion", - "defaultVirtualHost", "statisticsReportingPeriod", "statisticsReportingResetEnabled", - "connection.sessionCountLimit", "connection.heartBeatDelay"]; - - function Broker(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "broker", name: name }; - - if(parent) { - this.modelObj.parent = {}; - this.modelObj.parent[ parent.type] = parent; - } - } - - - Broker.prototype.getTitle = function() - { - return "Broker"; - }; - - Broker.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showBroker.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - that.brokerUpdater = new BrokerUpdater(contentPane.containerNode, that.modelObj, that.controller); - - var logViewerButton = query(".logViewer", contentPane.containerNode)[0]; - registry.byNode(logViewerButton).on("click", function(evt){ - that.controller.show("logViewer", ""); - }); - - - var addProviderButton = query(".addAuthenticationProvider", contentPane.containerNode)[0]; - connect.connect(registry.byNode(addProviderButton), "onClick", function(evt){ addAuthenticationProvider.show(); }); - - var deleteProviderButton = query(".deleteAuthenticationProvider", contentPane.containerNode)[0]; - connect.connect(registry.byNode(deleteProviderButton), "onClick", - function(evt){ - var warning = ""; - var data = that.brokerUpdater.authenticationProvidersGrid.grid.selection.getSelected(); - if(data.length && data.length > 0) - { - for(var i = 0; i<data.length; i++) - { - if (data[i].type.indexOf("File") != -1) - { - warning = "NOTE: provider deletion will also remove the password file on disk.\n\n" - break; - } - } - } - - util.deleteGridSelections( - that.brokerUpdater, - that.brokerUpdater.authenticationProvidersGrid.grid, - "api/latest/authenticationprovider", - warning + "Are you sure you want to delete authentication provider"); - } - ); - - var addVHNAndVHButton = query(".addVirtualHostNodeAndVirtualHostButton", contentPane.containerNode)[0]; - connect.connect(registry.byNode(addVHNAndVHButton), "onClick", function(evt){ addVirtualHostNodeAndVirtualHost.show(); }); - - var addPortButton = query(".addPort", contentPane.containerNode)[0]; - connect.connect(registry.byNode(addPortButton), "onClick", function(evt){ - addPort.show(null, "AMQP", that.brokerUpdater.brokerData.authenticationproviders, - that.brokerUpdater.brokerData.keystores, that.brokerUpdater.brokerData.truststores); - }); - - var deletePort = query(".deletePort", contentPane.containerNode)[0]; - connect.connect(registry.byNode(deletePort), "onClick", - function(evt){ - util.deleteGridSelections( - that.brokerUpdater, - that.brokerUpdater.portsGrid.grid, - "api/latest/port", - "Are you sure you want to delete port"); - } - ); - - var editButton = query(".editBroker", contentPane.containerNode)[0]; - connect.connect(registry.byNode(editButton), "onClick", - function(evt) - { - editBroker.show(that.brokerUpdater.brokerData); - } - ); - - var addKeystoreButton = query(".addKeystore", contentPane.containerNode)[0]; - connect.connect(registry.byNode(addKeystoreButton), "onClick", - function(evt) - { - addStore.setupTypeStore("KeyStore"); - addStore.show(); - }); - - var deleteKeystore = query(".deleteKeystore", contentPane.containerNode)[0]; - connect.connect(registry.byNode(deleteKeystore), "onClick", - function(evt){ - util.deleteGridSelections( - that.brokerUpdater, - that.brokerUpdater.keyStoresGrid.grid, - "api/latest/keystore", - "Are you sure you want to delete key store"); - } - ); - - var addTruststoreButton = query(".addTruststore", contentPane.containerNode)[0]; - connect.connect(registry.byNode(addTruststoreButton), "onClick", - function(evt) - { - addStore.setupTypeStore("TrustStore"); - addStore.show(); - }); - - var deleteTruststore = query(".deleteTruststore", contentPane.containerNode)[0]; - connect.connect(registry.byNode(deleteTruststore), "onClick", - function(evt){ - util.deleteGridSelections( - that.brokerUpdater, - that.brokerUpdater.trustStoresGrid.grid, - "api/latest/truststore", - "Are you sure you want to delete trust store"); - } - ); - - var addGroupProviderButton = query(".addGroupProvider", contentPane.containerNode)[0]; - connect.connect(registry.byNode(addGroupProviderButton), "onClick", - function(evt){addGroupProvider.show();}); - - var deleteGroupProvider = query(".deleteGroupProvider", contentPane.containerNode)[0]; - connect.connect(registry.byNode(deleteGroupProvider), "onClick", - function(evt){ - var warning = ""; - var data = that.brokerUpdater.groupProvidersGrid.grid.selection.getSelected(); - if(data.length && data.length > 0) - { - for(var i = 0; i<data.length; i++) - { - if (data[i].type.indexOf("File") != -1) - { - warning = "NOTE: provider deletion will also remove the group file on disk.\n\n" - break; - } - } - } - - util.deleteGridSelections( - that.brokerUpdater, - that.brokerUpdater.groupProvidersGrid.grid, - "api/latest/groupprovider", - warning + "Are you sure you want to delete group provider"); - } - ); - - var addAccessControlButton = query(".addAccessControlProvider", contentPane.containerNode)[0]; - connect.connect(registry.byNode(addAccessControlButton), "onClick", - function(evt){addAccessControlProvider.show();}); - - var deleteAccessControlProviderButton = query(".deleteAccessControlProvider", contentPane.containerNode)[0]; - connect.connect(registry.byNode(deleteAccessControlProviderButton), "onClick", - function(evt){ - util.deleteGridSelections( - that.brokerUpdater, - that.brokerUpdater.accessControlProvidersGrid.grid, - "api/latest/accesscontrolprovider", - "Are you sure you want to delete access control provider"); - } - ); - }); - }}); - }; - - Broker.prototype.close = function() { - updater.remove( this.brokerUpdater ); - }; - - function BrokerUpdater(node, brokerObj, controller) - { - this.controller = controller; - this.query = "api/latest/broker?depth=2"; - this.accessControlProvidersWarn = query(".broker-access-control-providers-warning", node)[0] - var that = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}) - .then(function(data) - { - that.brokerData= data[0]; - - util.flattenStatistics( that.brokerData); - - that.updateHeader(); - - var gridProperties = { - height: 400, - selectionMode: "single", - plugins: { - pagination: { - pageSizes: [10, 25, 50, 100], - description: true, - sizeSwitch: true, - pageStepper: true, - gotoButton: true, - maxPageStep: 4, - position: "bottom" - } - }}; - - function isActiveVH(item) - { - return item && item.virtualhosts && item.virtualhosts[0].state=="ACTIVE"; - } - - that.vhostsGrid = - new UpdatableStore(that.brokerData.virtualhostnodes, query(".broker-virtualhosts")[0], - [ - { name: "Node Name", field: "name", width: "10%"}, - { name: "Node State", field: "state", width: "10%"}, - { name: "Node Type", field: "type", width: "10%"}, - { name: "Host Name", field: "_item", width: "10%", - formatter: function(item){ - return item && item.virtualhosts? item.virtualhosts[0].name: "N/A"; - } - }, - { name: "Host State", field: "_item", width: "15%", - formatter: function(item){ - return item && item.virtualhosts? item.virtualhosts[0].state: "N/A"; - } - }, - { name: "Host Type", field: "_item", width: "15%", - formatter: function(item){ - return item && item.virtualhosts? item.virtualhosts[0].type: "N/A"; - } - }, - { name: "Connections", field: "_item", width: "8%", - formatter: function(item){ - return isActiveVH(item)? item.virtualhosts[0].statistics.connectionCount: "N/A"; - } - }, - { name: "Queues", field: "_item", width: "8%", - formatter: function(item){ - return isActiveVH(item)? item.virtualhosts[0].statistics.queueCount: "N/A"; - } - }, - { name: "Exchanges", field: "_item", width: "8%", - formatter: function(item){ - return isActiveVH(item)? item.virtualhosts[0].statistics.exchangeCount: "N/A"; - } - }, - { - name: "Default", field: "_item", width: "6%", - formatter: function(item){ - var val = item && item.virtualhosts? item.virtualhosts[0].name: null; - return "<input type='radio' disabled='disabled' "+(val == that.brokerData.defaultVirtualHost ? "checked='checked'": "")+" />"; - } - } - ], function(obj) { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - if (theItem.virtualhosts) - { - that.showVirtualHost(theItem, brokerObj); - } - }); - }, gridProperties, EnhancedGrid, true); - - that.virtualHostNodeMenuButton = registry.byNode(query(".virtualHostNodeMenuButton", node)[0]); - that.virtualHostMenuButton = registry.byNode(query(".virtualHostMenuButton", node)[0]); - - var hostMenuItems = that.virtualHostMenuButton.dropDown.getChildren(); - var viewVirtualHostItem = hostMenuItems[0]; - var startVirtualHostItem = hostMenuItems[1]; - var stopVirtualHostItem = hostMenuItems[2]; - - var nodeMenuItems = that.virtualHostNodeMenuButton.dropDown.getChildren(); - var viewNodeItem = nodeMenuItems[0]; - var deleteNodeItem = nodeMenuItems[1]; - var startNodeItem = nodeMenuItems[2]; - var stopNodeItem = nodeMenuItems[3]; - - var toggler = function(index){ that.toggleVirtualHostNodeNodeMenus(index);} - connect.connect(that.vhostsGrid.grid.selection, 'onSelected', toggler); - connect.connect(that.vhostsGrid.grid.selection, 'onDeselected', toggler); - - viewVirtualHostItem.on("click", function(){ - var data = that.vhostsGrid.grid.selection.getSelected(); - if (data.length == 1) - { - that.showVirtualHost(data[0], brokerObj); - that.vhostsGrid.grid.selection.clear(); - } - }); - - viewNodeItem.on("click", - function(evt){ - var data = that.vhostsGrid.grid.selection.getSelected(); - if (data.length == 1) - { - var item = data[0]; - that.controller.show("virtualhostnode", item.name, brokerObj, item.id); - that.vhostsGrid.grid.selection.clear(); - } - } - ); - - deleteNodeItem.on("click", - function(evt){ - util.deleteGridSelections( - that, - that.vhostsGrid.grid, - "api/latest/virtualhostnode", - "Deletion of virtual host node will delete both configuration and message data.\n\n Are you sure you want to delete virtual host node"); - } - ); - - startNodeItem.on("click", - function(event) - { - var data = that.vhostsGrid.grid.selection.getSelected(); - if (data.length == 1) - { - var item = data[0]; - util.sendRequest("api/latest/virtualhostnode/" + encodeURIComponent(item.name), - "PUT", {desiredState: "ACTIVE"}); - that.vhostsGrid.grid.selection.clear(); - } - }); - - stopNodeItem.on("click", - function(event) - { - var data = that.vhostsGrid.grid.selection.getSelected(); - if (data.length == 1) - { - var item = data[0]; - if (confirm("Stopping the node will also shutdown the virtual host. " - + "Are you sure you want to stop virtual host node '" - + entities.encode(String(item.name)) +"'?")) - { - util.sendRequest("api/latest/virtualhostnode/" + encodeURIComponent(item.name), - "PUT", {desiredState: "STOPPED"}); - that.vhostsGrid.grid.selection.clear(); - } - } - }); - - startVirtualHostItem.on("click", function(event) - { - var data = that.vhostsGrid.grid.selection.getSelected(); - if (data.length == 1 && data[0].virtualhosts) - { - var item = data[0]; - var host = item.virtualhosts[0]; - util.sendRequest("api/latest/virtualhost/" + encodeURIComponent(item.name) + "/" + encodeURIComponent(host.name), - "PUT", {desiredState: "ACTIVE"}); - that.vhostsGrid.grid.selection.clear(); - } - }); - - stopVirtualHostItem.on("click", function(event) - { - var data = that.vhostsGrid.grid.selection.getSelected(); - if (data.length == 1 && data[0].virtualhosts) - { - var item = data[0]; - var host = item.virtualhosts[0]; - if (confirm("Are you sure you want to stop virtual host '" - + entities.encode(String(host.name)) +"'?")) - { - util.sendRequest("api/latest/virtualhost/" + encodeURIComponent(item.name) + "/" + encodeURIComponent(host.name), - "PUT", {desiredState: "STOPPED"}); - that.vhostsGrid.grid.selection.clear(); - } - } - }); - gridProperties.selectionMode = "extended"; - gridProperties.plugins.indirectSelection = true; - - that.portsGrid = - new UpdatableStore(that.brokerData.ports, query(".broker-ports")[0], - [ { name: "Name", field: "name", width: "15%"}, - { name: "State", field: "state", width: "15%"}, - { name: "Auth Provider", field: "authenticationProvider", width: "15%"}, - { name: "Address", field: "bindingAddress", width: "15%"}, - { name: "Port", field: "port", width: "10%"}, - { name: "Transports", field: "transports", width: "15%"}, - { name: "Protocols", field: "protocols", width: "15%"} - ], function(obj) { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var name = obj.dataStore.getValue(theItem,"name"); - that.controller.show("port", name, brokerObj, theItem.id); - }); - }, gridProperties, EnhancedGrid); - - gridProperties = { - keepSelection: true, - plugins: { - indirectSelection: true - }}; - - that.authenticationProvidersGrid = - new UpdatableStore(that.brokerData.authenticationproviders, query(".broker-authentication-providers")[0], - [ { name: "Name", field: "name", width: "40%"}, - { name: "State", field: "state", width: "20%"}, - { name: "Type", field: "type", width: "20%"}, - { name: "User Management", field: "type", width: "20%", - formatter: function(val){ - return "<input type='radio' disabled='disabled' "+(util.isProviderManagingUsers(val)?"checked='checked'": "")+" />"; - } - } - ], function(obj) { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var name = obj.dataStore.getValue(theItem,"name"); - that.controller.show("authenticationprovider", name, brokerObj, theItem.id); - }); - }, gridProperties, EnhancedGrid); - - that.keyStoresGrid = - new UpdatableStore(that.brokerData.keystores, query(".broker-key-stores")[0], - [ { name: "Name", field: "name", width: "20%"}, - { name: "State", field: "state", width: "10%"}, - { name: "Type", field: "type", width: "10%"}, - { name: "Path", field: "path", width: "60%"} - ], function(obj) { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var name = obj.dataStore.getValue(theItem,"name"); - that.controller.show("keystore", name, brokerObj, theItem.id); - }); - }, gridProperties, EnhancedGrid); - - that.trustStoresGrid = - new UpdatableStore(that.brokerData.truststores, query(".broker-trust-stores")[0], - [ { name: "Name", field: "name", width: "20%"}, - { name: "State", field: "state", width: "10%"}, - { name: "Type", field: "type", width: "10%"}, - { name: "Path", field: "path", width: "50%"}, - { name: "Peers only", field: "peersOnly", width: "10%", - formatter: function(val){ - return "<input type='radio' disabled='disabled' "+(val ? "checked='checked'": "")+" />"; - } - } - ], function(obj) { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var name = obj.dataStore.getValue(theItem,"name"); - that.controller.show("truststore", name, brokerObj, theItem.id); - }); - }, gridProperties, EnhancedGrid); - that.groupProvidersGrid = - new UpdatableStore(that.brokerData.groupproviders, query(".broker-group-providers")[0], - [ { name: "Name", field: "name", width: "40%"}, - { name: "State", field: "state", width: "30%"}, - { name: "Type", field: "type", width: "30%"} - ], function(obj) { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var name = obj.dataStore.getValue(theItem,"name"); - that.controller.show("groupprovider", name, brokerObj, theItem.id); - }); - }, gridProperties, EnhancedGrid); - var aclData = that.brokerData.accesscontrolproviders ? that.brokerData.accesscontrolproviders :[]; - that.accessControlProvidersGrid = - new UpdatableStore(aclData, query(".broker-access-control-providers")[0], - [ { name: "Name", field: "name", width: "40%"}, - { name: "State", field: "state", width: "30%"}, - { name: "Type", field: "type", width: "30%"} - ], function(obj) { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var name = obj.dataStore.getValue(theItem,"name"); - that.controller.show("accesscontrolprovider", name, brokerObj, theItem.id); - }); - }, gridProperties, EnhancedGrid); - that.displayACLWarnMessage(aclData); - - updater.add( that); - - }); - } - - BrokerUpdater.prototype.showVirtualHost=function(item, brokerObj) - { - var nodeName = item.name; - var host = item.virtualhosts? item.virtualhosts[0]: null; - var nodeObject = { type: "virtualhostnode", name: nodeName, parent: brokerObj}; - this.controller.show("virtualhost", host?host.name:nodeName, nodeObject, host?host.id:null); - } - - BrokerUpdater.prototype.updateHeader = function() - { - var brokerData = this.brokerData; - window.document.title = "Qpid: " + brokerData.name + " Management"; - - for(var i in brokerAttributeNames) - { - var propertyName = brokerAttributeNames[i]; - var element = dojo.byId("brokerAttribute." + propertyName); - if (element) - { - if (brokerData.hasOwnProperty(propertyName)) - { - var container = dojo.byId("brokerAttribute." + propertyName + ".container"); - if (container) - { - container.style.display = "block"; - } - element.innerHTML = entities.encode(String(brokerData [propertyName])); - } - else - { - element.innerHTML = ""; - } - } - } - }; - - BrokerUpdater.prototype.displayACLWarnMessage = function(aclProviderData) - { - var message = ""; - if (aclProviderData.length > 1) - { - var aclProviders = {}; - var theSameTypeFound = false; - for(var d=0; d<aclProviderData.length; d++) - { - var acl = aclProviderData[d]; - var aclType = acl.type; - if (aclProviders[aclType]) - { - aclProviders[aclType].push(acl.name); - theSameTypeFound = true; - } - else - { - aclProviders[aclType] = [acl.name]; - } - } - - if (theSameTypeFound) - { - message = "Only one instance of a given type will be used. Please remove an instance of type(s):"; - for(var aclType in aclProviders) - { - if(aclProviders[aclType].length>1) - { - message += " " + aclType; - } - } - } - } - this.accessControlProvidersWarn.innerHTML = message; - } - - BrokerUpdater.prototype.update = function() - { - - var that = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - that.brokerData = data[0]; - util.flattenStatistics( that.brokerData ); - - that.updateHeader(); - - if (that.vhostsGrid.update(that.brokerData.virtualhostnodes)) - { - that.vhostsGrid.grid._refresh(); - that.toggleVirtualHostNodeNodeMenus(); - } - - that.portsGrid.update(that.brokerData.ports); - - that.authenticationProvidersGrid.update(that.brokerData.authenticationproviders); - - if (that.keyStoresGrid) - { - that.keyStoresGrid.update(that.brokerData.keystores); - } - if (that.trustStoresGrid) - { - that.trustStoresGrid.update(that.brokerData.truststores); - } - if (that.groupProvidersGrid) - { - that.groupProvidersGrid.update(that.brokerData.groupproviders); - } - if (that.accessControlProvidersGrid) - { - var data = that.brokerData.accesscontrolproviders ? that.brokerData.accesscontrolproviders :[]; - that.accessControlProvidersGrid.update(data); - that.displayACLWarnMessage(data); - } - }); - }; - - BrokerUpdater.prototype.toggleVirtualHostNodeNodeMenus = function(rowIndex) - { - var data = this.vhostsGrid.grid.selection.getSelected(); - var selected = data.length==1; - this.virtualHostNodeMenuButton.set("disabled", !selected); - this.virtualHostMenuButton.set("disabled", !selected || !data[0].virtualhosts); - if (selected) - { - var nodeMenuItems = this.virtualHostNodeMenuButton.dropDown.getChildren(); - var hostMenuItems = this.virtualHostMenuButton.dropDown.getChildren(); - - var startNodeItem = nodeMenuItems[2]; - var stopNodeItem = nodeMenuItems[3]; - - var viewVirtualHostItem = hostMenuItems[0]; - var startVirtualHostItem = hostMenuItems[1]; - var stopVirtualHostItem = hostMenuItems[2]; - - var node = data[0]; - startNodeItem.set("disabled", node.state != "STOPPED"); - stopNodeItem.set("disabled", node.state != "ACTIVE"); - - if (node.virtualhosts) - { - viewVirtualHostItem.set("disabled", false); - - var host = node.virtualhosts[0]; - startVirtualHostItem.set("disabled", host.state != "STOPPED"); - stopVirtualHostItem.set("disabled", host.state != "ACTIVE"); - } - else - { - viewVirtualHostItem.set("disabled", true); - startVirtualHostItem.set("disabled", true); - stopVirtualHostItem.set("disabled", true); - } - } - }; - return Broker; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Connection.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Connection.js deleted file mode 100644 index bbb4dc8322..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Connection.js +++ /dev/null @@ -1,243 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/_base/connect", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/formatter", - "qpid/common/UpdatableStore", - "qpid/management/UserPreferences", - "dojox/html/entities", - "dojo/domReady!"], - function (xhr, parser, query, connect, properties, updater, util, formatter, UpdatableStore, UserPreferences, entities) { - - function Connection(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "exchange", name: name, parent: parent }; - } - - Connection.prototype.getTitle = function() - { - return "Connection: " + this.name; - }; - - Connection.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showConnection.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - that.connectionUpdater = new ConnectionUpdater(contentPane.containerNode, that.modelObj, that.controller); - updater.add( that.connectionUpdater ); - that.connectionUpdater.update(); - }); - }}); - }; - - Connection.prototype.close = function() { - updater.remove( this.connectionUpdater ); - }; - - function ConnectionUpdater(containerNode, connectionObj, controller) - { - var that = this; - - function findNode(name) { - return query("." + name, containerNode)[0]; - } - - function storeNodes(names) - { - for(var i = 0; i < names.length; i++) { - that[names[i]] = findNode(names[i]); - } - } - - storeNodes(["name", - "clientVersion", - "clientId", - "principal", - "port", - "transport", - "remoteProcessPid", - "createdTime", - "lastIoTime", - "msgInRate", - "bytesInRate", - "bytesInRateUnits", - "msgOutRate", - "bytesOutRate", - "bytesOutRateUnits"]); - - - - this.query = "api/latest/connection/"+ encodeURIComponent(connectionObj.parent.parent.name) - + "/" + encodeURIComponent(connectionObj.parent.name) + "/" + encodeURIComponent(connectionObj.name); - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - that.connectionData = data[0]; - - util.flattenStatistics( that.connectionData ); - - that.updateHeader(); - that.sessionsGrid = new UpdatableStore(that.connectionData.sessions, findNode("sessions"), - [ { name: "Name", field: "name", width: "20%"}, - { name: "Consumers", field: "consumerCount", width: "15%"}, - { name: "Unacknowledged messages", field: "unacknowledgedMessages", width: "15%"}, - { name: "Current store transaction start", field: "transactionStartTime", width: "25%", - formatter: function (transactionStartTime) - { - if (transactionStartTime > 0) - { - return UserPreferences.formatDateTime(transactionStartTime, {selector: "time", addOffset: true, appendTimeZone: true}); - } - else - { - return "N/A"; - } - } - }, - { name: "Current store transaction update", field: "transactionUpdateTime", width: "25%", - formatter: function (transactionUpdateTime) - { - if (transactionUpdateTime > 0) - { - return UserPreferences.formatDateTime(transactionUpdateTime, {selector: "time", addOffset: true, appendTimeZone: true}); - } - else - { - return "N/A"; - } - } - } - ]); - - - }); - - } - - ConnectionUpdater.prototype.updateHeader = function() - { - this.name.innerHTML = entities.encode(String(this.connectionData[ "name" ])); - this.clientId.innerHTML = entities.encode(String(this.connectionData[ "clientId" ])); - this.clientVersion.innerHTML = entities.encode(String(this.connectionData[ "clientVersion" ])); - this.principal.innerHTML = entities.encode(String(this.connectionData[ "principal" ])); - this.port.innerHTML = entities.encode(String(this.connectionData[ "port" ])); - this.transport.innerHTML = entities.encode(String(this.connectionData[ "transport" ])); - var remoteProcessPid = this.connectionData[ "remoteProcessPid" ]; - this.remoteProcessPid.innerHTML = entities.encode(String(remoteProcessPid ? remoteProcessPid : "N/A")); - this.createdTime.innerHTML = UserPreferences.formatDateTime(this.connectionData[ "createdTime" ], {addOffset: true, appendTimeZone: true}); - this.lastIoTime.innerHTML = UserPreferences.formatDateTime(this.connectionData[ "lastIoTime" ], {addOffset: true, appendTimeZone: true}); - }; - - ConnectionUpdater.prototype.update = function() - { - - var that = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - that.connectionData = data[0]; - - util.flattenStatistics( that.connectionData ); - - var sessions = that.connectionData[ "sessions" ]; - - that.updateHeader(); - - var sampleTime = new Date(); - var messageIn = that.connectionData["messagesIn"]; - var bytesIn = that.connectionData["bytesIn"]; - var messageOut = that.connectionData["messagesOut"]; - var bytesOut = that.connectionData["bytesOut"]; - - if(that.sampleTime) - { - var samplePeriod = sampleTime.getTime() - that.sampleTime.getTime(); - - var msgInRate = (1000 * (messageIn - that.messageIn)) / samplePeriod; - var msgOutRate = (1000 * (messageOut - that.messageOut)) / samplePeriod; - var bytesInRate = (1000 * (bytesIn - that.bytesIn)) / samplePeriod; - var bytesOutRate = (1000 * (bytesOut - that.bytesOut)) / samplePeriod; - - that.msgInRate.innerHTML = msgInRate.toFixed(0); - var bytesInFormat = formatter.formatBytes( bytesInRate ); - that.bytesInRate.innerHTML = "(" + bytesInFormat.value; - that.bytesInRateUnits.innerHTML = bytesInFormat.units + "/s)"; - - that.msgOutRate.innerHTML = msgOutRate.toFixed(0); - var bytesOutFormat = formatter.formatBytes( bytesOutRate ); - that.bytesOutRate.innerHTML = "(" + bytesOutFormat.value; - that.bytesOutRateUnits.innerHTML = bytesOutFormat.units + "/s)"; - - if(sessions && that.sessions) - { - for(var i=0; i < sessions.length; i++) - { - var session = sessions[i]; - for(var j = 0; j < that.sessions.length; j++) - { - var oldSession = that.sessions[j]; - if(oldSession.id == session.id) - { - var msgRate = (1000 * (session.messagesOut - oldSession.messagesOut)) / - samplePeriod; - session.msgRate = msgRate.toFixed(0) + "msg/s"; - - var bytesRate = (1000 * (session.bytesOut - oldSession.bytesOut)) / - samplePeriod; - var bytesRateFormat = formatter.formatBytes( bytesRate ); - session.bytesRate = bytesRateFormat.value + bytesRateFormat.units + "/s"; - } - - - } - - } - } - - } - - that.sampleTime = sampleTime; - that.messageIn = messageIn; - that.bytesIn = bytesIn; - that.messageOut = messageOut; - that.bytesOut = bytesOut; - that.sessions = sessions; - - - // update sessions - that.sessionsGrid.update(that.connectionData.sessions) - }); - }; - - - return Connection; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Exchange.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Exchange.js deleted file mode 100644 index 1f1b8361a2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Exchange.js +++ /dev/null @@ -1,301 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/_base/connect", - "dijit/registry", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/formatter", - "qpid/common/UpdatableStore", - "qpid/management/addBinding", - "dojox/grid/EnhancedGrid", - "dojox/html/entities", - "dojo/domReady!"], - function (xhr, parser, query, connect, registry, properties, updater, util, formatter, UpdatableStore, addBinding, EnhancedGrid, entities) { - - function Exchange(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "exchange", name: name, parent: parent}; - } - - - Exchange.prototype.getExchangeName = function() - { - return this.name; - }; - - - Exchange.prototype.getVirtualHostName = function() - { - return this.modelObj.parent.name; - }; - - Exchange.prototype.getVirtualHostNodeName = function() - { - return this.modelObj.parent.parent.name; - }; - - Exchange.prototype.getTitle = function() - { - return "Exchange: " + this.name; - }; - - Exchange.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showExchange.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - - that.exchangeUpdater = new ExchangeUpdater(contentPane.containerNode, that.modelObj, that.controller); - - updater.add( that.exchangeUpdater ); - - that.exchangeUpdater.update(); - - - var addBindingButton = query(".addBindingButton", contentPane.containerNode)[0]; - connect.connect(registry.byNode(addBindingButton), "onClick", - function(evt){ - addBinding.show({ virtualhost: that.getVirtualHostName(), - virtualhostnode: that.getVirtualHostNodeName(), - exchange: that.getExchangeName()}); - }); - - var deleteBindingButton = query(".deleteBindingButton", contentPane.containerNode)[0]; - connect.connect(registry.byNode(deleteBindingButton), "onClick", - function(evt){ - that.deleteBindings(); - }); - - var isStandard = util.isReservedExchangeName(that.name); - var deleteExchangeButton = query(".deleteExchangeButton", contentPane.containerNode)[0]; - var node = registry.byNode(deleteExchangeButton); - if(isStandard) - { - node.set('disabled', true); - } - else - { - connect.connect(node, "onClick", - function(evt){ - that.deleteExchange(); - }); - } - }); - }}); - }; - - Exchange.prototype.close = function() { - updater.remove( this.exchangeUpdater ); - }; - - Exchange.prototype.deleteBindings = function() - { - util.deleteGridSelections( - this.exchangeUpdater, - this.exchangeUpdater.bindingsGrid.grid, - "api/latest/binding/" + encodeURIComponent(this.getVirtualHostNodeName()) - + "/" + encodeURIComponent(this.getVirtualHostName()) + "/" + encodeURIComponent(this.name), - "Are you sure you want to delete binding for queue"); - } - - function ExchangeUpdater(containerNode, exchangeObj, controller) - { - var that = this; - - function findNode(name) { - return query("." + name, containerNode)[0]; - } - - function storeNodes(names) - { - for(var i = 0; i < names.length; i++) { - that[names[i]] = findNode(names[i]); - } - } - - storeNodes(["name", - "type", - "state", - "durable", - "lifetimePolicy", - "alertRepeatGap", - "alertRepeatGapUnits", - "alertThresholdMessageAge", - "alertThresholdMessageAgeUnits", - "alertThresholdMessageSize", - "alertThresholdMessageSizeUnits", - "alertThresholdQueueDepthBytes", - "alertThresholdQueueDepthBytesUnits", - "alertThresholdQueueDepthMessages", - "msgInRate", - "bytesInRate", - "bytesInRateUnits", - "msgDropRate", - "bytesDropRate", - "bytesDropRateUnits"]); - - - - this.query = "api/latest/exchange/" + encodeURIComponent(exchangeObj.parent.parent.name) - + "/" + encodeURIComponent(exchangeObj.parent.name) + "/" + encodeURIComponent(exchangeObj.name); - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - that.exchangeData = data[0]; - util.flattenStatistics( that.exchangeData ); - - that.updateHeader(); - that.bindingsGrid = new UpdatableStore(that.exchangeData.bindings, findNode("bindings"), - [ { name: "Queue", field: "queue", width: "40%"}, - { name: "Binding Key", field: "name", width: "30%"}, - { name: "Arguments", field: "argumentString", width: "30%"} - ], null, { - keepSelection: true, - plugins: { - pagination: { - pageSizes: ["10", "25", "50", "100"], - description: true, - sizeSwitch: true, - pageStepper: true, - gotoButton: true, - maxPageStep: 4, - position: "bottom" - }, - indirectSelection: true - - }}, EnhancedGrid); - - }); - - } - - ExchangeUpdater.prototype.updateHeader = function() - { - this.name.innerHTML = entities.encode(String(this.exchangeData[ "name" ])); - this["type"].innerHTML = entities.encode(String(this.exchangeData[ "type" ])); - - this.state.innerHTML = entities.encode(String(this.exchangeData[ "state" ])); - this.durable.innerHTML = entities.encode(String(this.exchangeData[ "durable" ])); - this.lifetimePolicy.innerHTML = entities.encode(String(this.exchangeData[ "lifetimePolicy" ])); - - }; - - ExchangeUpdater.prototype.update = function() - { - - var thisObj = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - thisObj.exchangeData = data[0]; - - util.flattenStatistics( thisObj.exchangeData ); - - var bindings = thisObj.exchangeData[ "bindings" ]; - - if(bindings) - { - for(var i=0; i < bindings.length; i++) - { - if(bindings[i].arguments) - { - bindings[i].argumentString = dojo.toJson(bindings[i].arguments); - } - else - { - bindings[i].argumentString = ""; - } - } - } - - - var sampleTime = new Date(); - - thisObj.updateHeader(); - - var messageIn = thisObj.exchangeData["messagesIn"]; - var bytesIn = thisObj.exchangeData["bytesIn"]; - var messageDrop = thisObj.exchangeData["messagesDropped"]; - var bytesDrop = thisObj.exchangeData["bytesDropped"]; - - if(thisObj.sampleTime) - { - var samplePeriod = sampleTime.getTime() - thisObj.sampleTime.getTime(); - - var msgInRate = (1000 * (messageIn - thisObj.messageIn)) / samplePeriod; - var msgDropRate = (1000 * (messageDrop - thisObj.messageDrop)) / samplePeriod; - var bytesInRate = (1000 * (bytesIn - thisObj.bytesIn)) / samplePeriod; - var bytesDropRate = (1000 * (bytesDrop - thisObj.bytesDrop)) / samplePeriod; - - thisObj.msgInRate.innerHTML = msgInRate.toFixed(0); - var bytesInFormat = formatter.formatBytes( bytesInRate ); - thisObj.bytesInRate.innerHTML = "(" + bytesInFormat.value; - thisObj.bytesInRateUnits.innerHTML = bytesInFormat.units + "/s)"; - - thisObj.msgDropRate.innerHTML = msgDropRate.toFixed(0); - var bytesDropFormat = formatter.formatBytes( bytesDropRate ); - thisObj.bytesDropRate.innerHTML = "(" + bytesDropFormat.value; - thisObj.bytesDropRateUnits.innerHTML = bytesDropFormat.units + "/s)" - - } - - thisObj.sampleTime = sampleTime; - thisObj.messageIn = messageIn; - thisObj.bytesIn = bytesIn; - thisObj.messageDrop = messageDrop; - thisObj.bytesDrop = bytesDrop; - - // update bindings - thisObj.bindingsGrid.update(thisObj.exchangeData.bindings) - - }); - }; - - Exchange.prototype.deleteExchange = function() { - if(confirm("Are you sure you want to delete exchange '" +this.name+"'?")) { - var query = "api/latest/exchange/" + encodeURIComponent(this.getVirtualHostNodeName()) - + "/" + encodeURIComponent(this.getVirtualHostName()) + "/" + encodeURIComponent(this.name); - this.success = true - var that = this; - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.contentPane.onClose() - that.controller.tabContainer.removeChild(that.contentPane); - that.contentPane.destroyRecursive(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!this.success ) { - util.xhrErrorHandler(this.failureReason); - } - } - } - - return Exchange; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/GroupProvider.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/GroupProvider.js deleted file mode 100644 index 9b32d0e6b2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/GroupProvider.js +++ /dev/null @@ -1,199 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/_base/connect", - "dojo/_base/array", - "dojo/_base/event", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/metadata", - "qpid/common/UpdatableStore", - "dojox/grid/EnhancedGrid", - "dijit/registry", - "dojox/html/entities", - "dojo/text!showGroupProvider.html", - "qpid/management/addGroupProvider", - "dojox/grid/enhanced/plugins/Pagination", - "dojox/grid/enhanced/plugins/IndirectSelection", - "dojo/domReady!"], - function (xhr, parser, query, connect, array, event, properties, updater, util, metadata, UpdatableStore, - EnhancedGrid, registry, entities, template, addGroupProvider) - { - - function GroupProvider(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "groupprovider", name: name, parent: parent}; - } - - GroupProvider.prototype.getTitle = function() { - return "GroupProvider: " + this.name ; - }; - - GroupProvider.prototype.open = function(contentPane) - { - var that = this; - this.contentPane = contentPane; - contentPane.containerNode.innerHTML = template; - parser.parse(contentPane.containerNode).then(function(instances) { that.onOpen(); }); - }; - - GroupProvider.prototype.onOpen = function() - { - var that = this; - var contentPane = this.contentPane; - this.groupProviderUpdater = new GroupProviderUpdater(contentPane.containerNode, this.modelObj, this.controller); - - // load data - this.groupProviderUpdater.update(); - - this.deleteButton = registry.byNode(query(".deleteGroupProviderButton", contentPane.containerNode)[0]); - this.deleteButton.on("click", function(evt){ event.stop(evt); that.deleteGroupProvider(); }); - - this.editButton = registry.byNode(query(".editGroupProviderButton", contentPane.containerNode)[0]); - this.editButton.on("click", function(evt){ event.stop(evt); that.editGroupProvider(); }); - - var type = this.groupProviderUpdater.groupProviderData.type; - var providerDetailsNode = query(".providerDetails", contentPane.containerNode)[0]; - - require(["qpid/management/groupprovider/"+ encodeURIComponent(type.toLowerCase()) + "/show"], - function(DetailsUI) - { - that.groupProviderUpdater.details = new DetailsUI({containerNode: providerDetailsNode, parent: that}); - that.groupProviderUpdater.details.update(that.groupProviderUpdater.groupProviderData); - }); - - var managedInterfaces = metadata.getMetaData("GroupProvider", type).managedInterfaces; - if (managedInterfaces) - { - - var managedInterfaceUI = this.groupProviderUpdater.managedInterfaces; - - array.forEach(managedInterfaces, - function(managedInterface) - { - require(["qpid/management/groupprovider/" + encodeURIComponent(managedInterface)], - function(ManagedInterface) - { - managedInterfaceUI[ManagedInterface] = new ManagedInterface(providerDetailsNode, that.modelObj, that.controller); - managedInterfaceUI[ManagedInterface].update(that.groupProviderUpdater.groupProviderData); - }); - }); - } - - updater.add( this.groupProviderUpdater ); - }; - - - GroupProvider.prototype.close = function() { - updater.remove( this.groupProviderUpdater ); - }; - - GroupProvider.prototype.deleteGroupProvider = function() { - var warnMessage = ""; - if (this.groupProviderUpdater.groupProviderData && this.groupProviderUpdater.groupProviderData.type.indexOf("File") != -1) - { - warnMessage = "NOTE: provider deletion will also remove the group file on disk.\n\n"; - } - if(confirm(warnMessage + "Are you sure you want to delete group provider '" + this.name + "'?")) { - var query = "api/latest/groupprovider/" +encodeURIComponent(this.name); - this.success = true - var that = this; - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.close(); - that.contentPane.onClose() - that.controller.tabContainer.removeChild(that.contentPane); - that.contentPane.destroyRecursive(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!this.success ) { - util.xhrErrorHandler(this.failureReason); - } - } - }; - - GroupProvider.prototype.editGroupProvider = function() - { - xhr.get( - { - url: this.groupProviderUpdater.query, - sync: true, - content: { actuals: true }, - handleAs: "json", - load: function(actualData) - { - addGroupProvider.show(actualData[0]); - } - } - ); - } - - function GroupProviderUpdater(node, groupProviderObj, controller) - { - this.controller = controller; - this.name = query(".name", node)[0]; - this.type = query(".type", node)[0]; - this.state = query(".state", node)[0]; - this.query = "api/latest/groupprovider/"+encodeURIComponent(groupProviderObj.name); - this.managedInterfaces = {}; - this.details = null; - } - - GroupProviderUpdater.prototype.updateHeader = function() - { - this.name.innerHTML = entities.encode(String(this.groupProviderData[ "name" ])); - this.type.innerHTML = entities.encode(String(this.groupProviderData[ "type" ])); - this.state.innerHTML = entities.encode(String(this.groupProviderData[ "state" ])); - }; - - GroupProviderUpdater.prototype.update = function() - { - var that = this; - xhr.get({url: this.query, sync: true, handleAs: "json"}).then(function(data) {that._update(data[0]);}); - }; - - GroupProviderUpdater.prototype._update = function(data) - { - this.groupProviderData = data; - util.flattenStatistics( this.groupProviderData ); - this.updateHeader(); - - if (this.details) - { - this.details.update(this.groupProviderData); - } - - for(var managedInterface in this.managedInterfaces) - { - var managedInterfaceUI = this.managedInterfaces[managedInterface]; - if (managedInterfaceUI) - { - managedInterfaceUI.update(this.groupProviderData); - } - } - }; - - return GroupProvider; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/KeyStore.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/KeyStore.js deleted file mode 100644 index dfcb712740..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/KeyStore.js +++ /dev/null @@ -1,172 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/dom", - "dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/_base/connect", - "dijit/registry", - "dojox/html/entities", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/formatter", - "qpid/management/addStore", - "dojo/domReady!"], - function (dom, xhr, parser, query, connect, registry, entities, properties, updater, util, formatter, addStore) { - - function KeyStore(name, parent, controller) { - this.keyStoreName = name; - this.controller = controller; - this.modelObj = { type: "keystore", name: name, parent: parent}; - this.url = "api/latest/keystore/" + encodeURIComponent(name); - } - - KeyStore.prototype.getTitle = function() { - return "KeyStore: " + this.keyStoreName; - }; - - KeyStore.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showStore.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - - that.keyStoreUpdater = new KeyStoreUpdater(contentPane.containerNode, that.modelObj, that.controller, that.url); - that.keyStoreUpdater.update(); - updater.add( that.keyStoreUpdater ); - - var deleteKeyStoreButton = query(".deleteStoreButton", contentPane.containerNode)[0]; - var node = registry.byNode(deleteKeyStoreButton); - connect.connect(node, "onClick", - function(evt){ - that.deleteKeyStore(); - }); - - var editKeyStoreButton = query(".editStoreButton", contentPane.containerNode)[0]; - var node = registry.byNode(editKeyStoreButton); - connect.connect(node, "onClick", - function(evt){ - xhr.get({url: that.url, sync: properties.useSyncGet, handleAs: "json", content: { actuals: true }}) - .then(function(data) - { - addStore.setupTypeStore("KeyStore"); - addStore.show(data[0], that.url); - }); - }); - }); - }}); - }; - - KeyStore.prototype.close = function() { - updater.remove( this.keyStoreUpdater ); - }; - - function KeyStoreUpdater(containerNode, keyStoreObj, controller, url) - { - var that = this; - this.keyStoreDetailsContainer = query(".typeFieldsContainer", containerNode)[0]; - - function findNode(name) { - return query("." + name, containerNode)[0]; - } - - function storeNodes(names) - { - for(var i = 0; i < names.length; i++) { - that[names[i]] = findNode(names[i]); - } - } - - storeNodes(["name", - "type", - "state" - ]); - - this.query = url; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - that.keyStoreData = data[0]; - that.updateHeader(); - }); - - } - - KeyStoreUpdater.prototype.updateHeader = function() - { - this.name.innerHTML = entities.encode(String(this.keyStoreData[ "name" ])); - this.type.innerHTML = entities.encode(String(this.keyStoreData[ "type" ])); - this.state.innerHTML = entities.encode(String(this.keyStoreData[ "state" ])); - }; - - KeyStoreUpdater.prototype.update = function() - { - - var that = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - that.keyStoreData = data[0]; - that.updateHeader(); - - if (that.details) - { - that.details.update(that.keyStoreData); - } - else - { - require(["qpid/management/store/" + encodeURIComponent(that.keyStoreData.type.toLowerCase()) + "/show"], - function(DetailsUI) - { - that.details = new DetailsUI({containerNode:that.keyStoreDetailsContainer, parent: that}); - that.details.update(that.keyStoreData); - } - ); - } - }); - }; - - KeyStore.prototype.deleteKeyStore = function() { - if(confirm("Are you sure you want to delete key store '" +this.keyStoreName+"'?")) { - var query = this.url; - this.success = true - var that = this; - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.contentPane.onClose() - that.controller.tabContainer.removeChild(that.contentPane); - that.contentPane.destroyRecursive(); - that.close(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!this.success ) { - util.xhrErrorHandler(this.failureReason); - } - } - } - - return KeyStore; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Plugin.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Plugin.js deleted file mode 100644 index 300754ed8c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Plugin.js +++ /dev/null @@ -1,94 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/_base/connect", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "dijit/registry", - "dojo/_base/event", - "dojox/html/entities", - "dojo/domReady!"], - function (xhr, parser, query, connect, properties, updater, util, registry, event, entities) { - - function Plugin(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "plugin", name: name, parent: parent }; - } - - Plugin.prototype.getTitle = function() { - return "Plugin: " + this.name ; - }; - - Plugin.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showPlugin.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - that.pluginUpdater = new PluginUpdater(contentPane.containerNode, that.modelObj, that.controller); - }); - }}); - }; - - Plugin.prototype.close = function() { - updater.remove( this.pluginUpdater ); - }; - - function PluginUpdater(node, pluginObject, controller) - { - this.controller = controller; - this.name = query(".name", node)[0]; - this.type = query(".type", node)[0]; - this.query = "api/latest/plugin/"+encodeURIComponent(pluginObject.name); - - var that = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}) - .then(function(data) - { - that.pluginData = data[0]; - - that.updateHeader(); - - require(["qpid/management/plugin/"+ that.pluginData.type.toLowerCase().replace('-','')], - function(SpecificPlugin) { - that.details = new SpecificPlugin(query(".pluginDetails", node)[0], pluginObject, controller); - }); - - }); - - } - - PluginUpdater.prototype.updateHeader = function() - { - this.name.innerHTML = entities.encode(String(this.pluginData[ "name" ])); - this.type.innerHTML = entities.encode(String(this.pluginData[ "type" ])); - }; - - return Plugin; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Port.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Port.js deleted file mode 100644 index 91407c0e83..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Port.js +++ /dev/null @@ -1,220 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/dom", - "dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/_base/connect", - "dijit/registry", - "dojox/html/entities", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/formatter", - "qpid/management/addPort", - "qpid/common/metadata", - "dojo/domReady!"], - function (dom, xhr, parser, query, connect, registry, entities, properties, updater, util, formatter, addPort, metadata) { - - function Port(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "port", name: name, parent: parent}; - } - - Port.prototype.getTitle = function() { - return "Port: " + this.name; - }; - - Port.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showPort.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - that.portUpdater = new PortUpdater(contentPane.containerNode, that.modelObj, that.controller, "api/latest/port/" + encodeURIComponent(that.name)); - - updater.add( that.portUpdater ); - - that.portUpdater.update(); - - var deletePortButton = query(".deletePortButton", contentPane.containerNode)[0]; - var node = registry.byNode(deletePortButton); - connect.connect(node, "onClick", - function(evt){ - that.deletePort(); - }); - - var editPortButton = query(".editPortButton", contentPane.containerNode)[0]; - var node = registry.byNode(editPortButton); - connect.connect(node, "onClick", - function(evt){ - that.showEditDialog(); - }); - }); - }}); - }; - - Port.prototype.close = function() { - updater.remove( this.portUpdater ); - }; - - - Port.prototype.deletePort = function() { - if(confirm("Are you sure you want to delete port '" +this.name+"'?")) { - var query = "api/latest/port/" + encodeURIComponent(this.name); - this.success = true - var that = this; - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.contentPane.onClose() - that.controller.tabContainer.removeChild(that.contentPane); - that.contentPane.destroyRecursive(); - that.close(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!this.success ) { - util.xhrErrorHandler(this.failureReason); - } - } - } - - Port.prototype.showEditDialog = function() { - var that = this; - xhr.get({url: "api/latest/broker", sync: properties.useSyncGet, handleAs: "json"}) - .then(function(data) - { - var brokerData= data[0]; - addPort.show(that.name, that.portUpdater.portData.type, brokerData.authenticationproviders, brokerData.keystores, brokerData.truststores); - } - ); - } - - function PortUpdater(containerNode, portObj, controller, url) - { - var that = this; - - function findNode(name) { - return query("." + name, containerNode)[0]; - } - - function storeNodes(names) - { - for(var i = 0; i < names.length; i++) { - that[names[i]] = findNode(names[i]); - } - } - - storeNodes(["nameValue", - "stateValue", - "typeValue", - "portValue", - "authenticationProviderValue", - "protocolsValue", - "transportsValue", - "bindingAddressValue", - "keyStoreValue", - "needClientAuthValue", - "wantClientAuthValue", - "trustStoresValue", - "connectionCountValue", - "maxOpenConnectionsValue", - "authenticationProvider", - "bindingAddress", - "keyStore", - "needClientAuth", - "wantClientAuth", - "trustStores", - "maxOpenConnections" - ]); - - this.query = url; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - that.portData = data[0]; - util.flattenStatistics( that.portData ); - that.updateHeader(); - }); - - } - - PortUpdater.prototype.updateHeader = function() - { - function printArray(fieldName, object) - { - var array = object[fieldName]; - var data = "<div>"; - if (array) { - for(var i = 0; i < array.length; i++) { - data+= "<div>" + entities.encode(array[i]) + "</div>"; - } - } - return data + "</div>"; - } - - this.nameValue.innerHTML = entities.encode(String(this.portData[ "name" ])); - this.stateValue.innerHTML = entities.encode(String(this.portData[ "state" ])); - this.typeValue.innerHTML = entities.encode(String(this.portData[ "type" ])); - this.portValue.innerHTML = entities.encode(String(this.portData[ "port" ])); - this.authenticationProviderValue.innerHTML = this.portData[ "authenticationProvider" ] ? entities.encode(String(this.portData[ "authenticationProvider" ])) : ""; - this.protocolsValue.innerHTML = printArray( "protocols", this.portData); - this.transportsValue.innerHTML = printArray( "transports", this.portData); - this.bindingAddressValue.innerHTML = this.portData[ "bindingAddress" ] ? entities.encode(String(this.portData[ "bindingAddress" ])) : "" ; - this.connectionCountValue.innerHTML = this.portData[ "connectionCount" ] ? entities.encode(String(this.portData[ "connectionCount" ])) : "0" ; - this.maxOpenConnectionsValue.innerHTML = (this.portData[ "maxOpenConnections" ] && this.portData[ "maxOpenConnections" ] >= 0) ? entities.encode(String(this.portData[ "maxOpenConnections" ])) : "(no limit)" ; - - this.keyStoreValue.innerHTML = this.portData[ "keyStore" ] ? entities.encode(String(this.portData[ "keyStore" ])) : ""; - this.needClientAuthValue.innerHTML = "<input type='checkbox' disabled='disabled' "+(this.portData[ "needClientAuth" ] ? "checked='checked'": "")+" />" ; - this.wantClientAuthValue.innerHTML = "<input type='checkbox' disabled='disabled' "+(this.portData[ "wantClientAuth" ] ? "checked='checked'": "")+" />" ; - this.trustStoresValue.innerHTML = printArray( "trustStores", this.portData); - - var typeMetaData = metadata.getMetaData("Port", this.portData["type"]); - - this.authenticationProvider.style.display = "authenticationProvider" in typeMetaData.attributes ? "block" : "none"; - this.bindingAddress.style.display = "bindingAddress" in typeMetaData.attributes ? "block" : "none"; - this.keyStore.style.display = "keyStore" in typeMetaData.attributes ? "block" : "none"; - this.needClientAuth.style.display = "needClientAuth" in typeMetaData.attributes ? "block" : "none"; - this.wantClientAuth.style.display = "wantClientAuth" in typeMetaData.attributes ? "block" : "none"; - this.trustStores.style.display = "trustStores" in typeMetaData.attributes ? "block" : "none"; - - this.maxOpenConnections.style.display = "maxOpenConnections" in typeMetaData.attributes ? "block" : "none"; - - }; - - PortUpdater.prototype.update = function() - { - - var thisObj = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - thisObj.portData = data[0]; - util.flattenStatistics( thisObj.portData ); - thisObj.updateHeader(); - }); - }; - - return Port; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Preferences.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Preferences.js deleted file mode 100644 index c8e1d17e06..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Preferences.js +++ /dev/null @@ -1,281 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([ - "dojo/_base/declare", - "dojo/_base/xhr", - "dojo/_base/event", - "dojo/_base/connect", - "dojo/dom", - "dojo/dom-construct", - "dojo/parser", - "dojo/json", - "dojo/store/Memory", - "dojo/data/ObjectStore", - "dojox/html/entities", - "dijit/registry", - "qpid/common/TimeZoneSelector", - "dojo/text!../../showPreferences.html", - "qpid/common/util", - "qpid/management/UserPreferences", - "dijit/Dialog", - "dijit/form/NumberSpinner", - "dijit/form/CheckBox", - "dijit/form/Textarea", - "dijit/form/FilteringSelect", - "dijit/form/TextBox", - "dijit/form/DropDownButton", - "dijit/form/Button", - "dijit/form/Form", - "dijit/layout/BorderContainer", - "dijit/layout/TabContainer", - "dijit/layout/ContentPane", - "dojox/grid/EnhancedGrid", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], -function (declare, xhr, event, connect, dom, domConstruct, parser, json, Memory, ObjectStore, entities, registry, TimeZoneSelector, markup, util, UserPreferences) { - - var preferenceNames = ["timeZone", "updatePeriod"]; - - return declare("qpid.management.Preferences", null, { - - preferencesDialog: null, - - constructor: function() - { - var that = this; - - this.userPreferences = {}; - this.domNode = domConstruct.create("div", {innerHTML: markup}); - parser.parse(this.domNode).then(function(instances) - { - that._postParse(); - }); - }, - _postParse: function() - { - var that = this; - this.preferencesDialog = registry.byId("preferences.preferencesDialog"); - for(var i=0; i<preferenceNames.length; i++) - { - var name = preferenceNames[i]; - this[name] = registry.byId("preferences." + name); - this[name].on("change", function(val){that._toggleSetButtons();}); - } - - this.setButton = registry.byId("preferences.setButton"); - this.setAndCloseButton = registry.byId("preferences.setAndCloseButton"); - this.setButton.on("click", function(e){that._savePreferences(e, false);}); - this.setAndCloseButton.on("click", function(e){that._savePreferences(e, true);}); - this.theForm = registry.byId("preferences.preferencesForm"); - this.usersGrid = registry.byId("preferences.users"); - this.usersGrid.set("structure", [ { name: "User", field: "name", width: "50%"}, - { name: "Authentication Provider", field: "authenticationProvider", width: "50%"}]); - this.deleteButton = registry.byId("preferences.deleteButton"); - this.deleteAndCloseButton = registry.byId("preferences.deleteAndCloseButton"); - this.deleteButton.on("click", function(e){that._deletePreferences(false);}); - this.deleteAndCloseButton.on("click", function(e){that._deletePreferences(true);}); - - var deletePreferencesButtonToggler = function(rowIndex){ - var data = that.usersGrid.selection.getSelected(); - that.deleteButton.set("disabled",!data.length ); - that.deleteAndCloseButton.set("disabled",!data.length ); - }; - connect.connect(this.usersGrid.selection, 'onSelected', deletePreferencesButtonToggler); - connect.connect(this.usersGrid.selection, 'onDeselected', deletePreferencesButtonToggler); - this.theForm.on("submit", function(e){event.stop(e); return false;}); - - this._setValues(); - - deletePreferencesButtonToggler(); - this.preferencesDialog.startup(); - }, - - showDialog: function(){ - this._setValues(); - this._loadUserPreferences(); - this.preferencesDialog.show(); - }, - - destroy: function() - { - if (this.preferencesDialog) - { - this.preferencesDialog.destroyRecursevly(); - this.preferencesDialog = null; - } - }, - - _savePreferences: function(e, hideDialog) - { - var that =this; - event.stop(e); - if(this.theForm.validate()){ - var preferences = {}; - for(var i=0; i<preferenceNames.length; i++) - { - var name = preferenceNames[i]; - var preferenceWidget = this[name]; - if (preferenceWidget) - { - preferences[name] = preferenceWidget.hasOwnProperty("checked") ? preferenceWidget.checked : preferenceWidget.get("value"); - } - } - - UserPreferences.setPreferences( - preferences, - function(preferences) - { - success = true; - if (hideDialog) - { - that.preferencesDialog.hide(); - } - else - { - var reloadUsers = true; - if (that.users) - { - var authenticatedUser = dom.byId("authenticatedUser").innerHTML; - for(var i=0; i<that.users.length; i++) - { - if (that.users[i].name == authenticatedUser) - { - reloadUsers = false; - break; - } - } - } - if (reloadUsers) - { - that._loadUserPreferences(); - } - } - that._toggleSetButtons(); - }, - UserPreferences.defaultErrorHandler - ); - } - }, - - _deletePreferences: function(hideDialog){ - var data = this.usersGrid.selection.getSelected(); - if (util.deleteGridSelections( - null, - this.usersGrid, - "service/userpreferences", - "Are you sure you want to delete preferences for user", - "user")) - { - this._loadUserPreferences(); - var authenticatedUser = dom.byId("authenticatedUser").innerHTML; - for(i = 0; i<data.length; i++) - { - if (data[i].name == authenticatedUser) - { - UserPreferences.resetPreferences(); - this._setValues(); - break; - } - } - if (hideDialog) - { - this.preferencesDialog.hide(); - } - } - }, - - _setValues: function() - { - for(var i = 0; i < preferenceNames.length; i++) - { - var name = preferenceNames[i]; - var preferenceWidget = this[name]; - if (preferenceWidget) - { - var value = UserPreferences[name] - if (typeof value == "string") - { - value = entities.encode(String(value)) - } - if (!value && name == "updatePeriod") - { - // set to default - value = 5; - } - preferenceWidget.set("value", value); - if (preferenceWidget.hasOwnProperty("checked")) - { - preferenceWidget.set("checked", UserPreferences[name] ? true : false); - } - } - } - this._toggleSetButtons(); - }, - - _loadUserPreferences : function() - { - var that = this; - xhr.get({ - url: "service/userpreferences", - sync: false, - handleAs: "json" - }).then( - function(users) { - for(var i=0; i<users.length; i++) - { - users[i].id = users[i].authenticationProvider + "/" + users[i].name; - } - that.users = users; - var usersStore = new Memory({data: users, idProperty: "id"}); - var usersDataStore = new ObjectStore({objectStore: usersStore}); - if (that.usersGrid.store) - { - that.usersGrid.store.close(); - } - that.usersGrid.set("store", usersDataStore); - that.usersGrid._refresh(); - }); - }, - - _toggleSetButtons: function() - { - var changed = false; - for(var i=0; i<preferenceNames.length; i++) - { - var name = preferenceNames[i]; - var preferenceWidget = this[name]; - if (preferenceWidget) - { - var value = preferenceWidget.hasOwnProperty("checked") ? preferenceWidget.checked : preferenceWidget.get("value"); - if (value != UserPreferences[name]) - { - changed = true; - break; - } - } - } - this.setButton.set("disabled", !changed); - this.setAndCloseButton.set("disabled", !changed); - } - - }); -});
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/PreferencesProvider.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/PreferencesProvider.js deleted file mode 100644 index c145ba0d34..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/PreferencesProvider.js +++ /dev/null @@ -1,187 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/dom-construct", - "dojo/_base/array", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "dojo/_base/event", - "dijit/registry", - "dojo/dom-style", - "dojox/html/entities", - "qpid/management/addPreferencesProvider", - "dojo/domReady!"], - function (xhr, parser, query, construct, array, properties, updater, util, event, registry, domStyle, entities, addPreferencesProvider) { - - function PreferencesProvider(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "preferencesprovider", name: name, parent: parent}; - this.authenticationProviderName = parent.name; - } - - PreferencesProvider.prototype.getTitle = function() { - return "PreferencesProvider:" + this.authenticationProviderName + "/" + this.name ; - }; - - PreferencesProvider.prototype.init = function(node, parentObject) { - var that = this; - xhr.get({url: "showPreferencesProvider.html", - sync: true, - load: function(data) { - node.innerHTML = data; - parser.parse(node).then(function(instances) - { - that.containerNode = node; - that.parentObject = parentObject; - that.preferencesProviderType=query(".preferencesProviderType", node)[0]; - that.preferencesProviderState=query(".preferencesProviderState", node)[0]; - that.editPreferencesProviderButton = query(".editPreferencesProviderButton", node)[0]; - that.deletePreferencesProviderButton = query(".deletePreferencesProviderButton", node)[0]; - that.preferencesProviderAttributes = query(".preferencesProviderAttributes", node)[0]; - that.preferencesDetailsDiv = query(".preferencesDetails", node)[0]; - var editPreferencesProviderWidget = registry.byNode(that.editPreferencesProviderButton); - editPreferencesProviderWidget.on("click", function(evt){ event.stop(evt); that.editPreferencesProvider();}); - var deletePreferencesProviderWidget = registry.byNode(that.deletePreferencesProviderButton); - deletePreferencesProviderWidget.on("click", function(evt){ event.stop(evt); that.deletePreferencesProvider();}); - }); - }}); - }; - - PreferencesProvider.prototype.open = function(contentPane) { - this.contentPane = contentPane; - this.init(contentPane.containerNode); - this.reload(); - this.updater = new PreferencesProviderUpdater(this); - updater.add(this.updater); - }; - - PreferencesProvider.prototype.close = function() { - if (this.updater) - { - updater.remove( this.updater); - } - }; - - PreferencesProvider.prototype.deletePreferencesProvider = function() { - if (this.preferencesProviderData){ - var preferencesProviderData = this.preferencesProviderData; - if(confirm("Are you sure you want to delete preferences provider '" + preferencesProviderData.name + "'?")) { - var query = "api/latest/preferencesprovider/" + encodeURIComponent(this.authenticationProviderName) + "/" + encodeURIComponent(preferencesProviderData.name); - this.success = true - var that = this; - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.update(null); - - // if opened in tab - if (that.contentPane) - { - that.close(); - that.contentPane.onClose() - that.controller.tabContainer.removeChild(that.contentPane); - that.contentPane.destroyRecursive(); - } - else - { - var widgets = registry.findWidgets(that.containerNode); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - construct.empty(that.containerNode); - if (that.parentObject) - { - that.parentObject.onPreferencesProviderDeleted(); - } - } - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!this.success ) { - util.xhrErrorHandler(this.failureReason); - } - } - } - }; - - PreferencesProvider.prototype.editPreferencesProvider = function() { - if (this.preferencesProviderData){ - addPreferencesProvider.show(this.authenticationProviderName, this.name); - } - }; - - PreferencesProvider.prototype.update = function(data) { - this.preferencesProviderData = data; - if (data) - { - this.name = data.name; - this.preferencesProviderAttributes.style.display = 'block'; - this.editPreferencesProviderButton.style.display = 'inline'; - this.deletePreferencesProviderButton.style.display = 'inline'; - this.preferencesProviderType.innerHTML = entities.encode(String(data.type)); - this.preferencesProviderState.innerHTML = entities.encode(String(data.state)); - if (!this.details) - { - var that = this; - require(["qpid/management/preferencesprovider/" + data.type.toLowerCase() + "/show"], - function(PreferencesProviderDetails) { - that.details = new PreferencesProviderDetails(that.preferencesDetailsDiv); - that.details.update(data); - }); - } - else - { - this.details.update(data); - } - } - else - { - this.editPreferencesProviderButton.style.display = 'none'; - this.deletePreferencesProviderButton.style.display = 'none'; - this.preferencesProviderAttributes.style.display = 'none'; - this.details = null; - } - }; - - PreferencesProvider.prototype.reload = function() - { - var query = "api/latest/preferencesprovider/" + encodeURIComponent(this.authenticationProviderName) + "/" + encodeURIComponent(this.name); - var that = this; - xhr.get({url: query, sync: properties.useSyncGet, handleAs: "json"}) - .then(function(data) { - var preferencesProviderData = data[0]; - util.flattenStatistics( preferencesProviderData ); - that.update(preferencesProviderData); - }); - }; - - function PreferencesProviderUpdater(preferencesProvider) - { - this.preferencesProvider = preferencesProvider; - }; - - PreferencesProviderUpdater.prototype.update = function() - { - this.preferencesProvider.reload(); - }; - - return PreferencesProvider; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Queue.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Queue.js deleted file mode 100644 index 55d0df1241..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Queue.js +++ /dev/null @@ -1,566 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dijit/registry", - "dojo/_base/connect", - "dojo/_base/event", - "dojo/json", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/formatter", - "qpid/common/UpdatableStore", - "qpid/management/addBinding", - "qpid/management/moveCopyMessages", - "qpid/management/showMessage", - "qpid/management/UserPreferences", - "qpid/management/editQueue", - "dojo/store/JsonRest", - "dojox/grid/EnhancedGrid", - "dojo/data/ObjectStore", - "dojox/html/entities", - "dojox/grid/enhanced/plugins/Pagination", - "dojox/grid/enhanced/plugins/IndirectSelection", - "dojo/domReady!"], - function (xhr, parser, query, registry, connect, event, json, properties, updater, util, formatter, - UpdatableStore, addBinding, moveMessages, showMessage, UserPreferences, editQueue, JsonRest, EnhancedGrid, ObjectStore, entities) { - - function Queue(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "queue", name: name, parent: parent }; - } - - Queue.prototype.getQueueName = function() - { - return this.name; - }; - - - Queue.prototype.getVirtualHostName = function() - { - return this.modelObj.parent.name; - }; - - Queue.prototype.getVirtualHostNodeName = function() - { - return this.modelObj.parent.parent.name; - }; - - Queue.prototype.getTitle = function() - { - return "Queue: " + this.name; - }; - - Queue.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showQueue.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - - that.queueUpdater = new QueueUpdater(contentPane.containerNode, that, that.controller); - - updater.add( that.queueUpdater ); - - that.queueUpdater.update(); - - var myStore = new JsonRest({target:"service/message/"+ encodeURIComponent(that.getVirtualHostName()) + - "/" + encodeURIComponent(that.getQueueName())}); - var messageGridDiv = query(".messages",contentPane.containerNode)[0]; - that.dataStore = new ObjectStore({objectStore: myStore}); - that.grid = new EnhancedGrid({ - store: that.dataStore, - autoHeight: 10, - keepSelection: true, - structure: [ - {name:"Size", field:"size", width: "40%"}, - {name:"State", field:"state", width: "30%"}, - - {name:"Arrival", field:"arrivalTime", width: "30%", - formatter: function(val) { - return UserPreferences.formatDateTime(val, {addOffset: true, appendTimeZone: true}); - } } - ], - plugins: { - pagination: { - pageSizes: ["10", "25", "50", "100"], - description: true, - sizeSwitch: true, - pageStepper: true, - gotoButton: true, - maxPageStep: 4, - position: "bottom" - }, - indirectSelection: true - } - }, messageGridDiv); - - connect.connect(that.grid, "onRowDblClick", that.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var id = that.dataStore.getValue(theItem,"id"); - showMessage.show({ messageNumber: id, - queue: that.getQueueName(), - virtualhost: that.getVirtualHostName(), - virtualhostnode: that.getVirtualHostNodeName()}); - }); - - var deleteMessagesButton = query(".deleteMessagesButton", contentPane.containerNode)[0]; - var deleteWidget = registry.byNode(deleteMessagesButton); - connect.connect(deleteWidget, "onClick", - function(evt){ - event.stop(evt); - that.deleteMessages(); - }); - var clearQueueButton = query(".clearQueueButton", contentPane.containerNode)[0]; - var clearQueueWidget = registry.byNode(clearQueueButton); - connect.connect(clearQueueWidget, "onClick", - function(evt){ - event.stop(evt); - that.clearQueue(); - }); - var moveMessagesButton = query(".moveMessagesButton", contentPane.containerNode)[0]; - connect.connect(registry.byNode(moveMessagesButton), "onClick", - function(evt){ - event.stop(evt); - that.moveOrCopyMessages({move: true}); - }); - - - var copyMessagesButton = query(".copyMessagesButton", contentPane.containerNode)[0]; - connect.connect(registry.byNode(copyMessagesButton), "onClick", - function(evt){ - event.stop(evt); - that.moveOrCopyMessages({move: false}); - }); - - var addBindingButton = query(".addBindingButton", contentPane.containerNode)[0]; - connect.connect(registry.byNode(addBindingButton), "onClick", - function(evt){ - event.stop(evt); - addBinding.show({ virtualhost: that.getVirtualHostName(), - queue: that.getQueueName(), - virtualhostnode: that.getVirtualHostNodeName()}); - }); - - var deleteQueueButton = query(".deleteQueueButton", contentPane.containerNode)[0]; - connect.connect(registry.byNode(deleteQueueButton), "onClick", - function(evt){ - event.stop(evt); - that.deleteQueue(); - }); - var editQueueButton = query(".editQueueButton", contentPane.containerNode)[0]; - connect.connect(registry.byNode(editQueueButton), "onClick", - function(evt){ - event.stop(evt); - editQueue.show({nodeName:that.modelObj.parent.parent.name, hostName:that.modelObj.parent.name,queueName:that.name}); - }); - UserPreferences.addListener(that); - - }); - }}); - - - - }; - - Queue.prototype.deleteMessages = function() { - var data = this.grid.selection.getSelected(); - if(data.length) { - var that = this; - if(confirm("Delete " + data.length + " messages?")) { - var i, queryParam; - for(i = 0; i<data.length; i++) { - if(queryParam) { - queryParam += "&"; - } else { - queryParam = "?"; - } - - queryParam += "id=" + data[i].id; - } - var query = "service/message/"+ encodeURIComponent(that.getVirtualHostName()) - + "/" + encodeURIComponent(that.getQueueName()) + queryParam; - that.success = true - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.grid.setQuery({id: "*"}); - that.grid.selection.deselectAll(); - that.queueUpdater.update(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!that.success ) { - alert("Error:" + this.failureReason); - } - } - } - }; - Queue.prototype.clearQueue = function() { - var that = this; - if(confirm("Clear all messages from queue?")) { - var query = "service/message/"+ encodeURIComponent(that.getVirtualHostName()) - + "/" + encodeURIComponent(that.getQueueName()) + "?clear=true"; - that.success = true - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.grid.setQuery({id: "*"}); - that.grid.selection.deselectAll(); - that.queueUpdater.update(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!that.success ) { - alert("Error:" + this.failureReason); - } - } - }; - Queue.prototype.moveOrCopyMessages = function(obj) { - var that = this; - var move = obj.move; - var data = this.grid.selection.getSelected(); - if(data.length) { - var that = this; - var i, putData = { messages:[] }; - if(move) { - putData.move = true; - } - for(i = 0; i<data.length; i++) { - putData.messages.push(data[i].id); - } - moveMessages.show({ virtualhost: this.getVirtualHostName(), - queue: this.getQueueName(), - data: putData}, function() { - if(move) - { - that.grid.setQuery({id: "*"}); - that.grid.selection.deselectAll(); - } - }); - - } - - - - }; - - Queue.prototype.startup = function() { - this.grid.startup(); - }; - - Queue.prototype.close = function() { - updater.remove( this.queueUpdater ); - UserPreferences.removeListener(this); - }; - - Queue.prototype.onPreferencesChange = function(data) - { - this.grid._refresh(); - }; - - var queueTypeKeys = { - priority: "priorities", - lvq: "lvqKey", - sorted: "sortKey" - }; - - var queueTypeKeyNames = { - priority: "Number of priorities", - lvq: "LVQ key", - sorted: "Sort key" - }; - - function QueueUpdater(containerNode, queueObj, controller) - { - var that = this; - - function findNode(name) { - return query("." + name, containerNode)[0]; - } - - function storeNodes(names) - { - for(var i = 0; i < names.length; i++) { - that[names[i]] = findNode(names[i]); - } - } - - storeNodes(["name", - "state", - "durable", - "messageDurability", - "maximumMessageTtl", - "minimumMessageTtl", - "exclusive", - "owner", - "lifetimePolicy", - "type", - "typeQualifier", - "alertRepeatGap", - "alertRepeatGapUnits", - "alertThresholdMessageAge", - "alertThresholdMessageAgeUnits", - "alertThresholdMessageSize", - "alertThresholdMessageSizeUnits", - "alertThresholdQueueDepthBytes", - "alertThresholdQueueDepthBytesUnits", - "alertThresholdQueueDepthMessages", - "alternateExchange", - "messageGroups", - "messageGroupKey", - "messageGroupSharedGroups", - "queueDepthMessages", - "queueDepthBytes", - "queueDepthBytesUnits", - "unacknowledgedMessages", - "unacknowledgedBytes", - "unacknowledgedBytesUnits", - "msgInRate", - "bytesInRate", - "bytesInRateUnits", - "msgOutRate", - "bytesOutRate", - "bytesOutRateUnits", - "queueFlowResumeSizeBytes", - "queueFlowControlSizeBytes", - "maximumDeliveryAttempts", - "oldestMessageAge"]); - - - - this.query = "api/latest/queue/" + encodeURIComponent(queueObj.getVirtualHostNodeName()) + "/" + encodeURIComponent(queueObj.getVirtualHostName()) + "/" + encodeURIComponent(queueObj.getQueueName()); - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - that.queueData = data[0]; - - util.flattenStatistics( that.queueData ); - - that.updateHeader(); - that.bindingsGrid = new UpdatableStore(that.queueData.bindings, findNode("bindings"), - [ { name: "Exchange", field: "exchange", width: "40%"}, - { name: "Binding Key", field: "name", width: "30%"}, - { name: "Arguments", field: "argumentString", width: "30%"} - ]); - - that.consumersGrid = new UpdatableStore(that.queueData.consumers, findNode("consumers"), - [ { name: "Name", field: "name", width: "40%"}, - { name: "Mode", field: "distributionMode", width: "20%"}, - { name: "Msgs Rate", field: "msgRate", - width: "20%"}, - { name: "Bytes Rate", field: "bytesRate", - width: "20%"} - ]); - - - - - }); - - } - - QueueUpdater.prototype.updateHeader = function() - { - - var bytesDepth; - this.name.innerHTML = entities.encode(String(this.queueData[ "name" ])); - this.state.innerHTML = entities.encode(String(this.queueData[ "state" ])); - this.durable.innerHTML = entities.encode(String(this.queueData[ "durable" ])); - this.exclusive.innerHTML = entities.encode(String(this.queueData[ "exclusive" ])); - this.owner.innerHTML = this.queueData[ "owner" ] ? entities.encode(String(this.queueData[ "owner" ])) : "" ; - this.lifetimePolicy.innerHTML = entities.encode(String(this.queueData[ "lifetimePolicy" ])); - this.messageDurability.innerHTML = entities.encode(String(this.queueData[ "messageDurability" ])); - this.minimumMessageTtl.innerHTML = entities.encode(String(this.queueData[ "minimumMessageTtl" ])); - this.maximumMessageTtl.innerHTML = entities.encode(String(this.queueData[ "maximumMessageTtl" ])); - - this.alternateExchange.innerHTML = this.queueData[ "alternateExchange" ] ? entities.encode(String(this.queueData[ "alternateExchange" ])) : "" ; - - this.queueDepthMessages.innerHTML = entities.encode(String(this.queueData["queueDepthMessages"])); - bytesDepth = formatter.formatBytes( this.queueData["queueDepthBytes"] ); - this.queueDepthBytes.innerHTML = "(" + bytesDepth.value; - this.queueDepthBytesUnits.innerHTML = bytesDepth.units + ")"; - - this.unacknowledgedMessages.innerHTML = entities.encode(String(this.queueData["unacknowledgedMessages"])); - bytesDepth = formatter.formatBytes( this.queueData["unacknowledgedBytes"] ); - this.unacknowledgedBytes.innerHTML = "(" + bytesDepth.value; - this.unacknowledgedBytesUnits.innerHTML = bytesDepth.units + ")"; - this["type" ].innerHTML = entities.encode(this.queueData[ "type" ]); - if (this.queueData["type"] == "standard") - { - this.typeQualifier.style.display = "none"; - } - else - { - this.typeQualifier.innerHTML = entities.encode("(" + queueTypeKeyNames[this.queueData[ "type" ]] + ": " + this.queueData[queueTypeKeys[this.queueData[ "type" ]]] + ")"); - } - - if(this.queueData["messageGroupKey"]) - { - this.messageGroupKey.innerHTML = entities.encode(String(this.queueData["messageGroupKey"])); - this.messageGroupSharedGroups.innerHTML = entities.encode(String(this.queueData["messageGroupSharedGroups"])); - this.messageGroups.style.display = "block"; - } - else - { - this.messageGroups.style.display = "none"; - } - - this.queueFlowControlSizeBytes.innerHTML = entities.encode(String(this.queueData[ "queueFlowControlSizeBytes" ])); - this.queueFlowResumeSizeBytes.innerHTML = entities.encode(String(this.queueData[ "queueFlowResumeSizeBytes" ])); - - this.oldestMessageAge.innerHTML = entities.encode(String(this.queueData[ "oldestMessageAge" ] / 1000)); - var maximumDeliveryAttempts = this.queueData[ "maximumDeliveryAttempts" ]; - this.maximumDeliveryAttempts.innerHTML = entities.encode(String( maximumDeliveryAttempts == 0 ? "" : maximumDeliveryAttempts)); - }; - - QueueUpdater.prototype.update = function() - { - - var thisObj = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) { - var i,j; - thisObj.queueData = data[0]; - util.flattenStatistics( thisObj.queueData ); - - var bindings = thisObj.queueData[ "bindings" ]; - var consumers = thisObj.queueData[ "consumers" ]; - - if (bindings) - { - for(i=0; i < bindings.length; i++) { - bindings[i].argumentString = json.stringify(bindings[i].arguments); - } - } - thisObj.updateHeader(); - - - // update alerting info - var alertRepeatGap = formatter.formatTime( thisObj.queueData["alertRepeatGap"] ); - - thisObj.alertRepeatGap.innerHTML = alertRepeatGap.value; - thisObj.alertRepeatGapUnits.innerHTML = alertRepeatGap.units; - - - var alertMsgAge = formatter.formatTime( thisObj.queueData["alertThresholdMessageAge"] ); - - thisObj.alertThresholdMessageAge.innerHTML = alertMsgAge.value; - thisObj.alertThresholdMessageAgeUnits.innerHTML = alertMsgAge.units; - - var alertMsgSize = formatter.formatBytes( thisObj.queueData["alertThresholdMessageSize"] ); - - thisObj.alertThresholdMessageSize.innerHTML = alertMsgSize.value; - thisObj.alertThresholdMessageSizeUnits.innerHTML = alertMsgSize.units; - - var alertQueueDepth = formatter.formatBytes( thisObj.queueData["alertThresholdQueueDepthBytes"] ); - - thisObj.alertThresholdQueueDepthBytes.innerHTML = alertQueueDepth.value; - thisObj.alertThresholdQueueDepthBytesUnits.innerHTML = alertQueueDepth.units; - - thisObj.alertThresholdQueueDepthMessages.innerHTML = entities.encode(String(thisObj.queueData["alertThresholdQueueDepthMessages"])); - - var sampleTime = new Date(); - var messageIn = thisObj.queueData["totalEnqueuedMessages"]; - var bytesIn = thisObj.queueData["totalEnqueuedBytes"]; - var messageOut = thisObj.queueData["totalDequeuedMessages"]; - var bytesOut = thisObj.queueData["totalDequeuedBytes"]; - - if(thisObj.sampleTime) { - var samplePeriod = sampleTime.getTime() - thisObj.sampleTime.getTime(); - - var msgInRate = (1000 * (messageIn - thisObj.messageIn)) / samplePeriod; - var msgOutRate = (1000 * (messageOut - thisObj.messageOut)) / samplePeriod; - var bytesInRate = (1000 * (bytesIn - thisObj.bytesIn)) / samplePeriod; - var bytesOutRate = (1000 * (bytesOut - thisObj.bytesOut)) / samplePeriod; - - thisObj.msgInRate.innerHTML = msgInRate.toFixed(0); - var bytesInFormat = formatter.formatBytes( bytesInRate ); - thisObj.bytesInRate.innerHTML = "(" + bytesInFormat.value; - thisObj.bytesInRateUnits.innerHTML = bytesInFormat.units + "/s)"; - - thisObj.msgOutRate.innerHTML = msgOutRate.toFixed(0); - var bytesOutFormat = formatter.formatBytes( bytesOutRate ); - thisObj.bytesOutRate.innerHTML = "(" + bytesOutFormat.value; - thisObj.bytesOutRateUnits.innerHTML = bytesOutFormat.units + "/s)"; - - if(consumers && thisObj.consumers) { - for(i=0; i < consumers.length; i++) { - var consumer = consumers[i]; - for(j = 0; j < thisObj.consumers.length; j++) { - var oldConsumer = thisObj.consumers[j]; - if(oldConsumer.id == consumer.id) { - var msgRate = (1000 * (consumer.messagesOut - oldConsumer.messagesOut)) / - samplePeriod; - consumer.msgRate = msgRate.toFixed(0) + "msg/s"; - - var bytesRate = (1000 * (consumer.bytesOut - oldConsumer.bytesOut)) / - samplePeriod; - var bytesRateFormat = formatter.formatBytes( bytesRate ); - consumer.bytesRate = bytesRateFormat.value + bytesRateFormat.units + "/s"; - } - } - } - } - - } - - thisObj.sampleTime = sampleTime; - thisObj.messageIn = messageIn; - thisObj.bytesIn = bytesIn; - thisObj.messageOut = messageOut; - thisObj.bytesOut = bytesOut; - thisObj.consumers = consumers; - - // update bindings - thisObj.bindingsGrid.update(thisObj.queueData.bindings); - - // update consumers - thisObj.consumersGrid.update(thisObj.queueData.consumers) - - }); - }; - - Queue.prototype.deleteQueue = function() { - if(confirm("Are you sure you want to delete queue '" +this.name+"'?")) { - var query = "api/latest/queue/" + encodeURIComponent(this.getVirtualHostNodeName()) - + "/" + encodeURIComponent(this.getVirtualHostName()) + "/" + encodeURIComponent(this.name); - this.success = true - var that = this; - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.contentPane.onClose() - that.controller.tabContainer.removeChild(that.contentPane); - that.contentPane.destroyRecursive(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!this.success ) { - util.xhrErrorHandler(this.failureReason); - } - } - } - - return Queue; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/TrustStore.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/TrustStore.js deleted file mode 100644 index fa6b63212e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/TrustStore.js +++ /dev/null @@ -1,169 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/dom", - "dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/_base/connect", - "dijit/registry", - "dojox/html/entities", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/formatter", - "qpid/management/addStore", - "dojo/domReady!"], - function (dom, xhr, parser, query, connect, registry, entities, properties, updater, util, formatter, addStore) { - - function TrustStore(name, parent, controller) { - this.keyStoreName = name; - this.controller = controller; - this.modelObj = { type: "truststore", name: name, parent: parent}; - this.url = "api/latest/truststore/" + encodeURIComponent(name); - } - - TrustStore.prototype.getTitle = function() { - return "TrustStore: " + this.keyStoreName; - }; - - TrustStore.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showStore.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - - that.keyStoreUpdater = new KeyStoreUpdater(contentPane.containerNode, that.modelObj, that.controller, that.url); - that.keyStoreUpdater.update(); - updater.add( that.keyStoreUpdater ); - - var deleteTrustStoreButton = query(".deleteStoreButton", contentPane.containerNode)[0]; - var node = registry.byNode(deleteTrustStoreButton); - connect.connect(node, "onClick", - function(evt){ - that.deleteKeyStore(); - }); - - var editTrustStoreButton = query(".editStoreButton", contentPane.containerNode)[0]; - var node = registry.byNode(editTrustStoreButton); - connect.connect(node, "onClick", - function(evt){ - xhr.get({url: that.url, sync: properties.useSyncGet, handleAs: "json", content: { actuals: true }}) - .then(function(data) - { - addStore.setupTypeStore("TrustStore"); - addStore.show(data[0], that.url); - }); - }); - }); - }}); - }; - - TrustStore.prototype.close = function() { - updater.remove( this.keyStoreUpdater ); - }; - - function KeyStoreUpdater(containerNode, keyStoreObj, controller, url) - { - var that = this; - this.keyStoreDetailsContainer = query(".typeFieldsContainer", containerNode)[0]; - - function findNode(name) { - return query("." + name , containerNode)[0]; - } - - function storeNodes(names) - { - for(var i = 0; i < names.length; i++) { - that[names[i]] = findNode(names[i]); - } - } - - storeNodes(["name", - "type", - "state" - ]); - - this.query = url; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - that.keyStoreData = data[0]; - that.updateHeader(); - }); - - } - - KeyStoreUpdater.prototype.updateHeader = function() - { - this.name.innerHTML = entities.encode(String(this.keyStoreData[ "name" ])); - this.type.innerHTML = entities.encode(String(this.keyStoreData[ "type" ])); - this.state.innerHTML = entities.encode(String(this.keyStoreData[ "state" ])); - }; - - KeyStoreUpdater.prototype.update = function() - { - var that = this; - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - that.trustStoreData = data[0]; - that.updateHeader(); - if (that.details) - { - that.details.update(that.trustStoreData); - } - else - { - require(["qpid/management/store/" + encodeURIComponent(that.trustStoreData.type.toLowerCase()) + "/show"], - function(DetailsUI) - { - that.details = new DetailsUI({containerNode:that.keyStoreDetailsContainer, parent: that}); - that.details.update(that.trustStoreData); - } - ); - } - }); - }; - - TrustStore.prototype.deleteKeyStore = function() { - if(confirm("Are you sure you want to delete trust store '" +this.keyStoreName+"'?")) { - var query = this.url; - this.success = true - var that = this; - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.contentPane.onClose() - that.controller.tabContainer.removeChild(that.contentPane); - that.contentPane.destroyRecursive(); - that.close(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!this.success ) { - util.xhrErrorHandler(this.failureReason); - } - } - } - - return TrustStore; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/UserPreferences.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/UserPreferences.js deleted file mode 100644 index 4a9dfd532a..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/UserPreferences.js +++ /dev/null @@ -1,313 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/json", - "dojo/date", - "dojo/date/locale", - "dojo/number", - "qpid/common/timezone"], function (xhr, json, date, locale, number, timezone) { - - var listeners = []; - - var UserPreferences = { - - /* set time zone to 'UTC' by default*/ - timeZone: "UTC", - tabs: [], - - loadPreferences : function(callbackSuccessFunction, callbackErrorFunction) - { - var that = this; - xhr.get({ - url: "service/preferences", - sync: true, - handleAs: "json", - load: function(data) - { - for(var name in data) - { - that[name] = data[name]; - } - if (callbackSuccessFunction) - { - callbackSuccessFunction(); - } - }, - error: function(error) - { - if (callbackErrorFunction) - { - callbackErrorFunction(error); - } - } - }); - }, - - setPreferences : function(preferences, callbackSuccessFunction, callbackErrorFunction, noSync) - { - var that = this; - xhr.post({ - url: "service/preferences", - sync: !noSync, - handleAs: "json", - headers: { "Content-Type": "application/json"}, - postData: json.stringify(preferences), - load: function(x) - { - for(var name in preferences) - { - if (preferences.hasOwnProperty(name)) - that[name] = preferences[name]; - } - that._notifyListeners(preferences); - if (callbackSuccessFunction) - { - callbackSuccessFunction(preferences); - } - }, - error: function(error) - { - if (callbackErrorFunction) - { - callbackErrorFunction(error); - } - } - }); - }, - - resetPreferences : function() - { - var preferences = {}; - for(var name in this) - { - if (this.hasOwnProperty(name) && typeof this[name] != "function") - { - if (name == "preferencesError") - { - continue; - } - this[name] = null; - preferences[name] = undefined; - delete preferences[name]; - } - } - this._notifyListeners(preferences); - }, - - addListener : function(obj) - { - listeners.push(obj); - }, - - removeListener : function(obj) - { - for(var i = 0; i < listeners.length; i++) - { - if(listeners[i] === obj) - { - listeners.splice(i,1); - return; - } - } - }, - - _notifyListeners : function(preferences) - { - for(var i = 0; i < listeners.length; i++) - { - try - { - listeners[i].onPreferencesChange(preferences); - } - catch(e) - { - if (console && console.warn) - { - console.warn(e); - } - } - } - }, - - getTimeZoneInfo : function(timeZoneName) - { - if (!timeZoneName && this.timeZone) - { - timeZoneName = this.timeZone; - } - - if (!timeZoneName) - { - return null; - } - - return timezone.getTimeZoneInfo(timeZoneName); - }, - - addTimeZoneOffsetToUTC : function(utcTimeInMilliseconds, timeZone) - { - var tzi = null; - if (timeZone && timeZone.hasOwnProperty("offset")) - { - tzi = timeZone; - } - else - { - tzi = this.getTimeZoneInfo(timeZone); - } - - if (tzi) - { - var browserTimeZoneOffsetInMinutes = -new Date().getTimezoneOffset(); - return utcTimeInMilliseconds + ( tzi.offset - browserTimeZoneOffsetInMinutes ) * 60000; - } - return utcTimeInMilliseconds; - }, - - getTimeZoneDescription : function(timeZone) - { - var tzi = null; - if (timeZone && timeZone.hasOwnProperty("offset")) - { - tzi = timeZone; - } - else - { - tzi = this.getTimeZoneInfo(timeZone); - } - - if (tzi) - { - var timeZoneOfsetInMinutes = tzi.offset; - return (timeZoneOfsetInMinutes>0? "+" : "") - + number.format(timeZoneOfsetInMinutes/60, {pattern: "00"}) - + ":" + number.format(timeZoneOfsetInMinutes%60, {pattern: "00"}) - + " " + tzi.name; - } - return date.getTimezoneName(new Date()); - }, - - formatDateTime : function(utcTimeInMilliseconds, options) - { - var dateTimeOptions = options || {}; - var tzi = this.getTimeZoneInfo(dateTimeOptions.timeZoneName); - var timeInMilliseconds = utcTimeInMilliseconds; - - if (tzi && dateTimeOptions.addOffset) - { - timeInMilliseconds = this.addTimeZoneOffsetToUTC(utcTimeInMilliseconds, tzi); - } - - var d = new Date(timeInMilliseconds); - - var formatOptions = { - datePattern: dateTimeOptions.datePattern || "yyyy-MM-dd", - timePattern: dateTimeOptions.timePattern || "HH:mm:ss.SSS" - }; - - if ("date" == dateTimeOptions.selector) - { - formatOptions.selector = "date"; - } - else if ("time" == dateTimeOptions.selector) - { - formatOptions.selector = "time"; - } - - var result = locale.format(d, formatOptions); - if(dateTimeOptions.appendTimeZone) - { - result += " (" + this.getTimeZoneDescription(tzi) + ")"; - } - return result; - }, - - defaultErrorHandler: function(error) - { - if (error.status == 404) - { - alert("Cannot perform preferences operation: authentication provider is not configured"); - } - else - { - alert("Cannot perform preferences operation:" + error); - } - }, - - appendTab: function(tab) - { - if (!this.tabs) - { - this.tabs = []; - } - if (!this.isTabStored(tab)) - { - this.tabs.push(tab); - this.setPreferences({tabs: this.tabs}, null, this.defaultErrorHandler, true); - } - }, - - removeTab: function(tab) - { - if (this.tabs) - { - var index = this._getTabIndex(tab); - if (index != -1) - { - this.tabs.splice(index, 1); - this.setPreferences({tabs: this.tabs}, null, this.defaultErrorHandler, true); - } - } - }, - - isTabStored: function(tab) - { - return this._getTabIndex(tab) != -1; - }, - - _getTabIndex: function(tab) - { - var index = -1; - if (this.tabs) - { - for(var i = 0 ; i < this.tabs.length ; i++) - { - var t = this.tabs[i]; - if ( t.objectId == tab.objectId && t.objectType == tab.objectType ) - { - index = i; - break; - } - } - } - return index; - } - }; - - UserPreferences.loadPreferences(null, - function(error) - { - UserPreferences.preferencesError = error; - } - ); - - return UserPreferences; -});
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/VirtualHost.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/VirtualHost.js deleted file mode 100644 index e4482cc39e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/VirtualHost.js +++ /dev/null @@ -1,483 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/_base/connect", - "dijit/registry", - "dojox/html/entities", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/formatter", - "qpid/common/UpdatableStore", - "qpid/management/addQueue", - "qpid/management/addExchange", - "dojox/grid/EnhancedGrid", - "qpid/management/editVirtualHost", - "dojo/domReady!"], - function (xhr, parser, query, connect, registry, entities, properties, updater, util, formatter, UpdatableStore, addQueue, addExchange, EnhancedGrid, editVirtualHost) { - - function VirtualHost(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "virtualhost", name: name, parent: parent}; - } - - VirtualHost.prototype.getTitle = function() - { - return "VirtualHost: " + this.name; - }; - - VirtualHost.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showVirtualHost.html", - sync: true, - load: function(data) { - var containerNode = contentPane.containerNode; - containerNode.innerHTML = data; - parser.parse(containerNode).then(function(instances) - { - that.vhostUpdater = new Updater(containerNode, that.modelObj, that.controller, that); - - var addQueueButton = query(".addQueueButton", containerNode)[0]; - connect.connect(registry.byNode(addQueueButton), "onClick", function(evt){ - addQueue.show({virtualhost:that.name,virtualhostnode:that.modelObj.parent.name}) - }); - - var deleteQueueButton = query(".deleteQueueButton", containerNode)[0]; - connect.connect(registry.byNode(deleteQueueButton), "onClick", - function(evt){ - util.deleteGridSelections( - that.vhostUpdater, - that.vhostUpdater.queuesGrid.grid, - "api/latest/queue/" + encodeURIComponent(that.modelObj.parent.name) + "/" + encodeURIComponent(that.name), - "Are you sure you want to delete queue"); - } - ); - - var addExchangeButton = query(".addExchangeButton", containerNode)[0]; - connect.connect(registry.byNode(addExchangeButton), "onClick", function(evt){ addExchange.show({virtualhost:that.name,virtualhostnode:that.modelObj.parent.name}) }); - - var deleteExchangeButton = query(".deleteExchangeButton", containerNode)[0]; - connect.connect(registry.byNode(deleteExchangeButton), "onClick", - function(evt) - { - util.deleteGridSelections( - that.vhostUpdater, - that.vhostUpdater.exchangesGrid.grid, - "api/latest/exchange/"+ encodeURIComponent(that.modelObj.parent.name) + "/" + encodeURIComponent(that.name), - "Are you sure you want to delete exchange"); - } - ); - - that.stopButton = registry.byNode(query(".stopButton", containerNode)[0]); - that.startButton = registry.byNode(query(".startButton", containerNode)[0]); - that.editButton = registry.byNode(query(".editButton", containerNode)[0]); - that.downloadButton = registry.byNode(query(".downloadButton", containerNode)[0]); - that.downloadButton.on("click", - function(e) - { - var iframe = document.createElement('iframe'); - iframe.id = "downloader_" + that.name; - document.body.appendChild(iframe); - var suggestedAttachmentName = encodeURIComponent(that.name + ".json"); - iframe.src = "/api/latest/virtualhost/" + encodeURIComponent(that.modelObj.parent.name) + "/" + encodeURIComponent(that.name) + "?extractInitialConfig=true&contentDispositionAttachmentFilename=" + suggestedAttachmentName; - // It seems there is no way to remove this iframe in a manner that is cross browser compatible. - } - ); - - that.deleteButton = registry.byNode(query(".deleteButton", containerNode)[0]); - that.deleteButton.on("click", - function(e) - { - if (confirm("Deletion of virtual host will delete message data.\n\n" - + "Are you sure you want to delete virtual host '" + entities.encode(String(that.name)) + "'?")) - { - if (util.sendRequest("api/latest/virtualhost/" + encodeURIComponent(that.modelObj.parent.name) + "/" + encodeURIComponent( that.name) , "DELETE")) - { - that.destroy(); - } - } - } - ); - that.startButton.on("click", - function(event) - { - that.startButton.set("disabled", true); - util.sendRequest("api/latest/virtualhost/" + encodeURIComponent(that.modelObj.parent.name) + "/" + encodeURIComponent( that.name), - "PUT", {desiredState: "ACTIVE"}); - }); - - that.stopButton.on("click", - function(event) - { - if (confirm("Stopping the virtual host will also stop its children. " - + "Are you sure you want to stop virtual host '" - + entities.encode(String(that.name)) +"'?")) - { - that.stopButton.set("disabled", true); - util.sendRequest("api/latest/virtualhost/" + encodeURIComponent(that.modelObj.parent.name) + "/" + encodeURIComponent( that.name), - "PUT", {desiredState: "STOPPED"}); - } - }); - - that.editButton.on("click", - function(event) - { - editVirtualHost.show({nodeName:that.modelObj.parent.name,hostName:that.name}); - }); - - that.vhostUpdater.update(); - updater.add( that.vhostUpdater ); - }); - - }}); - - }; - - VirtualHost.prototype.close = function() { - updater.remove( this.vhostUpdater ); - }; - - VirtualHost.prototype.destroy = function() - { - this.close(); - this.contentPane.onClose() - this.controller.tabContainer.removeChild(this.contentPane); - this.contentPane.destroyRecursive(); - } - - function Updater(node, vhost, controller, virtualHost) - { - this.virtualHost = virtualHost; - var that = this; - - function findNode(name) { - return query("." + name, node)[0]; - } - - function storeNodes(names) - { - for(var i = 0; i < names.length; i++) { - that[names[i]] = findNode(names[i]); - } - } - - storeNodes(["name", - "type", - "state", - "durable", - "lifetimePolicy", - "msgInRate", - "bytesInRate", - "bytesInRateUnits", - "msgOutRate", - "bytesOutRate", - "bytesOutRateUnits", - "virtualHostDetailsContainer", - "deadLetterQueueEnabled", - "housekeepingCheckPeriod", - "housekeepingThreadCount", - "storeTransactionIdleTimeoutClose", - "storeTransactionIdleTimeoutWarn", - "storeTransactionOpenTimeoutClose", - "storeTransactionOpenTimeoutWarn", - "virtualHostConnections", - "virtualHostChildren" - ]); - - this.query = "api/latest/virtualhost/"+ encodeURIComponent(vhost.parent.name) + "/" + encodeURIComponent(vhost.name); - - var that = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) { - that.vhostData = data[0]; - - // flatten statistics into attributes - util.flattenStatistics( that.vhostData ); - - var gridProperties = { - keepSelection: true, - plugins: { - pagination: { - pageSizes: [10, 25, 50, 100], - description: true, - sizeSwitch: true, - pageStepper: true, - gotoButton: true, - maxPageStep: 4, - position: "bottom" - }, - indirectSelection: true - - }}; - - that.updateHeader(); - that.queuesGrid = new UpdatableStore(that.vhostData.queues, findNode("queues"), - [ { name: "Name", field: "name", width: "30%"}, - { name: "Type", field: "type", width: "20%"}, - { name: "Consumers", field: "consumerCount", width: "10%"}, - { name: "Depth (msgs)", field: "queueDepthMessages", width: "20%"}, - { name: "Depth (bytes)", field: "queueDepthBytes", width: "20%", - get: function(rowIndex, item) - { - if(!item){ - return; - } - var store = this.grid.store; - var qdb = store.getValue(item, "queueDepthBytes"); - var bytesFormat = formatter.formatBytes( qdb ); - return bytesFormat.value + " " + bytesFormat.units; - } - } - ], - function(obj) - { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var queueName = obj.dataStore.getValue(theItem,"name"); - controller.show("queue", queueName, vhost, theItem.id); - }); - } , gridProperties, EnhancedGrid); - - that.exchangesGrid = new UpdatableStore(that.vhostData.exchanges, findNode("exchanges"), - [ - { name: "Name", field: "name", width: "50%"}, - { name: "Type", field: "type", width: "30%"}, - { name: "Binding Count", field: "bindingCount", width: "20%"} - ], - function(obj) - { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var exchangeName = obj.dataStore.getValue(theItem,"name"); - controller.show("exchange", exchangeName, vhost, theItem.id); - }); - } , gridProperties, EnhancedGrid); - - - that.connectionsGrid = new UpdatableStore(that.vhostData.connections, - findNode("connections"), - [ { name: "Name", field: "name", width: "20%"}, - { name: "User", field: "principal", width: "10%"}, - { name: "Port", field: "port", width: "10%"}, - { name: "Transport", field: "transport", width: "10%"}, - { name: "Sessions", field: "sessionCount", width: "10%"}, - { name: "Msgs In", field: "msgInRate", - width: "10%"}, - { name: "Bytes In", field: "bytesInRate", - width: "10%"}, - { name: "Msgs Out", field: "msgOutRate", - width: "10%"}, - { name: "Bytes Out", field: "bytesOutRate", - width: "10%"} - ], - function(obj) - { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var connectionName = obj.dataStore.getValue(theItem,"name"); - controller.show("connection", connectionName, vhost, theItem.id); - }); - } ); - - - - }); - - } - - Updater.prototype.updateHeader = function() - { - this.name.innerHTML = entities.encode(String(this.vhostData[ "name" ])); - this.type.innerHTML = entities.encode(String(this.vhostData[ "type" ])); - this.state.innerHTML = entities.encode(String(this.vhostData[ "state" ])); - this.durable.innerHTML = entities.encode(String(this.vhostData[ "durable" ])); - this.lifetimePolicy.innerHTML = entities.encode(String(this.vhostData[ "lifetimePolicy" ])); - this.deadLetterQueueEnabled.innerHTML = entities.encode(String(this.vhostData[ "queue.deadLetterQueueEnabled" ])); - util.updateUI(this.vhostData, - ["housekeepingCheckPeriod", - "housekeepingThreadCount", - "storeTransactionIdleTimeoutClose", - "storeTransactionIdleTimeoutWarn", - "storeTransactionOpenTimeoutClose", - "storeTransactionOpenTimeoutWarn"], - this) - }; - - Updater.prototype.update = function() - { - var thisObj = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}) - .then(function(data) { - thisObj.vhostData = data[0] || {name: thisObj.virtualHost.name,statistics:{messagesIn:0,bytesIn:0,messagesOut:0,bytesOut:0}}; - try - { - thisObj._update(); - } - catch(e) - { - if (console && console.error) - { - console.error(e); - } - } - }); - } - - Updater.prototype._update = function() - { - var thisObj = this; - this.virtualHost.startButton.set("disabled", !this.vhostData.state || this.vhostData.state != "STOPPED"); - this.virtualHost.stopButton.set("disabled", !this.vhostData.state || this.vhostData.state != "ACTIVE"); - this.virtualHost.editButton.set("disabled", !this.vhostData.state || this.vhostData.state == "UNAVAILABLE"); - this.virtualHost.downloadButton.set("disabled", !this.vhostData.state || this.vhostData.state != "ACTIVE"); - this.virtualHost.deleteButton.set("disabled", !this.vhostData.state); - - util.flattenStatistics( thisObj.vhostData ); - var connections = thisObj.vhostData[ "connections" ]; - var queues = thisObj.vhostData[ "queues" ]; - var exchanges = thisObj.vhostData[ "exchanges" ]; - - thisObj.updateHeader(); - - var stats = thisObj.vhostData[ "statistics" ]; - - var sampleTime = new Date(); - var messageIn = stats["messagesIn"]; - var bytesIn = stats["bytesIn"]; - var messageOut = stats["messagesOut"]; - var bytesOut = stats["bytesOut"]; - - if(thisObj.sampleTime) - { - var samplePeriod = sampleTime.getTime() - thisObj.sampleTime.getTime(); - - var msgInRate = (1000 * (messageIn - thisObj.messageIn)) / samplePeriod; - var msgOutRate = (1000 * (messageOut - thisObj.messageOut)) / samplePeriod; - var bytesInRate = (1000 * (bytesIn - thisObj.bytesIn)) / samplePeriod; - var bytesOutRate = (1000 * (bytesOut - thisObj.bytesOut)) / samplePeriod; - - thisObj.msgInRate.innerHTML = msgInRate.toFixed(0); - var bytesInFormat = formatter.formatBytes( bytesInRate ); - thisObj.bytesInRate.innerHTML = "(" + bytesInFormat.value; - thisObj.bytesInRateUnits.innerHTML = bytesInFormat.units + "/s)"; - - thisObj.msgOutRate.innerHTML = msgOutRate.toFixed(0); - var bytesOutFormat = formatter.formatBytes( bytesOutRate ); - thisObj.bytesOutRate.innerHTML = "(" + bytesOutFormat.value; - thisObj.bytesOutRateUnits.innerHTML = bytesOutFormat.units + "/s)"; - - if(connections && thisObj.connections) - { - for(var i=0; i < connections.length; i++) - { - var connection = connections[i]; - for(var j = 0; j < thisObj.connections.length; j++) - { - var oldConnection = thisObj.connections[j]; - if(oldConnection.id == connection.id) - { - msgOutRate = (1000 * (connection.messagesOut - oldConnection.messagesOut)) / - samplePeriod; - connection.msgOutRate = msgOutRate.toFixed(0) + "msg/s"; - - bytesOutRate = (1000 * (connection.bytesOut - oldConnection.bytesOut)) / - samplePeriod; - var bytesOutRateFormat = formatter.formatBytes( bytesOutRate ); - connection.bytesOutRate = bytesOutRateFormat.value + bytesOutRateFormat.units + "/s"; - - - msgInRate = (1000 * (connection.messagesIn - oldConnection.messagesIn)) / - samplePeriod; - connection.msgInRate = msgInRate.toFixed(0) + "msg/s"; - - bytesInRate = (1000 * (connection.bytesIn - oldConnection.bytesIn)) / - samplePeriod; - var bytesInRateFormat = formatter.formatBytes( bytesInRate ); - connection.bytesInRate = bytesInRateFormat.value + bytesInRateFormat.units + "/s"; - } - - - } - - } - } - } - - thisObj.sampleTime = sampleTime; - thisObj.messageIn = messageIn; - thisObj.bytesIn = bytesIn; - thisObj.messageOut = messageOut; - thisObj.bytesOut = bytesOut; - thisObj.connections = connections; - - this._updateGrids(thisObj.vhostData) - - if (thisObj.details) - { - thisObj.details.update(thisObj.vhostData); - } - else - { - require(["qpid/management/virtualhost/" + thisObj.vhostData.type.toLowerCase() + "/show"], - function(VirtualHostDetails) - { - thisObj.details = new VirtualHostDetails({containerNode:thisObj.virtualHostDetailsContainer, parent: thisObj}); - thisObj.details.update(thisObj.vhostData); - } - ); - } - - }; - - Updater.prototype._updateGrids = function(data) - { - this.virtualHostChildren.style.display = data.state == "ACTIVE" ? "block" : "none"; - if (data.state == "ACTIVE" ) - { - util.updateUpdatableStore(this.queuesGrid, data.queues); - util.updateUpdatableStore(this.exchangesGrid, data.exchanges); - - var exchangesGrid = this.exchangesGrid.grid; - for(var i=0; i< data.exchanges.length; i++) - { - var item = exchangesGrid.getItem(i); - var isStandard = item && item.name && util.isReservedExchangeName(item.name); - exchangesGrid.rowSelectCell.setDisabled(i, isStandard); - } - this.virtualHostConnections.style.display = data.connections ? "block" : "none"; - util.updateUpdatableStore(this.connectionsGrid, data.connections); - } - }; - - - return VirtualHost; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/VirtualHostNode.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/VirtualHostNode.js deleted file mode 100644 index 837ff04c78..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/VirtualHostNode.js +++ /dev/null @@ -1,220 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/_base/connect", - "dijit/registry", - "dojox/html/entities", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/formatter", - "qpid/common/UpdatableStore", - "qpid/management/addQueue", - "qpid/management/addExchange", - "qpid/management/editVirtualHostNode", - "dojox/grid/EnhancedGrid", - "dojo/domReady!"], - function (xhr, parser, query, connect, registry, entities, properties, updater, util, formatter, UpdatableStore, addQueue, addExchange, editVirtualHostNode, EnhancedGrid) { - - function VirtualHostNode(name, parent, controller) - { - this.name = name; - this.controller = controller; - this.modelObj = { type: "virtualhostnode", name: name, parent: parent}; - } - - VirtualHostNode.prototype.getTitle = function() - { - return "VirtualHostNode: " + this.name; - }; - - VirtualHostNode.prototype.open = function(contentPane) - { - var that = this; - this.contentPane = contentPane; - xhr.get({url: "showVirtualHostNode.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - that.onOpen(contentPane.containerNode) - }); - }}); - - }; - - VirtualHostNode.prototype.onOpen = function(containerNode) - { - var that = this; - this.stopNodeButton = registry.byNode(query(".stopNodeButton", containerNode)[0]); - this.startNodeButton = registry.byNode(query(".startNodeButton", containerNode)[0]); - this.editNodeButton = registry.byNode(query(".editNodeButton", containerNode)[0]); - this.deleteNodeButton = registry.byNode(query(".deleteNodeButton", containerNode)[0]); - this.virtualHostGridPanel = registry.byNode(query(".virtualHostGridPanel", containerNode)[0]); - this.deleteNodeButton.on("click", - function(e) - { - if (confirm("Deletion of virtual host node will delete both configuration and message data.\n\n" - + "Are you sure you want to delete virtual host node '" + entities.encode(String(that.name)) + "'?")) - { - if (util.sendRequest("api/latest/virtualhostnode/" + encodeURIComponent( that.name) , "DELETE")) - { - that.destroy(); - } - } - } - ); - this.startNodeButton.on("click", - function(event) - { - that.startNodeButton.set("disabled", true); - util.sendRequest("api/latest/virtualhostnode/" + encodeURIComponent(that.name), - "PUT", {desiredState: "ACTIVE"}); - }); - - this.stopNodeButton.on("click", - function(event) - { - if (confirm("Stopping the node will also shutdown the virtual host. " - + "Are you sure you want to stop virtual host node '" - + entities.encode(String(that.name)) +"'?")) - { - that.stopNodeButton.set("disabled", true); - util.sendRequest("api/latest/virtualhostnode/" + encodeURIComponent(that.name), - "PUT", {desiredState: "STOPPED"}); - } - }); - - this.editNodeButton.on("click", - function(event) - { - editVirtualHostNode.show(that.vhostNodeUpdater.nodeData); - } - ); - - this.vhostsGrid = new UpdatableStore([], query(".virtualHost", containerNode)[0], - [ - { name: "Name", field: "name", width: "40%"}, - { name: "State", field: "state", width: "30%"}, - { name: "Type", field: "type", width: "30%"} - ], function(obj) { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - that.showVirtualHost(theItem); - }); - }, {height: 200, canSort : function(col) {return false;} }, EnhancedGrid); - - this.vhostNodeUpdater = new Updater(containerNode, this.modelObj, this); - this.vhostNodeUpdater.update(); - - updater.add( this.vhostNodeUpdater ); - } - - VirtualHostNode.prototype.showVirtualHost=function(item) - { - this.controller.show("virtualhost", item.name, this.modelObj, item.id); - } - - VirtualHostNode.prototype.close = function() - { - updater.remove( this.vhostNodeUpdater ); - }; - - VirtualHostNode.prototype.destroy = function() - { - this.close(); - this.contentPane.onClose() - this.controller.tabContainer.removeChild(this.contentPane); - this.contentPane.destroyRecursive(); - } - - function Updater(domNode, nodeObject, virtualHostNode) - { - this.virtualHostNode = virtualHostNode; - var that = this; - - function findNode(name) - { - return query("." + name, domNode)[0]; - } - - function storeNodes(names) - { - for(var i = 0; i < names.length; i++) - { - that[names[i]] = findNode(names[i]); - } - } - - storeNodes(["name", "state", "type"]); - this.detailsDiv = findNode("virtualhostnodedetails"); - - this.query = "api/latest/virtualhostnode/" + encodeURIComponent(nodeObject.name); - } - - Updater.prototype.update = function() - { - var that = this; - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then( - function(data) - { - that.nodeData = data[0]; - that.updateUI(data[0]); - } - ); - }; - - Updater.prototype.updateUI = function(data) - { - this.virtualHostNode.startNodeButton.set("disabled", !(data.state == "STOPPED" || data.state == "ERRORED")); - this.virtualHostNode.stopNodeButton.set("disabled", data.state != "ACTIVE"); - - this.name.innerHTML = entities.encode(String(data[ "name" ])); - this.state.innerHTML = entities.encode(String(data[ "state" ])); - this.type.innerHTML = entities.encode(String(data[ "type" ])); - if (!this.details) - { - var that = this; - require(["qpid/management/virtualhostnode/" + data.type.toLowerCase() + "/show"], - function(VirtualHostNodeDetails) - { - that.details = new VirtualHostNodeDetails({containerNode:that.detailsDiv, parent: that.virtualHostNode}); - that.details.update(data); - } - ); - } - else - { - this.details.update(data); - } - - - this.virtualHostNode.virtualHostGridPanel.domNode.style.display = data.virtualhosts? "block" : "none"; - util.updateUpdatableStore(this.virtualHostNode.vhostsGrid, data.virtualhosts); - } - - return VirtualHostNode; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/accesscontrolprovider/AclFile.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/accesscontrolprovider/AclFile.js deleted file mode 100644 index e8250217c6..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/accesscontrolprovider/AclFile.js +++ /dev/null @@ -1,96 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/parser", - "dojo/query", - "dojo/dom-construct", - "dojo/_base/connect", - "dojo/_base/window", - "dojo/_base/event", - "dojo/_base/json", - "dijit/registry", - "dojox/html/entities", - "qpid/common/util", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/UpdatableStore", - "dojox/grid/EnhancedGrid", - "dojox/grid/enhanced/plugins/Pagination", - "dojox/grid/enhanced/plugins/IndirectSelection", - "dojox/validate/us", "dojox/validate/web", - "dijit/Dialog", - "dijit/form/TextBox", - "dijit/form/ValidationTextBox", - "dijit/form/TimeTextBox", "dijit/form/Button", - "dijit/form/Form", - "dijit/form/DateTextBox", - "dojo/domReady!"], - function (xhr, dom, parser, query, construct, connect, win, event, json, registry, entities, util, properties, updater, UpdatableStore, EnhancedGrid) { - function AclFile(containerNode, aclProviderObj, controller) { - var node = construct.create("div", null, containerNode, "last"); - var that = this; - this.name = aclProviderObj.name; - xhr.get({url: "accesscontrolprovider/showAclFile.html", - sync: true, - load: function(data) { - node.innerHTML = data; - parser.parse(node).then(function(instances) - { - that.groupDatabaseUpdater= new AclFileUpdater(node, aclProviderObj, controller); - - updater.add( that.groupDatabaseUpdater); - - that.groupDatabaseUpdater.update(); - }); - - }}); - } - - AclFile.prototype.close = function() { - updater.remove( this.groupDatabaseUpdater ); - }; - - function AclFileUpdater(node, aclProviderObj, controller) - { - this.controller = controller; - this.query = "api/latest/accesscontrolprovider/"+encodeURIComponent(aclProviderObj.name); - this.name = aclProviderObj.name; - this.path = query(".path", node)[0]; - } - - AclFileUpdater.prototype.update = function() - { - var that = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}) - .then(function(data) { - if (data[0]) - { - that.aclProviderData = data[0]; - that.path.innerHTML = entities.encode(String(that.aclProviderData.path)); - } - }); - - }; - - return AclFile; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/accesscontrolprovider/aclfile/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/accesscontrolprovider/aclfile/add.js deleted file mode 100644 index 2c25149091..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/accesscontrolprovider/aclfile/add.js +++ /dev/null @@ -1,125 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/dom","dojo/query","dijit/registry","qpid/common/util"], - function (dom, query, registry, util) - { - var addACLFileAccessControlProvider = - { - init: function() - { - // Readers are HTML5 - this.reader = window.FileReader ? new FileReader() : undefined; - }, - show: function(data) - { - var that=this; - util.parseHtmlIntoDiv(data.containerNode, "accesscontrolprovider/aclfile/add.html", function(){that._postParse(data);}); - }, - _postParse: function(data) - { - var that=this; - this.aclServerPath = registry.byId("addAccessControlProvider.serverPath"); - this.aclUploadFields = dom.byId("addAccessControlProvider.uploadFields"); - this.aclSelectedFileContainer = dom.byId("addAccessControlProvider.selectedFile"); - this.aclSelectedFileStatusContainer = dom.byId("addAccessControlProvider.selectedFileStatus"); - this.aclFile = registry.byId("addAccessControlProvider.file"); - this.aclFileClearButton = registry.byId("addAccessControlProvider.fileClearButton"); - this.aclFileOldBrowserWarning = dom.byId("addAccessControlProvider.oldBrowserWarning"); - - //Only submitted field - this.aclPath = registry.byId("addAccessControlProvider.path"); - - this.addButton = data.parent.addButton; - - if (this.reader) - { - this.reader.onload = function(evt) {that._aclUploadFileComplete(evt);}; - this.reader.onerror = function(ex) {console.error("Failed to load ACL file", ex);}; - this.aclFile.on("change", function(selected){that._aclFileChanged(selected)}); - this.aclFileClearButton.on("click", function(event){that._aclFileClearButtonClicked(event)}); - } - else - { - // Fall back for IE8/9 which do not support FileReader - this.aclUploadFields.style.display = "none"; - this.aclFileOldBrowserWarning.innerHTML = "File upload requires a more recent browser with HTML5 support"; - this.aclFileOldBrowserWarning.className = this.aclFileOldBrowserWarning.className.replace("hidden", ""); - } - - this.aclServerPath.on("blur", function(){that._aclServerPathChanged()}); - }, - _aclFileChanged: function (evt) - { - // We only ever expect a single file - var file = this.aclFile.domNode.children[0].files[0]; - - this.addButton.setDisabled(true); - this.aclSelectedFileContainer.innerHTML = file.name; - this.aclSelectedFileStatusContainer.className = "loadingIcon"; - - console.log("Beginning to read ACL file " + file.name); - this.reader.readAsDataURL(file); - }, - _aclUploadFileComplete: function(evt) - { - var reader = evt.target; - var result = reader.result; - console.log("ACL file read complete, contents " + result); - this.addButton.setDisabled(false); - this.aclSelectedFileStatusContainer.className = "loadedIcon"; - - this.aclServerPath.set("value", ""); - this.aclServerPath.setDisabled(true); - this.aclServerPath.set("required", false); - - this.aclFileClearButton.setDisabled(false); - - this.aclPath.set("value", result); - }, - _aclFileClearButtonClicked: function(event) - { - this.aclFile.reset(); - this.aclSelectedFileStatusContainer.className = ""; - this.aclSelectedFileContainer.innerHTML = ""; - this.aclServerPath.set("required", true); - this.aclServerPath.setDisabled(false); - this.aclFileClearButton.setDisabled(true); - - this.aclPath.set("value", ""); - }, - _aclServerPathChanged: function() - { - var serverPathValue = this.aclServerPath.get("value"); - this.aclPath.set("value", serverPathValue); - } - }; - - try - { - addACLFileAccessControlProvider.init(); - } - catch(e) - { - console.warn(e); - } - return addACLFileAccessControlProvider; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addAccessControlProvider.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addAccessControlProvider.js deleted file mode 100644 index d961a31e52..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addAccessControlProvider.js +++ /dev/null @@ -1,149 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/lang", - "dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - 'dojo/json', - "qpid/common/util", - "qpid/common/metadata", - "dojo/text!addAccessControlProvider.html", - "dojo/store/Memory", - "dojox/validate/us", - "dojox/validate/web", - "dijit/Dialog", - "dijit/form/CheckBox", - "dijit/form/Textarea", - "dijit/form/ComboBox", - "dijit/form/TextBox", - "dijit/form/ValidationTextBox", - "dijit/form/Button", - "dijit/form/Form", - "dijit/layout/ContentPane", - "dojox/layout/TableContainer", - "dojo/domReady!"], - function (lang, xhr, dom, construct, registry, parser, array, event, json, util, metadata, template) - { - - var addAccessControlProvider = - { - init: function() - { - var that=this; - this.containerNode = construct.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances){ that._postParse(); }); - }, - _postParse: function() - { - var that=this; - this.accessControlProviderName = registry.byId("addAccessControlProvider.name"); - this.accessControlProviderName.set("regExpGen", util.nameOrContextVarRegexp); - - this.dialog = registry.byId("addAccessControlProvider"); - this.addButton = registry.byId("addAccessControlProvider.addButton"); - this.cancelButton = registry.byId("addAccessControlProvider.cancelButton"); - this.cancelButton.on("click", function(e){that._cancel(e);}); - this.addButton.on("click", function(e){that._add(e);}); - - this.accessControlProviderTypeFieldsContainer = dom.byId("addAccessControlProvider.typeFields"); - this.accessControlProviderForm = registry.byId("addAccessControlProvider.form"); - this.accessControlProviderType = registry.byId("addAccessControlProvider.type"); - this.supportedAccessControlProviderTypes = metadata.getTypesForCategory("AccessControlProvider"); - this.supportedAccessControlProviderTypes.sort(); - var accessControlProviderTypeStore = util.makeTypeStore(this.supportedAccessControlProviderTypes); - this.accessControlProviderType.set("store", accessControlProviderTypeStore); - this.accessControlProviderType.on("change", function(type){that._accessControlProviderTypeChanged(type);}); - }, - show: function(effectiveData) - { - this.accessControlProviderForm.reset(); - this.dialog.show(); - }, - _cancel: function(e) - { - event.stop(e); - if (this.reader) - { - this.reader.abort(); - } - this.dialog.hide(); - }, - _add: function(e) - { - event.stop(e); - this._submit(); - }, - _submit: function() - { - if (this.accessControlProviderForm.validate()) - { - var accessControlProviderData = util.getFormWidgetValues(this.accessControlProviderForm, this.initialData); - var that = this; - util.post("api/latest/accesscontrolprovider", accessControlProviderData, function(x){that.dialog.hide();}); - } - else - { - alert('Form contains invalid data. Please correct first'); - } - }, - _accessControlProviderTypeChanged: function(type) - { - this._typeChanged(type, this.accessControlProviderTypeFieldsContainer, "qpid/management/accesscontrolprovider/", "AccessControlProvider" ); - }, - _typeChanged: function(type, typeFieldsContainer, baseUrl, category ) - { - var widgets = registry.findWidgets(typeFieldsContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - construct.empty(typeFieldsContainer); - - if (type) - { - var that = this; - require([ baseUrl + type.toLowerCase() + "/add"], function(typeUI) - { - try - { - typeUI.show({containerNode:typeFieldsContainer, parent: that, data: that.initialData, effectiveData: that.effectiveData}); - util.applyMetadataToWidgets(typeFieldsContainer, category, type); - } - catch(e) - { - console.warn(e); - } - }); - } - } - }; - - try - { - addAccessControlProvider.init(); - } - catch(e) - { - console.warn(e); - } - return addAccessControlProvider; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addAuthenticationProvider.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addAuthenticationProvider.js deleted file mode 100644 index 3d85239789..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addAuthenticationProvider.js +++ /dev/null @@ -1,221 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - 'dojo/json', - "dojo/store/Memory", - "dijit/form/FilteringSelect", - "dojo/_base/connect", - "dojo/dom-style", - "qpid/common/util", - "qpid/common/metadata", - "dojo/text!addAuthenticationProvider.html", - "qpid/management/preferencesprovider/PreferencesProviderForm", - /* dojox/ validate resources */ - "dojox/validate/us", "dojox/validate/web", - /* basic dijit classes */ - "dijit/Dialog", - "dijit/form/CheckBox", "dijit/form/Textarea", - "dijit/form/TextBox", - "dijit/form/ValidationTextBox", - "dijit/form/Button", - "dijit/form/Form", - /* basic dojox classes */ - "dojox/form/BusyButton", "dojox/form/CheckedMultiSelect", - "dojox/layout/TableContainer", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, parser, array, event, json, Memory, FilteringSelect, connect, domStyle, util, metadata, template) - { - var addAuthenticationProvider = - { - init:function() - { - var that=this; - this.containerNode = construct.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances) { that._postParse(); }); - }, - _postParse: function() - { - var that = this; - this.authenticationProviderName = registry.byId("addAuthenticationProvider.name"); - this.authenticationProviderName.set("regExpGen", util.nameOrContextVarRegexp); - this.authenticationProviderName.on("change", function(newValue){that.preferencesProviderForm.preferencesProviderNameWidget.set("value",newValue);}); - - this.dialog = registry.byId("addAuthenticationProvider"); - this.addButton = registry.byId("addAuthenticationProvider.addButton"); - this.cancelButton = registry.byId("addAuthenticationProvider.cancelButton"); - this.cancelButton.on("click", function(e){that._cancel(e);}); - this.addButton.on("click", function(e){that._add(e);}); - - this.authenticationProviderTypeFieldsContainer = dom.byId("addAuthenticationProvider.typeFields"); - this.authenticationProviderForm = registry.byId("addAuthenticationProvider.form"); - this.authenticationProviderType = registry.byId("addAuthenticationProvider.type"); - this.supportedAuthenticationProviderTypes = metadata.getTypesForCategory("AuthenticationProvider"); - this.supportedAuthenticationProviderTypes.sort(); - var authenticationProviderTypeStore = util.makeTypeStore(this.supportedAuthenticationProviderTypes); - this.authenticationProviderType.set("store", authenticationProviderTypeStore); - this.authenticationProviderType.on("change", function(type){that._authenticationProviderTypeChanged(type);}); - - this.preferencesProviderForm = new qpid.preferencesprovider.PreferencesProviderForm({disabled: true}); - this.preferencesProviderForm.placeAt(dom.byId("addPreferencesProvider.form")); - }, - show:function(effectiveData) - { - this.authenticationProviderForm.reset(); - - if (effectiveData) - { - // editing - var actualData = null; - xhr.get( - { - url: "api/latest/authenticationprovider/" + encodeURIComponent(effectiveData.name), - sync: true, - content: { actuals: true }, - handleAs: "json", - load: function(data) - { - actualData = data[0]; - } - } - ); - this.initialData = actualData; - this.effectiveData = effectiveData; - this.authenticationProviderType.set("value", actualData.type); - - this.authenticationProviderType.set("disabled", true); - this.authenticationProviderName.set("disabled", true); - if (actualData.preferencesproviders && actualData.preferencesproviders[0]) - { - this.preferencesProviderForm.setData(actualData.preferencesproviders[0]); - } - else - { - this.preferencesProviderForm.reset(); - this.preferencesProviderForm.preferencesProviderNameWidget.set("value", actualData.name); - } - this.authenticationProviderName.set("value", actualData.name); - } - else - { - this.preferencesProviderForm.reset(); - this.authenticationProviderType.set("disabled", false); - this.authenticationProviderName.set("disabled", false); - this.initialData = {}; - this.effectiveData = {}; - } - - this.dialog.show(); - if (!this.resizeEventRegistered) - { - this.resizeEventRegistered = true; - util.resizeContentAreaAndRepositionDialog(dom.byId("addAuthenticationProvider.contentPane"), this.dialog); - } - }, - _cancel: function(e) - { - event.stop(e); - this.dialog.hide(); - }, - _add: function(e) - { - event.stop(e); - this._submit(); - }, - _submit: function() - { - if(this.authenticationProviderForm.validate() && this.preferencesProviderForm.validate()) - { - var authenticationProviderData = util.getFormWidgetValues(this.authenticationProviderForm, this.initialData); - - var that = this; - var encodedAuthenticationProviderName = encodeURIComponent(this.authenticationProviderName.value); - var url = "api/latest/authenticationprovider"; - if (this.initialData && this.initialData.id) - { - // update request - url += "/" + encodedAuthenticationProviderName; - } - util.post(url, authenticationProviderData, - function(x){ - var preferencesProviderResult = that.preferencesProviderForm.submit(encodedAuthenticationProviderName); - if (preferencesProviderResult.success == true) - { - that.dialog.hide(); - } - else - { - util.xhrErrorHandler(preferencesProviderResult.failureReason); - } - }); - } - else - { - alert('Form contains invalid data. Please correct first'); - } - }, - _authenticationProviderTypeChanged: function(type) - { - this._typeChanged(type, this.authenticationProviderTypeFieldsContainer, "qpid/management/authenticationprovider/", "AuthenticationProvider" ); - }, - _typeChanged: function(type, typeFieldsContainer, baseUrl, category ) - { - var widgets = registry.findWidgets(typeFieldsContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - construct.empty(typeFieldsContainer); - this.preferencesProviderForm.set("disabled", !type || !util.supportsPreferencesProvider(type)); - if (type) - { - var that = this; - require([ baseUrl + type.toLowerCase() + "/add"], function(typeUI) - { - try - { - typeUI.show({containerNode:typeFieldsContainer, parent: that, data: that.initialData, effectiveData: that.effectiveData}); - util.applyMetadataToWidgets(typeFieldsContainer, category, type); - } - catch(e) - { - console.warn(e); - } - }); - } - } - }; - - try - { - addAuthenticationProvider.init(); - } - catch(e) - { - console.warn(e); - } - return addAuthenticationProvider; - } - -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addBinding.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addBinding.js deleted file mode 100644 index 253861b5c5..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addBinding.js +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -define(["dojo/_base/connect", - "dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - 'dojo/_base/json', - "dojo/_base/lang", - "dojo/_base/declare", - "dojo/store/Memory", - "dijit/form/FilteringSelect", - "qpid/common/util", - "dijit/form/NumberSpinner", // required by the form - /* dojox/ validate resources */ - "dojox/validate/us", "dojox/validate/web", - /* basic dijit classes */ - "dijit/Dialog", - "dijit/form/CheckBox", "dijit/form/Textarea", - "dijit/form/FilteringSelect", "dijit/form/TextBox", - "dijit/form/ValidationTextBox", "dijit/form/DateTextBox", - "dijit/form/TimeTextBox", "dijit/form/Button", - "dijit/form/RadioButton", "dijit/form/Form", - "dijit/form/DateTextBox", - /* basic dojox classes */ - "dojox/form/BusyButton", "dojox/form/CheckedMultiSelect", - "dojox/grid/EnhancedGrid", - "dojo/data/ObjectStore", - "dojo/domReady!"], - function (connect, xhr, dom, construct, win, registry, parser, array, event, json, lang, declare, Memory, FilteringSelect, util) { - - var noLocalValues = new Memory({ - data: [ - {name:"true", id:true}, - {name:"false", id:false} - ] - }); - - var xMatchValues = new Memory({ - data: [ - {name:"all", id:"all"}, - {name:"any", id:"any"} - ] - }); - - var defaultBindingArguments = [ - {id: 0, name:"x-filter-jms-selector", value: null}, - {id: 1, name:"x-qpid-no-local", value: null} - ]; - - var GridWidgetProxy = declare("qpid.dojox.grid.cells.GridWidgetProxy", dojox.grid.cells._Widget, { - createWidget: function(inNode, inDatum, inRowIndex) - { - var WidgetClass = this.widgetClass; - var widgetProperties = this.getWidgetProps(inDatum); - var getWidgetProperties = widgetProperties.getWidgetProperties; - if (typeof getWidgetProperties == "function") - { - var item = this.grid.getItem(inRowIndex); - if (item) - { - var additionalWidgetProperties = getWidgetProperties(inDatum, inRowIndex, item); - if (additionalWidgetProperties) - { - WidgetClass = additionalWidgetProperties.widgetClass; - for(var prop in additionalWidgetProperties) - { - if(additionalWidgetProperties.hasOwnProperty(prop) && !widgetProperties[prop]) - { - widgetProperties[prop] = additionalWidgetProperties[ prop ]; - } - } - } - } - } - var widget = new WidgetClass(widgetProperties, inNode); - return widget; - }, - getValue: function(inRowIndex) - { - if (this.widget) - { - return this.widget.get('value'); - } - return null; - }, - _finish: function(inRowIndex) - { - if (this.widget) - { - this.inherited(arguments); - this.widget.destroyRecursive(); - this.widget = null; - } - } - }); - - var addBinding = {}; - - var node = construct.create("div", null, win.body(), "last"); - - var convertToBinding = function convertToBinding(formValues) - { - var newBinding = {}; - - newBinding.name = formValues.name; - for(var propName in formValues) - { - if(formValues.hasOwnProperty(propName)) - { - if(propName === "durable") - { - if (formValues.durable[0] && formValues.durable[0] == "durable") { - newBinding.durable = true; - } - } else { - if(formValues[ propName ] !== "") { - newBinding[ propName ] = formValues[propName]; - } - } - - } - } - if(addBinding.queue) { - newBinding.queue = addBinding.queue; - } - if(addBinding.exchange) { - newBinding.exchange = addBinding.exchange; - } - - addBinding.bindingArgumentsGrid.store.fetch({ - onComplete:function(items,request) - { - if(items.length) - { - array.forEach(items, function(item) - { - if (item && item.name && item.value) - { - var bindingArguments = newBinding.arguments; - if (!bindingArguments) - { - bindingArguments = {}; - newBinding.arguments = bindingArguments; - } - bindingArguments[item.name]=item.value; - } - }); - } - } - }); - return newBinding; - }; - - - xhr.get({url: "addBinding.html", - sync: true, - load: function(data) { - var theForm; - node.innerHTML = data; - addBinding.dialogNode = dom.byId("addBinding"); - parser.instantiate([addBinding.dialogNode]); - - theForm = registry.byId("formAddBinding"); - array.forEach(theForm.getDescendants(), function(widget) - { - if(widget.name === "type") { - widget.on("change", function(isChecked) { - - var obj = registry.byId(widget.id + ":fields"); - if(obj) { - if(isChecked) { - obj.domNode.style.display = "block"; - obj.resize(); - } else { - obj.domNode.style.display = "none"; - obj.resize(); - } - } - }) - } - - }); - - var argumentsGridNode = dom.byId("formAddbinding.bindingArguments"); - var objectStore = new dojo.data.ObjectStore({objectStore: new Memory({data:lang.clone(defaultBindingArguments), idProperty: "id"})}); - - var layout = [[ - { name: "Argument Name", field: "name", width: "50%", editable: true }, - { name: 'Argument Value', field: 'value', width: '50%', editable: true, type: GridWidgetProxy, - widgetProps: { - getWidgetProperties: function(inDatum, inRowIndex, item) - { - if (item.name == "x-qpid-no-local") - { - return { - labelAttr: "name", - searchAttr: "id", - selectOnClick: false, - query: { id: "*"}, - required: false, - store: noLocalValues, - widgetClass: dijit.form.FilteringSelect - }; - } - else if (item.name && item.name.toLowerCase() == "x-match") - { - return { - labelAttr: "name", - searchAttr: "id", - selectOnClick: false, - query: { id: "*"}, - required: false, - store: xMatchValues, - widgetClass: dijit.form.FilteringSelect - }; - } - return {widgetClass: dijit.form.TextBox }; - } - } - } - ]]; - - var grid = new dojox.grid.EnhancedGrid({ - selectionMode: "multiple", - store: objectStore, - singleClickEdit: true, - structure: layout, - autoHeight: true, - plugins: {indirectSelection: true} - }, argumentsGridNode); - grid.startup(); - - addBinding.bindingArgumentsGrid = grid; - addBinding.idGenerator = 1; - var addArgumentButton = registry.byId("formAddbinding.addArgumentButton"); - var deleteArgumentButton = registry.byId("formAddbinding.deleteArgumentButton"); - - var toggleGridButtons = function(index) - { - var data = grid.selection.getSelected(); - deleteArgumentButton.set("disabled", !data || data.length==0); - }; - connect.connect(grid.selection, 'onSelected', toggleGridButtons); - connect.connect(grid.selection, 'onDeselected', toggleGridButtons); - deleteArgumentButton.set("disabled", true); - - addArgumentButton.on("click", - function(event) - { - addBinding.idGenerator = addBinding.idGenerator + 1; - var newItem = {id:addBinding.idGenerator, name: "", value: ""}; - grid.store.newItem(newItem); - grid.store.save(); - grid.store.fetch( - { - onComplete:function(items,request) - { - var rowIndex = items.length - 1; - window.setTimeout(function() - { - grid.focus.setFocusIndex(rowIndex, 1 ); - },10); - } - }); - } - ); - - deleteArgumentButton.on("click", - function(event) - { - var data = grid.selection.getSelected(); - if(data.length) - { - array.forEach(data, function(selectedItem) { - if (selectedItem !== null) - { - grid.store.deleteItem(selectedItem); - } - }); - grid.store.save(); - } - } - ); - - theForm.on("submit", function(e) { - - event.stop(e); - if(theForm.validate()){ - - var newBinding = convertToBinding(theForm.getValues()); - var that = this; - var url = "api/latest/binding/"+encodeURIComponent(addBinding.vhostnode) - + "/"+encodeURIComponent(addBinding.vhost) - + "/"+encodeURIComponent(newBinding.exchange) - + "/"+encodeURIComponent(newBinding.queue); - util.post(url, newBinding, function(x){registry.byId("addBinding").hide();}); - return false; - }else{ - alert('Form contains invalid data. Please correct first'); - return false; - } - - }); - }}); - - addBinding.show = function(obj) { - var that = this; - - addBinding.vhostnode = obj.virtualhostnode; - addBinding.vhost = obj.virtualhost; - addBinding.queue = obj.queue; - addBinding.exchange = obj.exchange; - registry.byId("formAddBinding").reset(); - - var grid = addBinding.bindingArgumentsGrid; - grid.store.fetch({ - onComplete:function(items,request) - { - if(items.length) - { - array.forEach(items, function(item) - { - if (item !== null) - { - grid.store.deleteItem(item); - } - }); - } - } - }); - array.forEach(lang.clone(defaultBindingArguments), function(item) {grid.store.newItem(item); }); - grid.store.save(); - - xhr.get({url: "api/latest/queue/" + encodeURIComponent(obj.virtualhostnode) + "/" + encodeURIComponent(obj.virtualhost) + "?depth=0", - handleAs: "json"}).then( - function(data) { - var queues = []; - for(var i=0; i < data.length; i++) { - queues[i] = {id: data[i].name, name: data[i].name}; - } - var queueStore = new Memory({ data: queues }); - - - if(that.queueChooser) { - that.queueChooser.destroy( false ); - } - var queueDiv = dom.byId("addBinding.selectQueueDiv"); - var input = construct.create("input", {id: "addBindingSelectQueue"}, queueDiv); - - that.queueChooser = new FilteringSelect({ id: "addBindingSelectQueue", - name: "queue", - store: queueStore, - searchAttr: "name", - promptMessage: "Name of the queue", - title: "Select the name of the queue"}, input); - - if(obj.queue) - { - that.queueChooser.set("value", obj.queue); - that.queueChooser.set("disabled", true); - } - - xhr.get({url: "api/latest/exchange/" + encodeURIComponent(obj.virtualhostnode) + "/" + encodeURIComponent(obj.virtualhost) + "?depth=0", - handleAs: "json"}).then( - function(data) { - - var exchanges = []; - for(var i=0; i < data.length; i++) { - exchanges[i] = {id: data[i].name, name: data[i].name}; - } - var exchangeStore = new Memory({ data: exchanges }); - - - if(that.exchangeChooser) { - that.exchangeChooser.destroy( false ); - } - var exchangeDiv = dom.byId("addBinding.selectExchangeDiv"); - var input = construct.create("input", {id: "addBindingSelectExchange"}, exchangeDiv); - - that.exchangeChooser = new FilteringSelect({ id: "addBindingSelectExchange", - name: "exchange", - store: exchangeStore, - searchAttr: "name", - promptMessage: "Name of the exchange", - title: "Select the name of the exchange"}, input); - - if(obj.exchange) - { - that.exchangeChooser.set("value", obj.exchange); - that.exchangeChooser.set("disabled", true); - } - - - registry.byId("addBinding").show(); - }); - - - }); - - - }; - - return addBinding; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addExchange.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addExchange.js deleted file mode 100644 index 0385768889..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addExchange.js +++ /dev/null @@ -1,135 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/json", - "qpid/common/util", - "dijit/form/NumberSpinner", // required by the form - /* dojox/ validate resources */ - "dojox/validate/us", "dojox/validate/web", - /* basic dijit classes */ - "dijit/Dialog", - "dijit/form/CheckBox", "dijit/form/Textarea", - "dijit/form/FilteringSelect", "dijit/form/TextBox", - "dijit/form/ValidationTextBox", "dijit/form/DateTextBox", - "dijit/form/TimeTextBox", "dijit/form/Button", - "dijit/form/RadioButton", "dijit/form/Form", - "dijit/form/DateTextBox", - /* basic dojox classes */ - "dojox/form/BusyButton", "dojox/form/CheckedMultiSelect", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, parser, array, event, json, util) { - - var addExchange = {}; - - var node = construct.create("div", null, win.body(), "last"); - - var convertToExchange = function convertToExchange(formValues) - { - var newExchange = {}; - newExchange.name = formValues.name; - for(var propName in formValues) - { - if(formValues.hasOwnProperty(propName)) - { - if(propName === "durable") - { - if (formValues.durable[0] && formValues.durable[0] == "durable") { - newExchange.durable = true; - } - } else { - if(formValues[ propName ] !== "") { - newExchange[ propName ] = formValues[propName]; - } - } - - } - } - - return newExchange; - }; - - - xhr.get({url: "addExchange.html", - sync: true, - load: function(data) { - var theForm; - node.innerHTML = data; - addExchange.dialogNode = dom.byId("addExchange"); - parser.instantiate([addExchange.dialogNode]); - - theForm = registry.byId("formAddExchange"); - array.forEach(theForm.getDescendants(), function(widget) - { - if(widget.name === "type") { - widget.on("change", function(isChecked) { - - var obj = registry.byId(widget.id + ":fields"); - if(obj) { - if(isChecked) { - obj.domNode.style.display = "block"; - obj.resize(); - } else { - obj.domNode.style.display = "none"; - obj.resize(); - } - } - }) - } - - }); - - theForm.on("submit", function(e) { - - event.stop(e); - if(theForm.validate()){ - - var newExchange = convertToExchange(theForm.getValues()); - var that = this; - util.post("api/latest/exchange/" + encodeURIComponent(addExchange.vhostnode) - + "/" + encodeURIComponent(addExchange.vhost), - newExchange, function(x){ registry.byId("addExchange").hide(); }); - return false; - - - }else{ - alert('Form contains invalid data. Please correct first'); - return false; - } - - }); - }}); - - addExchange.show = function(data) { - addExchange.vhost = data.virtualhost; - addExchange.vhostnode = data.virtualhostnode; - registry.byId("formAddExchange").reset(); - registry.byId("addExchange").show(); - }; - - return addExchange; - });
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addGroupProvider.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addGroupProvider.js deleted file mode 100644 index b5491b4a6e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addGroupProvider.js +++ /dev/null @@ -1,178 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([ - "dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - 'dojo/json', - "qpid/common/util", - "qpid/common/metadata", - "dojo/text!addGroupProvider.html", - "dojo/store/Memory", - "dojox/validate/us", - "dojox/validate/web", - "dijit/Dialog", - "dijit/form/CheckBox", - "dijit/form/Textarea", - "dijit/form/ComboBox", - "dijit/form/TextBox", - "dijit/form/ValidationTextBox", - "dijit/form/Button", - "dijit/form/Form", - "dijit/layout/ContentPane", - "dojox/layout/TableContainer", - "dojo/domReady!"], - function (xhr, dom, construct, registry, parser, array, event, json, util, metadata, template) - { - - var addGroupProvider = - { - init: function() - { - var that=this; - this.containerNode = construct.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances) { that._postParse(); }); - }, - _postParse: function() - { - var that=this; - this.groupProviderName = registry.byId("addGroupProvider.name"); - this.groupProviderName.set("regExpGen", util.nameOrContextVarRegexp); - - this.dialog = registry.byId("addGroupProvider"); - this.addButton = registry.byId("addGroupProvider.addButton"); - this.cancelButton = registry.byId("addGroupProvider.cancelButton"); - this.cancelButton.on("click", function(e){that._cancel(e);}); - this.addButton.on("click", function(e){that._add(e);}); - - this.groupProviderTypeFieldsContainer = dom.byId("addGroupProvider.typeFields"); - this.groupProviderForm = registry.byId("addGroupProvider.form"); - - this.groupProviderType = registry.byId("addGroupProvider.type"); - this.groupProviderType.on("change", function(type){that._groupProviderTypeChanged(type);}); - - var supportedTypes = metadata.getTypesForCategory("GroupProvider"); - supportedTypes.sort(); - var supportedTypesStore = util.makeTypeStore(supportedTypes); - this.groupProviderType.set("store", supportedTypesStore); - }, - show: function(actualData) - { - this.initialData = actualData; - this.groupProviderForm.reset(); - - if (actualData) - { - this._destroyTypeFields(this.containerNode); - this._initFields(actualData); - } - this.groupProviderName.set("disabled", actualData == null ? false : true); - this.groupProviderType.set("disabled", actualData == null ? false : true); - this.dialog.set("title", actualData == null ? "Add Group Provider" : "Edit Group Provider - " + actualData.name) - this.dialog.show(); - }, - _initFields:function(data) - { - var type = data["type"]; - var attributes = metadata.getMetaData("GroupProvider", type).attributes; - for(var name in attributes) - { - var widget = registry.byId("addGroupProvider."+name); - if (widget) - { - widget.set("value", data[name]); - } - } - }, - _cancel: function(e) - { - event.stop(e); - this.dialog.hide(); - }, - _add: function(e) - { - event.stop(e); - this._submit(); - }, - _submit: function() - { - if (this.groupProviderForm.validate()) - { - var groupProviderData = util.getFormWidgetValues(this.groupProviderForm, this.initialData); - - var that = this; - var url = "api/latest/groupprovider"; - if (this.initialData) - { - // update request - url += "/" + encodeURIComponent(this.groupProviderName.value) - } - - util.post( url,groupProviderData, function(x){that.dialog.hide();}); - } - else - { - alert('Form contains invalid data. Please correct first'); - } - }, - _groupProviderTypeChanged: function(type) - { - this._destroyTypeFields(this.groupProviderTypeFieldsContainer); - if (type) - { - var that = this; - require([ "qpid/management/groupprovider/" + type.toLowerCase() + "/add"], function(typeUI) - { - try - { - typeUI.show({containerNode: that.groupProviderTypeFieldsContainer, parent: that, data: that.initialData}); - util.applyMetadataToWidgets(that.groupProviderTypeFieldsContainer, "GroupProvider", type); - } - catch(e) - { - console.warn(e); - } - }); - } - }, - _destroyTypeFields: function(typeFieldsContainer) - { - var widgets = registry.findWidgets(typeFieldsContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - construct.empty(typeFieldsContainer); - } - }; - - try - { - addGroupProvider.init(); - } - catch(e) - { - console.warn(e); - } - return addGroupProvider; - - });
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addPort.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addPort.js deleted file mode 100644 index aa3e43d604..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addPort.js +++ /dev/null @@ -1,476 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/_base/array", - "dojo/_base/event", - 'dojo/_base/json', - "dojo/store/Memory", - "dojo/data/ObjectStore", - "dijit/form/FilteringSelect", - "dojo/dom-style", - "dojo/_base/lang", - "qpid/common/util", - "qpid/common/metadata", - /* dojox/ validate resources */ - "dojox/validate/us", - "dojox/validate/web", - /* basic dijit classes */ - "dijit/Dialog", - "dijit/form/CheckBox", - "dijit/form/Textarea", - "dijit/form/TextBox", - "dijit/form/ValidationTextBox", - "dijit/form/DateTextBox", - "dijit/form/TimeTextBox", - "dijit/form/Button", - "dijit/form/RadioButton", - "dijit/form/Form", - "dijit/form/DateTextBox", - "dijit/form/MultiSelect", - "dijit/form/Select", - "dijit/form/NumberSpinner", - /* basic dojox classes */ - "dojox/grid/EnhancedGrid", - "dojox/grid/enhanced/plugins/IndirectSelection", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, array, event, json, Memory, ObjectStore, FilteringSelect, domStyle, lang, util, metadata) { - - var addPort = {}; - - var node = construct.create("div", null, win.body(), "last"); - - addPort._typeChanged = function (newValue) - { - var typeMetaData = metadata.getMetaData("Port", newValue); - - //protocols - var protocolsMultiSelect = dom.byId("formAddPort.protocols"); - var protocolValidValues = typeMetaData.attributes.protocols.validValues; - var protocolValues = metadata.extractUniqueListOfValues(protocolValidValues); - util.setMultiSelectOptions(protocolsMultiSelect, protocolValues.sort()); - - //authenticationProvider - registry.byId("formAddPort.authenticationProvider").set("disabled", ! ("authenticationProvider" in typeMetaData.attributes)); - dom.byId("formAddPort:fieldsAuthenticationProvider").style.display = "authenticationProvider" in typeMetaData.attributes ? "block" : "none"; - - //bindingAddress - registry.byId("formAddPort.bindingAddress").set("disabled", ! ("bindingAddress" in typeMetaData.attributes)); - dom.byId("formAddPort:fieldsBindingAddress").style.display = "bindingAddress" in typeMetaData.attributes ? "block" : "none"; - - //maxOpenConnections - registry.byId("formAddPort.maxOpenConnections").set("disabled", ! ("maxOpenConnections" in typeMetaData.attributes)); - dom.byId("formAddPort:maxOpenConnections").style.display = "maxOpenConnections" in typeMetaData.attributes ? "block" : "none"; - - //transports - var transportsMultiSelect = dom.byId("formAddPort.transports"); - var transportsValidValues = typeMetaData.attributes.transports.validValues; - var transportsValues = metadata.extractUniqueListOfValues(transportsValidValues); - util.setMultiSelectOptions(transportsMultiSelect, transportsValues.sort()); - - addPort._toggleSslWidgets(newValue, transportsMultiSelect.value); - util.applyMetadataToWidgets(registry.byId("addPort").domNode, "Port", newValue); - - }; - - addPort._isSecure = function(currentTransport) - { - return currentTransport == "SSL" || (lang.isArray(currentTransport) && array.indexOf(currentTransport, "SSL")>=0) - || currentTransport == "WSS" || (lang.isArray(currentTransport) && array.indexOf(currentTransport, "WSS")>=0); - } - - addPort._convertToPort = function(formValues) - { - var newPort = {}; - newPort.name = dijit.byId("formAddPort.name").value; - var id = dojo.byId("formAddPort.id").value; - if (id) - { - newPort.id = id; - } - for(var propName in formValues) - { - if(formValues.hasOwnProperty(propName) && formValues[propName]) - { - if (propName == "needClientAuth" || propName == "wantClientAuth") - { - continue; - } - else if (propName === "protocols") - { - var val = formValues[propName]; - - if(val === "" || (lang.isArray(val) && val.length == 0) ) - { - continue; - } - - if (!lang.isArray(val)) - { - val = [ val ]; - } - newPort[ propName ] = val; - } - else if (propName === "transports") - { - var val = formValues[propName]; - - if(val === "" || (lang.isArray(val) && val.length == 0) ) - { - continue; - } - - if (!lang.isArray(val)) - { - val = [ val ]; - } - newPort[ propName ] = val; - } - else if(formValues[ propName ] !== "") - { - newPort[ propName ] = formValues[propName]; - } - - } - } - - var type = dijit.byId("formAddPort.type").value; - if (type == "AMQP" || type == "HTTP") - { - var transportWidget = registry.byId("formAddPort.transports"); - var needClientAuth = dijit.byId("formAddPort.needClientAuth"); - var wantClientAuth = dijit.byId("formAddPort.wantClientAuth"); - var trustStoreWidget = dijit.byId("formAddPort.trustStores"); - - var initialTransport = transportWidget.initialValue; - var currentTransport = transportWidget.value; - if (addPort._isSecure(currentTransport)) - { - newPort.needClientAuth = needClientAuth.checked; - newPort.wantClientAuth = wantClientAuth.checked - - var items = trustStoreWidget.selection.getSelected(); - var trustStores = []; - if(items.length > 0){ - for(var i in items) - { - var item = items[i]; - trustStores.push(trustStoreWidget.store.getValue(item, "name")); - } - newPort.trustStores = trustStores; - } - else if (trustStoreWidget.initialValue && trustStoreWidget.initialValue.length > 0) - { - newPort.trustStores = null; - } - } - else if (initialTransport && currentTransport != initialTransport) - { - newPort.needClientAuth = false; - newPort.wantClientAuth = false; - newPort.trustStores = null; - } - } - - return newPort; - }; - - addPort._toggleSslWidgets = function(portType, transportType) - { - var clientAuthPanel = dojo.byId("formAddPort:fieldsClientAuth"); - var transportSSLPanelNode = dom.byId("formAddPort:fieldsTransportSSL"); - - if (addPort._isSecure(transportType)) - { - var typeMetaData = metadata.getMetaData("Port", portType); - var clientAuth = "needClientAuth" in typeMetaData.attributes || "wantClientAuth" in typeMetaData.attributes; - clientAuthPanel.style.display = clientAuth ? "block" : "none"; - if (clientAuth) - { - registry.byId("formAddPort.needClientAuth").set("disabled", !("needClientAuth" in typeMetaData.attributes)); - registry.byId("formAddPort.wantClientAuth").set("disabled", !("wantClientAuth" in typeMetaData.attributes)); - registry.byId("formAddPort.trustStores").resize(); - } - - transportSSLPanelNode.style.display = "block"; - registry.byId("formAddPort.keyStore").set("disabled", false); - } - else - { - clientAuthPanel.style.display = "none"; - registry.byId("formAddPort.needClientAuth").set("disabled", true); - registry.byId("formAddPort.wantClientAuth").set("disabled", true); - - transportSSLPanelNode.style.display = "none"; - registry.byId("formAddPort.keyStore").set("disabled", true); - } - - }; - - addPort._init = function() - { - xhr.get({url: "addPort.html", sync: true, load: function (data) - { - var theForm; - node.innerHTML = data; - addPort.dialogNode = dom.byId("addPort"); - }}); - } - - addPort._prepareForm = function() - { - //add the port types to formAddPort.type - var portTypeSelect = registry.byId("formAddPort.type"); - var supportedPortTypes = metadata.getTypesForCategory("Port"); - var portTypeSelectStore = util.makeTypeStore(supportedPortTypes); - portTypeSelect.set("store", portTypeSelectStore); - - //add handler for transports change - registry.byId("formAddPort.transports").on("change", function (newValue) - { - var portType = portTypeSelect.get("value"); - addPort._toggleSslWidgets(portType, newValue); - }); - - theForm = registry.byId("formAddPort"); - theForm.on("submit", function (e) - { - - event.stop(e); - if (theForm.validate()) - { - - var newPort = addPort._convertToPort(theForm.getValues()); - if ((newPort.needClientAuth || newPort.wantClientAuth) && (!newPort.hasOwnProperty("trustStores") || newPort.trustStores.length == 0)) - { - alert("A trust store must be selected when requesting client certificates."); - return false; - } - var url = "api/latest/port"; - if (registry.byId("formAddPort.name").get("disabled")) - { - // update request - url += "/" + encodeURIComponent(newPort.name); - } - util.post(url, newPort, function(x){registry.byId("addPort").hide()}); - return false; - } else - { - alert('Form contains invalid data. Please correct first'); - return false; - } - - }); - } - - addPort.show = function(portName, portType, providers, keystores, truststores) - { - - if (!this.formPrepared) - { - this._prepareForm(); - this.formPrepared = true; - } - - registry.byId("formAddPort").reset(); - dojo.byId("formAddPort.id").value = ""; - - var nameWidget = registry.byId("formAddPort.name"); - var typeWidget = registry.byId("formAddPort.type"); - var portWidget = registry.byId("formAddPort.port"); - var maxOpenConnectionsWidget = registry.byId("formAddPort.maxOpenConnections"); - var editWarning = dojo.byId("portEditWarning"); - - var providerWidget = registry.byId("formAddPort.authenticationProvider"); - if (providers) - { - var data = []; - for (var i=0; i< providers.length; i++) - { - data.push( {id: providers[i].name, name: providers[i].name} ); - } - var providersStore = new Memory({ data: data }); - providerWidget.set("store", providersStore); - providerWidget.startup(); - } - - var keystoreWidget = registry.byId("formAddPort.keyStore"); - if (keystores) - { - var data = []; - for (var i=0; i< keystores.length; i++) - { - data.push( {id: keystores[i].name, name: keystores[i].name} ); - } - var keystoresStore = new Memory({ data: data }); - keystoreWidget.set("store", keystoresStore); - keystoreWidget.startup(); - } - - var truststoreWidget = registry.byId("formAddPort.trustStores"); - if (truststores) - { - var layout = [[{name: "Name", field: "name", width: "80%"}, - {name: "Peers only", field: "peersOnly", width: "20%", - formatter: function(val){ - return "<input type='radio' disabled='disabled' "+(val?"checked='checked'": "")+" />" - } - }]]; - - var mem = new Memory({ data: truststores, idProperty: "id"}); - truststoreWidget.set("store", new ObjectStore({objectStore: mem})); - truststoreWidget.set("structure", layout); - truststoreWidget.rowSelectCell.toggleAllSelection(false); - truststoreWidget.startup(); - } - - // Editing existing port, de-register existing on change handler if set - if (this.typeChangeHandler) - { - this.typeChangeHandler.remove(); - } - - if (portName) - { - editWarning.style.display = "block"; - - xhr.get({ - url: "api/latest/port/" + encodeURIComponent(portName), - content: { actuals: true }, - handleAs: "json" - }).then( - function(data){ - var port = data[0]; - nameWidget.set("value", port.name); - nameWidget.set("disabled", true); - - dom.byId("formAddPort.id").value=port.id; - - //type - typeWidget.set("value", portType); - typeWidget.set("disabled", true); - var typeMetaData = metadata.getMetaData("Port", portType); - - //port number - portWidget.set("value", port.port); - portWidget.set("regExpGen", util.numericOrContextVarRegexp); - - //protocols - var protocolsMultiSelect = dom.byId("formAddPort.protocols"); - var protocolValidValues = typeMetaData.attributes.protocols.validValues; - var protocolValues = metadata.extractUniqueListOfValues(protocolValidValues); - util.setMultiSelectOptions(protocolsMultiSelect, protocolValues.sort()); - - var protocolsMultiSelectWidget = registry.byId("formAddPort.protocols"); - protocolsMultiSelectWidget.set("value", port.protocols); - - //authenticationProvider - providerWidget.set("value", port.authenticationProvider ? port.authenticationProvider : ""); - providerWidget.set("disabled", ! ("authenticationProvider" in typeMetaData.attributes)); - dom.byId("formAddPort:fieldsAuthenticationProvider").style.display = "authenticationProvider" in typeMetaData.attributes ? "block" : "none"; - - //transports - var transportsMultiSelect = dom.byId("formAddPort.transports"); - var transportsValidValues = typeMetaData.attributes.transports.validValues; - var transportsValues = metadata.extractUniqueListOfValues(transportsValidValues); - util.setMultiSelectOptions(transportsMultiSelect, transportsValues.sort()); - var transportWidget = registry.byId("formAddPort.transports"); - transportWidget.set("value", port.transports); - - //binding address - var bindAddressWidget = registry.byId("formAddPort.bindingAddress"); - bindAddressWidget.set("value", port.bindingAddress ? port.bindingAddress : ""); - bindAddressWidget.set("disabled", ! ("bindingAddress" in typeMetaData.attributes)); - dom.byId("formAddPort:fieldsBindingAddress").style.display = "bindingAddress" in typeMetaData.attributes ? "block" : "none"; - - //maxOpenConnections - var maxOpenConnectionsWidget = registry.byId("formAddPort.maxOpenConnections"); - maxOpenConnectionsWidget.set("regExpGen", util.signedOrContextVarRegexp); - maxOpenConnectionsWidget.set("value", port.maxOpenConnections ? port.maxOpenConnections : ""); - maxOpenConnectionsWidget.set("disabled", ! ("maxOpenConnections" in typeMetaData.attributes)); - dom.byId("formAddPort:maxOpenConnections").style.display = "maxOpenConnections" in typeMetaData.attributes ? "block" : "none"; - - //ssl - keystoreWidget.set("value", port.keyStore ? port.keyStore : ""); - if (port.trustStores) - { - var items = truststoreWidget.store.objectStore.data; - for (var j=0; j< items.length; j++) - { - var selected = false; - for (var i=0; i< port.trustStores.length; i++) - { - var trustStore = port.trustStores[i]; - if (items[j].name == trustStore) - { - selected = true; - break; - } - } - truststoreWidget.selection.setSelected(j,selected); - } - } - - // want/need client auth - registry.byId("formAddPort.needClientAuth").set("checked", port.needClientAuth); - registry.byId("formAddPort.wantClientAuth").set("checked", port.wantClientAuth); - - keystoreWidget.initialValue = port.keyStore; - truststoreWidget.initialValue = port.trustStores; - transportWidget.initialValue = transportWidget.value; - providerWidget.initialValue = providerWidget.value; - maxOpenConnectionsWidget.initialValue = maxOpenConnectionsWidget.value; - - registry.byId("addPort").show(); - util.applyMetadataToWidgets(registry.byId("addPort").domNode, "Port", portType); - }); - } - else - { - // Adding new port, register the on change handler - this.typeChangeHandler = typeWidget.on("change", addPort._typeChanged); - - if (typeWidget.get("disabled")) - { - typeWidget.set("disabled", false); - } - typeWidget.set("value", portType); - - nameWidget.set("disabled", false); - nameWidget.set("regExpGen", util.nameOrContextVarRegexp); - portWidget.set("regExpGen", util.numericOrContextVarRegexp); - maxOpenConnectionsWidget.set("regExpGen", util.signedOrContextVarRegexp); - - editWarning.style.display = "none"; - registry.byId("addPort").show(); - - util.applyMetadataToWidgets(registry.byId("addPort").domNode, "Port", portType); - } - - }; - - addPort._init(); - - return addPort; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addPreferencesProvider.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addPreferencesProvider.js deleted file mode 100644 index 2136318dfb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addPreferencesProvider.js +++ /dev/null @@ -1,94 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([ - "dojo/_base/event", - "dojo/dom-construct", - "dojo/parser", - "dijit/registry", - "qpid/management/preferencesprovider/PreferencesProviderForm", - "qpid/common/util", - "dojo/text!addPreferencesProvider.html", - "dojox/html/entities", - "dojox/validate/us", - "dojox/validate/web", - "dijit/Dialog", - "dijit/form/Button", - "dojo/domReady!"], - function ( event, construct, parser, registry, PreferencesProviderForm, util, template, entities) { - - var addPreferencesProvider = - { - init: function() - { - var that=this; - this.containerNode = construct.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances) { that._postParse(); }); - }, - _postParse: function() - { - var that=this; - this.preferencesProviderForm = registry.byId("addPreferencesProvider.preferencesProvider"); - this.dialog = registry.byId("addPreferencesProvider"); - - var cancelButton = registry.byId("addPreferencesProvider.cancelButton"); - cancelButton.on("click", function() { that.dialog.hide(); }); - - var saveButton = registry.byId("addPreferencesProvider.saveButton"); - saveButton.on("click", function() - { - var result = that.preferencesProviderForm.submit(encodeURIComponent(addPreferencesProvider.authenticationProviderName)); - if (result.success) - { - that.dialog.hide(); - } - else - { - util.xhrErrorHandler(result.failureReason); - } - }); - }, - show: function(authenticationProviderName, providerName) - { - this.authenticationProviderName = authenticationProviderName; - this.dialog.set("title", (providerName ? "Edit preferences provider '" + entities.encode(String(providerName)) + "' " : "Add preferences provider ") + " for '" + entities.encode(String(authenticationProviderName)) + "' "); - if (providerName) - { - this.preferencesProviderForm.load(authenticationProviderName, providerName); - } - else - { - this.preferencesProviderForm.reset(); - } - this.dialog.show(); - } - }; - - try - { - addPreferencesProvider.init(); - } - catch(e) - { - console.warn("Initialisation of add preferences dialog failed", e); - } - - return addPreferencesProvider; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addQueue.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addQueue.js deleted file mode 100644 index 8b2c60933d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addQueue.js +++ /dev/null @@ -1,185 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - 'dojo/_base/json', - "dojo/query", - 'qpid/common/util', - "qpid/common/ContextVariablesEditor", - "dijit/form/NumberSpinner", // required by the form - /* dojox/ validate resources */ - "dojox/validate/us", "dojox/validate/web", - /* basic dijit classes */ - "dijit/Dialog", - "dijit/form/CheckBox", "dijit/form/Textarea", - "dijit/form/FilteringSelect", "dijit/form/TextBox", - "dijit/form/ValidationTextBox", "dijit/form/DateTextBox", - "dijit/form/TimeTextBox", "dijit/form/Button", - "dijit/form/RadioButton", "dijit/form/Form", - "dijit/form/DateTextBox", - /* basic dojox classes */ - "dojox/form/BusyButton", "dojox/form/CheckedMultiSelect", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, parser, array, event, json, query, util) { - - var addQueue = {}; - - var node = construct.create("div", null, win.body(), "last"); - - var typeSpecificFields = { priorities: "priority", lvqKey: "lvq", sortKey: "sorted" }; - var requiredFields = { sorted: "sortKey"}; - - var fieldConverters = { - queueFlowControlSizeBytes: parseInt, - queueFlowResumeSizeBytes: parseInt, - alertThresholdMessageSize: parseInt, - alertThresholdQueueDepthMessages: parseInt, - alertThresholdQueueDepthBytes: parseInt, - maximumDeliveryAttempts: parseInt, - alertThresholdMessageAge: parseInt, - alertRepeatGap: parseInt - } - - var convertToQueue = function convertToQueue(formValues) - { - var newQueue = {}; - newQueue.name = formValues.name; - for(var propName in formValues) - { - if(formValues.hasOwnProperty(propName)) - { - if(propName === "durable") - { - if (formValues.durable[0] && formValues.durable[0] == "durable") { - newQueue.durable = true; - } - } - else if(propName === "dlqEnabled") - { - if (formValues.dlqEnabled[0] && formValues.dlqEnabled[0] == "dlqEnabled") { - newQueue["x-qpid-dlq-enabled"] = true; - } - } - else if(propName === "messageGroupSharedGroups") - { - if (formValues.messageGroupSharedGroups[0] && formValues.messageGroupSharedGroups[0] == "messageGroupSharedGroups") { - newQueue["messageGroupSharedGroups"] = true; - } - } - else if (!typeSpecificFields.hasOwnProperty(propName) || formValues[ "type" ] === typeSpecificFields[ propName ]) - { - if(formValues[ propName ] !== "") { - if (fieldConverters.hasOwnProperty(propName)) - { - newQueue[ propName ] = fieldConverters[propName](formValues[propName]); - } - else - { - newQueue[ propName ] = formValues[propName]; - } - } - } - - } - } - - return newQueue; - }; - - - xhr.get({url: "addQueue.html", - sync: true, - load: function(data) { - var theForm; - node.innerHTML = data; - addQueue.dialogNode = dom.byId("addQueue"); - parser.instantiate([addQueue.dialogNode]); - - // for children which have name type, add a function to make all the associated atrributes - // visible / invisible as the select is changed - theForm = registry.byId("formAddQueue"); - var typeSelector = registry.byId("formAddQueue.type"); - typeSelector.on("change", function(value) - { - query(".typeSpecificDiv").forEach(function(node, index, arr) - { - if (node.id === "formAddQueueType:" + value) - { - node.style.display = "block"; - util.applyMetadataToWidgets(node, "Queue", value); - } - else - { - node.style.display = "none"; - } - }); - for(var requiredField in requiredFields) - { - dijit.byId('formAddQueue.' + requiredFields[requiredField]).required = (requiredField == value); - } - }); - - theForm.on("submit", function(e) { - - event.stop(e); - if(theForm.validate()){ - - var newQueue = convertToQueue(theForm.getValues()); - util.post("api/latest/queue/" + encodeURIComponent(addQueue.vhostnode) - + "/"+encodeURIComponent(addQueue.vhost), - newQueue, function(x){registry.byId("addQueue").hide();}); - return false; - - - }else{ - alert('Form contains invalid data. Please correct first'); - return false; - } - - }); - }}); - - addQueue.show = function(data) { - addQueue.vhost = data.virtualhost; - addQueue.vhostnode = data.virtualhostnode; - var form = registry.byId("formAddQueue"); - form.reset(); - registry.byId("addQueue").show(); - util.applyMetadataToWidgets(form.domNode, "Queue", "standard"); - - if (!this.context) - { - this.context = new qpid.common.ContextVariablesEditor({name: 'context', title: 'Context variables'}); - this.context.placeAt(dom.byId("formAddQueue.context")); - } - - var escapedUrl = "api/latest/virtualhost/" + encodeURIComponent(addQueue.vhostnode) + "/" + encodeURIComponent(addQueue.vhost); - this.context.loadInheritedData(escapedUrl); - }; - - return addQueue; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addStore.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addStore.js deleted file mode 100644 index f0bdb0cefa..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addStore.js +++ /dev/null @@ -1,189 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/lang", - "dojo/dom", - "dojo/dom-construct", - "dijit/registry", - "dojo/parser", - "dojo/store/Memory", - "dojo/_base/array", - "dojo/_base/event", - 'dojo/json', - "qpid/common/util", - "qpid/common/metadata", - "dojo/text!addStore.html", - "dojo/store/Memory", - "dojox/validate/us", - "dojox/validate/web", - "dijit/Dialog", - "dijit/form/CheckBox", - "dijit/form/Textarea", - "dijit/form/ComboBox", - "dijit/form/TextBox", - "dijit/form/ValidationTextBox", - "dijit/form/Button", - "dijit/form/Form", - "dijit/layout/ContentPane", - "dojox/layout/TableContainer", - "dojo/domReady!"], - function (lang, dom, construct, registry, parser, memory, array, event, json, util, metadata, template) - { - var addStore = - { - init: function() - { - var that=this; - this.containerNode = construct.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances) { that._postParse(); }); - }, - _postParse: function() - { - var that=this; - this.storeName = registry.byId("addStore.name"); - this.storeName.set("regExpGen", util.nameOrContextVarRegexp); - - this.dialog = registry.byId("addStore"); - this.addButton = registry.byId("addStore.addButton"); - this.cancelButton = registry.byId("addStore.cancelButton"); - this.cancelButton.on("click", function(e){that._cancel(e);}); - this.addButton.on("click", function(e){that._add(e);}); - - this.storeTypeFieldsContainer = dom.byId("addStore.typeFields"); - this.storeForm = registry.byId("addStore.form"); - - this.storeType = registry.byId("addStore.type"); - this.storeType.on("change", function(type){that._storeTypeChanged(type);}); - }, - setupTypeStore: function(category) - { - this.category = category; - var storeTypeSupportedTypes = metadata.getTypesForCategory(category); - storeTypeSupportedTypes.sort(); - var storeTypeStore = util.makeTypeStore(storeTypeSupportedTypes); - this.storeType.set("store", storeTypeStore); - }, - show: function(effectiveData) - { - this.effectiveData = effectiveData; - this._destroyTypeFields(this.containerNode); - this.storeForm.reset(); - - if (effectiveData) - { - this._initFields(effectiveData); - } - this.storeName.set("disabled", effectiveData == null ? false : true); - this.storeType.set("disabled", effectiveData == null ? false : true); - this.dialog.set("title", effectiveData == null ? "Add Key Store" : "Edit Key Store - " + effectiveData.name) - this.dialog.show(); - }, - _initFields:function(data) - { - var type = data["type"]; - var attributes = metadata.getMetaData(this.category, type).attributes; - for(var name in attributes) - { - var widget = registry.byId("addStore."+name); - if (widget) - { - widget.set("value", data[name]); - } - } - }, - _cancel: function(e) - { - event.stop(e); - if (this.reader) - { - this.reader.abort(); - } - this.dialog.hide(); - }, - _add: function(e) - { - event.stop(e); - this._submit(); - }, - _submit: function() - { - if (this.storeForm.validate()) - { - var success = false,failureReason=null; - - var storeData = util.getFormWidgetValues(this.storeForm, this.initialData); - var that = this; - var url = "api/latest/" + encodeURIComponent(this.category.toLowerCase()); - - if (this.effectiveData) - { - // update request - url += "/" + encodeURIComponent(this.storeName.value); - } - util.post(url, storeData, function(x){that.dialog.hide();}); - } - else - { - alert('Form contains invalid data. Please correct first'); - } - }, - _storeTypeChanged: function(type) - { - this._typeChanged(type, this.storeTypeFieldsContainer, "qpid/management/store/", this.category ); - }, - _destroyTypeFields: function(typeFieldsContainer) - { - var widgets = registry.findWidgets(typeFieldsContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - construct.empty(typeFieldsContainer); - }, - _typeChanged: function(type, typeFieldsContainer, baseUrl, category ) - { - this._destroyTypeFields(typeFieldsContainer); - - if (type) - { - var that = this; - require([ baseUrl + type.toLowerCase() + "/add"], function(typeUI) - { - try - { - typeUI.show({containerNode:typeFieldsContainer, parent: that, data: that.initialData, effectiveData: that.effectiveData}); - util.applyMetadataToWidgets(typeFieldsContainer, category, type); - } - catch(e) - { - console.warn(e); - } - }); - } - } - }; - - try - { - addStore.init(); - } - catch(e) - { - console.warn(e); - } - return addStore; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addVirtualHostNodeAndVirtualHost.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addVirtualHostNodeAndVirtualHost.js deleted file mode 100644 index 9131df0582..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addVirtualHostNodeAndVirtualHost.js +++ /dev/null @@ -1,409 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([ - "dojo/_base/event", - "dojo/_base/lang", - "dojo/_base/array", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dojo/parser", - "dojo/store/Memory", - "dojo/window", - "dojo/on", - "dojox/lang/functional/object", - "dijit/registry", - "dijit/Dialog", - "dijit/form/Button", - "dijit/form/FilteringSelect", - "qpid/common/properties", - "qpid/common/util", - "qpid/common/metadata", - "dojo/text!addVirtualHostNodeAndVirtualHost.html", - "qpid/common/ContextVariablesEditor", - "dijit/TitlePane", - "dijit/layout/ContentPane", - "dijit/form/Form", - "dijit/form/CheckBox", - "dijit/form/RadioButton", - "dojox/form/Uploader", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], - function (event, lang, array, dom, domConstruct, json, parser, Memory, win, on, fobject, registry, Dialog, Button, FilteringSelect, properties, util, metadata, template) - { - - var addVirtualHostNodeAndVirtualHost = - { - init: function() - { - var that=this; - this.containerNode = domConstruct.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances) { that._postParse(); }); - }, - _postParse: function() - { - var that=this; - var virtualHostNodeName = registry.byId("addVirtualHostNode.nodeName"); - virtualHostNodeName.set("regExpGen", util.nameOrContextVarRegexp); - - // Readers are HTML5 - this.reader = window.FileReader ? new FileReader() : undefined; - - this.dialog = registry.byId("addVirtualHostNodeAndVirtualHost"); - this.addButton = registry.byId("addVirtualHostNodeAndVirtualHost.addButton"); - this.cancelButton = registry.byId("addVirtualHostNodeAndVirtualHost.cancelButton"); - this.cancelButton.on("click", function(e){that._cancel(e);}); - this.addButton.on("click", function(e){that._add(e);}); - - this.virtualHostNodeTypeFieldsContainer = dom.byId("addVirtualHostNode.typeFields"); - this.virtualHostNodeSelectedFileContainer = dom.byId("addVirtualHostNode.selectedFile"); - this.virtualHostNodeSelectedFileStatusContainer = dom.byId("addVirtualHostNode.selectedFileStatus"); - this.virtualHostNodeUploadFields = dom.byId("addVirtualHostNode.uploadFields"); - this.virtualHostNodeFileFields = dom.byId("addVirtualHostNode.fileFields"); - - this.virtualHostNodeForm = registry.byId("addVirtualHostNode.form"); - this.virtualHostNodeType = registry.byId("addVirtualHostNode.type"); - this.virtualHostNodeFileCheck = registry.byId("addVirtualHostNode.upload"); - this.virtualHostNodeFile = registry.byId("addVirtualHostNode.file"); - - this.virtualHostNodeType.set("disabled", true); - - this.virtualHostTypeFieldsContainer = dom.byId("addVirtualHost.typeFields"); - this.virtualHostForm = registry.byId("addVirtualHost.form"); - this.virtualHostType = registry.byId("addVirtualHost.type"); - - this.virtualHostType.set("disabled", true); - - var supportedVirtualHostNodeTypes = metadata.getTypesForCategory("VirtualHostNode"); - supportedVirtualHostNodeTypes.sort(); - - var virtualHostNodeTypeStore = util.makeTypeStore(supportedVirtualHostNodeTypes); - this.virtualHostNodeType.set("store", virtualHostNodeTypeStore); - this.virtualHostNodeType.set("disabled", false); - this.virtualHostNodeType.on("change", function(type){that._vhnTypeChanged(type, that.virtualHostNodeTypeFieldsContainer, "qpid/management/virtualhostnode/");}); - - this.virtualHostType.set("disabled", true); - this.virtualHostType.on("change", function(type){that._vhTypeChanged(type, that.virtualHostTypeFieldsContainer, "qpid/management/virtualhost/");}); - - if (this.reader) - { - this.reader.onload = function(evt) {that._vhnUploadFileComplete(evt);}; - this.reader.onerror = function(ex) {console.error("Failed to load JSON file", ex);}; - this.virtualHostNodeFile.on("change", function(selected){that._vhnFileChanged(selected)}); - this.virtualHostNodeFileCheck.on("change", function(selected){that._vhnFileFlagChanged(selected)}); - } - else - { - // Fall back for IE8/9 which do not support FileReader - this.virtualHostNodeFileCheck.set("disabled", "disabled"); - this.virtualHostNodeFileCheck.set("title", "Requires a more recent browser with HTML5 support"); - this.virtualHostNodeFileFields.style.display = "none"; - } - - this.virtualHostNodeUploadFields.style.display = "none"; - }, - show: function() - { - this.virtualHostNodeForm.reset(); - this.virtualHostNodeType.set("value", null); - - this.virtualHostForm.reset(); - this.virtualHostType.set("value", null); - if (!this.virtualHostNodeContext) - { - this.virtualHostNodeContext = new qpid.common.ContextVariablesEditor({name: 'context', title: 'Context variables'}); - this.virtualHostNodeContext.placeAt(dom.byId("addVirtualHostNode.context")); - var that = this; - this.virtualHostNodeContext.on("change", function(value){ - var inherited = that.virtualHostContext.inheritedActualValues; - var effective = that.virtualHostContext.effectiveValues; - var actuals = that.virtualHostContext.value; - for(var key in value) - { - var val = value[key]; - if (!(key in actuals)) - { - inherited[key] = val; - if (!(key in effective)) - { - effective[key] = val.indexOf("${") == -1 ? val : ""; - } - } - } - that.virtualHostContext.setData(that.virtualHostContext.value,effective,inherited); - }); - } - if (!this.virtualHostContext) - { - this.virtualHostContext = new qpid.common.ContextVariablesEditor({name: 'context', title: 'Context variables'}); - this.virtualHostContext.placeAt(dom.byId("addVirtualHost.context")); - - } - - this.virtualHostNodeContext.loadInheritedData("api/latest/broker"); - this.virtualHostContext.setData({}, this.virtualHostNodeContext.effectiveValues,this.virtualHostNodeContext.inheritedActualValues); - - this.dialog.show(); - if (!this.resizeEventRegistered) - { - this.resizeEventRegistered = true; - util.resizeContentAreaAndRepositionDialog(dom.byId("addVirtualHostNodeAndVirtualHost.contentPane"), this.dialog); - } - }, - destroy: function() - { - if (this.dialog) - { - this.dialog.destroyRecursive(); - this.dialog = null; - } - - if (this.containerNode) - { - domConstruct.destroy(this.containerNode); - this.containerNode = null; - } - }, - _vhnTypeChanged: function (type, typeFieldsContainer, urlStem) - { - var validChildTypes = metadata.validChildTypes("VirtualHostNode", type, "VirtualHost"); - validChildTypes.sort(); - - var virtualHostTypeStore = util.makeTypeStore( validChildTypes ); - - this.virtualHostType.set("store", virtualHostTypeStore); - this.virtualHostType.set("disabled", validChildTypes.length <= 1); - if (validChildTypes.length == 1) - { - this.virtualHostType.set("value", validChildTypes[0]); - } - else - { - this.virtualHostType.reset(); - } - - var vhnTypeSelected = !(type == ''); - this.virtualHostNodeUploadFields.style.display = vhnTypeSelected ? "block" : "none"; - - if (!vhnTypeSelected) - { - this._vhnFileFlagChanged(false); - } - - this._typeChanged(type, typeFieldsContainer, urlStem, "VirtualHostNode"); - }, - _vhTypeChanged: function (type, typeFieldsContainer, urlStem) - { - this._typeChanged(type, typeFieldsContainer, urlStem, "VirtualHost"); - }, - _typeChanged: function (type, typeFieldsContainer, urlStem, category) - { - var widgets = registry.findWidgets(typeFieldsContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(typeFieldsContainer); - if (category) - { - var context = this["v" + category.substring(1) + "Context"]; - if (context) - { - context.removeDynamicallyAddedInheritedContext(); - } - } - if (type) - { - var that = this; - require([urlStem + type.toLowerCase() + "/add"], - function(typeUI) - { - try - { - typeUI.show({containerNode:typeFieldsContainer, parent: that}); - - util.applyMetadataToWidgets(typeFieldsContainer,category, type); - } - catch(e) - { - console.warn(e); - } - } - ); - } - }, - _vhnFileFlagChanged: function (selected) - { - this.virtualHostForm.domNode.style.display = selected ? "none" : "block"; - this.virtualHostNodeFileFields.style.display = selected ? "block" : "none"; - this.virtualHostType.set("required", !selected); - this.virtualHostNodeFile.reset(); - this.virtualHostInitialConfiguration = undefined; - this.virtualHostNodeSelectedFileContainer.innerHTML = ""; - this.virtualHostNodeSelectedFileStatusContainer.className = ""; - }, - _vhnFileChanged: function (evt) - { - // We only ever expect a single file - var file = this.virtualHostNodeFile.domNode.children[0].files[0]; - - this.addButton.set("disabled", true); - this.virtualHostNodeSelectedFileContainer.innerHTML = file.name; - this.virtualHostNodeSelectedFileStatusContainer.className = "loadingIcon"; - - console.log("Beginning to read file " + file.name); - this.reader.readAsDataURL(file); - }, - _vhnUploadFileComplete: function(evt) - { - var reader = evt.target; - var result = reader.result; - console.log("File read complete, contents " + result); - this.virtualHostInitialConfiguration = result; - this.addButton.set("disabled", false); - this.virtualHostNodeSelectedFileStatusContainer.className = "loadedIcon"; - }, - _cancel: function(e) - { - if (this.reader) - { - this.reader.abort(); - } - this.dialog.hide(); - }, - _add: function(e) - { - event.stop(e); - this._submit(); - }, - _submit: function() - { - - var uploadVHConfig = this.virtualHostNodeFileCheck.get("checked"); - var virtualHostNodeData = undefined; - - if (uploadVHConfig && this.virtualHostNodeFile.getFileList().length > 0 && this.virtualHostNodeForm.validate()) - { - // VH config is being uploaded - virtualHostNodeData = this._getValues(this.virtualHostNodeForm); - var virtualHostNodeContext = this.virtualHostNodeContext.get("value"); - if (virtualHostNodeContext) - { - virtualHostNodeData["context"] = virtualHostNodeContext; - } - - // Add the loaded virtualhost configuration - virtualHostNodeData["virtualHostInitialConfiguration"] = this.virtualHostInitialConfiguration; - } - else if (!uploadVHConfig && this.virtualHostNodeForm.validate() && this.virtualHostForm.validate()) - { - virtualHostNodeData = this._getValues(this.virtualHostNodeForm); - var virtualHostNodeContext = this.virtualHostNodeContext.get("value"); - if (virtualHostNodeContext) - { - virtualHostNodeData["context"] = virtualHostNodeContext; - } - - var virtualHostData = this._getValues(this.virtualHostForm); - var virtualHostContext = this.virtualHostContext.get("value"); - if (virtualHostContext) - { - virtualHostData["context"] = virtualHostContext; - } - - //Default the VH name to be the same as the VHN name. - virtualHostData["name"] = virtualHostNodeData["name"]; - - virtualHostNodeData["virtualHostInitialConfiguration"] = json.stringify(virtualHostData) - - } - else - { - alert('Form contains invalid data. Please correct first'); - return; - } - - var that = this; - util.post("api/latest/virtualhostnode", virtualHostNodeData, function(x){that.dialog.hide();}); - }, - _getValues: function (form) - { - var values = {}; - var contextMap = {}; - - var formWidgets = form.getChildren(); - for(var i in formWidgets) - { - var widget = formWidgets[i]; - var value = widget.value; - var propName = widget.name; - if (propName && (widget.required || value )) - { - if (widget.contextvar) - { - contextMap [propName] = String(value); // Broker requires that context values are Strings - } - else - { - if (widget instanceof dijit.form.CheckBox) - { - values[ propName ] = widget.checked; - } - else if (widget instanceof dijit.form.RadioButton && value) - { - var currentValue = values[propName]; - if (currentValue) - { - if (lang.isArray(currentValue)) - { - currentValue.push(value) - } - else - { - values[ propName ] = [currentValue, value]; - } - } - else - { - values[ propName ] = value; - } - } - else - { - values[ propName ] = value ? value: null; - } - - } - } - } - - // One or more context variables were defined on form - if (fobject.keys(contextMap).length > 0) - { - values ["context"] = contextMap; - } - return values; - } - }; - - addVirtualHostNodeAndVirtualHost.init(); - - return addVirtualHostNodeAndVirtualHost; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/PrincipalDatabaseAuthenticationManager.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/PrincipalDatabaseAuthenticationManager.js deleted file mode 100644 index 8eaaa0e463..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/PrincipalDatabaseAuthenticationManager.js +++ /dev/null @@ -1,279 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/parser", - "dojo/query", - "dojo/dom-construct", - "dojo/_base/connect", - "dojo/_base/window", - "dojo/_base/event", - "dojo/_base/json", - "dijit/registry", - "qpid/common/util", - "qpid/common/properties", - "qpid/common/UpdatableStore", - "dojox/grid/EnhancedGrid", - "dojox/grid/enhanced/plugins/Pagination", - "dojox/grid/enhanced/plugins/IndirectSelection", - "dojox/validate/us", "dojox/validate/web", - "dijit/Dialog", - "dijit/form/TextBox", - "dijit/form/ValidationTextBox", - "dijit/form/TimeTextBox", "dijit/form/Button", - "dijit/form/Form", - "dijit/form/DateTextBox", - "dojo/domReady!"], - function (xhr, dom, parser, query, construct, connect, win, event, json, registry, util, properties, UpdatableStore, EnhancedGrid) { - function DatabaseAuthManager(containerNode, authProviderObj, controller) { - var node = construct.create("div", null, containerNode, "last"); - var that = this; - this.name = authProviderObj.name; - xhr.get({url: "authenticationprovider/showPrincipalDatabaseAuthenticationManager.html", - sync: true, - load: function(data) { - node.innerHTML = data; - parser.parse(node).then(function(instances) - { - that.init(node, authProviderObj, controller); - }); - }}); - } - - DatabaseAuthManager.prototype.update = function() { - this.authDatabaseUpdater.update(); - }; - - DatabaseAuthManager.prototype.close = function() { - updater.remove( this.authDatabaseUpdater ); - }; - - DatabaseAuthManager.prototype.init = function(node, authProviderObj, controller) - { - this.controller = controller; - var that = this; - - that.authProviderData = authProviderObj; - - var userDiv = query(".users")[0]; - - var gridProperties = { - height: 400, - keepSelection: true, - plugins: { - pagination: { - pageSizes: ["10", "25", "50", "100"], - description: true, - sizeSwitch: true, - pageStepper: true, - gotoButton: true, - maxPageStep: 4, - position: "bottom" - }, - indirectSelection: true - - }}; - - - that.usersGrid = - new UpdatableStore(that.authProviderData.users, userDiv, - [ { name: "User Name", field: "name", width: "100%" } - ], function(obj) { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var name = obj.dataStore.getValue(theItem,"name"); - var id = obj.dataStore.getValue(theItem,"id"); - setPassword.show(that.name, {name: name, id: id}); - }); - }, gridProperties, EnhancedGrid); - - - var addUserButton = query(".addUserButton", node)[0]; - connect.connect(registry.byNode(addUserButton), "onClick", function(evt){ addUser.show(that.name) }); - - var deleteUserButton = query(".deleteUserButton", node)[0]; - var deleteWidget = registry.byNode(deleteUserButton); - connect.connect(deleteWidget, "onClick", - function(evt){ - event.stop(evt); - that.deleteUsers(); - }); -} - - DatabaseAuthManager.prototype.deleteUsers = function() - { - var grid = this.usersGrid.grid; - var data = grid.selection.getSelected(); - if(data.length) { - var that = this; - if(confirm("Delete " + data.length + " users?")) { - var i, queryParam; - for(i = 0; i<data.length; i++) { - if(queryParam) { - queryParam += "&"; - } else { - queryParam = "?"; - } - - queryParam += "id=" + data[i].id; - } - var query = "api/latest/user/"+ encodeURIComponent(that.name) - + queryParam; - that.success = true - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - grid.setQuery({id: "*"}); - grid.selection.deselectAll(); - that.update(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!that.success ) { - util.xhrErrorHandler(this.failureReason); - } - } -} - }; - - DatabaseAuthManager.prototype.update = function(data) - { - this.authProviderData = data; - this.name = data.name - this.usersGrid.update(this.authProviderData.users); - }; - - var addUser = {}; - - var node = construct.create("div", null, win.body(), "last"); - - var convertToUser = function convertToUser(formValues) { - var newUser = {}; - newUser.name = formValues.name; - for(var propName in formValues) - { - if(formValues.hasOwnProperty(propName)) { - if(formValues[ propName ] !== "") { - newUser[ propName ] = formValues[propName]; - } - } - } - - return newUser; - }; - - - xhr.get({url: "authenticationprovider/addUser.html", - sync: true, - load: function(data) { - var theForm; - node.innerHTML = data; - addUser.dialogNode = dom.byId("addUser"); - parser.instantiate([addUser.dialogNode]); - - var that = this; - - theForm = registry.byId("formAddUser"); - theForm.on("submit", function(e) { - - event.stop(e); - if(theForm.validate()){ - - var newUser = convertToUser(theForm.getValues()); - - - var url = "api/latest/user/"+encodeURIComponent(addUser.authProvider); - util.post(url, newUser, function(x){registry.byId("addUser").hide();}); - return false; - - - }else{ - alert('Form contains invalid data. Please correct first'); - return false; - } - - }); - }}); - - addUser.show = function(authProvider) { - addUser.authProvider = authProvider; - registry.byId("formAddUser").reset(); - registry.byId("addUser").show(); - }; - - - var setPassword = {}; - - var setPasswordNode = construct.create("div", null, win.body(), "last"); - - xhr.get({url: "authenticationprovider/setPassword.html", - sync: true, - load: function(data) { - var theForm; - setPasswordNode.innerHTML = data; - setPassword.dialogNode = dom.byId("setPassword"); - parser.instantiate([setPassword.dialogNode]); - - var that = this; - - theForm = registry.byId("formSetPassword"); - theForm.on("submit", function(e) { - - event.stop(e); - if(theForm.validate()){ - - var newUser = convertToUser(theForm.getValues()); - newUser.name = setPassword.name; - newUser.id = setPassword.id; - - var url = "api/latest/user/"+encodeURIComponent(setPassword.authProvider) + - "/"+encodeURIComponent(newUser.name); - - util.post(url, newUser, function(x){registry.byId("setPassword").hide();}); - return false; - - - }else{ - alert('Form contains invalid data. Please correct first'); - return false; - } - - }); - }}); - - setPassword.show = function(authProvider, user) { - setPassword.authProvider = authProvider; - setPassword.name = user.name; - setPassword.id = user.id; - registry.byId("formSetPassword").reset(); - - var namebox = registry.byId("formSetPassword.name"); - namebox.set("value", user.name); - namebox.set("disabled", true); - - registry.byId("setPassword").show(); - - }; - - - - return DatabaseAuthManager; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/anonymous/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/anonymous/add.js deleted file mode 100644 index 73022a0855..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/anonymous/add.js +++ /dev/null @@ -1,21 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], function () { return { show: function(data){} }; }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/anonymous/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/anonymous/show.js deleted file mode 100644 index ca2b56fda0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/anonymous/show.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], - function () - { - - function NoFieldAuthenticationProvider(data) - { - } - - NoFieldAuthenticationProvider.prototype.update = function(data) - { - } - - return NoFieldAuthenticationProvider; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/base64md5passwordfile/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/base64md5passwordfile/add.js deleted file mode 100644 index cbc5ce356d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/base64md5passwordfile/add.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/query","dijit/registry","qpid/common/util"], - function (query, registry, util) - { - return { - show: function(data) - { - util.parseHtmlIntoDiv(data.containerNode, "authenticationprovider/filebased/add.html", - function() - { - if (data.data) - { - var path = registry.byNode(query(".path", data.containerNode)[0]); - path.set("value", data.data.path); - } - }); - } - }; - } -); - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/base64md5passwordfile/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/base64md5passwordfile/show.js deleted file mode 100644 index 1456a4847c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/base64md5passwordfile/show.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["qpid/common/util", "dojo/domReady!"], - function (util, metadata) - { - - function Base64MD5PasswordFile(data) - { - util.buildUI(data.containerNode, data.parent, "authenticationprovider/filebased/show.html", ["path"], this); - data.parent.editButton.set("disabled", false); - } - - Base64MD5PasswordFile.prototype.update = function(data) - { - util.updateUI(data, ["path"], this); - } - - return Base64MD5PasswordFile; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/external/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/external/add.js deleted file mode 100644 index 979a10cae9..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/external/add.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/query","dijit/registry","qpid/common/util"], - function (query, registry, util) - { - return { - show: function(data) - { - util.parseHtmlIntoDiv(data.containerNode, "authenticationprovider/external/add.html", - function() - { - if (data.data) - { - var useFullDN = registry.byNode(query(".useFullDN", data.containerNode)[0]); - useFullDN.set("value", data.data.useFullDN); - } - }); - } - }; - } -); - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/external/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/external/show.js deleted file mode 100644 index 84b1ed387d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/external/show.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["qpid/common/util", "dojo/domReady!"], - function (util, metadata) - { - - function External(data) - { - util.buildUI(data.containerNode, data.parent, "authenticationprovider/external/show.html", ["useFullDN"], this); - data.parent.editButton.set("disabled", false); - } - - External.prototype.update = function(data) - { - util.updateUI(data, ["useFullDN"], this); - } - - return External; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/kerberos/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/kerberos/add.js deleted file mode 100644 index f76c75f05e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/kerberos/add.js +++ /dev/null @@ -1,22 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], function () { return { show: function(data){} }; }); - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/kerberos/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/kerberos/show.js deleted file mode 100644 index ca2b56fda0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/kerberos/show.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], - function () - { - - function NoFieldAuthenticationProvider(data) - { - } - - NoFieldAuthenticationProvider.prototype.update = function(data) - { - } - - return NoFieldAuthenticationProvider; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/md5/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/md5/add.js deleted file mode 100644 index 73022a0855..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/md5/add.js +++ /dev/null @@ -1,21 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], function () { return { show: function(data){} }; }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/md5/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/md5/show.js deleted file mode 100644 index ca2b56fda0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/md5/show.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], - function () - { - - function NoFieldAuthenticationProvider(data) - { - } - - NoFieldAuthenticationProvider.prototype.update = function(data) - { - } - - return NoFieldAuthenticationProvider; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plain/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plain/add.js deleted file mode 100644 index 73022a0855..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plain/add.js +++ /dev/null @@ -1,21 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], function () { return { show: function(data){} }; }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plain/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plain/show.js deleted file mode 100644 index ca2b56fda0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plain/show.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], - function () - { - - function NoFieldAuthenticationProvider(data) - { - } - - NoFieldAuthenticationProvider.prototype.update = function(data) - { - } - - return NoFieldAuthenticationProvider; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plainpasswordfile/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plainpasswordfile/add.js deleted file mode 100644 index cbc5ce356d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plainpasswordfile/add.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/query","dijit/registry","qpid/common/util"], - function (query, registry, util) - { - return { - show: function(data) - { - util.parseHtmlIntoDiv(data.containerNode, "authenticationprovider/filebased/add.html", - function() - { - if (data.data) - { - var path = registry.byNode(query(".path", data.containerNode)[0]); - path.set("value", data.data.path); - } - }); - } - }; - } -); - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plainpasswordfile/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plainpasswordfile/show.js deleted file mode 100644 index f428a8ec55..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plainpasswordfile/show.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["qpid/common/util", "dojo/domReady!"], - function (util, metadata) - { - - function PlainPasswordFile(data) - { - util.buildUI(data.containerNode, data.parent, "authenticationprovider/filebased/show.html", ["path"], this); - data.parent.editButton.set("disabled", false); - } - - PlainPasswordFile.prototype.update = function(data) - { - util.updateUI(data, ["path"], this); - } - - return PlainPasswordFile; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-1/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-1/add.js deleted file mode 100644 index 73022a0855..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-1/add.js +++ /dev/null @@ -1,21 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], function () { return { show: function(data){} }; }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-1/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-1/show.js deleted file mode 100644 index ca2b56fda0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-1/show.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], - function () - { - - function NoFieldAuthenticationProvider(data) - { - } - - NoFieldAuthenticationProvider.prototype.update = function(data) - { - } - - return NoFieldAuthenticationProvider; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-256/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-256/add.js deleted file mode 100644 index 73022a0855..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-256/add.js +++ /dev/null @@ -1,21 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], function () { return { show: function(data){} }; }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-256/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-256/show.js deleted file mode 100644 index ca2b56fda0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-256/show.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], - function () - { - - function NoFieldAuthenticationProvider(data) - { - } - - NoFieldAuthenticationProvider.prototype.update = function(data) - { - } - - return NoFieldAuthenticationProvider; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/simpleldap/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/simpleldap/add.js deleted file mode 100644 index 4e04bfd6f0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/simpleldap/add.js +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr","dojo/query","dijit/registry","qpid/common/util","qpid/common/metadata","dojo/store/Memory","dijit/form/FilteringSelect","dijit/form/ValidationTextBox","dijit/form/CheckBox"], - function (xhr, query, registry, util, metadata, Memory) - { - return { - show: function(data) - { - var that = this; - util.parseHtmlIntoDiv(data.containerNode, "authenticationprovider/simpleldap/add.html", function(){that._postParse(data);}); - }, - _postParse: function(data) - { - var that = this; - xhr.get({url: "api/latest/truststore", sync: true, handleAs: "json"}).then( - function(trustStores) - { - that._initTrustStores(trustStores, data.containerNode); - } - ); - - if (data.data) - { - this._initFields(data.data, data.containerNode ); - } - }, - _initTrustStores: function(trustStores, containerNode) - { - var data = []; - for (var i=0; i< trustStores.length; i++) - { - data.push( {id: trustStores[i].name, name: trustStores[i].name} ); - } - var trustStoresStore = new Memory({ data: data }); - - var trustStore = registry.byNode(query(".trustStore", containerNode)[0]); - trustStore.set("store", trustStoresStore); - }, - _initFields:function(data, containerNode) - { - var attributes = metadata.getMetaData("AuthenticationProvider", "SimpleLDAP").attributes; - for(var name in attributes) - { - var domNode = query("." + name, containerNode)[0]; - if (domNode) - { - var widget = registry.byNode(domNode); - if (widget) - { - if (widget instanceof dijit.form.CheckBox) - { - widget.set("checked", data[name]); - } - else - { - widget.set("value", data[name]); - } - } - } - } - } - }; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/simpleldap/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/simpleldap/show.js deleted file mode 100644 index 554e856035..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/simpleldap/show.js +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["qpid/common/util", "qpid/common/metadata", "dojo/domReady!"], - function (util, metadata) - { - - function SimpleLdapAuthenticationProvider(data) - { - this.fields = []; - var attributes = metadata.getMetaData("AuthenticationProvider", "SimpleLDAP").attributes; - for(var name in attributes) - { - this.fields.push(name); - } - util.buildUI(data.containerNode, data.parent, "authenticationprovider/simpleldap/show.html", this.fields, this); - data.parent.editButton.set("disabled", false); - } - - SimpleLdapAuthenticationProvider.prototype.update = function(data) - { - util.updateUI(data, this.fields, this); - } - - return SimpleLdapAuthenticationProvider; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/controller.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/controller.js deleted file mode 100644 index 4b8e9db4b0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/controller.js +++ /dev/null @@ -1,140 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/dom", - "dijit/registry", - "dijit/layout/ContentPane", - "dijit/form/CheckBox", - "qpid/management/UserPreferences", - "dojox/html/entities", - "qpid/management/Broker", - "qpid/management/VirtualHost", - "qpid/management/Exchange", - "qpid/management/Queue", - "qpid/management/Connection", - "qpid/management/AuthenticationProvider", - "qpid/management/GroupProvider", - "qpid/management/group/Group", - "qpid/management/KeyStore", - "qpid/management/TrustStore", - "qpid/management/AccessControlProvider", - "qpid/management/Port", - "qpid/management/Plugin", - "qpid/management/logs/LogViewer", - "qpid/management/PreferencesProvider", - "qpid/management/VirtualHostNode", - "dojo/ready", - "dojo/domReady!"], - function (dom, registry, ContentPane, CheckBox, UserPreferences, entities, Broker, VirtualHost, Exchange, Queue, Connection, AuthProvider, - GroupProvider, Group, KeyStore, TrustStore, AccessControlProvider, Port, Plugin, LogViewer, PreferencesProvider, VirtualHostNode, ready) { - var controller = {}; - - var constructors = { broker: Broker, virtualhost: VirtualHost, exchange: Exchange, - queue: Queue, connection: Connection, - authenticationprovider: AuthProvider, groupprovider: GroupProvider, - group: Group, keystore: KeyStore, truststore: TrustStore, - accesscontrolprovider: AccessControlProvider, port: Port, - plugin: Plugin, logViewer: LogViewer, preferencesprovider: PreferencesProvider, - virtualhostnode: VirtualHostNode}; - - var tabDiv = dom.byId("managedViews"); - - ready(function() { - controller.tabContainer = registry.byId("managedViews"); - }); - - - controller.viewedObjects = {}; - - controller.show = function(objType, name, parent, objectId) { - - function generateName(obj) - { - if(obj) { - var name = obj.type + (obj.type == "broker" ? "" : ":" + obj.name); - if (obj.parent) - { - name = generateName(obj.parent) + "/" + name; - } - return name; - } - return ""; - } - - var that = this; - var objId = (parent ? generateName(parent) + "/" : "") + objType + ":" + name; - - var obj = this.viewedObjects[ objId ]; - if(obj) { - this.tabContainer.selectChild(obj.contentPane); - } else { - var Constructor = constructors[ objType ]; - if(Constructor) { - obj = new Constructor(name, parent, this); - obj.tabData = { - objectId: objectId, - objectType: objType - }; - this.viewedObjects[ objId ] = obj; - - var contentPane = new ContentPane({ region: "center" , - title: entities.encode(obj.getTitle()), - closable: true, - onClose: function() { - obj.close(); - delete that.viewedObjects[ objId ]; - return true; - } - }); - this.tabContainer.addChild( contentPane ); - if (objType != "broker") - { - var preferencesCheckBox = new dijit.form.CheckBox({ - checked: UserPreferences.isTabStored(obj.tabData), - title: "If checked the tab is saved in user preferences and restored on next login" - }); - var tabs = this.tabContainer.tablist.getChildren(); - preferencesCheckBox.placeAt(tabs[tabs.length-1].titleNode, "first"); - preferencesCheckBox.on("change", function(value){ - if (value) - { - UserPreferences.appendTab(obj.tabData); - } - else - { - UserPreferences.removeTab(obj.tabData); - } - }); - } - obj.open(contentPane); - contentPane.startup(); - if(obj.startup) { - obj.startup(); - } - this.tabContainer.selectChild( contentPane ); - } - - } - - }; - - - return controller; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editBroker.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editBroker.js deleted file mode 100644 index 66eb907c69..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editBroker.js +++ /dev/null @@ -1,188 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojox/html/entities", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/lang", - "dojo/_base/window", - "dojo/dom", - "dojo/dom-construct", - "dijit/registry", - "dojo/parser", - 'dojo/json', - "dojo/query", - "dojo/store/Memory", - "dojo/data/ObjectStore", - "qpid/common/util", - "dojo/text!editBroker.html", - "qpid/common/ContextVariablesEditor", - "dijit/Dialog", - "dijit/form/CheckBox", - "dijit/form/FilteringSelect", - "dijit/form/ValidationTextBox", - "dijit/form/Button", - "dijit/form/Form", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], - function (xhr, entities, array, event, lang, win, dom, domConstruct, registry, parser, json, query, Memory, ObjectStore, util, template) - { - var fields = [ "name", "defaultVirtualHost", "statisticsReportingPeriod", "statisticsReportingResetEnabled", "connection.sessionCountLimit", "connection.heartBeatDelay"]; - var numericFieldNames = ["statisticsReportingPeriod", "connection.sessionCountLimit", "connection.heartBeatDelay"]; - - var brokerEditor = - { - init: function() - { - var that=this; - this.containerNode = domConstruct.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances){ that._postParse();}); - }, - _postParse: function() - { - var that=this; - this.dialog = registry.byId("editBrokerDialog"); - this.saveButton = registry.byId("editBroker.saveButton"); - this.cancelButton = registry.byId("editBroker.cancelButton"); - this.cancelButton.on("click", function(e){that._cancel(e);}); - this.saveButton.on("click", function(e){that._save(e);}); - for(var i = 0; i < fields.length; i++) - { - var fieldName = fields[i]; - this[fieldName] = registry.byId("editBroker." + fieldName); - } - this.form = registry.byId("editBrokerForm"); - this.form.on("submit", function(){return false;}); - this.context = registry.byId("editBroker.context"); - util.applyMetadataToWidgets(dom.byId("editBroker.allFields"), "Broker", "broker"); - - for(var i = 0; i < numericFieldNames.length; i++) - { - this[numericFieldNames[i]].set("regExpGen", util.numericOrContextVarRegexp); - } - }, - show: function(brokerData) - { - var that=this; - this.query = "api/latest/broker"; - this.dialog.set("title", "Edit Broker - " + entities.encode(String(brokerData.name))); - xhr.get( - { - url: this.query, - sync: true, - content: { actuals: true }, - handleAs: "json", - load: function(data) - { - that._show(data[0], brokerData); - } - } - ); - }, - destroy: function() - { - if (this.dialog) - { - this.dialog.destroyRecursive(); - this.dialog = null; - } - - if (this.containerNode) - { - domConstruct.destroy(this.containerNode); - this.containerNode = null; - } - }, - _cancel: function(e) - { - this.dialog.hide(); - }, - _save: function(e) - { - event.stop(e); - if(this.form.validate()) - { - var data = util.getFormWidgetValues(this.form, this.initialData); - var context = this.context.get("value"); - if (context && !util.equals(context, this.initialData.context)) - { - data["context"] = context; - } - - var that = this; - util.post(this.query, data, function(x){that.dialog.hide()}) - } - else - { - alert('Form contains invalid data. Please correct first'); - } - }, - _show:function(actualData, effectiveData) - { - this.initialData = actualData; - var nodes = effectiveData.virtualhostnodes - var data = []; - if (nodes) - { - for (var i=0; i< nodes.length; i++) - { - if (nodes[i].virtualhosts) - { - data.push({id: nodes[i].virtualhosts[0].name, name: nodes[i].virtualhosts[0].name}); - } - } - } - var hostsStore = new dojo.store.Memory({ data: data }); - this["defaultVirtualHost"].set("store", hostsStore); - - - for(var i = 0; i < fields.length; i++) - { - var fieldName = fields[i]; - var widget = this[fieldName]; - widget.reset(); - - if (widget instanceof dijit.form.CheckBox) - { - widget.set("checked", actualData[fieldName]); - } - else - { - widget.set("value", actualData[fieldName]); - } - } - this.context.load(this.query, {actualValues: actualData.context, effectiveValues: effectiveData.context}); - this.dialog.startup(); - this.dialog.show(); - if (!this.resizeEventRegistered) - { - this.resizeEventRegistered = true; - util.resizeContentAreaAndRepositionDialog(dom.byId("editBroker.contentPane"), this.dialog); - } - } - }; - - brokerEditor.init(); - - return brokerEditor; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editQueue.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editQueue.js deleted file mode 100644 index cf3f171536..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editQueue.js +++ /dev/null @@ -1,219 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojox/html/entities", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/lang", - "dojo/_base/window", - "dojo/dom", - "dojo/dom-construct", - "dijit/registry", - "dojo/parser", - 'dojo/json', - "dojo/query", - "qpid/common/util", - "dojo/text!editQueue.html", - "qpid/common/ContextVariablesEditor", - "dijit/Dialog", - "dijit/form/CheckBox", - "dijit/form/FilteringSelect", - "dijit/form/ValidationTextBox", - "dijit/form/Button", - "dijit/form/Form", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], - function (xhr, entities, array, event, lang, win, dom, domConstruct, registry, parser, json, query, util, template) - { - var fields = ["name", - "type", - "durable", - "messageDurability", - "maximumMessageTtl", - "minimumMessageTtl", - "queueFlowControlSizeBytes", - "queueFlowResumeSizeBytes", - "alertThresholdQueueDepthMessages", - "alertThresholdQueueDepthBytes", - "alertThresholdMessageAge", - "alertThresholdMessageSize", - "alertRepeatGap", - "maximumDeliveryAttempts", - "priorities", - "lvqKey", - "sortKey"]; - - var numericFieldNames = ["maximumMessageTtl", - "minimumMessageTtl", - "queueFlowControlSizeBytes", - "queueFlowResumeSizeBytes", - "alertThresholdQueueDepthMessages", - "alertThresholdQueueDepthBytes", - "alertThresholdMessageAge", - "alertThresholdMessageSize", - "alertRepeatGap", - "maximumDeliveryAttempts"]; - - var queueEditor = - { - init: function() - { - var that=this; - this.containerNode = domConstruct.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances){ that._postParse();}); - }, - _postParse: function() - { - var that=this; - this.allFieldsContainer = dom.byId("formEditQueue.allFields"); - this.dialog = registry.byId("editQueue"); - this.saveButton = registry.byId("formEditQueue.saveButton"); - this.cancelButton = registry.byId("formEditQueue.cancelButton"); - this.cancelButton.on("click", function(e){that._cancel(e);}); - this.saveButton.on("click", function(e){that._save(e);}); - for(var i = 0; i < fields.length; i++) - { - var fieldName = fields[i]; - this[fieldName] = registry.byId("formEditQueue." + fieldName); - } - this.form = registry.byId("formEditQueue"); - this.form.on("submit", function(){return false;}); - this.typeSelector = registry.byId("formEditQueue.type"); - }, - show: function(hostData) - { - var that=this; - if (!this.context) - { - this.context = new qpid.common.ContextVariablesEditor({name: 'context', title: 'Context variables'}); - this.context.placeAt(dom.byId("formEditQueue.context")); - } - this.query = "api/latest/queue/" + encodeURIComponent(hostData.nodeName) + "/" + encodeURIComponent(hostData.hostName) + "/" + encodeURIComponent(hostData.queueName); - this.dialog.set("title", "Edit Queue - " + entities.encode(String(hostData.queueName))); - xhr.get( - { - url: this.query, - sync: true, - content: { actuals: true }, - handleAs: "json", - load: function(data) - { - that._show(data[0], hostData); - } - } - ); - var queueType = this.typeSelector.get("value"); - query(".typeSpecificDiv").forEach(function(node, index, arr){ - if (node.id === "formEditQueueType:" + queueType) - { - node.style.display = "block"; - util.applyMetadataToWidgets(node, "Queue", queueType); - } - else - { - node.style.display = "none"; - } - }); - }, - destroy: function() - { - if (this.dialog) - { - this.dialog.destroyRecursive(); - this.dialog = null; - } - - if (this.containerNode) - { - domConstruct.destroy(this.containerNode); - this.containerNode = null; - } - }, - _cancel: function(e) - { - this.dialog.hide(); - }, - _save: function(e) - { - event.stop(e); - if(this.form.validate()) - { - var data = util.getFormWidgetValues(this.form, this.initialData); - var context = this.context.get("value"); - if (context && !util.equals(context, this.initialData.context)) - { - data["context"] = context; - } - var that = this; - util.post(this.query, data, function(x){that.dialog.hide()}); - } - else - { - alert('Form contains invalid data. Please correct first'); - } - }, - _show:function(actualData, effectiveData) - { - - this.initialData = actualData; - for(var i = 0; i < fields.length; i++) - { - var fieldName = fields[i]; - var widget = this[fieldName]; - widget.reset(); - - if (widget instanceof dijit.form.CheckBox) - { - widget.set("checked", actualData[fieldName]); - } - else - { - widget.set("value", actualData[fieldName]); - } - } - - var that = this; - util.applyMetadataToWidgets(that.allFieldsContainer, "Queue", actualData.type); - - this.context.load(this.query, {actualValues:actualData.context, effectiveValues:effectiveData.context}); - - // Add regexp to the numeric fields - for(var i = 0; i < numericFieldNames.length; i++) - { - this[numericFieldNames[i]].set("regExpGen", util.numericOrContextVarRegexp); - } - - this.dialog.startup(); - this.dialog.show(); - if (!this.resizeEventRegistered) - { - this.resizeEventRegistered = true; - util.resizeContentAreaAndRepositionDialog(dom.byId("formEditQueue.contentPane"), this.dialog); - } - } - }; - - queueEditor.init(); - - return queueEditor; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editVirtualHost.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editVirtualHost.js deleted file mode 100644 index cf038826ae..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editVirtualHost.js +++ /dev/null @@ -1,207 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojox/html/entities", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/lang", - "dojo/_base/window", - "dojo/dom", - "dojo/dom-construct", - "dijit/registry", - "dojo/parser", - 'dojo/json', - "dojo/query", - "dojo/store/Memory", - "dojo/data/ObjectStore", - "qpid/common/util", - "dojo/text!editVirtualHost.html", - "qpid/common/ContextVariablesEditor", - "dijit/Dialog", - "dijit/form/CheckBox", - "dijit/form/FilteringSelect", - "dijit/form/ValidationTextBox", - "dijit/form/Button", - "dijit/form/Form", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], - function (xhr, entities, array, event, lang, win, dom, domConstruct, registry, parser, json, query, Memory, ObjectStore, util, template) - { - var fields = [ "name", "queue.deadLetterQueueEnabled", "storeTransactionIdleTimeoutWarn", "storeTransactionIdleTimeoutClose", "storeTransactionOpenTimeoutWarn", "storeTransactionOpenTimeoutClose", "housekeepingCheckPeriod", "housekeepingThreadCount"]; - var numericFieldNames = ["storeTransactionIdleTimeoutWarn", "storeTransactionIdleTimeoutClose", "storeTransactionOpenTimeoutWarn", "storeTransactionOpenTimeoutClose", "housekeepingCheckPeriod", "housekeepingThreadCount"]; - - - var virtualHostEditor = - { - init: function() - { - var that=this; - this.containerNode = domConstruct.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances){ that._postParse();}); - }, - _postParse: function() - { - var that=this; - this.allFieldsContainer = dom.byId("editVirtualHost.allFields"); - this.typeFieldsContainer = dom.byId("editVirtualHost.typeFields"); - this.dialog = registry.byId("editVirtualHostDialog"); - this.saveButton = registry.byId("editVirtualHost.saveButton"); - this.cancelButton = registry.byId("editVirtualHost.cancelButton"); - this.cancelButton.on("click", function(e){that._cancel(e);}); - this.saveButton.on("click", function(e){that._save(e);}); - for(var i = 0; i < fields.length; i++) - { - var fieldName = fields[i]; - this[fieldName] = registry.byId("editVirtualHost." + fieldName); - } - this.form = registry.byId("editVirtualHostForm"); - this.form.on("submit", function(){return false;}); - }, - show: function(hostData) - { - var that=this; - if (!this.context) - { - this.context = new qpid.common.ContextVariablesEditor({name: 'context', title: 'Context variables'}); - this.context.placeAt(dom.byId("editVirtualHost.context")); - } - this.query = "api/latest/virtualhost/" + encodeURIComponent(hostData.nodeName) + "/" + encodeURIComponent(hostData.hostName); - this.dialog.set("title", "Edit Virtual Host - " + entities.encode(String(hostData.hostName))); - xhr.get( - { - url: this.query, - sync: true, - content: { actuals: true }, - handleAs: "json", - load: function(data) - { - that._show(data[0], hostData); - } - } - ); - }, - destroy: function() - { - if (this.dialog) - { - this.dialog.destroyRecursive(); - this.dialog = null; - } - - if (this.containerNode) - { - domConstruct.destroy(this.containerNode); - this.containerNode = null; - } - }, - _cancel: function(e) - { - this.dialog.hide(); - }, - _save: function(e) - { - event.stop(e); - if(this.form.validate()) - { - var data = util.getFormWidgetValues(this.form, this.initialData); - var context = this.context.get("value"); - if (context && !util.equals(context, this.initialData.context)) - { - data["context"] = context; - } - var that=this; - util.post(this.query, data, function(x){ that.dialog.hide();} ); - } - else - { - alert('Form contains invalid data. Please correct first'); - } - }, - _show:function(actualData, effectiveData) - { - - this.initialData = actualData; - for(var i = 0; i < fields.length; i++) - { - var fieldName = fields[i]; - var widget = this[fieldName]; - widget.reset(); - - if (widget instanceof dijit.form.CheckBox) - { - widget.set("checked", actualData[fieldName]); - } - else - { - widget.set("value", actualData[fieldName]); - } - } - - this.context.load(this.query, {actualValues:actualData.context, effectiveValues:effectiveData.context}); - - // Add regexp to the numeric fields - for(var i = 0; i < numericFieldNames.length; i++) - { - this[numericFieldNames[i]].set("regExpGen", util.numericOrContextVarRegexp); - } - - var that = this; - - var widgets = registry.findWidgets(this.typeFieldsContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(this.typeFieldsContainer); - - require(["qpid/management/virtualhost/" + actualData.type.toLowerCase() + "/edit"], - function(TypeUI) - { - try - { - TypeUI.show({containerNode:that.typeFieldsContainer, parent: that, data: actualData}); - that.form.connectChildren(); - - util.applyToWidgets(that.allFieldsContainer, "VirtualHost", actualData.type, actualData); - } - catch(e) - { - if (console && console.warn ) - { - console.warn(e); - } - } - } - ); - - this.dialog.startup(); - this.dialog.show(); - if (!this.resizeEventRegistered) - { - this.resizeEventRegistered = true; - util.resizeContentAreaAndRepositionDialog(dom.byId("editVirtualHost.contentPane"), this.dialog); - } - } - }; - - virtualHostEditor.init(); - - return virtualHostEditor; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editVirtualHostNode.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editVirtualHostNode.js deleted file mode 100644 index c9dc9d2029..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editVirtualHostNode.js +++ /dev/null @@ -1,177 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojox/html/entities", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/lang", - "dojo/_base/window", - "dojo/dom", - "dojo/dom-construct", - "dijit/registry", - "dojo/parser", - 'dojo/json', - "dojo/query", - "dojo/store/Memory", - "dojo/data/ObjectStore", - "qpid/common/util", - "dojo/text!editVirtualHostNode.html", - "qpid/common/ContextVariablesEditor", - "dijit/Dialog", - "dijit/form/CheckBox", - "dijit/form/FilteringSelect", - "dijit/form/ValidationTextBox", - "dijit/form/Button", - "dijit/form/Form", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], - function (xhr, entities, array, event, lang, win, dom, domConstruct, registry, parser, json, query, Memory, ObjectStore, util, template) - { - var virtualHostNodeEditor = - { - init: function() - { - var that=this; - this.containerNode = domConstruct.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances){ that._postParse();}); - }, - _postParse: function() - { - var that=this; - this.allFieldsContainer = dom.byId("editVirtualHostNode.allFields"); - this.typeFieldsContainer = dom.byId("editVirtualHostNode.typeFields"); - this.dialog = registry.byId("editVirtualHostNodeDialog"); - this.saveButton = registry.byId("editVirtualHostNode.saveButton"); - this.cancelButton = registry.byId("editVirtualHostNode.cancelButton"); - this.cancelButton.on("click", function(e){that._cancel(e);}); - this.saveButton.on("click", function(e){that._save(e);}); - this.name = registry.byId("editVirtualHostNode.name"); - this.form = registry.byId("editVirtualHostNodeForm"); - this.form.on("submit", function(){return false;}); - }, - show: function(effectiveData) - { - var that=this; - if (!this.context) - { - this.context = new qpid.common.ContextVariablesEditor({name: 'context', title: 'Context variables'}); - this.context.placeAt(dom.byId("editVirtualHostNode.context")); - } - this.query = "api/latest/virtualhostnode/" + encodeURIComponent(effectiveData.name); - this.dialog.set("title", "Edit Virtual Host Node - " + entities.encode(String(effectiveData.name))); - xhr.get( - { - url: this.query, - sync: true, - content: { actuals: true }, - handleAs: "json", - load: function(data) - { - that._show(data[0], effectiveData); - } - } - ); - }, - destroy: function() - { - if (this.dialog) - { - this.dialog.destroyRecursive(); - this.dialog = null; - } - - if (this.containerNode) - { - domConstruct.destroy(this.containerNode); - this.containerNode = null; - } - }, - _cancel: function(e) - { - this.dialog.hide(); - }, - _save: function(e) - { - event.stop(e); - if(this.form.validate()) - { - var data = util.getFormWidgetValues(this.form, this.initialData); - var context = this.context.get("value"); - if (context && !util.equals(context, this.initialData.context)) - { - data["context"] = context; - } - var that = this; - util.post(this.query, data, function(x){ that.dialog.hide();} ); - } - else - { - alert('Form contains invalid data. Please correct first'); - } - }, - _show:function(actualData, effectiveData) - { - this.initialData = actualData; - this.name.set("value", actualData.name); - this.context.load( this.query, {actualValues: actualData.context, effectiveValues: effectiveData.context}); - - var that = this; - - var widgets = registry.findWidgets(this.typeFieldsContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(this.typeFieldsContainer); - - require(["qpid/management/virtualhostnode/" + actualData.type.toLowerCase() + "/edit"], - function(TypeUI) - { - try - { - TypeUI.show({containerNode:that.typeFieldsContainer, parent: that, data: actualData, effectiveData: effectiveData}); - that.form.connectChildren(); - - util.applyToWidgets(that.allFieldsContainer, "VirtualHostNode", actualData.type, actualData); - } - catch(e) - { - if (console && console.warn ) - { - console.warn(e); - } - } - } - ); - - this.dialog.startup(); - this.dialog.show(); - if (!this.resizeEventRegistered) - { - this.resizeEventRegistered = true; - util.resizeContentAreaAndRepositionDialog(dom.byId("editVirtualHostNode.contentPane"), this.dialog); - } - } - }; - - virtualHostNodeEditor.init(); - - return virtualHostNodeEditor; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/group/Group.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/group/Group.js deleted file mode 100644 index 7832941e71..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/group/Group.js +++ /dev/null @@ -1,204 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dijit/registry", - "dojo/_base/connect", - "dojo/_base/event", - "dojo/json", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/util", - "qpid/common/formatter", - "qpid/common/UpdatableStore", - "dojo/store/JsonRest", - "dojox/grid/EnhancedGrid", - "dojo/data/ObjectStore", - "qpid/management/group/addGroupMember", - "dojox/html/entities", - "dojox/grid/enhanced/plugins/Pagination", - "dojox/grid/enhanced/plugins/IndirectSelection", - "dojo/domReady!"], - function (xhr, parser, query, registry, connect, event, json, properties, updater, util, formatter, - UpdatableStore, JsonRest, EnhancedGrid, ObjectStore, addGroupMember, entities) { - - function Group(name, parent, controller) { - this.name = name; - this.controller = controller; - this.modelObj = { type: "group", name: name }; - - if(parent) { - this.modelObj.parent = {}; - this.modelObj.parent[ parent.type] = parent; - } - } - - Group.prototype.getGroupName = function() - { - return this.name; - }; - - - Group.prototype.getGroupProviderName = function() - { - return this.modelObj.parent.groupprovider.name; - }; - - Group.prototype.getTitle = function() - { - return "Group: " + this.name; - }; - - Group.prototype.open = function(contentPane) { - var that = this; - this.contentPane = contentPane; - - xhr.get({url: "group/showGroup.html", - sync: true, - load: function(data) { - contentPane.containerNode.innerHTML = data; - parser.parse(contentPane.containerNode).then(function(instances) - { - that.groupUpdater = new GroupUpdater(contentPane.containerNode, that, that.controller); - that.groupUpdater.update(); - updater.add( that.groupUpdater ); - - var addGroupMemberButton = query(".addGroupMemberButton", contentPane.containerNode)[0]; - connect.connect(registry.byNode(addGroupMemberButton), "onClick", - function(evt){ - addGroupMember.show(that.getGroupProviderName(), that.getGroupName()) - } - ); - - var removeGroupMemberButton = query(".removeGroupMemberButton", contentPane.containerNode)[0]; - connect.connect(registry.byNode(removeGroupMemberButton), "onClick", - function(evt){ - util.deleteGridSelections( - that.groupUpdater, - that.groupUpdater.groupMembersUpdatableStore.grid, - "api/latest/groupmember/"+ encodeURIComponent(that.getGroupProviderName()) + - "/" + encodeURIComponent(that.getGroupName()), - "Are you sure you want to remove group member"); - } - ); - }); - }}); - }; - - Group.prototype.close = function() { - updater.remove( this.groupUpdater ); - }; - - function GroupUpdater(containerNode, groupObj, controller) - { - var that = this; - - function findNode(name) { - return query("." + name, containerNode)[0]; - } - - function storeNodes(names) - { - for(var i = 0; i < names.length; i++) { - that[names[i]] = findNode(names[i]); - } - } - - storeNodes(["name", - "state", - "durable", - "lifetimePolicy", - "type"]); - this.name.innerHTML = entities.encode(String(groupObj.getGroupName())); - this.query = "api/latest/groupmember/"+ encodeURIComponent(groupObj.getGroupProviderName()) + "/" + encodeURIComponent(groupObj.getGroupName()); - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}).then(function(data) - { - that.groupMemberData = data; - - util.flattenStatistics( that.groupMemberData ); - - var gridProperties = { - keepSelection: true, - plugins: { - pagination: { - pageSizes: ["10", "25", "50", "100"], - description: true, - sizeSwitch: true, - pageStepper: true, - gotoButton: true, - maxPageStep: 4, - position: "bottom" - }, - indirectSelection: true - - }}; - - that.groupMembersUpdatableStore = new UpdatableStore(that.groupMemberData, findNode("groupMembers"), - [ { name: "Group Member Name", field: "name", width: "100%" }], - function(obj) - { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - - }); - } , gridProperties, EnhancedGrid); - - }); - - } - - GroupUpdater.prototype.update = function() - { - - var that = this; - - xhr.get({url: this.query, sync: properties.useSyncGet, handleAs: "json"}) - .then(function(data) { - that.groupMemberData = data; - - util.flattenStatistics( that.groupMemberData ); - - that.groupMembersUpdatableStore.update(that.groupMemberData); - }); - }; - - Group.prototype.deleteGroupMember = function() { - if(confirm("Are you sure you want to delete group member'" +this.name+"'?")) { - var query = "api/latest/groupmember/"+ encodeURIComponent(this.getGroupProviderName()) + "/" + encodeURIComponent(this.name); - this.success = true - var that = this; - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - that.contentPane.onClose() - that.controller.tabContainer.removeChild(that.contentPane); - that.contentPane.destroyRecursive(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!this.success ) { - util.xhrErrorHandler(this.failureReason); - } - } - } - - return Group; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/group/addGroupMember.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/group/addGroupMember.js deleted file mode 100644 index e653eb8ac1..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/group/addGroupMember.js +++ /dev/null @@ -1,97 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/json", - "qpid/common/util", - "dijit/form/NumberSpinner", // required by the form - /* dojox/ validate resources */ - "dojox/validate/us", "dojox/validate/web", - /* basic dijit classes */ - "dijit/Dialog", - "dijit/form/CheckBox", "dijit/form/Textarea", - "dijit/form/FilteringSelect", "dijit/form/TextBox", - "dijit/form/ValidationTextBox", "dijit/form/DateTextBox", - "dijit/form/TimeTextBox", "dijit/form/Button", - "dijit/form/RadioButton", "dijit/form/Form", - "dijit/form/DateTextBox", - /* basic dojox classes */ - "dojox/form/BusyButton", "dojox/form/CheckedMultiSelect", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, parser, array, event, json, util) { - - var addGroupMember = {}; - - var node = construct.create("div", null, win.body(), "last"); - - var convertToGroupMember = function convertToGroupMember(formValues) - { - var newGroupMember = {}; - newGroupMember.name = formValues.name; - return newGroupMember; - }; - - xhr.get({url: "group/addGroupMember.html", - sync: true, - load: function(data) { - var theForm; - node.innerHTML = data; - addGroupMember.dialogNode = dom.byId("addGroupMember"); - parser.instantiate([addGroupMember.dialogNode]); - - theForm = registry.byId("formAddGroupMember"); - theForm.on("submit", function(e) { - - event.stop(e); - if(theForm.validate()){ - - var newGroupMember = convertToGroupMember(theForm.getValues()); - var that = this; - - var url = "api/latest/groupmember/"+encodeURIComponent(addGroupMember.groupProvider) + - "/" + encodeURIComponent(addGroupMember.group); - util.post(url, newGroupMember, function(x){registry.byId("addGroupMember").hide();}); - return false; - - - }else{ - alert('Form contains invalid data. Please correct first'); - return false; - } - - }); - }}); - - addGroupMember.show = function(groupProvider, group) { - addGroupMember.groupProvider = groupProvider; - addGroupMember.group = group; - registry.byId("formAddGroupMember").reset(); - registry.byId("addGroupMember").show(); - }; - - return addGroupMember; - });
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/GroupManagingGroupProvider.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/GroupManagingGroupProvider.js deleted file mode 100644 index 418e04d34c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/GroupManagingGroupProvider.js +++ /dev/null @@ -1,196 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/parser", - "dojo/query", - "dojo/dom-construct", - "dojo/_base/connect", - "dojo/_base/window", - "dojo/_base/event", - "dojo/_base/json", - "dijit/registry", - "dojox/html/entities", - "qpid/common/util", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/UpdatableStore", - "dojox/grid/EnhancedGrid", - "dojo/text!groupprovider/showGroupManagingGroupProvider.html", - "dojox/grid/enhanced/plugins/Pagination", - "dojox/grid/enhanced/plugins/IndirectSelection", - "dojox/validate/us", "dojox/validate/web", - "dijit/Dialog", - "dijit/form/TextBox", - "dijit/form/ValidationTextBox", - "dijit/form/TimeTextBox", "dijit/form/Button", - "dijit/form/Form", - "dijit/form/DateTextBox", - "dojo/domReady!"], - function (xhr, dom, parser, query, construct, connect, win, event, json, registry, entities, util, properties, - updater, UpdatableStore, EnhancedGrid, template) - { - function GroupManagingGroupProvider(containerNode, groupProviderObj, controller) - { - var node = construct.create("div", null, containerNode, "last"); - var that = this; - this.name = groupProviderObj.name; - node.innerHTML = template; - this.controller = controller; - parser.parse(node).then(function(instances) - { - var groupDiv = query(".groups", node)[0]; - - var gridProperties = { - height: 400, - keepSelection: true, - plugins: { - pagination: { - pageSizes: [10, 25, 50, 100], - description: true, - sizeSwitch: true, - pageStepper: true, - gotoButton: true, - maxPageStep: 4, - position: "bottom" - }, - indirectSelection: true - - }}; - that.groupsGrid = new UpdatableStore([], groupDiv, - [ { name: "Group Name", field: "name", width: "100%" } - ], function(obj) { - connect.connect(obj.grid, "onRowDblClick", obj.grid, - function(evt){ - var idx = evt.rowIndex, - theItem = this.getItem(idx); - var name = obj.dataStore.getValue(theItem,"name"); - that.controller.show("group", name, groupProviderObj, theItem.id); - }); - }, gridProperties, EnhancedGrid); - var addGroupButton = query(".addGroupButton", node)[0]; - registry.byNode(addGroupButton).on("click", function(evt){ addGroup.show(groupProviderObj.name) }); - var deleteWidget = registry.byNode(query(".deleteGroupButton", node)[0]); - deleteWidget.on("click", function(evt){ event.stop(evt); that.deleteGroups(); }); - }); - } - - GroupManagingGroupProvider.prototype.deleteGroups = function() - { - var grid = this.groupsGrid.grid; - var data = grid.selection.getSelected(); - if(data.length) { - var that = this; - if(confirm("Delete " + data.length + " groups?")) { - var i, queryParam; - for(i = 0; i<data.length; i++) { - if(queryParam) { - queryParam += "&"; - } else { - queryParam = "?"; - } - - queryParam += "id=" + data[i].id; - } - var query = "api/latest/group/"+ encodeURIComponent(that.name) - + queryParam; - that.success = true - xhr.del({url: query, sync: true, handleAs: "json"}).then( - function(data) { - grid.setQuery({id: "*"}); - grid.selection.deselectAll(); - that.update(); - }, - function(error) {that.success = false; that.failureReason = error;}); - if(!that.success ) { - util.xhrErrorHandler(this.failureReason); - } - } -} - }; - - GroupManagingGroupProvider.prototype.update = function(data) - { - if (data) - { - this.groupsGrid.update(data.groups); - } - }; - - var addGroup = {}; - - var node = construct.create("div", null, win.body(), "last"); - - var convertToGroup = function convertToGroup(formValues) { - var newGroup = {}; - newGroup.name = formValues.name; - for(var propName in formValues) - { - if(formValues.hasOwnProperty(propName)) { - if(formValues[ propName ] !== "") { - newGroup[ propName ] = formValues[propName]; - } - } - } - - return newGroup; - }; - - - xhr.get({url: "groupprovider/addGroup.html", - sync: true, - load: function(data) { - var theForm; - node.innerHTML = data; - addGroup.dialogNode = dom.byId("addGroup"); - parser.instantiate([addGroup.dialogNode]); - - var that = this; - - theForm = registry.byId("formAddGroup"); - theForm.on("submit", function(e) { - - event.stop(e); - if(theForm.validate()){ - - var newGroup = convertToGroup(theForm.getValues()); - - var url = "api/latest/group/"+encodeURIComponent(addGroup.groupProvider); - util.post(url, newGroup, function(x){registry.byId("addGroup").hide();}); - return false; - - - }else{ - alert('Form contains invalid data. Please correct first'); - return false; - } - - }); - }}); - - addGroup.show = function(groupProvider) { - addGroup.groupProvider = groupProvider; - registry.byId("formAddGroup").reset(); - registry.byId("addGroup").show(); - }; - - return GroupManagingGroupProvider; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/groupfile/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/groupfile/add.js deleted file mode 100644 index 6543d6a797..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/groupfile/add.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/dom","dojo/query", "dojo/_base/array", "dijit/registry","qpid/common/util", "qpid/common/metadata"], - function (dom, query, array, registry, util, metadata) - { - - return { show: function(data) - { - var that=this; - util.parseHtmlIntoDiv(data.containerNode, "groupprovider/groupfile/add.html", - function() - { - if (data.data) - { - var pathWidget = registry.byNode(query(".addGroupProviderPath", data.containerNode)[0]); - pathWidget.set("value", data.data.path); - } - }); - } - }; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/groupfile/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/groupfile/show.js deleted file mode 100644 index a559140898..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/groupfile/show.js +++ /dev/null @@ -1,37 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["qpid/common/util", "dojo/domReady!"], - function (util, metadata) - { - - function GroupFile(data) - { - util.buildUI(data.containerNode, data.parent, "groupprovider/groupfile/show.html", ["path"], this); - } - - GroupFile.prototype.update = function(data) - { - util.updateUI(data, ["path"], this); - } - - return GroupFile; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/managedgroupprovider/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/managedgroupprovider/add.js deleted file mode 100644 index fd8e09dcda..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/managedgroupprovider/add.js +++ /dev/null @@ -1,26 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], - function (dom, query, array, registry, util, metadata) - { - return { show: function(data) { /* nothing to do */ } }; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/managedgroupprovider/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/managedgroupprovider/show.js deleted file mode 100644 index ed6a0e155b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/managedgroupprovider/show.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([], - function () - { - - function ManagedGroupProvider(data) - { - } - - ManagedGroupProvider.prototype.update = function(data) - { - } - - return ManagedGroupProvider; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/logs/LogFileDownloadDialog.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/logs/LogFileDownloadDialog.js deleted file mode 100644 index c013a88d0a..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/logs/LogFileDownloadDialog.js +++ /dev/null @@ -1,178 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([ - "dojo/_base/declare", - "dojo/_base/event", - "dojo/_base/xhr", - "dojo/_base/connect", - "dojo/dom-construct", - "dojo/query", - "dojo/parser", - "dojo/store/Memory", - "dojo/data/ObjectStore", - "qpid/management/UserPreferences", - "dojo/number", - "dijit/registry", - "dijit/Dialog", - "dijit/form/Button", - "dojox/grid/EnhancedGrid", - "dojo/text!../../../logs/showLogFileDownloadDialog.html", - "dojo/domReady!" -], function(declare, event, xhr, connect, domConstruct, query, parser, Memory, ObjectStore, UserPreferences, number, - registry, Dialog, Button, EnhancedGrid, template){ - - -return declare("qpid.management.logs.LogFileDownloadDialog", null, { - - templateString: template, - containerNode: null, - widgetsInTemplate: true, - logFileDialog: null, - logFilesGrid: null, - downloadLogsButton: null, - closeButton: null, - - constructor: function(args){ - var that = this; - this.containerNode = domConstruct.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances){that._postParse();}); - }, - _postParse: function() - { - var that = this; - this.logFileTreeDiv = query(".logFilesGrid", this.containerNode)[0]; - this.downloadLogsButton = registry.byNode(query(".downloadLogsButton", this.containerNode)[0]); - this.closeButton = registry.byNode(query(".downloadLogsDialogCloseButton", this.containerNode)[0]); - - var self = this; - this.closeButton.on("click", function(e){self._onCloseButtonClick(e);}); - this.downloadLogsButton.on("click", function(e){self._onDownloadButtonClick(e);}); - this.downloadLogsButton.set("disabled", true) - - this.logFileDialog = new Dialog({ - title:"Broker Log Files", - style: "width: 600px", - content: this.containerNode - }); - - var layout = [ - { name: "Appender", field: "appenderName", width: "auto"}, - { name: "Name", field: "name", width: "auto"}, - { name: "Size", field: "size", width: "60px", - formatter: function(val){ - return val > 1024 ? (val > 1048576? number.round(val/1048576) + "MB": number.round(val/1024) + "KB") : val + "bytes"; - } - }, - { name: "Last Modified", field: "lastModified", width: "250px", - formatter: function(val) { - return UserPreferences.formatDateTime(val, {addOffset: true, appendTimeZone: true}); - } - } - ]; - - var gridProperties = { - store: new ObjectStore({objectStore: new Memory({data: [], idProperty: "id"}) }), - structure: layout, - autoHeight: true, - plugins: { - pagination: { - pageSizes: [10, 25, 50, 100], - description: true, - sizeSwitch: true, - pageStepper: true, - gotoButton: true, - maxPageStep: 4, - position: "bottom" - }, - indirectSelection: { - headerSelector:true, - width:"20px", - styles:"text-align: center;" - } - } - }; - - this.logFilesGrid = new EnhancedGrid(gridProperties, this.logFileTreeDiv); - var self = this; - var downloadButtonToggler = function(rowIndex){ - var data = self.logFilesGrid.selection.getSelected(); - self.downloadLogsButton.set("disabled",!data.length ); - }; - connect.connect(this.logFilesGrid.selection, 'onSelected', downloadButtonToggler); - connect.connect(this.logFilesGrid.selection, 'onDeselected', downloadButtonToggler); - }, - - _onCloseButtonClick: function(evt){ - event.stop(evt); - this.logFileDialog.hide(); - }, - - _onDownloadButtonClick: function(evt){ - event.stop(evt); - var data = this.logFilesGrid.selection.getSelected(); - if (data.length) - { - var query = ""; - for(var i = 0 ; i< data.length; i++) - { - if (i>0) - { - query+="&"; - } - query+="l="+encodeURIComponent(data[i].appenderName +'/' + data[i].name); - } - window.location="service/logfile?" + query; - this.logFileDialog.hide(); - } - }, - - destroy: function(){ - this.inherited(arguments); - if (this.logFileDialog) - { - this.logFileDialog.destroyRecursive(); - this.logFileDialog = null; - } - }, - - showDialog: function(){ - var self = this; - var requestArguments = {url: "service/logfilenames", sync: true, handleAs: "json"}; - xhr.get(requestArguments).then(function(data){ - try - { - self.logFilesGrid.store.objectStore.setData(data); - self.logFilesGrid.startup(); - self.logFileDialog.startup(); - self.logFileDialog.show(); - self.logFilesGrid._refresh(); - - } - catch(e) - { - console.error(e); - } - }); - } - - }); - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/logs/LogViewer.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/logs/LogViewer.js deleted file mode 100644 index 4a76110a58..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/logs/LogViewer.js +++ /dev/null @@ -1,228 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/query", - "dojo/date/locale", - "dijit/registry", - "qpid/management/UserPreferences", - "qpid/common/grid/GridUpdater", - "qpid/common/grid/UpdatableGrid", - "qpid/management/logs/LogFileDownloadDialog", - "dojo/text!../../../logs/showLogViewer.html", - "dojo/domReady!"], - function (xhr, parser, query, locale, registry, UserPreferences, GridUpdater, UpdatableGrid, LogFileDownloadDialog, markup) { - - var defaulGridRowLimit = 4096; - var currentTimeZone; - - function dataTransformer(data) - { - for(var i=0; i < data.length; i++) - { - data[i].time = UserPreferences.addTimeZoneOffsetToUTC(data[i].timestamp); - } - return data; - } - - function LogViewer(name, parent, controller) { - var self = this; - - this.name = name; - this.lastLogId = 0; - this.contentPane = null; - this.downloadLogsButton = null; - this.downloadLogDialog = null; - } - - LogViewer.prototype.getTitle = function() { - return "Log Viewer"; - }; - - LogViewer.prototype.open = function(contentPane) { - var self = this; - this.contentPane = contentPane; - this.contentPane.containerNode.innerHTML = markup; - - parser.parse(this.contentPane.containerNode).then(function(instances){self._postParse();}); - }; - LogViewer.prototype._postParse = function() - { - var self = this; - - this.downloadLogsButton = registry.byNode(query(".downloadLogs", this.contentPane.containerNode)[0]); - this.downloadLogDialog = new LogFileDownloadDialog(); - - this.downloadLogsButton.on("click", function(evt){ - self.downloadLogDialog.showDialog(); - }); - this._buildGrid(); - }; - - LogViewer.prototype._buildGrid = function() { - var self = this; - currentTimeZone = UserPreferences.getTimeZoneDescription(); - - var gridStructure = [ - { - hidden: false, - name: "ID", - field: "id", - width: "50px", - datatype: "number", - filterable: true - }, - { - name: "Date", field: "time", width: "100px", datatype: "date", - formatter: function(val) { - return UserPreferences.formatDateTime(val, {selector:"date"}); - } - }, - { name: "Time ", field: "time", width: "100px", datatype: "time", - formatter: function(val) { - return UserPreferences.formatDateTime(val, {selector:"time"}); - } - }, - { - name: "Time zone", - field: "time", - width: "80px", - datatype: "string", - hidden: true, - filterable: false, - formatter: function(val) { - return currentTimeZone; - } - }, - { name: "Level", field: "level", width: "50px", datatype: "string", autoComplete: true, hidden: true}, - { name: "Logger", field: "logger", width: "150px", datatype: "string", autoComplete: false, hidden: true}, - { name: "Thread", field: "thread", width: "100px", datatype: "string", hidden: true}, - { name: "Log Message", field: "message", width: "auto", datatype: "string"} - ]; - - var gridNode = query("#broker-logfile", this.contentPane.containerNode)[0]; - try - { - var updater = new GridUpdater({ - updatable: false, - serviceUrl: function() - { - return "service/logrecords?lastLogId=" + self.lastLogId; - }, - onUpdate: function(items) - { - if (items) - { - var maxId = -1; - for(var i in items) - { - var item = items[i]; - if (item.id > maxId) - { - maxId = item.id - } - } - if (maxId != -1) - { - self.lastLogId = maxId - } - } - }, - append: true, - appendLimit: defaulGridRowLimit, - dataTransformer: dataTransformer - }); - this.grid = new UpdatableGrid(updater.buildUpdatableGridArguments({ - structure: gridStructure, - selectable: true, - selectionMode: "none", - sortInfo: -1, - sortFields: [{attribute: 'id', descending: true}], - plugins:{ - nestedSorting:true, - enhancedFilter:{defaulGridRowLimit: defaulGridRowLimit,displayLastUpdateTime:true}, - indirectSelection: false, - pagination: {defaultPageSize: 10} - } - }), gridNode); - var onStyleRow = function(row) - { - var item = self.grid.getItem(row.index); - if(item){ - var level = self.grid.store.getValue(item, "level", null); - var changed = false; - if(level == "ERROR"){ - row.customClasses += " redBackground"; - changed = true; - } else if(level == "WARN"){ - row.customClasses += " yellowBackground"; - changed = true; - } else if(level == "DEBUG"){ - row.customClasses += " grayBackground"; - changed = true; - } - if (changed) - { - self.grid.focus.styleRow(row); - } - } - }; - this.grid.on("styleRow", onStyleRow); - this.grid.startup(); - UserPreferences.addListener(this); - } - catch(err) - { - if (console && console.error) - { - console.error(err); - } - } - }; - - LogViewer.prototype.close = function() { - UserPreferences.removeListener(this); - if (this.grid) - { - this.grid.destroy(); - this.grid = null; - } - if (this.downloadLogDialog) - { - this.downloadLogDialog.destroy(); - this.downloadLogDialog = null; - } - if (this.downloadLogsButton) - { - this.downloadLogsButton.destroy(); - this.downloadLogsButton = null; - } - }; - - LogViewer.prototype.onPreferencesChange = function(data) - { - currentTimeZone = UserPreferences.getTimeZoneDescription(); - dataTransformer(this.grid.updater.memoryStore.data); - this.grid._refresh(); - }; - - return LogViewer; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/moveCopyMessages.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/moveCopyMessages.js deleted file mode 100644 index f1afff9c03..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/moveCopyMessages.js +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - 'dojo/_base/json', - "dojo/store/Memory", - "dijit/form/FilteringSelect", - "dojo/query", - "dojo/_base/connect", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, parser, array, event, json, Memory, FilteringSelect, query, connect) { - - var moveMessages = {}; - - var node = construct.create("div", null, win.body(), "last"); - - xhr.get({url: "moveCopyMessages.html", - sync: true, - load: function(data) { - var theForm; - node.innerHTML = data; - moveMessages.dialogNode = dom.byId("moveMessages"); - parser.instantiate([moveMessages.dialogNode]); - - theForm = registry.byId("formMoveMessages"); - - - var cancelButton = query(".moveMessageCancel")[0]; - connect.connect(registry.byNode(cancelButton), "onClick", - function(evt){ - event.stop(evt); - registry.byId("moveMessages").hide(); - }); - - - theForm.on("submit", function(e) { - - event.stop(e); - if(theForm.validate()){ - - moveMessages.data.destinationQueue = theForm.getValues()["queue"]; - var that = this; - - xhr.post({url: "service/message/"+encodeURIComponent(moveMessages.vhost) - +"/"+encodeURIComponent(moveMessages.queue), - sync: true, handleAs: "json", - headers: { "Content-Type": "application/json"}, - postData: json.toJson(moveMessages.data), - load: function(x) {that.success = true; }, - error: function(error) {that.success = false; that.failureReason = error;}}); - - if(this.success === true) { - registry.byId("moveMessages").hide(); - if(moveMessages.next) { - moveMessages.next(); - } - } else { - alert("Error:" + this.failureReason); - } - - return false; - - - }else{ - alert('Form contains invalid data. Please correct first'); - return false; - } - - }); - - }}); - - moveMessages.show = function(obj, next) { - var that = this; - - moveMessages.vhost = obj.virtualhost; - moveMessages.queue = obj.queue; - moveMessages.data = obj.data; - moveMessages.next = next; - registry.byId("formMoveMessages").reset(); - - - - xhr.get({url: "api/latest/queue/" + encodeURIComponent(obj.virtualhost) + "?depth=0", - handleAs: "json"}).then( - function(data) { - var queues = []; - for(var i=0; i < data.length; i++) { - queues[i] = {id: data[i].name, name: data[i].name}; - } - var queueStore = new Memory({ data: queues }); - - - if(that.queueChooser) { - that.queueChooser.destroy( false ); - } - var queueDiv = dom.byId("moveMessages.selectQueueDiv"); - var input = construct.create("input", {id: "moveMessagesSelectQueue"}, queueDiv); - - that.queueChooser = new FilteringSelect({ id: "moveMessagesSelectQueue", - name: "queue", - store: queueStore, - searchAttr: "name"}, input); - - - - registry.byId("moveMessages").show(); - - - }); - - - }; - - return moveMessages; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/plugin/managementhttp.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/plugin/managementhttp.js deleted file mode 100644 index 4c32cce7cd..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/plugin/managementhttp.js +++ /dev/null @@ -1,185 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/parser", - "dojo/query", - "dojo/dom-construct", - "dojo/_base/connect", - "dojo/_base/window", - "dojo/_base/event", - "dojo/_base/json", - "dijit/registry", - "qpid/common/util", - "qpid/common/properties", - "qpid/common/updater", - "dijit/form/Button", - "dijit/form/ValidationTextBox", - "dijit/form/CheckBox", - "dijit/form/NumberSpinner", - "dojo/domReady!"], - function (xhr, dom, parser, query, construct, connect, win, event, json, registry, util, properties, updater) { - - function ManagementHttp(containerNode, pluginObject, controller) { - var node = construct.create("div", null, containerNode, "last"); - var that = this; - this.name = pluginObject.name; - xhr.get({ - url: "plugin/showManagementHttp.html", - sync: true, - load: function(data) { - node.innerHTML = data; - parser.parse(node).then(function(instances) - { - that.managementHttpUpdater= new ManagementHttpUpdater(node, pluginObject, controller); - that.managementHttpUpdater.update(true); - updater.add( that.managementHttpUpdater); - - var editButton = query(".editPluginButton", node)[0]; - connect.connect(registry.byNode(editButton), "onClick", function(evt){ that.edit(); }); - }); - }}); - } - - ManagementHttp.prototype.close = function() { - updater.remove( this.managementHttpUpdater ); - }; - - ManagementHttp.prototype.edit = function() { - var widgetFactories = [{ - name: "name", - createWidget: function(plugin) { - return new dijit.form.ValidationTextBox({ - required: true, - value: plugin.name, - disabled: true, - label: "Name:", - regexp: "^[\x20-\x2e\x30-\x7F]{1,255}$", - name: "name"}); - } - }, { - name: "httpBasicAuthenticationEnabled", - createWidget: function(plugin) { - return new dijit.form.CheckBox({ - required: false, - checked: plugin.httpBasicAuthenticationEnabled, - label: "HTTP Basic Authentication Enabled:", - name: "httpBasicAuthenticationEnabled"}); - } - }, { - name: "httpsBasicAuthenticationEnabled", - createWidget: function(plugin) { - return new dijit.form.CheckBox({ - required: false, - checked: plugin.httpsBasicAuthenticationEnabled, - label: "HTTPS Basic Authentication Enabled:", - name: "httpsBasicAuthenticationEnabled"}); - } - }, { - name: "httpSaslAuthenticationEnabled", - createWidget: function(plugin) { - return new dijit.form.CheckBox({ - required: false, - checked: plugin.httpSaslAuthenticationEnabled, - label: "HTTP SASL Authentication Enabled:", - name: "httpSaslAuthenticationEnabled"}); - } - }, { - name: "httpsSaslAuthenticationEnabled", - createWidget: function(plugin) { - return new dijit.form.CheckBox({ - required: false, - checked: plugin.httpsSaslAuthenticationEnabled, - label: "HTTPS SASL Authentication Enabled:", - name: "httpsSaslAuthenticationEnabled"}); - } - }, { - name: "sessionTimeout", - createWidget: function(plugin) { - return new dijit.form.NumberSpinner({ - invalidMessage: "Invalid value", - required: false, - value: plugin.sessionTimeout, - smallDelta: 1, - constraints: {min:1,places:0, pattern: "#####"}, - label: "Session timeout (s):", - name: "sessionTimeout" - }); - } - }, { - name: "compressResponses", - createWidget: function(plugin) { - return new dijit.form.CheckBox({ - required: false, - checked: plugin.compressResponses, - label: "Compress responses:", - name: "compressResponses"}); - } - } - ]; - var data = this.managementHttpUpdater.pluginData; - util.showSetAttributesDialog( - widgetFactories, - data, - "api/latest/plugin/" + encodeURIComponent(data.name), - "Edit plugin - " + data.name, - "Plugin", - "MANAGEMENT-HTTP"); - }; - - function ManagementHttpUpdater(node, pluginObject, controller) - { - this.controller = controller; - this.query = "api/latest/plugin/"+encodeURIComponent(pluginObject.name); - this.name = pluginObject.name; - this.httpBasicAuthenticationEnabled = query(".httpBasicAuthenticationEnabled", node)[0]; - this.httpsBasicAuthenticationEnabled = query(".httpsBasicAuthenticationEnabled", node)[0]; - this.sessionTimeout = query(".sessionTimeout", node)[0]; - this.httpsSaslAuthenticationEnabled = query(".httpsSaslAuthenticationEnabled", node)[0]; - this.httpSaslAuthenticationEnabled = query(".httpSaslAuthenticationEnabled", node)[0]; - this.compressResponses = query(".compressResponses", node)[0]; - - } - - ManagementHttpUpdater.prototype.update = function(syncRequest) - { - var that = this; - - function showBoolean(val) - { - return "<input type='checkbox' disabled='disabled' "+(val ? "checked='checked'": "")+" />" ; - } - - xhr.get({url: this.query, sync: syncRequest ? syncRequest : properties.useSyncGet, handleAs: "json"}) - .then(function(data) { - that.pluginData = data[0]; - that.httpBasicAuthenticationEnabled.innerHTML = showBoolean(that.pluginData.httpBasicAuthenticationEnabled); - that.httpsBasicAuthenticationEnabled.innerHTML = showBoolean(that.pluginData.httpsBasicAuthenticationEnabled); - that.httpsSaslAuthenticationEnabled.innerHTML = showBoolean(that.pluginData.httpsSaslAuthenticationEnabled); - that.httpSaslAuthenticationEnabled.innerHTML = showBoolean(that.pluginData.httpSaslAuthenticationEnabled); - that.compressResponses.innerHTML = showBoolean(that.pluginData.compressResponses); - that.sessionTimeout.innerHTML = that.pluginData.sessionTimeout; - }); - - }; - - return ManagementHttp; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/plugin/managementjmx.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/plugin/managementjmx.js deleted file mode 100644 index 4141b6b670..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/plugin/managementjmx.js +++ /dev/null @@ -1,121 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/parser", - "dojo/query", - "dojo/dom-construct", - "dojo/_base/connect", - "dojo/_base/window", - "dojo/_base/event", - "dojo/_base/json", - "dijit/registry", - "qpid/common/util", - "qpid/common/properties", - "qpid/common/updater", - "dojo/domReady!"], - function (xhr, dom, parser, query, construct, connect, win, event, json, registry, util, properties, updater) { - - function ManagementJmx(containerNode, pluginObject, controller) { - var node = construct.create("div", null, containerNode, "last"); - var that = this; - this.name = pluginObject.name; - xhr.get({ - url: "plugin/showManagementJmx.html", - sync: true, - load: function(data) { - node.innerHTML = data; - parser.parse(node).then(function(instances) - { - that.managementJmxUpdater= new ManagementJmxUpdater(node, pluginObject, controller); - that.managementJmxUpdater.update(true); - updater.add( that.managementJmxUpdater); - - var editButton = query(".editPluginButton", node)[0]; - connect.connect(registry.byNode(editButton), "onClick", function(evt){ that.edit(); }); - }); - }}); - } - - ManagementJmx.prototype.close = function() { - updater.remove( this.managementJmxUpdater ); - }; - - ManagementJmx.prototype.edit = function() { - var widgetFactories = [{ - name: "name", - createWidget: function(plugin) { - return new dijit.form.ValidationTextBox({ - required: true, - value: plugin.name, - disabled: true, - label: "Name:", - regexp: "^[\x20-\x2e\x30-\x7F]{1,255}$", - name: "name"}); - } - }, { - name: "usePlatformMBeanServer", - createWidget: function(plugin) { - return new dijit.form.CheckBox({ - required: false, - checked: plugin.usePlatformMBeanServer, - label: "Use Platform MBean Server:", - name: "usePlatformMBeanServer"}); - } - } - ]; - var data = this.managementJmxUpdater.pluginData; - util.showSetAttributesDialog( - widgetFactories, - data, - "api/latest/plugin/" + encodeURIComponent(data.name), - "Edit plugin - " + data.name, - "Plugin", - "MANAGEMENT-JMX"); - }; - - function ManagementJmxUpdater(node, pluginObject, controller) - { - this.controller = controller; - this.query = "api/latest/plugin/"+encodeURIComponent(pluginObject.name); - this.name = pluginObject.name; - this.usePlatformMBeanServer = query(".usePlatformMBeanServer", node)[0]; - } - - ManagementJmxUpdater.prototype.update = function(syncRequest) - { - var that = this; - - function showBoolean(val) - { - return "<input type='checkbox' disabled='disabled' "+(val ? "checked='checked'": "")+" />" ; - } - - xhr.get({url: this.query, sync: syncRequest ? syncRequest : properties.useSyncGet, handleAs: "json"}) - .then(function(data) { - that.pluginData = data[0]; - that.usePlatformMBeanServer.innerHTML = showBoolean(that.pluginData.usePlatformMBeanServer); - }); - - }; - - return ManagementJmx; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/PreferencesProviderForm.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/PreferencesProviderForm.js deleted file mode 100644 index 994c748803..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/PreferencesProviderForm.js +++ /dev/null @@ -1,198 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([ - "qpid/common/util", - "qpid/common/metadata", - "dojo/_base/xhr", - "dojo/_base/declare", - "dojo/_base/array", - "dojo/dom-construct", - "dojo/_base/window", - "dojo/query", - "dojo/json", - "dijit/_WidgetBase", - "dijit/_OnDijitClickMixin", - "dijit/_TemplatedMixin", - "dijit/_WidgetsInTemplateMixin", - "dijit/registry", - "dojo/text!preferencesprovider/preferencesProviderForm.html", - "dojox/html/entities", - "dijit/form/ValidationTextBox", - "dijit/form/FilteringSelect", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], -function (util, metadata, xhr, declare, array, domConstruct, win, query, json, _WidgetBase, - _OnDijitClickMixin, _TemplatedMixin, _WidgetsInTemplateMixin, registry, template, entities) - { - - return declare("qpid.preferencesprovider.PreferencesProviderForm", - [_WidgetBase, _OnDijitClickMixin, _TemplatedMixin, _WidgetsInTemplateMixin], { - - templateString: template, - domNode: null, - preferencesProviderForm : null, - preferencesProviderNameWidget : null, - preferencesProviderTypeWidget : null, - preferencesProviderTypeFieldsContainer: null, - - buildRendering: function() - { - //Strip out the apache comment header from the template html as comments unsupported. - this.templateString = this.templateString.replace(/<!--[\s\S]*?-->/g, ""); - this.inherited(arguments); - }, - postCreate: function() - { - this.inherited(arguments); - var that = this; - - this.preferencesProviderNameWidget.set("regExpGen", util.nameOrContextVarRegexp); - - var supportedPreferencesProviderTypes = metadata.getTypesForCategory("PreferencesProvider"); - supportedPreferencesProviderTypes.sort(); - supportedPreferencesProviderTypes.splice(0,0,"None"); - var preferencesProviderTypeStore = util.makeTypeStore(supportedPreferencesProviderTypes); - this.preferencesProviderTypeWidget.set("store", preferencesProviderTypeStore); - this.preferencesProviderTypeWidget.on("change", function(type){that._preferencesProviderTypeChanged(type);}); - this.preferencesProviderForm.on("submit", function() { return false; }) - }, - reset: function() - { - this.data = null; - this.preferencesProviderForm.reset(); - this.preferencesProviderTypeWidget.set("value", "None"); - }, - submit: function(encodedAuthenticationProviderName) - { - if (this.preferencesProviderTypeWidget.get("value") != "None") - { - var preferencesProviderData = util.getFormWidgetValues(this.preferencesProviderForm, this.data) - var encodedPreferencesProviderName = encodeURIComponent(this.preferencesProviderNameWidget.get("value")); - var url = "api/latest/preferencesprovider/" + encodedAuthenticationProviderName; - if (this.data) - { - // update request - url += "/" + encodedPreferencesProviderName; - } - return util.post(url, preferencesProviderData); - } - return { success: true, failureReason: null }; - }, - validate: function() - { - return this.preferencesProviderForm.validate(); - }, - load: function(authenticationProviderName, providerName) - { - var that = this; - xhr.get({ - url: "api/latest/preferencesprovider/" + encodeURIComponent(authenticationProviderName) + "/" + encodeURIComponent(providerName), - handleAs: "json" - }).then(function(data){that._load(data[0])}); - }, - setData: function(data) - { - this._load(data); - }, - _load:function(data) - { - data = data || {} - this.data = data; - this.preferencesProviderNameWidget.set("value", data.name); - if (data.type == this.preferencesProviderTypeWidget.get("value")) - { - // re-create UI anyway - this._preferencesProviderTypeChanged(data.type); - } - else - { - this.preferencesProviderTypeWidget.set("value", data.type); - } - }, - _preferencesProviderTypeChanged: function(type) - { - var typeFieldsContainer = this.preferencesProviderTypeFieldsContainer; - var widgets = registry.findWidgets(typeFieldsContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(typeFieldsContainer); - this._toggleWidgets(type); - if (type) - { - if (type == "None") - { - this.preferencesProviderNameWidget.set("value", ""); - } - else - { - var that = this; - require([ "qpid/management/preferencesprovider/" + type.toLowerCase() + "/add"], function(typeUI) - { - try - { - typeUI.show({containerNode:typeFieldsContainer, parent: that, data: that.data}); - util.applyMetadataToWidgets(typeFieldsContainer, "PreferencesProvider", type); - } - catch(e) - { - console.warn(e); - } - }); - } - } - }, - _toggleWidgets: function(type) - { - if (this.disabled) - { - this.preferencesProviderNameWidget.set("disabled", true); - this.preferencesProviderTypeWidget.set("disabled", true); - } - else - { - if (this.data) - { - // editing - this.preferencesProviderNameWidget.set("disabled", true); - this.preferencesProviderTypeWidget.set("disabled", true); - } - else - { - this.preferencesProviderNameWidget.set("disabled", !type || type == "None"); - this.preferencesProviderTypeWidget.set("disabled", false); - } - } - }, - _setDisabledAttr: function(disabled) - { - this.inherited(arguments); - this.disabled = disabled; - if (disabled) - { - this.reset(); - } - else - { - this._toggleWidgets(this.preferencesProviderTypeWidget.value); - } - }, - }); -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/filesystempreferences/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/filesystempreferences/add.js deleted file mode 100644 index 929d318b4f..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/filesystempreferences/add.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["dojo/query", "dijit/registry", "qpid/common/util"], - function (query, registry, util) - { - return { - show: function (data) - { - util.parseHtmlIntoDiv(data.containerNode, "preferencesprovider/filesystempreferences/add.html", - function() - { - if (data.data) - { - var pathWidget = registry.byNode(query(".addPreferencesProviderPath", data.containerNode)[0]); - pathWidget.set("value", data.data.path); - } - }); - } - }; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/filesystempreferences/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/filesystempreferences/show.js deleted file mode 100644 index 660b6673f2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/filesystempreferences/show.js +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/string", - "dojox/html/entities", - "dojo/query", - "dojo/domReady!"], - function (xhr, parser, json, entities, query) { - - function FileSystemPreferences(containerNode) { - var that = this; - xhr.get({url: "preferencesprovider/filesystempreferences/show.html", - sync: true, - load: function(template) { - containerNode.innerHTML = template; - parser.parse(containerNode).then(function(instances) - { - that.preferencesProviderPath=query(".fileSystemPreferencesProviderPath", containerNode)[0]; - }); - }}); - } - - FileSystemPreferences.prototype.update=function(data) - { - this.preferencesProviderPath.innerHTML = entities.encode(String(data["path"])); - }; - - return FileSystemPreferences; -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/showMessage.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/showMessage.js deleted file mode 100644 index cc6242b976..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/showMessage.js +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/dom-class", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - 'dojo/_base/json', - "dojo/query", - "dojo/_base/connect", - "qpid/common/properties", - "dojox/html/entities", - "qpid/management/UserPreferences", - "dojo/domReady!"], - function (xhr, dom, construct, domClass, win, registry, parser, array, event, json, query, connect, properties, entities, UserPreferences) { - - - function encode(val){ - return typeof val === 'string' ? entities.encode(val) : val; - } - - var populatedFields = []; - var showMessage = {}; - - showMessage.hide = function () { - registry.byId("showMessage").hide(); - }; - - showMessage.loadViewMessage = function(data) { - var that = this; - node.innerHTML = data; - showMessage.dialogNode = dom.byId("showMessage"); - parser.instantiate([showMessage.dialogNode]); - - var closeButton = query(".closeViewMessage")[0]; - connect.connect(closeButton, "onclick", - function (evt) { - event.stop(evt); - showMessage.hide(); - }); - }; - - showMessage.populateShowMessage = function(data) { - - // clear fields set by previous invocation. - if(populatedFields) { - for(var i = 0 ; i < populatedFields.length; i++) { - populatedFields[i].innerHTML = ""; - } - populatedFields = []; - } - - for(var attrName in data) { - if(data.hasOwnProperty(attrName)) { - var fields = query(".message-"+attrName, this.dialogNode); - if(fields && fields.length != 0) { - var field = fields[0]; - populatedFields.push(field); - var val = data[attrName]; - if(val != null) { - if(domClass.contains(field,"map")) { - var tableStr = "<table style='border: 1pt'><tr><th style='width: 6em; font-weight: bold'>Header</th><th style='font-weight: bold'>Value</th></tr>"; - for(var name in val) { - if(val.hasOwnProperty(name)) { - - tableStr += "<tr><td>"+encode(name)+"</td>"; - tableStr += "<td>"+encode(val[ name ])+"</td></tr>"; - } - field.innerHTML = tableStr; - } - tableStr += "</table>"; - } else if(domClass.contains(field,"datetime")) { - field.innerHTML = UserPreferences.formatDateTime(val, {addOffset: true, appendTimeZone: true}); - } else { - field.innerHTML = encode(val); - } - } - } - } - } - var contentField = query(".message-content", this.dialogNode)[0]; - - if(data.mimeType && data.mimeType.match(/text\/.*/)) { - xhr.get({url: "service/message-content/" + encodeURIComponent(showMessage.virtualhost) - + "/" + encodeURIComponent(showMessage.queue) - + "/" + encodeURIComponent(showMessage.messageNumber), - sync: true - - }).then(function(obj) { contentField.innerHTML = encode(obj) }); - } else { - contentField.innerHTML = "<a href=\"" + "service/message-content/" + encodeURIComponent(showMessage.virtualhost) - + "/" + encodeURIComponent(showMessage.queue) - + "/" + encodeURIComponent(showMessage.messageNumber) - + "\" target=\"_blank\">Download</a>"; - } - populatedFields.push(contentField); - - registry.byId("showMessage").show(); - }; - - showMessage.show = function(obj) { - showMessage.virtualhost = obj.virtualhost; - showMessage.queue = obj.queue; - showMessage.messageNumber = obj.messageNumber; - - xhr.get({url: "service/message/" + encodeURIComponent(obj.virtualhost) - + "/" + encodeURIComponent(obj.queue) - + "/" + encodeURIComponent(obj.messageNumber), - sync: properties.useSyncGet, - handleAs: "json", - load: this.populateShowMessage - }); - }; - - var node = construct.create("div", null, win.body(), "last"); - - xhr.get({url: "showMessage.html", - sync: true, - load: showMessage.loadViewMessage - }); - - return showMessage; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filekeystore/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filekeystore/add.js deleted file mode 100644 index dfe8e5059a..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filekeystore/add.js +++ /dev/null @@ -1,101 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/dom", - "dojo/query", - "dojo/_base/array", - "dijit/registry", - "qpid/common/util", - "qpid/common/metadata", - "dojo/parser", - "dojo/text!store/filekeystore/add.html", - "dojo/domReady!"], - function (dom, query, array, registry, util, metadata, parser, template) - { - var addKeyStore = - { - show: function(data) - { - var that=this; - this.containerNode = data.containerNode; - data.containerNode.innerHTML = template; - parser.parse(this.containerNode).then(function(instances) - { - that.keyStoreOldBrowserWarning = dom.byId("addStore.oldBrowserWarning"); - - if (!window.FileReader) - { - that.keyStoreOldBrowserWarning.innerHTML = "File upload requires a more recent browser with HTML5 support"; - that.keyStoreOldBrowserWarning.className = that.keyStoreOldBrowserWarning.className.replace("hidden", ""); - } - - if (data.effectiveData) - { - that.update(data.effectiveData); - } - - util.applyMetadataToWidgets(data.containerNode, "KeyStore", "FileKeyStore"); - }); - }, - update: function(effectiveData) - { - var attributes = metadata.getMetaData("KeyStore", "FileKeyStore").attributes; - var widgets = registry.findWidgets(this.containerNode); - array.forEach(widgets, function(item) - { - var name = item.id.replace("addStore.",""); - if (name in attributes ) - { - var attribute = attributes[name]; - var value = effectiveData[name]; - if (value) - { - if (attribute.secure) - { - if (!/^\*+/.test(value) ) - { - item.set("value", value); - } - else - { - item.set("required", false); - if (name == "storeUrl") - { - item.set("uploaded", true) - } - else - { - item.set("placeHolder", value); - } - } - } - else - { - item.set("value", value); - } - } - } - }); - } - }; - - return addKeyStore; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filekeystore/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filekeystore/show.js deleted file mode 100644 index fbe2bbc9c2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filekeystore/show.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["qpid/common/util", "qpid/common/metadata", "dojo/domReady!"], - function (util, metadata) - { - - function FileKeyStoreProvider(data) - { - this.fields = []; - var attributes = metadata.getMetaData("KeyStore", "FileKeyStore").attributes; - for(var name in attributes) - { - this.fields.push(name); - } - util.buildUI(data.containerNode, data.parent, "store/filekeystore/show.html", this.fields, this); - } - - FileKeyStoreProvider.prototype.update = function(data) - { - util.updateUI(data, this.fields, this); - } - - return FileKeyStoreProvider; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filetruststore/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filetruststore/add.js deleted file mode 100644 index 5893ce0d2d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filetruststore/add.js +++ /dev/null @@ -1,96 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/dom", - "dojo/query", - "dojo/_base/array", - "dijit/registry", - "qpid/common/util", - "qpid/common/metadata", - "dojo/parser", - "dojo/text!store/filetruststore/add.html", - "dojo/domReady!"], - function (dom, query, array, registry, util, metadata, parser, template) - { - var addTrustStore = - { - show: function(data) - { - var that=this; - this.containerNode = data.containerNode; - data.containerNode.innerHTML = template; - parser.parse(this.containerNode).then(function(instances) - { - that.keyStoreOldBrowserWarning = dom.byId("addStore.oldBrowserWarning"); - - if (!window.FileReader) - { - // Fall back for IE8/9 which do not support FileReader - that.keyStoreOldBrowserWarning.innerHTML = "File upload requires a more recent browser with HTML5 support"; - that.keyStoreOldBrowserWarning.className = that.keyStoreOldBrowserWarning.className.replace("hidden", ""); - } - - if (data.effectiveData) - { - that.update(data.effectiveData); - } - - util.applyMetadataToWidgets(data.containerNode, "TrustStore", "FileTrustStore"); - }); - }, - update: function(effectiveData) - { - var attributes = metadata.getMetaData("TrustStore", "FileTrustStore").attributes; - var widgets = registry.findWidgets(this.containerNode); - array.forEach(widgets, function(item) - { - var name = item.id.replace("addStore.",""); - if (name in attributes ) - { - var attribute = attributes[name]; - var value = effectiveData[name]; - if (value) - { - if (attribute.secure) - { - if (!/^\*+/.test(value) ) - { - item.set("value", value); - } - else - { - item.set("placeHolder", value); - item.set("required", false); - } - } - else - { - item.set("value", value); - } - } - } - }); - - } - }; - - return addTrustStore; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filetruststore/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filetruststore/show.js deleted file mode 100644 index b03199021d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filetruststore/show.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["qpid/common/util", "qpid/common/metadata", "dojo/domReady!"], - function (util, metadata) - { - - function FileTrustStoreProvider(data) - { - this.fields = []; - var attributes = metadata.getMetaData("TrustStore", "FileTrustStore").attributes; - for(var name in attributes) - { - this.fields.push(name); - } - util.buildUI(data.containerNode, data.parent, "store/filetruststore/show.html", this.fields, this); - } - - FileTrustStoreProvider.prototype.update = function(data) - { - util.updateUI(data, this.fields, this); - } - - return FileTrustStoreProvider; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavakeystore/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavakeystore/add.js deleted file mode 100644 index 5c25ae2cc6..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavakeystore/add.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/dom", - "dojo/query", - "dojo/_base/array", - "dijit/registry", - "qpid/common/util", - "qpid/common/metadata", - "dojo/parser", - "dojo/text!store/nonjavakeystore/add.html", - "qpid/common/ResourceWidget", - "dojo/domReady!"], - function (dom, query, array, registry, util, metadata, parser, template) - { - var addKeyStore = - { - show: function(data) - { - var that=this; - this.containerNode = data.containerNode; - data.containerNode.innerHTML = template; - parser.parse(this.containerNode).then(function(instances) - { - that.keyStoreOldBrowserWarning = dom.byId("addStore.oldBrowserWarning"); - - if (!window.FileReader) - { - that.keyStoreOldBrowserWarning.innerHTML = "File upload requires a more recent browser with HTML5 support"; - that.keyStoreOldBrowserWarning.className = that.keyStoreOldBrowserWarning.className.replace("hidden", ""); - } - - if (data.effectiveData) - { - that.update(data.effectiveData); - } - - util.applyMetadataToWidgets(data.containerNode, "KeyStore", "NonJavaKeyStore"); - }); - }, - update: function(effectiveData) - { - var attributes = metadata.getMetaData("KeyStore", "NonJavaKeyStore").attributes; - var widgets = registry.findWidgets(this.containerNode); - array.forEach(widgets, function(item) - { - var name = item.id.replace("addStore.",""); - if (name in attributes ) - { - var attribute = attributes[name]; - var value = effectiveData[name]; - if (value) - { - if (attribute.secure) - { - if (!/^\*+/.test(value) ) - { - item.set("value", value); - } - else - { - item.set("required", false); - if (name == "privateKeyUrl") - { - item.set("uploaded", true) - } - else - { - item.set("placeHolder", value); - } - } - } - else - { - item.set("value", value); - } - } - } - }); - } - }; - - return addKeyStore; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavakeystore/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavakeystore/show.js deleted file mode 100644 index c31b020e3e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavakeystore/show.js +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["qpid/common/util", "qpid/common/metadata", "qpid/management/UserPreferences", "dojox/html/entities", "dojo/domReady!"], - function (util, metadata, UserPreferences, entities) - { - - function toDate(value) - { - return value ? entities.encode(String(UserPreferences.formatDateTime(value, {addOffset: true, appendTimeZone: true}))) : ""; - } - - var dateFields = ["certificateValidEnd","certificateValidStart"]; - - function NonJavaKeyStore(data) - { - this.fields = []; - var attributes = metadata.getMetaData("KeyStore", "NonJavaKeyStore").attributes; - for(var name in attributes) - { - if (dateFields.indexOf(name) == -1) - { - this.fields.push(name); - } - } - var allFields = this.fields.concat(dateFields); - util.buildUI(data.containerNode, data.parent, "store/nonjavakeystore/show.html",allFields, this); - } - - NonJavaKeyStore.prototype.update = function(data) - { - util.updateUI(data, this.fields, this); - if (data) - { - for(var idx in dateFields) - { - var name = dateFields[idx]; - this[name].innerHTML = toDate(data[name]); - } - } - } - - return NonJavaKeyStore; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavatruststore/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavatruststore/add.js deleted file mode 100644 index 550c388910..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavatruststore/add.js +++ /dev/null @@ -1,94 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/dom", - "dojo/query", - "dojo/_base/array", - "dijit/registry", - "qpid/common/util", - "qpid/common/metadata", - "dojo/parser", - "dojo/text!store/nonjavatruststore/add.html", - "dojo/domReady!"], - function (dom, query, array, registry, util, metadata, parser, template) - { - var addKeyStore = - { - show: function(data) - { - var that=this; - this.containerNode = data.containerNode; - data.containerNode.innerHTML = template; - parser.parse(this.containerNode).then(function(instances) - { - that.keyStoreOldBrowserWarning = dom.byId("addStore.oldBrowserWarning"); - - if (!window.FileReader) - { - that.keyStoreOldBrowserWarning.innerHTML = "File upload requires a more recent browser with HTML5 support"; - that.keyStoreOldBrowserWarning.className = that.keyStoreOldBrowserWarning.className.replace("hidden", ""); - } - - if (data.effectiveData) - { - that.update(data.effectiveData); - } - - util.applyMetadataToWidgets(data.containerNode, "TrustStore", "NonJavaTrustStore"); - }); - }, - update: function(effectiveData) - { - var attributes = metadata.getMetaData("TrustStore", "NonJavaTrustStore").attributes; - var widgets = registry.findWidgets(this.containerNode); - array.forEach(widgets, function(item) - { - var name = item.id.replace("addStore.",""); - if (name in attributes ) - { - var attribute = attributes[name]; - var value = effectiveData[name]; - if (value) - { - if (attribute.secure) - { - if (!/^\*+/.test(value) ) - { - item.set("value", value); - } - else - { - item.set("placeHolder", value); - item.set("required", false); - } - } - else - { - item.set("value", value); - } - } - } - }); - } - }; - - return addKeyStore; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavatruststore/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavatruststore/show.js deleted file mode 100644 index 7d78026d05..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavatruststore/show.js +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["dojo/query", - "qpid/common/util", - "qpid/common/metadata", - "dojox/grid/DataGrid", - "qpid/common/UpdatableStore", - "qpid/management/UserPreferences", - "dojo/domReady!"], - function (query, util, metadata, DataGrid, UpdatableStore, UserPreferences) - { - - - function NonJavaTrustStore(data) - { - this.fields = []; - var attributes = metadata.getMetaData("TrustStore", "NonJavaTrustStore").attributes; - for(var name in attributes) - { - this.fields.push(name); - } - var that = this; - util.buildUI(data.containerNode, data.parent, "store/nonjavatruststore/show.html", this.fields, this, function() - { - var gridNode = query(".details", data.containerNode)[0]; - var dateTimeFormatter = function(value){ return value ? UserPreferences.formatDateTime(value, {addOffset: true, appendTimeZone: true}) : "";}; - that.detailsGrid = new UpdatableStore([], - gridNode, - [ - { name: 'Subject', field: 'SUBJECT_NAME', width: '25%' }, - { name: 'Issuer', field: 'ISSUER_NAME', width: '25%' }, - { name: 'Valid from', field: 'VALID_START', width: '25%', formatter: dateTimeFormatter }, - { name: 'Valid to', field: 'VALID_END', width: '25%', formatter: dateTimeFormatter} - ]); - }); - } - - NonJavaTrustStore.prototype.update = function(data) - { - util.updateUI(data, this.fields, this); - var details = data.certificateDetails; - for(var i=0; i < details.length; i++) - { - details[i].id = details[i].SUBJECT_NAME + "_" + details[i].ISSUER_NAME + "_" + details[i].VALID_START + "_" + details[i].VALID_END; - } - this.detailsGrid.grid.beginUpdate(); - this.detailsGrid.update(details); - this.detailsGrid.grid.endUpdate(); - } - - return NonJavaTrustStore; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/treeView.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/treeView.js deleted file mode 100644 index 06faf3c9da..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/treeView.js +++ /dev/null @@ -1,365 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/query", - "dojo/io-query", - "dijit/Tree", - "qpid/common/util", - "qpid/common/updater", - "qpid/management/controller", - "qpid/management/UserPreferences", - "dojo/ready", - "dojo/domReady!"], - function (xhr, query, ioQuery, Tree, util, updater, controller, UserPreferences, ready) { - - function TreeViewModel(queryString) { - this.query = queryString; - - this.onChildrenChange = function (parent, children) { - // fired when the set of children for an object change - }; - - this.onChange = function (object) { - // fired when the properties of an object change - }; - - this.onDelete = function (object) { - // fired when an object is deleted - }; - } - - - TreeViewModel.prototype.buildModel = function (data) { - this.model = data; - - }; - - TreeViewModel.prototype.updateModel = function (data) { - var that = this; - - function checkForChanges(oldData, data) { - var propName; - if (oldData.name != data.name) { - that.onChange(data); - } - - var childChanges = false; - // Iterate over old childTypes, check all are in new - for (propName in oldData) { - if (oldData.hasOwnProperty(propName)) { - var oldChildren = oldData[ propName ]; - if (util.isArray(oldChildren)) { - - var newChildren = data[ propName ]; - - if (!(newChildren && util.isArray(newChildren))) { - childChanges = true; - } else { - var subChanges = false; - // iterate over elements in array, make sure in both, in which case recurse - for (var i = 0; i < oldChildren.length; i++) { - var matched = false; - for (var j = 0; j < newChildren.length; j++) { - if (oldChildren[i].id == newChildren[j].id) { - checkForChanges(oldChildren[i], newChildren[j]); - matched = true; - break; - } - } - if (!matched) { - subChanges = true; - } - } - if (subChanges == true || oldChildren.length != newChildren.length) { - that.onChildrenChange({ id:data.id + propName, _dummyChild:propName, data:data }, - newChildren); - } - } - } - } - } - - for (propName in data) { - if (data.hasOwnProperty(propName)) { - var prop = data[ propName ]; - if (util.isArray(prop)) { - if (!(oldData[ propName ] && util.isArray(oldData[propName]))) { - childChanges = true; - } - } - } - } - - if (childChanges) { - var children = []; - that.getChildren(data, function (theChildren) { - children = theChildren - }); - that.onChildrenChange(data, children); - } - } - - var oldData = this.model; - this.model = data; - - checkForChanges(oldData, data); - }; - - - TreeViewModel.prototype.fetchItemByIdentity = function (id) { - - function fetchItem(id, data) { - var propName; - - if (data.id == id) { - return data; - } else if (id.indexOf(data.id) == 0) { - return { id:id, _dummyChild:id.substring(id.length), data:data }; - } else { - for (propName in data) { - if (data.hasOwnProperty(propName)) { - var prop = data[ propName ]; - if (util.isArray(prop)) { - for (var i = 0; i < prop.length; i++) { - var theItem = fetchItem(id, prop[i]); - if (theItem) { - return theItem; - } - } - } - } - } - return null; - } - } - - return fetchItem(id, this.model); - }; - - TreeViewModel.prototype.getChildren = function (parentItem, onComplete) { - - if (parentItem) { - if (parentItem._dummyChild) { - onComplete(parentItem.data[ parentItem._dummyChild ]); - } else { - var children = []; - for (var propName in parentItem) { - if (parentItem.hasOwnProperty(propName)) { - var prop = parentItem[ propName ]; - - if (util.isArray(prop)) { - children.push({ id:parentItem.id - + propName, _dummyChild:propName, data:parentItem }); - } - } - } - onComplete(children); - } - } else { - onComplete([]); - } - }; - - TreeViewModel.prototype.getIdentity = function (theItem) { - if (theItem) { - return theItem.id; - } - - }; - - TreeViewModel.prototype.getLabel = function (theItem) { - if (theItem) { - if (theItem._dummyChild) { - return theItem._dummyChild; - } else { - return theItem.name; - } - } else { - return ""; - } - }; - - TreeViewModel.prototype.getRoot = function (onItem) { - onItem(this.model); - }; - - TreeViewModel.prototype.mayHaveChildren = function (theItem) { - if (theItem) { - if (theItem._dummyChild) { - return true; - } else { - for (var propName in theItem) { - if (theItem.hasOwnProperty(propName)) { - var prop = theItem[ propName ]; - if (util.isArray(prop)) { - return true; - } - } - } - return false; - } - } else { - return false; - } - }; - - TreeViewModel.prototype.relocate = function (theItem) { - - function findItemDetails(theItem, details, type, object, parent) { - if (theItem.id == object.id) { - details.type = type; - details[ type ] = object.name; - details.parent = parent; - } else { - var parentObject ={ - type: type, - name: object.name - }; - if (parent) - { - parentObject.parent = parent; - } - // iterate over children - for (var propName in object) { - if (object.hasOwnProperty(propName)) { - var prop = object[ propName ]; - if (util.isArray(prop)) { - for (var i = 0; i < prop.length; i++) { - findItemDetails(theItem, details, propName.substring(0, propName.length - 1), - prop[i], parentObject); - - if (details.type) { - break; - } - } - } - if (details.type) { - break; - } - } - } - - if (!details.type) { - details[ type ] = null; - } - } - } - - var details = new Object(); - findItemDetails(theItem, details, "broker", this.model, null); - - if (details.type == "broker") { - controller.show("broker", "", null, theItem.id); - } else if (details.type == "virtualhost") { - controller.show("virtualhost", details.virtualhost, details.parent, theItem.id); - } else if (details.type == "exchange") { - controller.show("exchange", details.exchange, details.parent, theItem.id); - } else if (details.type == "queue") { - controller.show("queue", details.queue, details.parent, theItem.id); - } else if (details.type == "connection") { - controller.show("connection", details.connection, details.parent, theItem.id); - } else if (details.type == 'port') { - controller.show("port", details.port, details.parent, theItem.id); - } else if (details.type == 'authenticationprovider') { - controller.show("authenticationprovider", details.authenticationprovider, details.parent, theItem.id); - } else if (details.type == 'groupprovider') { - controller.show("groupprovider", details.groupprovider, details.parent, theItem.id); - } else if (details.type == 'group') { - controller.show("group", details.group, details.parent, theItem.id); - } else if (details.type == 'keystore') { - controller.show("keystore", details.keystore, details.parent, theItem.id); - } else if (details.type == 'truststore') { - controller.show("truststore", details.truststore, details.parent, theItem.id); - } else if (details.type == 'accesscontrolprovider') { - controller.show("accesscontrolprovider", details.accesscontrolprovider, details.parent, theItem.id); - } else if (details.type == 'plugin') { - controller.show("plugin", details.plugin, {type:"broker", name:""}, theItem.id); - } else if (details.type == "preferencesprovider") { - controller.show("preferencesprovider", details.preferencesprovider, details.parent, theItem.id); - } else if (details.type == "virtualhostnode") { - controller.show("virtualhostnode", details.virtualhostnode, details.parent, theItem.id); - } - }; - - TreeViewModel.prototype.update = function () { - var thisObj = this; - - xhr.get({url:this.query, sync: true, handleAs:"json"}) - .then(function (data) { - if (thisObj.model) { - thisObj.updateModel(data); - } - else { - thisObj.buildModel(data); - } - }, util.xhrErrorHandler); - - }; - - query('div[qpid-type="treeView"]').forEach(function(node, index, arr) { - var treeModel = new TreeViewModel("service/structure"); - treeModel.update(); - var tree = new Tree({ model: treeModel }, node); - tree.on("dblclick", - function (object) { - if (object && !object._dummyChild) { - treeModel.relocate(object); - } - - }, true); - tree.startup(); - updater.add( treeModel ); - - ready(function() { - controller.show("broker",""); - - var tabs = UserPreferences.tabs; - if (tabs) - { - for(var i in tabs) - { - var tab = tabs[i], modelObject; - if (tab.objectType != "broker") - { - if (tab.objectId) - { - modelObject = treeModel.fetchItemByIdentity(tab.objectId); - if (modelObject) - { - treeModel.relocate(modelObject); - } - else - { - UserPreferences.removeTab(tab); - } - } - else - { - controller.show(tab.objectType, ""); - } - } - } - } - }); - }); - - return TreeViewModel; - });
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/add.js deleted file mode 100644 index c4e44f5027..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/add.js +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dijit/registry", - "dojo/text!virtualhost/providedstore/add.html", - "qpid/common/util", - "dijit/form/ValidationTextBox", - "dojo/domReady!"], - function (xhr, parser, dom, domConstruct, json, registry, template, util) - { - return { - show: function (data) - { - var that= this; - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode).then(function(instances) {that._postParse(data);}); - }, - _postParse: function(data) - { - registry.byId("addVirtualHost.storeUnderfullSize").set("regExpGen", util.numericOrContextVarRegexp); - registry.byId("addVirtualHost.storeOverfullSize").set("regExpGen", util.numericOrContextVarRegexp); - - if (data.parent.virtualHostNodeType.value == "JDBC") - { - dom.byId("addVirtualHost.diskFlowControls").style.display = "none"; - } - - } - }; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/edit.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/edit.js deleted file mode 100644 index 3a305fb016..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/edit.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["dijit/registry", "qpid/common/util", "dojo/domReady!"], - function (registry, util) - { - return { - show: function(data) - { - util.parseHtmlIntoDiv(data.containerNode, "virtualhost/providedstore/edit.html", - function() - { - registry.byId("editVirtualHost.storeUnderfullSize").set("regExpGen", util.numericOrContextVarRegexp); - registry.byId("editVirtualHost.storeOverfullSize").set("regExpGen", util.numericOrContextVarRegexp); - }); - } - }; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/show.js deleted file mode 100644 index 8416211c62..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/show.js +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define(["qpid/common/util", "dojo/domReady!"], - function (util) - { - var fields = ["storeUnderfullSize", "storeOverfullSize"]; - - function ProvidedStore(data) - { - util.buildUI(data.containerNode, data.parent, "virtualhost/providedstore/show.html", fields, this); - } - - ProvidedStore.prototype.update = function(data) - { - util.updateUI(data, fields, this); - } - - return ProvidedStore; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/add.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/add.js deleted file mode 100644 index 17d20fde32..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/add.js +++ /dev/null @@ -1,41 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dijit/registry", - "dojo/text!virtualhostnode/json/add.html", - "dijit/form/ValidationTextBox", - "dijit/form/CheckBox", - "dojo/domReady!"], - function (xhr, parser, dom, domConstruct, json, registry, template) - { - return { - show: function(data) - { - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode); - } - }; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/edit.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/edit.js deleted file mode 100644 index 4c70b4a22d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/edit.js +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -define(["qpid/common/util", "dijit/registry", "dojo/domReady!"], - function (util, registry) - { - return { - show: function(data) - { - util.parseHtmlIntoDiv(data.containerNode, "virtualhostnode/filebased/edit.html", - function() - { - registry.byId("editVirtualHostNode.storePath").set("disabled", !(data.data.state == "STOPPED" || data.data.state == "ERRORED")); - }); - } - }; - } -); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/show.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/show.js deleted file mode 100644 index 80e3ce26f1..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/show.js +++ /dev/null @@ -1,39 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - define(["qpid/common/util", - "dojo/domReady!"], - function (util) - { - var fields = ["storePath"]; - - function JSON(data) - { - util.buildUI(data.containerNode, data.parent, "virtualhostnode/json/show.html", fields, this); - } - - JSON.prototype.update = function(data) - { - util.updateUI(data, fields, this); - } - - return JSON; - } - ); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/login.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/login.html deleted file mode 100644 index 6e7f05e41b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/login.html +++ /dev/null @@ -1,120 +0,0 @@ -<!DOCTYPE HTML> -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> -<html lang="en"> -<head> - <meta charset="utf-8"> - <title>Qpid Management Login</title> - <link rel="stylesheet" href="dojo/dojo/resources/dojo.css"> - <link rel="stylesheet" href="dojo/dijit/themes/claro/claro.css"> - <link rel="stylesheet" href="css/common.css" media="screen"> - <script> - function getContextPath() - { - var contextPath = "/"; - var documentURL = document.URL; - var managementPageStart = documentURL.lastIndexOf("/"); - var firstSlashPos = documentURL.indexOf("/", documentURL.indexOf("//") + 2); - if (managementPageStart > firstSlashPos) - { - contextPath = documentURL.substring(firstSlashPos, managementPageStart); - } - return contextPath; - } - - var dojoConfig = { - tlmSiblingOfDojo:false, - parseOnLoad:true, - async:true, - baseUrl: getContextPath(), - packages:[ - { name:"dojo", location:"dojo/dojo" }, - { name:"dijit", location:"dojo/dijit" }, - { name:"dojox", location:"dojo/dojox" }, - { name:"qpid", location:"js/qpid" } - ] - }; - - </script> - <script src="dojo/dojo/dojo.js"> - </script> - - <script> - require(["dojo/_base/xhr", - "dojo/parser", - "dijit/form/Form", - "dijit/form/Button", - "dijit/form/TextBox", - "dijit/form/ValidationTextBox", - "dijit/layout/BorderContainer", - "dijit/layout/ContentPane", - "dijit/TitlePane", - "dojox/layout/TableContainer", - "dojox/validate/us", - "dojox/validate/web", - "qpid/common/footer"]); - </script> - -</head> -<body class="claro"> - -<div id="pageLayout" data-dojo-type="dijit.layout.BorderContainer" data-dojo-props="design: 'headline', gutters: false"> - <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'top'"> - <div id="header" class="header" style="float: left; width: 300px"></div> - <div id="login" style="float: right"></div> - </div> - <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'center'"> - <div style="width:350px; margin-left: auto; margin-right: auto;"> - <div data-dojo-type="dijit.form.Form" method="POST" id="loginForm"> - <script type="dojo/on" data-dojo-event="submit" data-dojo-args="e"> - e.preventDefault() - if(this.validate()){ - require(["qpid/authorization/sasl"], function(sasl){ - var redirectIfAuthenticated = function redirectIfAuthenticated(){ - sasl.getUser(function(data){ - if(data.user){ - window.location = "index.html"; - } - }); - }; - - sasl.authenticate(dijit.byId("username").value, dijit.byId("password").value, redirectIfAuthenticated); - }); - } - return false; - </script> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title:'Login', toggleable: false" > - <div class="dijitDialogPaneContentArea"> - <div data-dojo-type="dojox.layout.TableContainer" data-dojo-props="cols:1,labelWidth:'100',showLabels:true,orientation:'horiz',customClass:'formLabel'"> - <div data-dojo-type="dijit.form.ValidationTextBox" id="username" name="username" data-dojo-props="label:'User name:',required:true, intermediateChanges:true"></div> - <div data-dojo-type="dijit.form.ValidationTextBox" type="password" id="password" name="password" data-dojo-props="label:'Password:',required:true, intermediateChanges:true"></div> - </div> - </div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" type="submit" id="loginButton">Login</button> - </div> - </div> - </div> - </div> - </div> - <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'bottom'"> - <div qpid-type="footer"></div> - </div> -</div> - -</body> -</html>
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/logs/showLogFileDownloadDialog.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/logs/showLogFileDownloadDialog.html deleted file mode 100644 index d48682a566..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/logs/showLogFileDownloadDialog.html +++ /dev/null @@ -1,33 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="contentArea" style="height:320px;overflow:auto"> - <div><b>Select log files to download</b></div> - <div class="logFilesGrid" style='height:300px;width: 580px'></div> - </div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button value="Download" data-dojo-type="dijit.form.Button" - class="downloadLogsButton" - data-dojo-props="iconClass: 'downloadLogsIcon', label: 'Download' "></button> - <button value="Close" data-dojo-type="dijit.form.Button" data-dojo-props="label: 'Close'" - class="downloadLogsDialogCloseButton"></button> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/logs/showLogViewer.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/logs/showLogViewer.html deleted file mode 100644 index ab927153fa..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/logs/showLogViewer.html +++ /dev/null @@ -1,29 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="logViewer"> - - <div id="broker-logfile"></div> - <br/> - <button data-dojo-type="dijit.form.Button" class="downloadLogs" - data-dojo-props="iconClass: 'downloadLogsIcon', title:'Download Log Files', name: 'downloadLogs'">Download Log Files</button> - <br/> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/moveCopyMessages.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/moveCopyMessages.html deleted file mode 100644 index f188c3001c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/moveCopyMessages.html +++ /dev/null @@ -1,36 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> - -<div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" style="width:600px;" data-dojo-props="title:'Move/Copy Messages'" id="moveMessages"> - <form id="formMoveMessages" method="post" dojoType="dijit.form.Form"> - <table cellpadding="0" cellspacing="2"> - <tr> - <td valign="top"><strong>Queue: </strong></td> - <td><div id="moveMessages.selectQueueDiv"></div></td> - </tr> - </table> - <br/> - - <!-- submit buttons --> - - <input type="button" value="Cancel" label="Cancel" dojoType="dijit.form.Button" class="moveMessageCancel"/> - <input type="submit" value="Move Messages" label="Move Messages" dojoType="dijit.form.Button" /> - - </form> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/plugin/showManagementHttp.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/plugin/showManagementHttp.html deleted file mode 100644 index b12869981d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/plugin/showManagementHttp.html +++ /dev/null @@ -1,52 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div> - <div class="clear"> - <div class="formLabel-labelCell">Basic Authentication for HTTP enabled:</div> - <div class="httpBasicAuthenticationEnabled"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Basic Authentication for HTTPS enabled:</div> - <div class="httpsBasicAuthenticationEnabled"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">SASL Authentication for HTTP enabled:</div> - <div class="httpSaslAuthenticationEnabled"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">SASL Authentication for HTTPS enabled:</div> - <div class="httpsSaslAuthenticationEnabled"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Session timeout (s):</div> - <div class="sessionTimeout"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Compress content:</div> - <div class="compressResponses"></div> - </div> - </div> - <br/> - <div class="dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="editPluginButton" type="button">Edit</button> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/plugin/showManagementJmx.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/plugin/showManagementJmx.html deleted file mode 100644 index f70b126277..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/plugin/showManagementJmx.html +++ /dev/null @@ -1,32 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div> - <div class="clear"> - <div class="formLabel-labelCell">Use Platform MBean Server:</div> - <div class="usePlatformMBeanServer"></div> - </div> - </div> - <br/> - <div class="dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="editPluginButton" type="button">Edit</button> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/filesystempreferences/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/filesystempreferences/add.html deleted file mode 100644 index 5990b43b98..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/filesystempreferences/add.html +++ /dev/null @@ -1,37 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Path*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" class="addPreferencesProviderPath" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'path', - required: true, - placeHolder: 'path/to/store', - title: 'Enter preferences store path', - promptMessage: 'File system location for the preferences store.'"/> - </div> - </div> - - <div class="clear"></div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/filesystempreferences/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/filesystempreferences/show.html deleted file mode 100644 index 663415e6d5..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/filesystempreferences/show.html +++ /dev/null @@ -1,21 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> - -<div class="clear"> - <div class="formLabel-labelCell">Path:</div> - <div class="fileSystemPreferencesProviderPath"></div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/preferencesProviderForm.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/preferencesProviderForm.html deleted file mode 100644 index b995d4e8dd..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/preferencesProviderForm.html +++ /dev/null @@ -1,62 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> -<form class="addPreferencesProviderForm" method="post" data-dojo-type="dijit/form/Form" data-dojo-attach-point="preferencesProviderForm"> - <div class="formBox"> - <fieldset> - <legend>Preferences Provider</legend> - <div class="clear hidden"> - <div class="formLabel-labelCell tableContainer-labelCell">Name*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" - data-dojo-attach-point="preferencesProviderNameWidget" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'name', - required: true, - disabled: true, - placeHolder: 'preferences provider name', - promptMessage: 'Name of preferences provider, must be unique', - title: 'Enter a unique preferences provider name per broker'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Type*:</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <select data-dojo-attach-point="preferencesProviderTypeWidget" - data-dojo-type="dijit/form/FilteringSelect" - data-dojo-props=" - name: 'type', - required: true, - disabled: true, - placeHolder: 'select preferences provider type', - promptMessage: 'Type of preferences provider', - title: 'Select preferences provider type', - searchAttr: 'name'"> - </select> - </div> - </div> - <div class="clear"></div> - <div data-dojo-attach-point="preferencesProviderTypeFieldsContainer"></div> - </fieldset> - </div> -</form> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showAccessControlProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showAccessControlProvider.html deleted file mode 100644 index b65154e83b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showAccessControlProvider.html +++ /dev/null @@ -1,44 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="accessControlProvider" data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Access Control Provider Attributes', open: true"> - <div class="clear"> - <div class="formLabel-labelCell">Name:</div> - <div class="name"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Type:</div> - <div class="type"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">State:</div> - <div class="state"></div> - </div> - <div class="clear"></div> - - <div class="providerDetails"></div> - - - <div class="dijitDialogPaneActionBar"> - <input class="deleteAccessControlProviderButton" type="button" value="Delete Access Control provider" label="Delete Access Control Provider" dojoType="dijit.form.Button" /> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showAuthProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showAuthProvider.html deleted file mode 100644 index 992da02027..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showAuthProvider.html +++ /dev/null @@ -1,45 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="authorizationProvider" data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Authentication Provider Attributes', open: true"> - <div class="clear"> - <div class="formLabel-labelCell">Name:</div> - <div class="name"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Type:</div> - <div class="type"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">State:</div> - <div class="state"></div> - </div> - <div class="clear authenticationProviderDetails"></div> - <div class="clear"></div> - <div class="clear dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="editAuthenticationProviderButton" type="button" data-dojo-props="disabled: true">Edit</button> - <button data-dojo-type="dijit.form.Button" class="deleteAuthenticationProviderButton" type="button">Delete</button> - </div> - </div> - <br/> - <div class="preferencesProviderDetails"></div> - <br/> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showBroker.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showBroker.html deleted file mode 100644 index 08b01e98bc..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showBroker.html +++ /dev/null @@ -1,136 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="broker"> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Broker Attributes', open: false"> - <div id="brokerAttributes" class="clear"> - <div id="brokerAttribute.name.container" class="clear"> - <div class="formLabel-labelCell">Broker name:</div> - <div id="brokerAttribute.name"></div> - </div> - <div id="brokerAttribute.operatingSystem.container" class="clear"> - <div class="formLabel-labelCell">Operation system:</div> - <div id="brokerAttribute.operatingSystem"></div> - </div> - <div id="brokerAttribute.platform.container" class="clear"> - <div class="formLabel-labelCell">Platform:</div> - <div id="brokerAttribute.platform"></div> - </div> - <div id="brokerAttribute.productVersion.container" class="clear"> - <div class="formLabel-labelCell">Broker version:</div> - <div id="brokerAttribute.productVersion"></div> - </div> - <div id="brokerAttribute.modelVersion.container" class="clear"> - <div class="formLabel-labelCell">Broker model version:</div> - <div id="brokerAttribute.modelVersion"></div> - </div> - <div id="brokerAttribute.defaultVirtualHost.container" class="hidden clear"> - <div class="formLabel-labelCell">Default virtual host:</div> - <div id="brokerAttribute.defaultVirtualHost"></div> - </div> - <div id="brokerAttribute.statisticsReportingPeriod.container" class="hidden clear"> - <div class="formLabel-labelCell">Statistics reporting period (ms):</div> - <div id="brokerAttribute.statisticsReportingPeriod"></div> - </div> - <div id="brokerAttribute.statisticsReportingResetEnabled.container" class="hidden clear"> - <div class="formLabel-labelCell">Statistics reporting period enabled:</div> - <div id="brokerAttribute.statisticsReportingResetEnabled"></div> - </div> - <div class="clear"></div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Global Connection Defaults', open: true"> - <div id="brokerAttribute.connection.sessionCountLimit.container" class="clear"> - <div class="formLabel-labelCell">Maximum number of sessions:</div> - <div id="brokerAttribute.connection.sessionCountLimit"></div> - </div> - <div id="brokerAttribute.connection.heartBeatDelay.container" class="clear"> - <div class="formLabel-labelCell">Heart beat delay (ms):</div> - <div id="brokerAttribute.connection.heartBeatDelay"></div> - </div> - <div class="clear"></div> - </div> - </div> - <br/> - <button data-dojo-type="dijit.form.Button" class="editBroker">Edit</button> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Virtual Hosts'"> - <div class="broker-virtualhosts"></div> - <button data-dojo-type="dijit.form.Button" class="addVirtualHostNodeAndVirtualHostButton">Add</button> - <div data-dojo-type="dijit.form.DropDownButton" class="virtualHostNodeMenuButton" data-dojo-props="iconClass: 'dijitIconConnector',disabled:true"> - <span>Virtual Host Node</span> - <div data-dojo-type="dijit.Menu"> - <div data-dojo-type="dijit.MenuItem">View</div> - <div data-dojo-type="dijit.MenuItem">Delete</div> - <div data-dojo-type="dijit.MenuItem" data-dojo-props="disabled:true">Start</div> - <div data-dojo-type="dijit.MenuItem" data-dojo-props="disabled:true">Stop</div> - </div> - </div> - <div data-dojo-type="dijit.form.DropDownButton" class="virtualHostMenuButton" data-dojo-props="iconClass: 'dijitIconPackage',disabled:true"> - <span>Virtual Host</span> - <div data-dojo-type="dijit.Menu" class="virtualHostMenu"> - <div data-dojo-type="dijit.MenuItem" class="viewVirtualHost" >View</div> - <div data-dojo-type="dijit.MenuItem" data-dojo-props="disabled:true">Start</div> - <div data-dojo-type="dijit.MenuItem" data-dojo-props="disabled:true">Stop</div> - </div> - </div> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Ports'"> - <div class="broker-ports"></div> - <button data-dojo-type="dijit.form.Button" class="addPort">Add Port</button> - <button data-dojo-type="dijit.form.Button" class="deletePort">Delete Port</button> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Authentication Providers'"> - <div class="broker-authentication-providers"></div> - <button data-dojo-type="dijit.form.Button" class="addAuthenticationProvider">Add Provider</button> - <button data-dojo-type="dijit.form.Button" class="deleteAuthenticationProvider">Delete Provider</button> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Key stores'"> - <div class="broker-key-stores"></div> - <button data-dojo-type="dijit.form.Button" class="addKeystore">Add Key Store</button> - <button data-dojo-type="dijit.form.Button" class="deleteKeystore">Delete Key Store</button> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Trust stores'"> - <div class="broker-trust-stores"></div> - <button data-dojo-type="dijit.form.Button" class="addTruststore">Add Trust Store</button> - <button data-dojo-type="dijit.form.Button" class="deleteTruststore">Delete Trust Store</button> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Group Providers'"> - <div class="broker-group-providers"></div> - <button data-dojo-type="dijit.form.Button" class="addGroupProvider">Add Group Provider</button> - <button data-dojo-type="dijit.form.Button" class="deleteGroupProvider">Delete Group Provider</button> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Access Control Providers'"> - <div class="broker-access-control-providers-warning" style="color: red"></div> - <div class="broker-access-control-providers"></div> - <button data-dojo-type="dijit.form.Button" class="addAccessControlProvider">Add Access Control Provider</button> - <button data-dojo-type="dijit.form.Button" class="deleteAccessControlProvider">Delete Access Control Provider</button> - </div> - <br/> - <button data-dojo-type="dijit.form.Button" class="logViewer" data-dojo-props="iconClass: 'logViewerIcon'">Log Viewer</button> - <br/><br/> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showConnection.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showConnection.html deleted file mode 100644 index cd04b962ce..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showConnection.html +++ /dev/null @@ -1,96 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="connection"> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Connection Attributes', open: true"> - <div class="alignLeft"> - <div class="clear"> - <div class="formLabel-labelCell">Name:</div> - <div class="name formValue-valueCell"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">User:</div> - <div class="principal formValue-valueCell"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Client ID:</div> - <div class="clientId formValue-valueCell"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Client Version:</div> - <div class="clientVersion formValue-valueCell"></div> - </div> - </div> - <div class="alignRight"> - <div class="clear"> - <div class="formLabel-labelCell">Inbound:</div> - <div class="formValue-valueCell"> - <span class="msgInRate"></span> - <span> msg/s</span> - <span class="bytesInRate"></span> - <span class="bytesInRateUnits"></span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Outbound:</div> - <div class="formValue-valueCell"> - <span class="msgOutRate"></span> - <span> msg/s</span> - <span class="bytesOutRate"></span> - <span class="bytesOutRateUnits"></span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Connect Time:</div> - <div class="formValue-valueCell"> - <div class="createdTime"></div> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Last I/O Time:</div> - <div class="formValue-valueCell"> - <div class="lastIoTime"></div> - </div> - </div> - </div> - <div class="clear"></div> - <div class="clear"> - <div class="formLabel-labelCell">Remote Process (PID):</div> - <div class="remoteProcessPid"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Port:</div> - <div class="port"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Transport:</div> - <div class="transport"></div> - </div> - </div> - <div class="clear"/> - - <br/> - - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Sessions'"> - <div class="sessions"></div> - </div> - <br/> - -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showExchange.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showExchange.html deleted file mode 100644 index b67ea2f590..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showExchange.html +++ /dev/null @@ -1,83 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="exchange"> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Exchange Attributes', open: true"> - <div class="clear"> - <div class="formLabel-labelCell">Name:</div> - <div class="name"></div> - </div> - <div class="clear"> - <div class="alignLeft"> - - <div class="clear"> - <div class="formLabel-labelCell">Type:</div> - <div class="type formValue-valueCell"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">State:</div> - <div class="state formValue-valueCell"></div> - </div> - </div> - <div class="alignRight"> - <div class="clear"> - <div class="formLabel-labelCell">Inbound:</div> - <div class="formValue-valueCell"> - <span class="msgInRate"></span> - <span> msg/s</span> - <span class="bytesInRate">(</span> - <span class="bytesInRateUnits">)</span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Dropped:</div> - <div class="formValue-valueCell"> - <span class="msgDropRate"></span> - <span> msg/s</span> - <span class="bytesDropRate">(</span> - <span class="bytesDropRateUnits">)</span> - </div> - </div> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Durable:</div> - <div class="durable"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Lifespan:</div> - <div class="lifetimePolicy"></div> - </div> - - <div class="clear"></div> - </div> - <br/> - - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Bindings'"> - <div class="bindings"></div> - <button data-dojo-type="dijit.form.Button" class="addBindingButton">Add Binding</button> - <button data-dojo-type="dijit.form.Button" class="deleteBindingButton">Delete Binding</button> - </div> - <br/> - - <div class="dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="deleteExchangeButton" type="button">Delete Exchange</button> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showGroupProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showGroupProvider.html deleted file mode 100644 index 3793a4407a..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showGroupProvider.html +++ /dev/null @@ -1,45 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="groupProvider" data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Group Provider', open: true"> - <div class="clear"> - <div class="formLabel-labelCell">Name:</div> - <div class="name"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Type:</div> - <div class="type"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">State:</div> - <div class="state"></div> - </div> - <div class="clear"></div> - - <div class="providerDetails"></div> - <br/> - <div class="dijitDialogPaneActionBar"> - <input class="deleteGroupProviderButton" type="button" value="Delete" label="Delete" data-dojo-type="dijit.form.Button" /> - <input class="editGroupProviderButton" type="button" value="Edit" label="Edit" data-dojo-type="dijit.form.Button" data-dojo-props="disabled:true"/> - </div> - </div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showMessage.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showMessage.html deleted file mode 100644 index caf26bc075..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showMessage.html +++ /dev/null @@ -1,81 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> - -<div class="dijitHidden"> - <div data-dojo-type="dijit.Dialog" style="width:600px;" data-dojo-props="title:'View Message'" id="showMessage"> - - <table style="border: 0;"> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">Message Number:</span></td> - <td><span class="message-id"></span></td> - </tr> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">Size:</span></td> - <td><span class="message-size"></span> bytes</td> - </tr> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">Message Id:</span></td> - <td><span class="message-messageId"></span></td> - </tr> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">Correlation Id:</span></td> - <td><span class="message-correlationId"></span></td> - </tr> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">State:</span></td> - <td><span class="message-state"></span></td> - </tr> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">Persistent:</span></td> - <td><span class="message-persistent boolean"></span></td> - </tr> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">Priority:</span></td> - <td><span class="message-priority"></span></td> - </tr> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">Arrival Time:</span> - </td><td><span class="message-arrivalTime datetime"></span></td> - </tr> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">Expiration:</span></td> - <td><span class="message-expirationTime datetime"></span></td> - </tr> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">MIME Type:</span></td> - <td><span class="message-mimeType"></span></td> - </tr> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">User:</span></td> - <td><span class="message-userId"></span></td> - </tr> - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">Headers:</span></td> - <td><div class="message-headers map"></div></td> - </tr> - - <tr style="margin-bottom: 4pt"> - <td style="width: 10em; vertical-align: top"><span style="font-weight: bold;">Content:</span></td> - <td><div class="message-content"></div></td> - </tr> - </table> - <br/> - <input type="button" value="Close" label="Close" dojoType="dijit.form.Button" class="closeViewMessage"/> - - </div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showPlugin.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showPlugin.html deleted file mode 100644 index 72f0f22a0d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showPlugin.html +++ /dev/null @@ -1,33 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="plugin"> - <div> - <div style="both:clear"> - <div class="formLabel-labelCell">Name:</div> - <div class="name"></div> - </div> - <div style="both:clear"> - <div class="formLabel-labelCell">Type:</div> - <div class="type"></div> - </div> - </div> - <div class="pluginDetails"></div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showPort.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showPort.html deleted file mode 100644 index 5e324bd219..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showPort.html +++ /dev/null @@ -1,102 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="portContainer" data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Port Attributes', open: true"> - - <div class="clear name"> - <div class="formLabel-labelCell">Name:</div> - <div class="nameValue"></div> - </div> - <div class="clear"></div> - <div class="alignLeft"> - <div class="clear type"> - <div class="formLabel-labelCell">Port Type:</div> - <div class="formValue-valueCell typeValue"></div> - </div> - </div> - <div class="alignRight"> - <div class="clear maxOpenConnections"> - <div class="formLabel-labelCell">Open connections (current/maximum):</div> - <div class="formValue-valueCell"> - <span class="connectionCountValue"></span><span>/</span><span class="maxOpenConnectionsValue"></span> - </div> - </div> - </div> - - <div class="clear state"> - <div class="formLabel-labelCell">State:</div> - <div class="formValue-valueCell stateValue"></div> - </div> - - <div class="clear port"> - <div class="formLabel-labelCell">Port Number:</div> - <div class="formValue-valueCell portValue"></div> - </div> - - <div class="clear protocols"> - <div class="formLabel-labelCell">Protocols:</div> - <div class="formValue-valueCell protocolsValue multiLineValue"></div> - </div> - - <div class="clear authenticationProvider"> - <div class="formLabel-labelCell">Authentication Provider:</div> - <div class="formValue-valueCell authenticationProviderValue"></div> - </div> - - <div class="clear bindingAddress"> - <div class="formLabel-labelCell">Binding address:</div> - <div class="formValue-valueCell bindingAddressValue"></div> - </div> - - <div class="clear transports"> - <div class="formLabel-labelCell">Transports:</div> - <div class="formValue-valueCell transportsValue multiLineValue"></div> - </div> - - <div class="clear keyStore"> - <div class="formLabel-labelCell">Key Store:</div> - <div class="formValue-valueCell keyStoreValue"></div> - </div> - - <div class="clear needClientAuth"> - <div class="formLabel-labelCell">Need SSL Client Certificate:</div> - <div class="formValue-valueCell needClientAuthValue"></div> - </div> - - <div class="clear wantClientAuth"> - <div class="formLabel-labelCell">Want SSL Client Certificate:</div> - <div class="formValue-valueCell wantClientAuthValue"></div> - </div> - - <div class="clear trustStores"> - <div class="formLabel-labelCell">Trust Stores:</div> - <div class="formValue-valueCell trustStoresValue multiLineValue"></div> - </div> - - <div class="clear"></div> - </div> - <br/> - - <div class="dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="editPortButton" type="button">Edit</button> - <button data-dojo-type="dijit.form.Button" class="deletePortButton" type="button">Delete</button> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showPreferences.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showPreferences.html deleted file mode 100644 index 8dff5132bd..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showPreferences.html +++ /dev/null @@ -1,79 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div data-dojo-type="dijit/Dialog" data-dojo-props="title:'Preferences'" id="preferences.preferencesDialog"> - <div data-dojo-type="dijit/layout/TabContainer" style="width: 600px; height: 400px"> - <div data-dojo-type="dijit/layout/ContentPane" title="Own Preferences" data-dojo-props="selected:true" id="preferences.preferencesTab"> - <form method="post" data-dojo-type="dijit/form/Form" id="preferences.preferencesForm"> - <div style="height:300px"> - <table cellpadding="0" cellspacing="2"> - <tr> - <td colspan="2"><span id="preferences.timeZone" data-dojo-type="qpid/common/TimeZoneSelector" data-dojo-props="name: 'timeZone', labelStyle: {width: '105px'}"></span></td> - </tr> - <tr> - <td style="width: 105px"><strong>Update period:</strong></td> - <td><input id="preferences.updatePeriod" name="updatePeriod" data-dojo-type="dijit/form/NumberSpinner" data-dojo-props=" - invalidMessage: 'Invalid value', - required: false, - smallDelta: 1, - value: 5, - constraints: {min:1,max:65535,places:0, pattern: '#####'} - "/> - </td> - </tr> - </table> - </div> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button data-dojo-type="dijit/form/Button" data-dojo-props="label: 'Set'" id="preferences.setButton">Set</button> - <button data-dojo-type="dijit/form/Button" data-dojo-props="label: 'Set and Close'" id="preferences.setAndCloseButton">Set and Close</button> - </div> - </form> - </div> - <div data-dojo-type="dijit/layout/ContentPane" title="Users with Preferences" id="preferences.usersTab"> - <table id="preferences.users" data-dojo-type="dojox/grid/EnhancedGrid" data-dojo-props=" - label:'Trust Stores:', - plugins:{ - indirectSelection: true, - pagination: { - pageSizes: [10, 25, 50, 100], - description: true, - sizeSwitch: true, - pageStepper: true, - gotoButton: true, - maxPageStep: 4, - position: 'bottom' - } - }, - rowSelector:'0px' - " style="height: 300px;"> - <thead> - <tr> - <th field="name" style="width:50%">User</th> - <th field="authenticationProvider" style="width:50%">Authentication Provider</th> - </tr> - </thead> - </table> - <div class="dijitDialogPaneActionBar qpidDialogPaneActionBar"> - <button id="preferences.deleteButton" data-dojo-type="dijit/form/Button" data-dojo-props="label:'Delete', title:'Delete preferences for selected users'">Delete</button> - <button id="preferences.deleteAndCloseButton" data-dojo-type="dijit/form/Button" data-dojo-props="label: 'Delete and Close', title:'Delete preferences for selected users and close the dialog'">Delete and Close</button> - </div> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showPreferencesProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showPreferencesProvider.html deleted file mode 100644 index 49eb355ff3..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showPreferencesProvider.html +++ /dev/null @@ -1,38 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="preferencesProvider"> - <div class="preferencesProviderAttributes" data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Preferences Provider Attributes', open: true"> - <div class="clear"> - <div class="formLabel-labelCell">Type:</div> - <div class="preferencesProviderType"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">State:</div> - <div class="preferencesProviderState"></div> - </div> - <div class="preferencesDetails"></div> - <div class="clear"></div> - <div class="clear dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="editPreferencesProviderButton">Edit</button> - <button data-dojo-type="dijit.form.Button" class="deletePreferencesProviderButton">Delete</button> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showQueue.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showQueue.html deleted file mode 100644 index 7132dd8105..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showQueue.html +++ /dev/null @@ -1,215 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div class="queue"> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Queue Attributes', open: true"> - - <div class="clear"> - <div class="formLabel-labelCell">Name:</div> - <div class="name formValue-valueCell"></div> - </div> - <div class="clear"></div> - <div class="alignLeft"> - <div class="clear"> - <div class="formLabel-labelCell">Type:</div> - <div class="type formValue-valueCell"></div> - <div class="typeQualifier formValue-valueCell"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">State:</div> - <div class="state formValue-valueCell"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Durable:</div> - <div class="durable formValue-valueCell"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Lifespan:</div> - <div class="lifetimePolicy formValue-valueCell"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Persist Messages:</div> - <div class="messageDurability formValue-valueCell"></div> - </div> - </div> - <div class="alignRight"> - <div class="clear"> - <div class="formLabel-labelCell">Inbound:</div> - <div class="formValue-valueCell"> - <span class="msgInRate"></span> - <span> msg/s</span> - <span class="bytesInRate"></span> - <span class="bytesInRateUnits"></span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Outbound:</div> - <div class="formValue-valueCell"> - <span class="msgOutRate"></span> - <span> msg/s</span> - <span class="bytesOutRate"></span> - <span class="bytesOutRateUnits"></span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Size:</div> - <div class="formValue-valueCell"> - <span class="queueDepthMessages"></span> - <span> msgs</span> - <span class="queueDepthBytes">(</span> - <span class="queueDepthBytesUnits">)</span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Pre-fetched:</div> - <div class="formValue-valueCell"> - <span class="unacknowledgedMessages"></span> - <span> msgs</span> - <span class="unacknowledgedBytes">(</span> - <span class="unacknowledgedBytesUnits">)</span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Oldest Message Age:</div> - <div class="formValue-valueCell"> - <span class="oldestMessageAge"></span> - <span> secs</span> - </div> - </div> - </div> - <div class="clear"></div> - <div class="clear"> - <div class="formLabel-labelCell">Enforced Max. Ttl(ms):</div> - <div class="maximumMessageTtl"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Enforced Min. Ttl(ms):</div> - <div class="minimumMessageTtl"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Exclusive:</div> - <div class="exclusive"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Owner:</div> - <div class="owner"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Alternate Exchange:</div> - <div class="alternateExchange"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Maximum Delivery Attempts:</div> - <div class="maximumDeliveryAttempts"></div> - </div> - <div class="clear messageGroups"> - <div class="clear"> - <div class="messageGroupKeyLabel formLabel-labelCell ">Message Group Key:</div> - <div class="messageGroupKey"></div> - </div> - <div class="clear"> - <div class="messageGroupSharedGroupsLabel formLabel-labelCell">Shared Message Groups:</div> - <div class="messageGroupSharedGroups"></div> - </div> - </div> - <div class="clear"></div> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Bindings'"> - <div class="bindings"></div> - <button data-dojo-type="dijit.form.Button" class="addBindingButton" type="button">Add Binding</button> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Consumers'"> - <div class="consumers"></div> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Messages'"> - <div class="messages"></div> - <button data-dojo-type="dijit.form.Button" class="deleteMessagesButton" type="button">Delete Messages</button> - <button data-dojo-type="dijit.form.Button" class="clearQueueButton" type="button">Clear Queue</button> - <button data-dojo-type="dijit.form.Button" class="moveMessagesButton" type="button">Move Messages</button> - <button data-dojo-type="dijit.form.Button" class="copyMessagesButton" type="button">Copy Messages</button> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Flow Control Settings', open: false"> - <div class="clear"> - <div class="formLabel-labelCell">Capacity:</div> - <div> - <span class="queueFlowControlSizeBytes"></span> - <span>B</span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Resume Capacity:</div> - <div> - <span class="queueFlowResumeSizeBytes"></span> - <span>B</span> - </div> - </div> - <div class="clear"></div> - </div> - - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Alerting Thresholds', open: false"> - <div class="clear"> - <div class="formLabel-labelCell">Queue Depth:</div> - <div> - <span class="alertThresholdQueueDepthMessages"></span> - <span>msgs</span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Queue Depth:</div> - <div> - <span class="alertThresholdQueueDepthBytes"></span> - <span class="alertThresholdQueueDepthBytesUnits"></span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Message Age:</div> - <div> - <span class="alertThresholdMessageAge"></span> - <span class="alertThresholdMessageAgeUnits"></span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Message Size:</div> - <div> - <span class="alertThresholdMessageSize"></span> - <span class="alertThresholdMessageSizeUnits"></span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Gap between alerts:</div> - <div> - <span class="alertRepeatGap"></span> - <span class="alertRepeatGapUnits"></span> - </div> - </div> - <div class="clear"></div> - </div> - - <div class="dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="editQueueButton" type="button">Edit Queue</button> - <button data-dojo-type="dijit.form.Button" class="deleteQueueButton" type="button">Delete Queue</button> - </div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showStore.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showStore.html deleted file mode 100644 index e564726cbb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showStore.html +++ /dev/null @@ -1,46 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Show Store', open: true"> - <div id="showStore.contentPane"> - <div class="clear"> - <div class="formLabel-labelCell">Name:</div> - <div class="name"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Type:</div> - <div class="type"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">State:</div> - <div class="state"></div> - </div> - <div class="clear"> - <div class="typeFieldsContainer"></div> - </div> - <div class="clear"> - </div> - </div> - - <div class="dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="editStoreButton" type="button">Edit</button> - <button data-dojo-type="dijit.form.Button" class="deleteStoreButton" type="button">Delete</button> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showVirtualHost.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showVirtualHost.html deleted file mode 100644 index 1a2b5293b6..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showVirtualHost.html +++ /dev/null @@ -1,140 +0,0 @@ -<!DOCTYPE HTML> -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> - -<div class="virtualhost"> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Virtual Host Attributes', open: true"> - <div class="alignLeft"> - <div class="clear"> - <div class="formLabel-labelCell">Name:</div> - <div class="name formValue-valueCell"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Type:</div> - <div class="type formValue-valueCell"></div> - </div> - </div> - <div class="alignRight"> - <div class="clear"> - <div class="formLabel-labelCell">Inbound:</div> - <div class="formValue-valueCell"> - <span class="msgInRate"></span> - <span> msg/s</span> - <span class="bytesInRate"></span> - <span class="bytesInRateUnits"></span> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Outbound:</div> - <div class="formValue-valueCell"> - <span class="msgOutRate"></span> - <span> msg/s</span> - <span class="bytesOutRate"></span> - <span class="bytesOutRateUnits"></span> - </div> - </div> - </div> - <div class="clear"></div> - <div class="clear"> - <div class="formLabel-labelCell">State:</div> - <div class="state"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Durable:</div> - <div class="durable"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Lifespan:</div> - <div class="lifetimePolicy"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Dead letter queue enabled:</div> - <div class="deadLetterQueueEnabled"></div> - </div> - <div class="clear virtualHostDetailsContainer"></div> - <div class="clear"></div> - - <br/> - - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Store Transaction Settings', open: false"> - <div class="clear"> - <div class="formLabel-labelCell">Idle timeout before a warning (ms) :</div> - <div class="storeTransactionIdleTimeoutWarn"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Idle timeout before closing (ms) :</div> - <div class="storeTransactionIdleTimeoutClose"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell" >Open timeout before warning (ms) :</div> - <div class="storeTransactionOpenTimeoutWarn"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Open timeout before closing (ms) :</div> - <div class="storeTransactionOpenTimeoutClose"></div> - </div> - <div class="clear"></div> - </div> - - <br/> - - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'House Keeping Settings', open: false"> - <div class="clear"> - <div class="formLabel-labelCell">House keeping check period (ms):</div> - <div class="housekeepingCheckPeriod"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">House keeping thread count:</div> - <div class="housekeepingThreadCount"></div> - </div> - <div class="clear"></div> - </div> - - </div> - - <div class="dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="startButton" type="button" data-dojo-props="disabled: true">Start</button> - <button data-dojo-type="dijit.form.Button" class="stopButton" type="button" data-dojo-props="disabled: true">Stop</button> - <button data-dojo-type="dijit.form.Button" class="editButton" type="button" data-dojo-props="disabled: true">Edit</button> - <button data-dojo-type="dijit.form.Button" class="downloadButton" type="button" data-dojo-props="disabled: true">Download</button> - <button data-dojo-type="dijit.form.Button" class="deleteButton" data-dojo-props="iconClass: 'dijitIconDelete'">Delete</button> - </div> - - <br/> - <div class="virtualHostChildren"> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Exchanges'"> - <div class="exchanges"></div> - <button data-dojo-type="dijit.form.Button" class="addExchangeButton">Add Exchange</button> - <button data-dojo-type="dijit.form.Button" class="deleteExchangeButton">Delete Exchange</button> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Queues'"> - <div class="queues"></div> - <button data-dojo-type="dijit.form.Button" class="addQueueButton">Add Queue</button> - <button data-dojo-type="dijit.form.Button" class="deleteQueueButton">Delete Queue</button> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Connections'" class="virtualHostConnections"> - <div class="connections"></div> - </div> - </div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/showVirtualHostNode.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/showVirtualHostNode.html deleted file mode 100644 index 4c32a9ace7..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/showVirtualHostNode.html +++ /dev/null @@ -1,52 +0,0 @@ -<!DOCTYPE HTML> -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> - -<div class="virtualhostnode"> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Virtual Host Node Attributes', open: true"> - <div class="clear"> - <div class="formLabel-labelCell">Name:</div> - <div class="name"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Type:</div> - <div class="type"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">State:</div> - <div class="state"></div> - </div> - <div class="clear virtualhostnodedetails"> - </div> - <div class="clear"></div> - </div> - <div class="dijitDialogPaneActionBar"> - <button data-dojo-type="dijit.form.Button" class="startNodeButton" type="button" data-dojo-props="disabled: true">Start</button> - <button data-dojo-type="dijit.form.Button" class="stopNodeButton" type="button" data-dojo-props="disabled: true">Stop</button> - <button data-dojo-type="dijit.form.Button" class="editNodeButton" type="button" data-dojo-props="disabled: true">Edit</button> - <button data-dojo-type="dijit.form.Button" class="deleteNodeButton" data-dojo-props="iconClass: 'dijitIconDelete'">Delete</button> - </div> - <br/> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Virtual Host'" class="clear virtualHostGridPanel"> - <div class="virtualHost"></div> - </div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filekeystore/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filekeystore/add.html deleted file mode 100644 index 676ae4007b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filekeystore/add.html +++ /dev/null @@ -1,86 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div id="addStore.oldBrowserWarning" class="infoMessage hidden clear"></div> - <div class="clear"> - <div id="addStore.serverPathLabel" class="formLabel-labelCell tableContainer-labelCell">Server path or upload*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.storeUrl" - data-dojo-type="qpid/common/ResourceWidget" - data-dojo-props=" - name: 'storeUrl', - placeHolder: 'key store file server path', - required: true, - promptMessage: 'Location of the key store file on the server', - title: 'Enter the key store file path'" /> - </div> - - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Password*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="password" id="addStore.password" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'password', - placeHolder: 'store password', - required: true, - promptMessage: 'password for store', - title: 'Enter a password for the store'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Certificate alias:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.certificateAlias" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'certificateAlias', - placeHolder: 'certificate alias', - promptMessage: 'Used to identify one certificate in a store that has many', - title: 'Enter an alias to identify one certificate in a store with many'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell clear">Key manager factory algorithm:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.keyManagerFactoryAlgorithm" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'keyManagerFactoryAlgorithm', - placeHolder: 'key manager factory algorithm', - promptMessage: 'Name of the key manager algorithm known to Java', - title: 'Enter the key manager algorithm known to Java'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Java key store type:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.keyStoreType" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'keyStoreType', - placeHolder: 'java key store type', - promptMessage: 'Name of the store type known to Java', - title: 'Enter the store type known to Java'" /> - </div> - </div> - - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filekeystore/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filekeystore/show.html deleted file mode 100644 index 9a1d93d83a..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filekeystore/show.html +++ /dev/null @@ -1,39 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div class="clear"> - <div class="formLabel-labelCell">Path:</div> - <div ><span class="path" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Certificate alias:</div> - <div><span class="certificateAlias" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Java key store type:</div> - <div><span class="keyStoreType" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Key manager factory algorithm:</div> - <div><span class="keyManagerFactoryAlgorithm" ></span></div> - </div> - <div class="clear"></div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filetruststore/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filetruststore/add.html deleted file mode 100644 index 15b1692300..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filetruststore/add.html +++ /dev/null @@ -1,84 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div id="addStore.oldBrowserWarning" class="infoMessage hidden clear"></div> - <div class="clear"> - <div id="addStore.serverPathLabel" class="formLabel-labelCell tableContainer-labelCell">Server path or upload*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.storeUrl" - data-dojo-type="qpid/common/ResourceWidget" - data-dojo-props=" - name: 'storeUrl', - placeHolder: 'trust store file server path', - required: true, - promptMessage: 'Location of the trust store file on the server', - title: 'Enter the store file path'" /> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Password*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="password" id="addStore.password" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'password', - placeHolder: 'store password', - required: true, - promptMessage: 'password for store', - title: 'Enter a password for the store'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Peers only:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.peersOnly" - data-dojo-type="dijit/form/CheckBox" - data-dojo-props=" - name: 'peersOnly', - promptMessage: 'Peers only or not', - title: 'Tick if peers only'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Trust manager factory algorithm:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.keyManagerFactoryAlgorithm" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'trustManagerFactoryAlgorithm', - placeHolder: 'trust manager factory algorithm', - promptMessage: 'Name of the trust manager algorithm known to Java', - title: 'Enter the trust manager algorithm known to Java'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Java trust store type:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.trustStoreType" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'trustStoreType', - placeHolder: 'java trust store type', - promptMessage: 'Name of the store type known to Java', - title: 'Enter the store type known to Java'" /> - </div> - </div> - - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filetruststore/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filetruststore/show.html deleted file mode 100644 index 99190d1f90..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/filetruststore/show.html +++ /dev/null @@ -1,39 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div class="clear"> - <div class="formLabel-labelCell">Store Url:</div> - <div ><span class="storeUrl" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Peers only:</div> - <div><span class="peersOnly" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Java trust store type:</div> - <div><span class="trustStoreType" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Trust manager factory algorithm:</div> - <div><span class="trustManagerFactoryAlgorithm" ></span></div> - </div> - <div class="clear"></div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavakeystore/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavakeystore/add.html deleted file mode 100644 index b7af1c6b47..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavakeystore/add.html +++ /dev/null @@ -1,66 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - - -<div> - <div id="addStore.oldBrowserWarning" class="infoMessage hidden clear"></div> - - <div class="clear"> - <div id="addStore.privateKeyLabel" class="formLabel-labelCell tableContainer-labelCell">Private Key (Server path or upload)*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.privateKeyUrl" - data-dojo-type="qpid/common/ResourceWidget" - data-dojo-props=" - name: 'privateKeyUrl', - placeHolder: 'path to file with private key in PEM/DER format', - required: true, - promptMessage: 'Enter broker server path to file containing unencrypted private key in DER or PEM format', - title: 'Enter broker server path to file containing unencrypted private key in DER or PEM format'" /> - - </div> - </div> - - <div class="clear"> - <div id="addStore.serverPathLabel" class="formLabel-labelCell tableContainer-labelCell">Certificate (Server path or upload)*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.certificateUrl" - data-dojo-type="qpid/common/ResourceWidget" - data-dojo-props=" - name: 'certificateUrl', - placeHolder: 'path to file with certificate in PEM/DER format', - required: true, - promptMessage: 'Enter broker server path to file containing certificate in DER or PEM format', - title: 'Enter broker server path to file containing certificate in DER or PEM format'" /> - </div> - </div> - - <div class="clear"> - <div id="addStore.intermediateCertificateLabel" class="formLabel-labelCell tableContainer-labelCell">Intermediate Certificates (Server path or upload):</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.intermediateCertificateUrl" - data-dojo-type="qpid/common/ResourceWidget" - data-dojo-props=" - name: 'intermediateCertificateUrl', - placeHolder: 'path to file with certificates in PEM/DER format', - required: false, - promptMessage: 'Enter broker server path to file containing intermediate certificates in DER or PEM format', - title: 'Enter path to file containing intermediate certificates in format DER or PEM'" /> - </div> - </div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavakeystore/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavakeystore/show.html deleted file mode 100644 index 51ebd06012..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavakeystore/show.html +++ /dev/null @@ -1,47 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div class="clear privateKeyUrlContainer"> - <div class="formLabel-labelCell">Private Key:</div> - <div ><span class="privateKeyUrl" ></span></div> - </div> - <div class="clear certificateUrlContainer"> - <div class="formLabel-labelCell">Certificate:</div> - <div><span class="certificateUrl" ></span></div> - </div> - <div class="clear intermediateCertificateUrlContainer"> - <div class="formLabel-labelCell">Intermediate Certificate:</div> - <div><span class="intermediateCertificateUrl" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Subject:</div> - <div><span class="subjectName" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Certificate valid to:</div> - <div><span class="certificateValidEnd" ></span></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Certificate valid from:</div> - <div><span class="certificateValidStart" ></span></div> - </div> - <div class="clear"></div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavatruststore/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavatruststore/add.html deleted file mode 100644 index 4ec2678575..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavatruststore/add.html +++ /dev/null @@ -1,38 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - - -<div> - <div id="addStore.oldBrowserWarning" class="infoMessage hidden clear"></div> - - <div class="clear"> - <div id="addStore.certificatesLabel" class="formLabel-labelCell tableContainer-labelCell">Certificates (Server path or upload)*:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addStore.certificatesUrl" - data-dojo-type="qpid/common/ResourceWidget" - data-dojo-props=" - name: 'certificatesUrl', - placeHolder: 'path to file with certificate(s) in PEM/DER format', - required: true, - promptMessage: 'Enter broker server path to file containing certificate(s) in DER or PEM format', - title: 'Enter broker server path to file containing certificate(s) in DER or PEM format'" /> - </div> - </div> - -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavatruststore/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavatruststore/show.html deleted file mode 100644 index b45f457e41..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavatruststore/show.html +++ /dev/null @@ -1,31 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div class="clear certificatesUrlContainer"> - <div class="formLabel-labelCell">Certificate:</div> - <div><span class="certificatesUrl" ></span></div> - </div> - <div class="clear"></div> - <div data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Certificate details'" class="detailsGridPanel"> - <div class="details"></div> - </div> - <div></div> -</div> - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/strings.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/strings.html deleted file mode 100644 index d29ef5c21c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/strings.html +++ /dev/null @@ -1,21 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div> - <div id="promptTemplateWithDefault"><i>Optional:</i> ${prompt}.<br/>Defaults to <code>${default}</code></div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/add.html deleted file mode 100644 index c0cd3f5653..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/add.html +++ /dev/null @@ -1,51 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div id="addVirtualHost.diskFlowControls"> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Store overfull size:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHost.storeOverfullSize" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'storeOverfullSize', - placeHolder: 'size in bytes', - required: false, - title: 'Enter ceiling (in bytes) at which store will begin to throttle sessions producing messages', - promptMessage: 'Ceiling (in bytes) at which store will begin to throttle sessions producing messages'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Store underfull size:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHost.storeUnderfullSize" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'storeUnderfullSize', - placeHolder: 'size in bytes', - required: false, - title: 'Enter floor (in bytes) at which store will cease to throttle sessions producing messages', - promptMessage: 'Floor (in bytes) at which store will cease to throttle sessions producing messages'" /> - </div> - </div> - </div> - <div class="clear"></div> - <div class="infoMessage">The virtual host will have the same name as the node.</div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/edit.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/edit.html deleted file mode 100644 index 427a1bab86..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/edit.html +++ /dev/null @@ -1,53 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Store overfull size (bytes):</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editVirtualHost.storeOverfullSize" - data-dojo-props=" - name: 'storeOverfullSize', - placeHolder: 'size in bytes', - required: false, - title: 'Enter ceiling (in bytes) at which store will begin to throttle sessions producing messages', - promptMessage: 'Ceiling (in bytes) at which store will begin to throttle sessions producing messages'" - /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Store underfull size (bytes):</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editVirtualHost.storeUnderfullSize" - data-dojo-props=" - name: 'storeUnderfullSize', - placeHolder: 'size in bytes', - required: false, - title: 'Enter floor (in bytes) at which store will cease to throttle sessions producing messages', - promptMessage: 'Floor (in bytes) at which store will cease to throttle sessions producing messages'" - /> - </div> - </div> - - <div class="clear"></div> - -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/show.html deleted file mode 100644 index e889149e99..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/show.html +++ /dev/null @@ -1,30 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div class="clear"> - <div class="formLabel-labelCell">Store overfull size:</div> - <div ><span class="storeOverfullSize" ></span> bytes</div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Store underfull size:</div> - <div><span class="storeUnderfullSize" ></span> bytes</div> - </div> - <div class="clear"></div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/add.html deleted file mode 100644 index 484a85b965..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/add.html +++ /dev/null @@ -1,61 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Message store path:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHost.storePath" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'storePath', - placeHolder: 'path/to/store', - title: 'Enter message store path', - promptMessage: 'File system location for the message store'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Store overfull size:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHost.storeOverfullSize" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'storeOverfullSize', - placeHolder: 'size in bytes', - required: false, - title: 'Enter ceiling (in bytes) at which store will begin to throttle sessions producing messages', - promptMessage: 'Ceiling (in bytes) at which store will begin to throttle sessions producing messages'" /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Store underfull size:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHost.storeUnderfullSize" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'storeUnderfullSize', - placeHolder: 'size in bytes', - required: false, - title: 'Enter floor (in bytes) at which store will cease to throttle sessions producing messages', - promptMessage: 'Floor (in bytes) at which store will cease to throttle sessions producing messages'" /> - </div> - </div> - <div class="clear"></div> - <div class="infoMessage">The virtual host will have the same name as the node.</div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/edit.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/edit.html deleted file mode 100644 index 2486cdcf42..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/edit.html +++ /dev/null @@ -1,65 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Message store path:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editVirtualHost.storePath" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'storePath', - disabled: true, - title: 'Enter message store path'" /> - </div> - </div> - - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Store overfull size (bytes):</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editVirtualHost.storeOverfullSize" - data-dojo-props=" - name: 'storeOverfullSize', - placeHolder: 'size in bytes', - required: false, - title: 'Enter ceiling (in bytes) at which store will begin to throttle sessions producing messages', - promptMessage: 'Ceiling (in bytes) at which store will begin to throttle sessions producing messages'" - /> - </div> - </div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Store underfull size (bytes):</div> - <div class="tableContainer-valueCell formLabel-controlCell"> - <input data-dojo-type="dijit/form/ValidationTextBox" - id="editVirtualHost.storeUnderfullSize" - data-dojo-props=" - name: 'storeUnderfullSize', - placeHolder: 'size in bytes', - required: false, - title: 'Enter floor (in bytes) at which store will cease to throttle sessions producing messages', - promptMessage: 'Floor (in bytes) at which store will cease to throttle sessions producing messages'" - /> - </div> - </div> - - <div class="clear"></div> - -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/show.html deleted file mode 100644 index 1f3c1e820c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/show.html +++ /dev/null @@ -1,34 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - <div class="clear"> - <div class="formLabel-labelCell">Message store path:</div> - <div class="storePath"></div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Store overfull size:</div> - <div><span class="storeOverfullSize"></span> bytes</div> - </div> - <div class="clear"> - <div class="formLabel-labelCell">Store underfull size:</div> - <div><span class="storeUnderfullSize"></span> bytes</div> - </div> - <div class="clear"></div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/filebased/edit.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/filebased/edit.html deleted file mode 100644 index 2f0d72fe9a..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/filebased/edit.html +++ /dev/null @@ -1,36 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> - -<div> - - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Configuration store path:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="editVirtualHostNode.storePath" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'storePath', - placeHolder: 'path/to/store', - title: 'Enter configuration store path'" /> - </div> - </div> - - <div class="clear"></div> - -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/json/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/json/add.html deleted file mode 100644 index ec3ef79fa0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/json/add.html +++ /dev/null @@ -1,34 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="clear"> - <div class="formLabel-labelCell tableContainer-labelCell">Store path:</div> - <div class="formLabel-controlCell tableContainer-valueCell"> - <input type="text" id="addVirtualHostNode.jsonStorePath" - data-dojo-type="dijit/form/ValidationTextBox" - data-dojo-props=" - name: 'storePath', - placeHolder: 'path/to/store', - title: 'Enter store path'" /> - </div> - </div> - <div class="clear"></div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/json/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/json/show.html deleted file mode 100644 index 48aec9c342..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/json/show.html +++ /dev/null @@ -1,21 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one or more - ~ contributor license agreements. See the NOTICE file distributed with - ~ this work for additional information regarding copyright ownership. - ~ The ASF licenses this file to You under the Apache License, Version 2.0 - ~ (the "License"); you may not use this file except in compliance with - ~ the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, software - ~ distributed under the License is distributed on an "AS IS" BASIS, - ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ~ See the License for the specific language governing permissions and - ~ limitations under the License. - --> - -<div class="clear"> - <div class="formLabel-labelCell">Configuration store path:</div> - <div class="storePath"></div> -</div> diff --git a/qpid/java/broker-plugins/management-http/src/main/resources-maven/dojoconfig.properties b/qpid/java/broker-plugins/management-http/src/main/resources-maven/dojoconfig.properties deleted file mode 100644 index c5c11a8486..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/resources-maven/dojoconfig.properties +++ /dev/null @@ -1,25 +0,0 @@ -# -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# -# -dojo-version=${dojo-version} -dojo-path=/dojo-${dojo-version}/dojo -dijit-path=/dojo-${dojo-version}/dijit -dojox-path=/dojo-${dojo-version}/dojox - diff --git a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/HttpManagementTest.java b/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/HttpManagementTest.java deleted file mode 100644 index 4031f13655..0000000000 --- a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/HttpManagementTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.configuration.updater.TaskExecutorImpl; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ConfiguredObjectFactory; -import org.apache.qpid.server.model.ConfiguredObjectFactoryImpl; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.port.HttpPort; -import org.apache.qpid.test.utils.QpidTestCase; - -public class HttpManagementTest extends QpidTestCase -{ - private UUID _id; - private Broker _broker; - private HttpManagement _management; - - @Override - public void setUp() throws Exception - { - super.setUp(); - _id = UUID.randomUUID(); - _broker = mock(Broker.class); - ConfiguredObjectFactory objectFactory = new ConfiguredObjectFactoryImpl(BrokerModel.getInstance()); - - when(_broker.getObjectFactory()).thenReturn(objectFactory); - when(_broker.getModel()).thenReturn(objectFactory.getModel()); - when(_broker.getCategoryClass()).thenReturn(Broker.class); - when(_broker.getEventLogger()).thenReturn(mock(EventLogger.class)); - TaskExecutor taskExecutor = new TaskExecutorImpl(); - taskExecutor.start(); - when(_broker.getTaskExecutor()).thenReturn(taskExecutor); - when(_broker.getChildExecutor()).thenReturn(taskExecutor); - - - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(HttpManagement.HTTP_BASIC_AUTHENTICATION_ENABLED, false); - attributes.put(HttpManagement.HTTPS_BASIC_AUTHENTICATION_ENABLED, true); - attributes.put(HttpManagement.HTTP_SASL_AUTHENTICATION_ENABLED, false); - attributes.put(HttpManagement.HTTPS_SASL_AUTHENTICATION_ENABLED, true); - attributes.put(HttpManagement.NAME, getTestName()); - attributes.put(HttpManagement.TIME_OUT, 10000l); - attributes.put(ConfiguredObject.ID, _id); - attributes.put(HttpManagement.DESIRED_STATE, State.QUIESCED); - _management = new HttpManagement(attributes, _broker); - _management.open(); - } - - public void testGetSessionTimeout() - { - assertEquals("Unexpected session timeout", 10000l, _management.getSessionTimeout()); - } - - public void testGetName() - { - assertEquals("Unexpected name", getTestName(), _management.getName()); - } - - public void testIsHttpsSaslAuthenticationEnabled() - { - assertEquals("Unexpected value for the https sasl enabled attribute", true, - _management.isHttpsSaslAuthenticationEnabled()); - } - - public void testIsHttpSaslAuthenticationEnabled() - { - assertEquals("Unexpected value for the http sasl enabled attribute", false, _management.isHttpSaslAuthenticationEnabled()); - } - - public void testIsHttpsBasicAuthenticationEnabled() - { - assertEquals("Unexpected value for the https basic authentication enabled attribute", true, - _management.isHttpsBasicAuthenticationEnabled()); - } - - public void testIsHttpBasicAuthenticationEnabled() - { - assertEquals("Unexpected value for the http basic authentication enabled attribute", false, - _management.isHttpBasicAuthenticationEnabled()); - } - - -} diff --git a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/log/LogFileHelperTest.java b/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/log/LogFileHelperTest.java deleted file mode 100644 index 26e6cddc82..0000000000 --- a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/log/LogFileHelperTest.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.log; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -import org.apache.log4j.Appender; -import org.apache.log4j.DailyRollingFileAppender; -import org.apache.log4j.FileAppender; -import org.apache.log4j.QpidCompositeRollingAppender; -import org.apache.log4j.RollingFileAppender; -import org.apache.log4j.varia.ExternallyRolledFileAppender; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; -import org.apache.qpid.util.FileUtils; - -public class LogFileHelperTest extends QpidTestCase -{ - private Map<String, List<File>> _appendersFiles; - private File _compositeRollingAppenderBackupFolder; - private List<Appender> _appenders; - private LogFileHelper _helper; - - public void setUp() throws Exception - { - super.setUp(); - _appendersFiles = new HashMap<String, List<File>>(); - _compositeRollingAppenderBackupFolder = new File(TMP_FOLDER, "_compositeRollingAppenderBackupFolder"); - _compositeRollingAppenderBackupFolder.mkdirs(); - - _appendersFiles.put(FileAppender.class.getSimpleName(), - Collections.singletonList(TestFileUtils.createTempFile(this, ".log", "FileAppender"))); - _appendersFiles.put(DailyRollingFileAppender.class.getSimpleName(), - Collections.singletonList(TestFileUtils.createTempFile(this, ".log", "DailyRollingFileAppender"))); - _appendersFiles.put(RollingFileAppender.class.getSimpleName(), - Collections.singletonList(TestFileUtils.createTempFile(this, ".log", "RollingFileAppender"))); - _appendersFiles.put(ExternallyRolledFileAppender.class.getSimpleName(), - Collections.singletonList(TestFileUtils.createTempFile(this, ".log", "ExternallyRolledFileAppender"))); - - File file = TestFileUtils.createTempFile(this, ".log", "QpidCompositeRollingAppender"); - File backUpFile = File.createTempFile(file.getName() + ".", ".1." + LogFileHelper.GZIP_EXTENSION); - _appendersFiles.put(QpidCompositeRollingAppender.class.getSimpleName(), Arrays.asList(file, backUpFile)); - - FileAppender fileAppender = new FileAppender(); - DailyRollingFileAppender dailyRollingFileAppender = new DailyRollingFileAppender(); - RollingFileAppender rollingFileAppender = new RollingFileAppender(); - ExternallyRolledFileAppender externallyRolledFileAppender = new ExternallyRolledFileAppender(); - QpidCompositeRollingAppender qpidCompositeRollingAppender = new QpidCompositeRollingAppender(); - qpidCompositeRollingAppender.setbackupFilesToPath(_compositeRollingAppenderBackupFolder.getPath()); - - _appenders = new ArrayList<Appender>(); - _appenders.add(fileAppender); - _appenders.add(dailyRollingFileAppender); - _appenders.add(rollingFileAppender); - _appenders.add(externallyRolledFileAppender); - _appenders.add(qpidCompositeRollingAppender); - - for (Appender appender : _appenders) - { - FileAppender fa = (FileAppender) appender; - fa.setName(fa.getClass().getSimpleName()); - fa.setFile(_appendersFiles.get(fa.getClass().getSimpleName()).get(0).getPath()); - } - - _helper = new LogFileHelper(_appenders); - } - - public void tearDown() throws Exception - { - try - { - for (List<File> files : _appendersFiles.values()) - { - for (File file : files) - { - try - { - FileUtils.delete(file, false); - } - catch (Exception e) - { - // ignore - } - } - } - FileUtils.delete(_compositeRollingAppenderBackupFolder, true); - } - finally - { - super.tearDown(); - } - } - - public void testGetLogFileDetailsWithLocations() throws Exception - { - List<LogFileDetails> details = _helper.getLogFileDetails(true); - - assertLogFiles(details, true); - } - - public void testGetLogFileDetailsWithoutLocations() throws Exception - { - List<LogFileDetails> details = _helper.getLogFileDetails(false); - - assertLogFiles(details, false); - } - - public void testWriteLogFilesForAllLogs() throws Exception - { - List<LogFileDetails> details = _helper.getLogFileDetails(true); - File f = TestFileUtils.createTempFile(this, ".zip"); - - FileOutputStream os = new FileOutputStream(f); - try - { - _helper.writeLogFiles(details, os); - } - finally - { - if (os != null) - { - os.close(); - } - } - - assertWrittenFile(f, details); - } - - public void testWriteLogFile() throws Exception - { - File file = _appendersFiles.get(FileAppender.class.getSimpleName()).get(0); - - File f = TestFileUtils.createTempFile(this, ".log"); - FileOutputStream os = new FileOutputStream(f); - try - { - _helper.writeLogFile(file, os); - } - finally - { - if (os != null) - { - os.close(); - } - } - - assertEquals("Unexpected log content", FileAppender.class.getSimpleName(), FileUtils.readFileAsString(f)); - } - - public void testFindLogFileDetails() - { - String[] logFileDisplayedPaths = new String[6]; - File[] files = new File[logFileDisplayedPaths.length]; - int i = 0; - for (Map.Entry<String, List<File>> entry : _appendersFiles.entrySet()) - { - String appenderName = entry.getKey(); - List<File> appenderFiles = entry.getValue(); - for (File logFile : appenderFiles) - { - logFileDisplayedPaths[i] = appenderName + "/" + logFile.getName(); - files[i++] = logFile; - } - } - - List<LogFileDetails> logFileDetails = _helper.findLogFileDetails(logFileDisplayedPaths); - assertEquals("Unexpected details size", logFileDisplayedPaths.length, logFileDetails.size()); - - boolean gzipFileFound = false; - for (int j = 0; j < logFileDisplayedPaths.length; j++) - { - String displayedPath = logFileDisplayedPaths[j]; - String[] parts = displayedPath.split("/"); - LogFileDetails d = logFileDetails.get(j); - assertEquals("Unexpected name", parts[1], d.getName()); - assertEquals("Unexpected appender", parts[0], d.getAppenderName()); - if (files[j].getName().endsWith(LogFileHelper.GZIP_EXTENSION)) - { - assertEquals("Unexpected mime type for gz file", LogFileHelper.GZIP_MIME_TYPE, d.getMimeType()); - gzipFileFound = true; - } - else - { - assertEquals("Unexpected mime type", LogFileHelper.TEXT_MIME_TYPE, d.getMimeType()); - } - assertEquals("Unexpected file location", files[j], d.getLocation()); - assertEquals("Unexpected file size", files[j].length(), d.getSize()); - assertEquals("Unexpected file last modified date", files[j].lastModified(), d.getLastModified()); - } - assertTrue("Gzip log file is not found", gzipFileFound); - } - - public void testFindLogFileDetailsForNotExistingAppender() - { - String[] logFileDisplayedPaths = { "NotExistingAppender/qpid.log" }; - List<LogFileDetails> details = _helper.findLogFileDetails(logFileDisplayedPaths); - assertTrue("No details should be created for non-existing appender", details.isEmpty()); - } - - public void testFindLogFileDetailsForNotExistingFile() - { - String[] logFileDisplayedPaths = { "FileAppender/qpid-non-existing.log" }; - List<LogFileDetails> details = _helper.findLogFileDetails(logFileDisplayedPaths); - assertTrue("No details should be created for non-existing file", details.isEmpty()); - } - - public void testFindLogFileDetailsForIncorrectlySpecifiedLogFilePath() - { - String[] logFileDisplayedPaths = { "FileAppender\\" + _appendersFiles.get("FileAppender").get(0).getName() }; - try - { - _helper.findLogFileDetails(logFileDisplayedPaths); - fail("Exception is expected for incorrectly set path to log file"); - } - catch (IllegalArgumentException e) - { - // pass - } - } - - private void assertLogFiles(List<LogFileDetails> details, boolean includeLocation) - { - for (Map.Entry<String, List<File>> appenderData : _appendersFiles.entrySet()) - { - String appenderName = (String) appenderData.getKey(); - List<File> files = appenderData.getValue(); - - for (File logFile : files) - { - String logFileName = logFile.getName(); - LogFileDetails d = findLogFileDetails(logFileName, appenderName, details); - assertNotNull("Log file " + logFileName + " is not found for appender " + appenderName, d); - if (includeLocation) - { - assertEquals("Log file " + logFileName + " is different in appender " + appenderName, d.getLocation(), - logFile); - } - } - } - } - - private LogFileDetails findLogFileDetails(String logFileName, String appenderName, List<LogFileDetails> logFileDetails) - { - LogFileDetails d = null; - for (LogFileDetails lfd : logFileDetails) - { - if (lfd.getName().equals(logFileName) && lfd.getAppenderName().equals(appenderName)) - { - d = lfd; - break; - } - } - return d; - } - - private void assertWrittenFile(File f, List<LogFileDetails> details) throws FileNotFoundException, IOException - { - FileInputStream fis = new FileInputStream(f); - try - { - ZipInputStream zis = new ZipInputStream(fis); - ZipEntry ze = zis.getNextEntry(); - - while (ze != null) - { - String entryName = ze.getName(); - String[] parts = entryName.split("/"); - - String appenderName = parts[0]; - String logFileName = parts[1]; - - LogFileDetails d = findLogFileDetails(logFileName, appenderName, details); - - assertNotNull("Unexpected entry " + entryName, d); - details.remove(d); - - File logFile = d.getLocation(); - String logContent = FileUtils.readFileAsString(logFile); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int len; - while ((len = zis.read(buffer)) > 0) - { - baos.write(buffer, 0, len); - } - baos.close(); - - assertEquals("Unexpected log file content", logContent, baos.toString()); - - ze = zis.getNextEntry(); - } - - zis.closeEntry(); - zis.close(); - - } - finally - { - if (fis != null) - { - fis.close(); - } - } - assertEquals("Not all log files have been output", 0, details.size()); - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/ReportRunnerTest.java b/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/ReportRunnerTest.java deleted file mode 100644 index 38432a26f4..0000000000 --- a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/ReportRunnerTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.report; - -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.ByteArrayOutputStream; -import java.io.ObjectOutputStream; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.queue.QueueEntryVisitor; -import org.apache.qpid.test.utils.QpidTestCase; - -public class ReportRunnerTest extends QpidTestCase -{ - public void testTextReportCountsMessages() - { - ReportRunner<String> runner = (ReportRunner<String>) ReportRunner.createRunner(TestTextReport.NAME, - Collections.<String, String[]>emptyMap()); - Queue queue = createMockQueue(); - assertEquals("There are 0 messages on the queue.", runner.runReport(queue)); - - runner = (ReportRunner<String>) ReportRunner.createRunner(TestTextReport.NAME, - Collections.<String, String[]>emptyMap()); - Queue queue1 = createMockQueue(mock(ServerMessage.class)); - assertEquals("There are 1 messages on the queue.", runner.runReport(queue1)); - - runner = (ReportRunner<String>) ReportRunner.createRunner(TestTextReport.NAME, - Collections.<String, String[]>emptyMap()); - Queue queue2 = createMockQueue(mock(ServerMessage.class), mock(ServerMessage.class)); - assertEquals("There are 2 messages on the queue.", runner.runReport(queue2)); - } - - public void testTextReportSingleStringParam() - { - Queue queue2 = createMockQueue(mock(ServerMessage.class), mock(ServerMessage.class)); - - Map<String, String[]> parameterMap = new HashMap<>(); - parameterMap.put("stringParam", new String[]{"hello world"}); - ReportRunner<String> runner = - (ReportRunner<String>) ReportRunner.createRunner(TestTextReport.NAME, parameterMap); - assertEquals("There are 2 messages on the queue. stringParam = hello world.", runner.runReport(queue2)); - } - - public void testTextReportSingleStringArrayParam() - { - Queue queue = createMockQueue(); - - Map<String, String[]> parameterMap = new HashMap<>(); - parameterMap.put("stringArrayParam", new String[] { "hello world", "goodbye"}); - ReportRunner<String> runner = (ReportRunner<String>) ReportRunner.createRunner(TestTextReport.NAME, parameterMap); - assertEquals("There are 0 messages on the queue. stringArrayParam = [hello world, goodbye].", runner.runReport(queue)); - - } - - - public void testTextReportBothParams() - { - Queue queue = createMockQueue(); - - Map<String, String[]> parameterMap = new HashMap<>(); - parameterMap.put("stringParam", new String[]{"hello world"}); - parameterMap.put("stringArrayParam", new String[] { "hello world", "goodbye"}); - ReportRunner<String> runner = (ReportRunner<String>) ReportRunner.createRunner(TestTextReport.NAME, parameterMap); - assertEquals("There are 0 messages on the queue. stringParam = hello world. stringArrayParam = [hello world, goodbye].", runner.runReport(queue)); - - } - - public void testInvalidReportName() - { - try - { - ReportRunner.createRunner("unknown", Collections.<String, String[]>emptyMap()); - fail("Unknown report name should throw exception"); - } - catch(IllegalArgumentException e) - { - assertEquals("Unknown report: unknown", e.getMessage()); - } - } - - public void testBinaryReportWithLimit() throws Exception - { - Queue queue = createMockQueue(createMessageWithAppProperties(Collections.<String,Object>singletonMap("key",1)), - createMessageWithAppProperties(Collections.<String,Object>singletonMap("key",2)), - createMessageWithAppProperties(Collections.<String, Object>singletonMap("key", 3)), - createMessageWithAppProperties(Collections.<String, Object>singletonMap("key", 4))); - Map<String, String[]> parameterMap = new HashMap<>(); - parameterMap.put("propertyName", new String[]{"key"}); - parameterMap.put("limit", new String[] { "3" }); - - ReportRunner<byte[]> runner = (ReportRunner<byte[]>) ReportRunner.createRunner(TestBinaryReport.NAME, parameterMap); - - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - ObjectOutputStream objects = new ObjectOutputStream(bytes); - objects.writeObject(Integer.valueOf(1)); - objects.writeObject(Integer.valueOf(2)); - objects.writeObject(Integer.valueOf(3)); - objects.flush(); - byte[] expected = bytes.toByteArray(); - byte[] actual = runner.runReport(queue); - assertTrue("Output not as expected", Arrays.equals(expected, actual)); - } - - private ServerMessage<?> createMessageWithAppProperties(final Map<String,Object> props) - { - ServerMessage<?> message = mock(ServerMessage.class); - final AMQMessageHeader header = mock(AMQMessageHeader.class); - when(message.getMessageHeader()).thenReturn(header); - final ArgumentCaptor<String> headerNameCaptor = ArgumentCaptor.forClass(String.class); - when(header.getHeader(headerNameCaptor.capture())).thenAnswer(new Answer<Object>() - { - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable - { - String header = headerNameCaptor.getValue(); - return props.get(header); - } - }); - when(header.getHeaderNames()).thenReturn(props.keySet()); - return message; - } - - private Queue createMockQueue(final ServerMessage<?>... messages) - { - final AMQQueue queue = mock(AMQQueue.class); - final ArgumentCaptor<QueueEntryVisitor> captor = ArgumentCaptor.forClass(QueueEntryVisitor.class); - doAnswer(new Answer() - { - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable - { - QueueEntryVisitor visitor = captor.getValue(); - for(ServerMessage<?> message : messages) - { - if(visitor.visit(makeEntry(queue, message))) - { - break; - } - } - return null; - } - }).when(queue).visit(captor.capture()); - return queue; - } - - private QueueEntry makeEntry(final AMQQueue queue, final ServerMessage<?> message) - { - QueueEntry entry = mock(QueueEntry.class); - when(entry.getQueue()).thenReturn(queue); - when(entry.getMessage()).thenReturn(message); - return entry; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/TestBinaryReport.java b/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/TestBinaryReport.java deleted file mode 100644 index fc5e93631e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/TestBinaryReport.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.report; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; - -public class TestBinaryReport extends QueueBinaryReport -{ - - - private int _limit; - private String _propertyName; - private int _count; - private final ByteArrayOutputStream _bytesOutputStream = new ByteArrayOutputStream(); - private final ObjectOutputStream _objectOutputStream; - public static final String NAME = "testBinary"; - - public TestBinaryReport() - { - try - { - _objectOutputStream = new ObjectOutputStream(_bytesOutputStream); - } - catch (IOException e) - { - throw new RuntimeException(e); - } - ; - } - - @Override - public String getName() - { - return NAME; - } - - @Override - public String getContentType() - { - return "application/octet-stream"; - } - - @Override - public void addMessage(final ReportableMessage reportableMessage) - { - if(_propertyName != null) - { - Object value = reportableMessage.getMessageHeader().getHeader(_propertyName); - if(value != null) - { - try - { - _objectOutputStream.writeObject(value); - } - catch (IOException e) - { - // ignore - } - } - } - _count++; - } - - @Override - public boolean isComplete() - { - return _limit != 0 && _count >= _limit; - } - - @Override - public byte[] getReport() - { - try - { - _objectOutputStream.flush(); - - return _bytesOutputStream.toByteArray(); - } - catch (IOException e) - { - throw new RuntimeException(e); - } - } - - public void setLimit(final String limit) - { - _limit = Integer.parseInt(limit); - } - - public void setPropertyName(final String propertyName) - { - this._propertyName = propertyName; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/TestTextReport.java b/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/TestTextReport.java deleted file mode 100644 index 7f9e1e2962..0000000000 --- a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/TestTextReport.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.report; - -import java.util.Arrays; - -public class TestTextReport extends QueueTextReport -{ - public static final String NAME = "testText"; - private int _count; - private String _stringParam; - private String[] _stringArrayParam; - - @Override - public String getName() - { - return NAME; - } - - @Override - public String getContentType() - { - return "text/plain"; - } - - @Override - public void addMessage(final ReportableMessage reportableMessage) - { - _count++; - } - - @Override - public boolean isComplete() - { - return false; - } - - @Override - public String getReport() - { - StringBuilder result = new StringBuilder("There are " + _count + " messages on the queue."); - if(_stringParam != null) - { - result.append(" stringParam = " + _stringParam + "."); - } - if(_stringArrayParam != null) - { - result.append(" stringArrayParam = " + Arrays.asList(_stringArrayParam) + "."); - } - return result.toString(); - } - - @SuppressWarnings("unused") - public void setStringParam(final String value) - { - _stringParam = value; - } - - @SuppressWarnings("unused") - public void setStringArrayParam(final String[] value) - { - _stringArrayParam = value; - } - - -} diff --git a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/servlet/rest/ConfiguredObjectToMapConverterTest.java b/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/servlet/rest/ConfiguredObjectToMapConverterTest.java deleted file mode 100644 index 5fb73c8ee4..0000000000 --- a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/servlet/rest/ConfiguredObjectToMapConverterTest.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.servlet.rest; - -import static org.apache.qpid.server.management.plugin.servlet.rest.ConfiguredObjectToMapConverter.STATISTICS_MAP_KEY; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import junit.framework.TestCase; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ConfiguredObjectAttribute; -import org.apache.qpid.server.model.ConfiguredObjectTypeRegistry; -import org.apache.qpid.server.model.Model; - -public class ConfiguredObjectToMapConverterTest extends TestCase -{ - private ConfiguredObjectToMapConverter _converter = new ConfiguredObjectToMapConverter(); - private ConfiguredObject _configuredObject = mock(ConfiguredObject.class); - - @Override - protected void setUp() throws Exception - { - super.setUp(); - } - - public void testConfiguredObjectWithSingleStatistics() throws Exception - { - final String statisticName = "statisticName"; - final int statisticValue = 10; - - when(_configuredObject.getStatistics()).thenReturn(Collections.singletonMap(statisticName, (Number) statisticValue)); - - Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 0, - false, - false, - false, - false, - 120, - false); - Map<String, Object> statsAsMap = (Map<String, Object>) resultMap.get(STATISTICS_MAP_KEY); - assertNotNull("Statistics should be part of map", statsAsMap); - assertEquals("Unexpected number of statistics", 1, statsAsMap.size()); - assertEquals("Unexpected statistic value", statisticValue, statsAsMap.get(statisticName)); - } - - public void testConfiguredObjectWithSingleNonConfiguredObjectAttribute() throws Exception - { - final String attributeName = "attribute"; - final String attributeValue = "value"; - Model model = createTestModel(); - when(_configuredObject.getModel()).thenReturn(model); - configureMockToReturnOneAttribute(_configuredObject, attributeName, attributeValue); - - Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 0, - false, - false, - false, - false, - 120, - false); - assertEquals("Unexpected number of attributes", 1, resultMap.size()); - assertEquals("Unexpected attribute value", attributeValue, resultMap.get(attributeName)); - } - - /* - * For now, it is the name of the configured object is returned as the attribute value, rather than the - * configured object itself - */ - public void testConfiguredObjectWithSingleConfiguredObjectAttribute() throws Exception - { - final String attributeName = "attribute"; - final ConfiguredObject attributeValue = mock(ConfiguredObject.class); - when(attributeValue.getName()).thenReturn("attributeConfiguredObjectName"); - - configureMockToReturnOneAttribute(_configuredObject, attributeName, attributeValue); - - Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 0, - false, - false, - false, - false, - 120, - false); - assertEquals("Unexpected number of attributes", 1, resultMap.size()); - assertEquals("Unexpected attribute value", "attributeConfiguredObjectName", resultMap.get(attributeName)); - } - - public void testConfiguredObjectWithChildAndDepth1() - { - final String childAttributeName = "childattribute"; - final String childAttributeValue = "childvalue"; - - Model model = createTestModel(); - - TestChild mockChild = mock(TestChild.class); - when(mockChild.getModel()).thenReturn(model); - when(_configuredObject.getModel()).thenReturn(model); - configureMockToReturnOneAttribute(mockChild, childAttributeName, childAttributeValue); - when(_configuredObject.getChildren(TestChild.class)).thenReturn(Arrays.asList(mockChild)); - - Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 1, - false, - false, - false, - false, - 120, - false); - assertEquals("Unexpected parent map size", 1, resultMap.size()); - - final List<Map<String, Object>> childList = (List<Map<String, Object>>) resultMap.get("testchilds"); - assertEquals("Unexpected number of children", 1, childList.size()); - final Map<String, Object> childMap = childList.get(0); - assertEquals("Unexpected child map size", 1, childMap.size()); - assertNotNull(childMap); - - assertEquals("Unexpected child attribute value", childAttributeValue, childMap.get(childAttributeName)); - } - - public void testActuals() - { - final String childAttributeName = "childattribute"; - final String childAttributeValue = "childvalue"; - final String childActualAttributeValue = "${actualvalue}"; - final Map<String,Object> actualContext = Collections.<String,Object>singletonMap("key","value"); - final Set<String> inheritedKeys = new HashSet<>(Arrays.asList("key","inheritedkey")); - - Model model = createTestModel(); - - TestChild mockChild = mock(TestChild.class); - when(mockChild.getModel()).thenReturn(model); - when(_configuredObject.getModel()).thenReturn(model); - when(_configuredObject.getAttributeNames()).thenReturn(Collections.singletonList(ConfiguredObject.CONTEXT)); - when(_configuredObject.getContextValue(eq(String.class), eq("key"))).thenReturn("value"); - when(_configuredObject.getContextValue(eq(String.class),eq("inheritedkey"))).thenReturn("foo"); - when(_configuredObject.getContextKeys(anyBoolean())).thenReturn(inheritedKeys); - when(_configuredObject.getContext()).thenReturn(actualContext); - when(_configuredObject.getActualAttributes()).thenReturn(Collections.singletonMap(ConfiguredObject.CONTEXT, actualContext)); - when(mockChild.getAttributeNames()).thenReturn(Arrays.asList(childAttributeName, ConfiguredObject.CONTEXT)); - when(mockChild.getAttribute(childAttributeName)).thenReturn(childAttributeValue); - when(mockChild.getActualAttributes()).thenReturn(Collections.singletonMap(childAttributeName, childActualAttributeValue)); - when(_configuredObject.getChildren(TestChild.class)).thenReturn(Arrays.asList(mockChild)); - - - Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 1, - true, - false, - false, - false, - 120, - false); - assertEquals("Unexpected parent map size", 2, resultMap.size()); - assertEquals("Incorrect context", resultMap.get(ConfiguredObject.CONTEXT), actualContext); - List<Map<String, Object>> childList = (List<Map<String, Object>>) resultMap.get("testchilds"); - assertEquals("Unexpected number of children", 1, childList.size()); - Map<String, Object> childMap = childList.get(0); - assertNotNull(childMap); - assertEquals("Unexpected child map size", 1, childMap.size()); - - assertEquals("Unexpected child attribute value", childActualAttributeValue, childMap.get(childAttributeName)); - - resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 1, - false, - false, - false, - false, - 120, - false); - assertEquals("Unexpected parent map size", 2, resultMap.size()); - Map<String, Object> inheritedContext = new HashMap<>(); - inheritedContext.put("key","value"); - inheritedContext.put("inheritedkey","foo"); - assertEquals("Incorrect context", inheritedContext, resultMap.get(ConfiguredObject.CONTEXT)); - childList = (List<Map<String, Object>>) resultMap.get("testchilds"); - assertEquals("Unexpected number of children", 1, childList.size()); - childMap = childList.get(0); - assertEquals("Unexpected child map size", 1, childMap.size()); - assertNotNull(childMap); - - assertEquals("Unexpected child attribute value", childAttributeValue, childMap.get(childAttributeName)); - - } - - public void testOversizedAttributes() - { - - Model model = createTestModel(); - ConfiguredObjectTypeRegistry typeRegistry = model.getTypeRegistry(); - final Map<String, ConfiguredObjectAttribute<?, ?>> attributeTypes = - typeRegistry.getAttributeTypes(TestChild.class); - final ConfiguredObjectAttribute longAttr = mock(ConfiguredObjectAttribute.class); - when(longAttr.isOversized()).thenReturn(true); - when(longAttr.getOversizedAltText()).thenReturn(""); - when(attributeTypes.get(eq("longAttr"))).thenReturn(longAttr); - - TestChild mockChild = mock(TestChild.class); - when(mockChild.getModel()).thenReturn(model); - when(_configuredObject.getModel()).thenReturn(model); - configureMockToReturnOneAttribute(mockChild, "longAttr", "this is not long"); - when(_configuredObject.getChildren(TestChild.class)).thenReturn(Arrays.asList(mockChild)); - - - Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 1, - false, - false, - false, - false, - 20, - false); - Object children = resultMap.get("testchilds"); - assertNotNull(children); - assertTrue(children instanceof Collection); - assertTrue(((Collection)children).size()==1); - Object attrs = ((Collection)children).iterator().next(); - assertTrue(attrs instanceof Map); - assertEquals("this is not long", ((Map) attrs).get("longAttr")); - - - - resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 1, - false, - false, - false, - false, - 8, - false); - - children = resultMap.get("testchilds"); - assertNotNull(children); - assertTrue(children instanceof Collection); - assertTrue(((Collection)children).size()==1); - attrs = ((Collection)children).iterator().next(); - assertTrue(attrs instanceof Map); - assertEquals("this...", ((Map) attrs).get("longAttr")); - - - - - when(longAttr.getOversizedAltText()).thenReturn("test alt text"); - - resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 1, - false, - false, - false, - false, - 8, - false); - - children = resultMap.get("testchilds"); - assertNotNull(children); - assertTrue(children instanceof Collection); - assertTrue(((Collection)children).size()==1); - attrs = ((Collection)children).iterator().next(); - assertTrue(attrs instanceof Map); - assertEquals("test alt text", ((Map) attrs).get("longAttr")); - - - } - - public void testSecureAttributes() - { - - Model model = createTestModel(); - ConfiguredObjectTypeRegistry typeRegistry = model.getTypeRegistry(); - Map<String, ConfiguredObjectAttribute<?, ?>> attributeTypes = typeRegistry.getAttributeTypes(TestChild.class); - ConfiguredObjectAttribute secureAttribute = mock(ConfiguredObjectAttribute.class); - when(secureAttribute.isSecure()).thenReturn(true); - when(secureAttribute.isSecureValue(any())).thenReturn(true); - when(attributeTypes.get(eq("secureAttribute"))).thenReturn(secureAttribute); - - TestChild mockChild = mock(TestChild.class); - when(mockChild.getModel()).thenReturn(model); - when(_configuredObject.getModel()).thenReturn(model); - - // set encoded value - configureMockToReturnOneAttribute(mockChild, "secureAttribute", "*****"); - - // set actual values - when(mockChild.getActualAttributes()).thenReturn(Collections.singletonMap("secureAttribute", "secret")); - when(_configuredObject.getChildren(TestChild.class)).thenReturn(Arrays.asList(mockChild)); - when(model.getParentTypes(TestChild.class)).thenReturn(Collections.<Class<? extends ConfiguredObject>>singleton(TestChild.class)); - when(_configuredObject.getCategoryClass()).thenReturn(TestChild.class); - when(mockChild.isDurable()).thenReturn(true); - - Map<String, Object> resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 1, - false, - false, - false, - false, - 20, - false); - Object children = resultMap.get("testchilds"); - assertNotNull(children); - assertTrue(children instanceof Collection); - assertTrue(((Collection)children).size()==1); - Object attrs = ((Collection)children).iterator().next(); - assertTrue(attrs instanceof Map); - assertEquals("*****", ((Map) attrs).get("secureAttribute")); - - resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 1, - true, - true, - false, - true, - 20, - true); - - children = resultMap.get("testchilds"); - assertNotNull(children); - assertTrue(children instanceof Collection); - assertTrue(((Collection)children).size()==1); - attrs = ((Collection)children).iterator().next(); - assertTrue(attrs instanceof Map); - assertEquals("secret", ((Map) attrs).get("secureAttribute")); - - resultMap = _converter.convertObjectToMap(_configuredObject, - ConfiguredObject.class, - 1, - true, - true, - false, - false, - 20, - true); - - children = resultMap.get("testchilds"); - assertNotNull(children); - assertTrue(children instanceof Collection); - assertTrue(((Collection)children).size()==1); - attrs = ((Collection)children).iterator().next(); - assertTrue(attrs instanceof Map); - assertEquals("*****", ((Map) attrs).get("secureAttribute")); - } - - private Model createTestModel() - { - Model model = mock(Model.class); - final List<Class<? extends ConfiguredObject>> list = new ArrayList<Class<? extends ConfiguredObject>>(); - list.add(TestChild.class); - when(model.getChildTypes(ConfiguredObject.class)).thenReturn(list); - final ConfiguredObjectTypeRegistry typeRegistry = mock(ConfiguredObjectTypeRegistry.class); - final Map<String, ConfiguredObjectAttribute<?, ?>> attrTypes = mock(Map.class); - when(attrTypes.get(any(String.class))).thenReturn(mock(ConfiguredObjectAttribute.class)); - when(typeRegistry.getAttributeTypes(any(Class.class))).thenReturn(attrTypes); - when(model.getTypeRegistry()).thenReturn(typeRegistry); - return model; - } - - private void configureMockToReturnOneAttribute(ConfiguredObject mockConfiguredObject, String attributeName, Object attributeValue) - { - when(mockConfiguredObject.getAttributeNames()).thenReturn(Arrays.asList(attributeName)); - when(mockConfiguredObject.getAttribute(attributeName)).thenReturn(attributeValue); - } - - private static interface TestChild extends ConfiguredObject - { - } -} diff --git a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/session/LoginLogoutReporterTest.java b/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/session/LoginLogoutReporterTest.java deleted file mode 100644 index 45fa3fabd0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/session/LoginLogoutReporterTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.management.plugin.session; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Matchers.argThat; -import static org.mockito.Mockito.when; - -import javax.security.auth.Subject; - -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.logging.LogMessage; -import org.apache.qpid.server.logging.MessageLogger; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.mockito.ArgumentMatcher; - -import junit.framework.TestCase; - -public class LoginLogoutReporterTest extends TestCase -{ - private LoginLogoutReporter _loginLogoutReport; - private Subject _subject = new Subject(); - private MessageLogger _logger = mock(MessageLogger.class); - - @Override - protected void setUp() throws Exception - { - super.setUp(); - - _subject.getPrincipals().add(new AuthenticatedPrincipal("mockusername")); - when(_logger.isEnabled()).thenReturn(true); - when(_logger.isMessageEnabled(anyString())).thenReturn(true); - EventLogger eventLogger = new EventLogger(_logger); - EventLoggerProvider provider = mock(EventLoggerProvider.class); - when(provider.getEventLogger()).thenReturn(eventLogger); - _loginLogoutReport = new LoginLogoutReporter(_subject, provider); - } - - public void testLoginLogged() - { - _loginLogoutReport.valueBound(null); - verify(_logger).message(isLogMessageWithMessage("MNG-1007 : Open : User mockusername")); - } - - public void testLogoutLogged() - { - _loginLogoutReport.valueUnbound(null); - verify(_logger).message(isLogMessageWithMessage("MNG-1008 : Close : User mockusername")); - } - - private LogMessage isLogMessageWithMessage(final String expectedMessage) - { - return argThat( new ArgumentMatcher<LogMessage>() - { - @Override - public boolean matches(Object argument) - { - LogMessage actual = (LogMessage) argument; - return actual.toString().equals(expectedMessage); - } - }); - } -} diff --git a/qpid/java/broker-plugins/management-http/src/test/resources/META-INF/services/org.apache.qpid.server.management.plugin.report.QueueReport b/qpid/java/broker-plugins/management-http/src/test/resources/META-INF/services/org.apache.qpid.server.management.plugin.report.QueueReport deleted file mode 100644 index 7d25ec4378..0000000000 --- a/qpid/java/broker-plugins/management-http/src/test/resources/META-INF/services/org.apache.qpid.server.management.plugin.report.QueueReport +++ /dev/null @@ -1,2 +0,0 @@ -org.apache.qpid.server.management.plugin.report.TestTextReport -org.apache.qpid.server.management.plugin.report.TestBinaryReport diff --git a/qpid/java/broker-plugins/management-jmx/pom.xml b/qpid/java/broker-plugins/management-jmx/pom.xml deleted file mode 100644 index f90eb6c863..0000000000 --- a/qpid/java/broker-plugins/management-jmx/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-management-jmx</artifactId> - <name>Qpid JMX Management Broker Plug-in</name> - <description>JMX management broker plug-in</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-management-common</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <version>${log4j-version}</version> - </dependency> - - <!-- test dependencies --> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-test-utils</artifactId> - <version>${project.version}</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>commons-beanutils</groupId> - <artifactId>commons-beanutils-core</artifactId> - <version>${commons-beanutils-version}</version> - <scope>test</scope> - </dependency> - - </dependencies> - - <build> - </build> - -</project> diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/AMQManagedObject.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/AMQManagedObject.java deleted file mode 100644 index 5c39a0c26a..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/AMQManagedObject.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import java.util.concurrent.atomic.AtomicLong; - -import javax.management.ListenerNotFoundException; -import javax.management.NotCompliantMBeanException; -import javax.management.NotificationBroadcaster; -import javax.management.NotificationBroadcasterSupport; -import javax.management.NotificationFilter; -import javax.management.NotificationListener; - -/** - * This class provides additional feature of Notification Broadcaster to the - * DefaultManagedObject. - * @author Bhupendra Bhardwaj - * @version 0.1 - */ -public abstract class AMQManagedObject extends DefaultManagedObject - implements NotificationBroadcaster -{ - private final NotificationBroadcasterSupport _broadcaster = new NotificationBroadcasterSupport(); - - private AtomicLong _notificationSequenceNumber = new AtomicLong(); - - protected AMQManagedObject(Class<?> managementInterface, String typeName, ManagedObjectRegistry registry) - throws NotCompliantMBeanException - { - super(managementInterface, typeName, registry); - // CurrentActor will be defined as these objects are created during - // broker startup. - - } - - // notification broadcaster implementation - - public void addNotificationListener(NotificationListener listener, - NotificationFilter filter, - Object handback) - { - _broadcaster.addNotificationListener(listener, filter, handback); - } - - public void removeNotificationListener(NotificationListener listener) - throws ListenerNotFoundException - { - _broadcaster.removeNotificationListener(listener); - } - - - /** - * broadcaster support class - */ - protected NotificationBroadcasterSupport getBroadcaster() - { - return _broadcaster; - } - - protected long incrementAndGetSequenceNumber() - { - return _notificationSequenceNumber.incrementAndGet(); - } - - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/DefaultManagedObject.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/DefaultManagedObject.java deleted file mode 100644 index 95f60d62a6..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/DefaultManagedObject.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import javax.management.JMException; -import javax.management.MBeanInfo; -import javax.management.MBeanNotificationInfo; -import javax.management.MalformedObjectNameException; -import javax.management.NotCompliantMBeanException; -import javax.management.ObjectName; -import javax.management.StandardMBean; - -/** - * Provides implementation of the boilerplate ManagedObject interface. Most managed objects should find it useful - * to extend this class rather than implementing ManagedObject from scratch. - * - */ -public abstract class DefaultManagedObject extends StandardMBean implements ManagedObject -{ - private final Class<?> _managementInterface; - - private final String _typeName; - - private final MBeanInfo _mbeanInfo; - - private ManagedObjectRegistry _registry; - - protected DefaultManagedObject(Class<?> managementInterface, String typeName, ManagedObjectRegistry registry) - throws NotCompliantMBeanException - { - super(managementInterface); - _registry = registry; - _managementInterface = managementInterface; - _typeName = typeName; - _mbeanInfo = buildMBeanInfo(); - } - - public ManagedObjectRegistry getRegistry() - { - return _registry; - } - - @Override - public MBeanInfo getMBeanInfo() - { - return _mbeanInfo; - } - - public String getType() - { - return _typeName; - } - - public Class<?> getManagementInterface() - { - return _managementInterface; - } - - public abstract ManagedObject getParentObject(); - - - public void register() throws JMException - { - _registry.registerObject(this); - } - - public void unregister() throws JMException - { - try - { - if(_registry != null) - { - _registry.unregisterObject(this); - } - } - finally - { - _registry = null; - } - } - - public String toString() - { - return getObjectInstanceName() + "[" + getType() + "]"; - } - - /** - * Created the ObjectName as per the JMX Specs - * @return ObjectName - * @throws javax.management.MalformedObjectNameException - */ - public ObjectName getObjectName() throws MalformedObjectNameException - { - String name = getObjectInstanceName(); - StringBuffer objectName = new StringBuffer(ManagedObject.DOMAIN); - - objectName.append(":type="); - objectName.append(getHierarchicalType(this)); - - objectName.append(","); - objectName.append(getHierarchicalName(this)); - objectName.append("name=").append(name); - - return new ObjectName(objectName.toString()); - } - - protected ObjectName getObjectNameForSingleInstanceMBean() throws MalformedObjectNameException - { - StringBuffer objectName = new StringBuffer(ManagedObject.DOMAIN); - - objectName.append(":type="); - objectName.append(getHierarchicalType(this)); - - String hierarchyName = getHierarchicalName(this); - if (hierarchyName != null) - { - objectName.append(","); - objectName.append(hierarchyName.substring(0, hierarchyName.lastIndexOf(","))); - } - - return new ObjectName(objectName.toString()); - } - - protected String getHierarchicalType(ManagedObject obj) - { - if (obj.getParentObject() != null) - { - String parentType = getHierarchicalType(obj.getParentObject()).toString(); - return parentType + "." + obj.getType(); - } - else - { - return obj.getType(); - } - } - - protected String getHierarchicalName(ManagedObject obj) - { - if (obj.getParentObject() != null) - { - String parentName = obj.getParentObject().getType() + "=" + - obj.getParentObject().getObjectInstanceName() + ","+ - getHierarchicalName(obj.getParentObject()); - - return parentName; - } - else - { - return ""; - } - } - - private MBeanInfo buildMBeanInfo() throws NotCompliantMBeanException - { - return new MBeanInfo(this.getClass().getName(), - MBeanIntrospector.getMBeanDescription(this.getClass()), - MBeanIntrospector.getMBeanAttributesInfo(getManagementInterface()), - MBeanIntrospector.getMBeanConstructorsInfo(this.getClass()), - MBeanIntrospector.getMBeanOperationsInfo(getManagementInterface()), - this.getNotificationInfo()); - } - - public MBeanNotificationInfo[] getNotificationInfo() - { - return null; - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagedObjectRegistry.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagedObjectRegistry.java deleted file mode 100644 index 381295a18a..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagedObjectRegistry.java +++ /dev/null @@ -1,432 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.rmi.AlreadyBoundException; -import java.rmi.NoSuchObjectException; -import java.rmi.NotBoundException; -import java.rmi.RemoteException; -import java.rmi.registry.LocateRegistry; -import java.rmi.registry.Registry; -import java.rmi.server.RMIClientSocketFactory; -import java.rmi.server.RMIServerSocketFactory; -import java.rmi.server.UnicastRemoteObject; -import java.security.GeneralSecurityException; -import java.util.HashMap; -import java.util.Set; - -import javax.management.JMException; -import javax.management.MBeanServer; -import javax.management.MBeanServerFactory; -import javax.management.ObjectName; -import javax.management.remote.JMXConnectorServer; -import javax.management.remote.JMXServiceURL; -import javax.management.remote.MBeanServerForwarder; -import javax.management.remote.rmi.RMIConnectorServer; -import javax.net.ssl.SSLContext; -import javax.rmi.ssl.SslRMIClientSocketFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.JmxPort; -import org.apache.qpid.server.model.port.RmiPort; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.jmx.JMXPasswordAuthenticator; -import org.apache.qpid.server.util.ServerScopedRuntimeException; - -/** - * This class starts up an MBeanserver. If out of the box agent has been enabled then there are no - * security features implemented like user authentication and authorisation. - */ -public class JMXManagedObjectRegistry implements ManagedObjectRegistry -{ - private static final Logger _log = LoggerFactory.getLogger(JMXManagedObjectRegistry.class); - - private static final String OPERATIONAL_LOGGING_NAME = "JMX"; - - private final MBeanServer _mbeanServer; - - private JMXConnectorServer _cs; - private Registry _rmiRegistry; - - private final Broker _broker; - private final RmiPort _registryPort; - private final JmxPort _connectorPort; - - public JMXManagedObjectRegistry( - Broker broker, - JmxPort connectorPort, RmiPort registryPort, - JMXManagementPlugin jmxManagement) - { - _broker = broker; - _registryPort = registryPort; - _connectorPort = connectorPort; - - boolean usePlatformServer = (Boolean)jmxManagement.getAttribute(JMXManagementPlugin.USE_PLATFORM_MBEAN_SERVER); - - _mbeanServer = - usePlatformServer ? ManagementFactory.getPlatformMBeanServer() - : MBeanServerFactory.createMBeanServer(ManagedObject.DOMAIN); - } - - private EventLogger getEventLogger() - { - return _broker.getEventLogger(); - } - - @Override - public void start() throws IOException - { - getEventLogger().message(ManagementConsoleMessages.STARTUP(OPERATIONAL_LOGGING_NAME)); - - //check if system properties are set to use the JVM's out-of-the-box JMXAgent - if (areOutOfTheBoxJMXOptionsSet()) - { - getEventLogger().message(ManagementConsoleMessages.READY(OPERATIONAL_LOGGING_NAME)); - } - else - { - startRegistryAndConnector(); - } - } - - private void startRegistryAndConnector() throws IOException - { - //Socket factories for the RMIConnectorServer, either default or SSL depending on configuration - RMIClientSocketFactory csf; - RMIServerSocketFactory ssf; - - //check ssl enabled option on connector port (note we don't provide ssl for registry server at - //moment). - boolean connectorSslEnabled = _connectorPort.getTransports().contains(Transport.SSL); - - if (connectorSslEnabled) - { - KeyStore keyStore = _connectorPort.getKeyStore(); - - SSLContext sslContext; - try - { - - sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyStore.getKeyManagers(), null, null); - } - catch (GeneralSecurityException e) - { - throw new ServerScopedRuntimeException("Unable to create SSLContext for key store", e); - } - - //create the SSL RMI socket factories - csf = new SslRMIClientSocketFactory(); - ssf = new QpidSslRMIServerSocketFactory(sslContext,_connectorPort.getEnabledCipherSuites(), _connectorPort.getDisabledCipherSuites()); - } - else - { - csf = null; // signifies the default - ssf = new QpidRMIServerSocketFactory(); - } - - int jmxPortRegistryServer = _registryPort.getPort(); - int jmxPortConnectorServer = _connectorPort.getPort(); - - //add a JMXAuthenticator implementation the env map to authenticate the RMI based JMX connector server - SubjectCreator subjectCreator =_connectorPort.getAuthenticationProvider().getSubjectCreator(connectorSslEnabled); - if (subjectCreator == null) - { - throw new SecurityException("Can't get subject creator for " + _connectorPort); - } - - JMXPasswordAuthenticator rmipa = new JMXPasswordAuthenticator(subjectCreator, _broker.getSecurityManager()); - HashMap<String,Object> connectorEnv = new HashMap<>(); - connectorEnv.put(JMXConnectorServer.AUTHENTICATOR, rmipa); - - System.setProperty("java.rmi.server.randomIDs", "true"); - boolean useCustomSocketFactory = Boolean.parseBoolean(System.getProperty(BrokerProperties.PROPERTY_USE_CUSTOM_RMI_SOCKET_FACTORY, Boolean.TRUE.toString())); - - /* - * Start a RMI registry on the management port, to hold the JMX RMI ConnectorServer stub. - * Using custom socket factory to prevent anyone (including us unfortunately) binding to the registry using RMI. - * As a result, only binds made using the object reference will succeed, thus securing it from external change. - */ - _rmiRegistry = createRmiRegistry(jmxPortRegistryServer, useCustomSocketFactory); - - /* - * We must now create the RMI ConnectorServer manually, as the JMX Factory methods use RMI calls - * to bind the ConnectorServer to the registry, which will now fail as for security we have - * locked it from any RMI based modifications, including our own. Instead, we will manually bind - * the RMIConnectorServer stub to the registry using its object reference, which will still succeed. - * - * The registry is exported on the defined management port 'port'. - */ - final UsernameCachingRMIJRMPServer usernameCachingRmiServer = new UsernameCachingRMIJRMPServer(jmxPortConnectorServer, csf, ssf, connectorEnv); - - final String localHostName = getLocalhost(); - final JMXServiceURL externalUrl = new JMXServiceURL( - "service:jmx:rmi://"+localHostName+":"+(jmxPortConnectorServer)+"/jndi/rmi://"+localHostName+":"+jmxPortRegistryServer+"/jmxrmi"); - - final JMXServiceURL internalUrl = new JMXServiceURL("rmi", localHostName, jmxPortConnectorServer); - _cs = new RMIConnectorServer(internalUrl, connectorEnv, usernameCachingRmiServer, _mbeanServer) - { - @Override - public synchronized void start() throws IOException - { - try - { - //manually bind the connector server to the registry at key 'jmxrmi', like the out-of-the-box agent - _rmiRegistry.bind("jmxrmi", usernameCachingRmiServer); - } - catch (AlreadyBoundException abe) - { - //key was already in use. shouldnt happen here as its a new registry, unbindable by normal means. - - //IOExceptions are the only checked type throwable by the method, wrap and rethrow - IOException ioe = new IOException(abe.getMessage()); - ioe.initCause(abe); - throw ioe; - } - - //now do the normal tasks - super.start(); - } - - @Override - public synchronized void stop() throws IOException - { - try - { - if (_rmiRegistry != null) - { - _rmiRegistry.unbind("jmxrmi"); - } - } - catch (NotBoundException nbe) - { - _log.error("Failed to unbind jmxrmi", nbe); - //ignore - } - - //now do the normal tasks - super.stop(); - } - - @Override - public JMXServiceURL getAddress() - { - //must return our pre-crafted url that includes the full details, inc JNDI details - return externalUrl; - } - }; - - //Add the custom invoker as an MBeanServerForwarder, and start the RMIConnectorServer. - MBeanServerForwarder mbsf = MBeanInvocationHandlerImpl.newProxyInstance(_broker); - _cs.setMBeanServerForwarder(mbsf); - - // Install a ManagementLogonLogoffReporter so we can report as users logon/logoff - ManagementLogonLogoffReporter jmxManagementUserLogonLogoffReporter = new ManagementLogonLogoffReporter(_broker, usernameCachingRmiServer); - _cs.addNotificationListener(jmxManagementUserLogonLogoffReporter, jmxManagementUserLogonLogoffReporter, null); - - // Install the usernameCachingRmiServer as a listener so it may cleanup as clients disconnect - _cs.addNotificationListener(usernameCachingRmiServer, usernameCachingRmiServer, null); - - _cs.start(); - - Set<Transport> connectorTransports = _connectorPort.getTransports(); - for (Transport transport: connectorTransports) - { - getEventLogger().message(ManagementConsoleMessages.LISTENING("JMX RMIConnectorServer", transport.name(), jmxPortConnectorServer)); - } - - getEventLogger().message(ManagementConsoleMessages.READY(OPERATIONAL_LOGGING_NAME)); - } - - private Registry createRmiRegistry(int jmxPortRegistryServer, boolean useCustomRmiRegistry) - throws RemoteException - { - final RMIServerSocketFactory ssf = getRmiServerSocketFactory(useCustomRmiRegistry); - Registry rmiRegistry = LocateRegistry.createRegistry(jmxPortRegistryServer, null, ssf); - - getEventLogger().message(ManagementConsoleMessages.LISTENING("RMI Registry", Transport.TCP.name(), jmxPortRegistryServer)); - return rmiRegistry; - } - - @Override - public void registerObject(ManagedObject managedObject) throws JMException - { - _mbeanServer.registerMBean(managedObject, managedObject.getObjectName()); - } - - @Override - public void unregisterObject(ManagedObject managedObject) throws JMException - { - _mbeanServer.unregisterMBean(managedObject.getObjectName()); - } - - @Override - public void close() - { - _log.debug("close() called"); - - closeConnectorAndRegistryServers(); - - unregisterAllMbeans(); - - getEventLogger().message(ManagementConsoleMessages.STOPPED(OPERATIONAL_LOGGING_NAME)); - } - - private void closeConnectorAndRegistryServers() - { - closeConnectorServer(); - closeRegistryServer(); - } - - // checks if the system properties are set which enable the JVM's out-of-the-box JMXAgent. - private boolean areOutOfTheBoxJMXOptionsSet() - { - if (System.getProperty("com.sun.management.jmxremote") != null) - { - return true; - } - - if (System.getProperty("com.sun.management.jmxremote.port") != null) - { - return true; - } - - return false; - } - - private String getLocalhost() - { - String localHost; - try - { - localHost = InetAddress.getLocalHost().getHostName(); - } - catch(UnknownHostException ex) - { - localHost="127.0.0.1"; - } - return localHost; - } - - private void closeRegistryServer() - { - if (_rmiRegistry != null) - { - // Stopping the RMI registry - getEventLogger().message(ManagementConsoleMessages.SHUTTING_DOWN("RMI Registry", _registryPort.getPort())); - try - { - boolean success = UnicastRemoteObject.unexportObject(_rmiRegistry, false); - if (!success) - { - _log.warn("Failed to unexport object " + _rmiRegistry); - } - } - catch (NoSuchObjectException e) - { - _log.error("Exception while closing the RMI Registry: ", e); - } - finally - { - _rmiRegistry = null; - } - } - } - - private void closeConnectorServer() - { - if (_cs != null) - { - // Stopping the JMX ConnectorServer - try - { - getEventLogger().message(ManagementConsoleMessages.SHUTTING_DOWN("JMX RMIConnectorServer", - _cs.getAddress().getPort())); - _cs.stop(); - } - catch (IOException e) - { - _log.error("Exception while closing the JMX ConnectorServer: ", e); - } - finally - { - _cs = null; - } - } - } - - private void unregisterAllMbeans() - { - //ObjectName query to gather all Qpid related MBeans - ObjectName mbeanNameQuery = null; - try - { - mbeanNameQuery = new ObjectName(ManagedObject.DOMAIN + ":*"); - } - catch (Exception e1) - { - _log.warn("Unable to generate MBean ObjectName query for close operation"); - } - - for (ObjectName name : _mbeanServer.queryNames(mbeanNameQuery, null)) - { - try - { - _mbeanServer.unregisterMBean(name); - } - catch (JMException e) - { - _log.error("Exception unregistering MBean '"+ name +"': " + e.getMessage()); - } - } - } - - private RMIServerSocketFactory getRmiServerSocketFactory(final boolean useCustomRmiRegistry) - { - final RMIServerSocketFactory ssf; - if(useCustomRmiRegistry) - { - if (_log.isDebugEnabled()) - { - _log.debug("Using registry-protecting RMIServerSocketFactory"); - } - ssf = new RegistryProtectingRMIServerSocketFactory(); - } - else - { - ssf = new QpidRMIServerSocketFactory(); - } - return ssf; - } - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementPlugin.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementPlugin.java deleted file mode 100644 index 36efd4cb4c..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementPlugin.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import org.apache.qpid.server.model.*; - -@org.apache.qpid.server.model.ManagedObject( category = false , type = "MANAGEMENT-JMX" ) -public interface JMXManagementPlugin<X extends JMXManagementPlugin<X>> extends Plugin<X> -{ - String PLUGIN_TYPE = "MANAGEMENT-JMX"; - // attributes - String USE_PLATFORM_MBEAN_SERVER = "usePlatformMBeanServer"; - String DEFAULT_USE_PLATFORM_MBEAN_SERVER = "true"; - - @ManagedAttribute( defaultValue = DEFAULT_USE_PLATFORM_MBEAN_SERVER ) - boolean getUsePlatformMBeanServer(); -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementPluginImpl.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementPluginImpl.java deleted file mode 100644 index 94e5933ff8..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementPluginImpl.java +++ /dev/null @@ -1,527 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.jmx; - -import java.io.IOException; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import javax.management.InstanceAlreadyExistsException; -import javax.management.JMException; - -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.jmx.mbeans.LoggingManagementMBean; -import org.apache.qpid.server.jmx.mbeans.ServerInformationMBean; -import org.apache.qpid.server.jmx.mbeans.Shutdown; -import org.apache.qpid.server.jmx.mbeans.UserManagementMBean; -import org.apache.qpid.server.jmx.mbeans.VirtualHostMBean; -import org.apache.qpid.server.logging.log4j.LoggingManagementFacade; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfigurationChangeListener; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.PasswordCredentialManagingAuthenticationProvider; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.StateTransition; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.model.adapter.AbstractPluginAdapter; -import org.apache.qpid.server.model.port.JmxPort; -import org.apache.qpid.server.model.port.PortManager; -import org.apache.qpid.server.model.port.RmiPort; -import org.apache.qpid.server.plugin.QpidServiceLoader; - -public class JMXManagementPluginImpl - extends AbstractPluginAdapter<JMXManagementPluginImpl> implements JMXManagementPlugin<JMXManagementPluginImpl>, PortManager -{ - private static final Logger LOGGER = LoggerFactory.getLogger(JMXManagementPluginImpl.class); - - public static final String NAME = "name"; - - // default values - public static final String DEFAULT_NAME = "JMXManagement"; - - private JMXManagedObjectRegistry _objectRegistry; - - private final Object _childrenLock = new Object(); - private final Map<ConfiguredObject<?>, Map<MBeanProvider, ManagedObject>> _children = new HashMap<ConfiguredObject<?>, Map<MBeanProvider,ManagedObject>>(); - - @ManagedAttributeField - private boolean _usePlatformMBeanServer; - - private boolean _allowPortActivation; - - private final Set<MBeanProvider> _mBeanProviders; - private final ChangeListener _changeListener; - private final PluginMBeansProvider _pluginMBeanProvider; - - @ManagedObjectFactoryConstructor - public JMXManagementPluginImpl(Map<String, Object> attributes, Broker<?> broker) - { - super(attributes, broker); - _changeListener = new ChangeListener(); - _pluginMBeanProvider = new PluginMBeansProvider(); - _mBeanProviders = new HashSet<MBeanProvider>(); - QpidServiceLoader qpidServiceLoader = new QpidServiceLoader(); - for (MBeanProvider provider : qpidServiceLoader.instancesOf(MBeanProvider.class)) - { - _mBeanProviders.add(provider); - } - } - - @Override - public boolean getUsePlatformMBeanServer() - { - return _usePlatformMBeanServer; - } - - @StateTransition(currentState = {State.UNINITIALIZED,State.ERRORED}, desiredState = State.ACTIVE) - private ListenableFuture<Void> doStart() throws JMException, IOException - { - _allowPortActivation = true; - Broker<?> broker = getBroker(); - JmxPort<?> connectorPort = null; - RmiPort registryPort = null; - Collection<Port<?>> ports = broker.getPorts(); - for (Port<?> port : ports) - { - if (port.getDesiredState() != State.ACTIVE) - { - continue; - } - - if(isRegistryPort(port)) - { - registryPort = (RmiPort) port; - registryPort.setPortManager(this); - if(port.getState() != State.ACTIVE) - { - // TODO - RG - port.startAsync(); - } - - } - else if(isConnectorPort(port)) - { - connectorPort = (JmxPort<?>) port; - connectorPort.setPortManager(this); - if(port.getState() != State.ACTIVE) - { - port.startAsync(); - } - - } - } - if(connectorPort == null) - { - throw new IllegalStateException("No JMX connector port found supporting protocol " + Protocol.JMX_RMI); - } - if(registryPort == null) - { - throw new IllegalStateException("No JMX RMI port found supporting protocol " + Protocol.RMI); - } - - _objectRegistry = new JMXManagedObjectRegistry(broker, connectorPort, registryPort, this); - - broker.addChangeListener(_changeListener); - - synchronized (_childrenLock) - { - for(VirtualHostNode<?> virtualHostNode : broker.getVirtualHostNodes()) - { - createObjectMBeans(virtualHostNode); - } - - Collection<AuthenticationProvider<?>> authenticationProviders = broker.getAuthenticationProviders(); - for (AuthenticationProvider<?> authenticationProvider : authenticationProviders) - { - createObjectMBeans(authenticationProvider); - } - } - new Shutdown(_objectRegistry); - new ServerInformationMBean(_objectRegistry, broker); - if (LoggingManagementFacade.getCurrentInstance() != null) - { - new LoggingManagementMBean(LoggingManagementFacade.getCurrentInstance(), _objectRegistry); - } - _objectRegistry.start(); - setState(State.ACTIVE); - _allowPortActivation = false; - return Futures.immediateFuture(null); - } - - @Override - public boolean isActivationAllowed(final Port<?> port) - { - return _allowPortActivation; - } - - private boolean isConnectorPort(Port<?> port) - { - return port.getProtocols().contains(Protocol.JMX_RMI); - } - - private boolean isRegistryPort(Port<?> port) - { - return port.getProtocols().contains(Protocol.RMI); - } - - @Override - protected void onClose() - { - synchronized (_childrenLock) - { - for(ConfiguredObject<?> object : _children.keySet()) - { - unregisterObjectMBeans(object); - } - _children.clear(); - } - getBroker().removeChangeListener(_changeListener); - closeObjectRegistry(); - } - - private void unregisterObjectMBeans(ConfiguredObject<?> object) - { - Map<?, ManagedObject> mbeans = _children.get(object); - if (mbeans != null) - { - for (ManagedObject mbean : mbeans.values()) - { - if (mbean instanceof ConfigurationChangeListener) - { - object.removeChangeListener((ConfigurationChangeListener)mbean); - } - - if (LOGGER.isDebugEnabled()) - { - String mbeanName = null; - try - { - mbeanName = mbean.getObjectName().toString(); - } - catch(Exception e) - { - // ignore - } - LOGGER.debug("Unregistering MBean " + mbeanName + " for configured object " + object); - } - - try - { - mbean.unregister(); - } - catch (Exception e) - { - LOGGER.error("Exception while unregistering mbean for " + object.getClass().getSimpleName() + " " + object.getName(), e); - } - } - } - } - - private void createAdditionalMBeansFromProvidersIfNecessary(ConfiguredObject<?> child, ManagedObjectRegistry registry) throws JMException - { - for (MBeanProvider provider : _mBeanProviders) - { - if(LOGGER.isDebugEnabled()) - { - LOGGER.debug("Consulting mbean provider : " + provider + " for child : " + child); - } - - ManagedObject mBean = null; - if (provider.isChildManageableByMBean(child) && !providerMBeanExists(child, provider)) - { - if(LOGGER.isDebugEnabled()) - { - LOGGER.debug("Provider of type " + provider.getType() + " will create mbean for " + child); - } - - mBean = provider.createMBean(child, registry); - if (mBean != null) - { - registerMBean(child, provider, mBean); - } - } - - if(LOGGER.isDebugEnabled()) - { - LOGGER.debug("Provider " + provider + (mBean == null ? " did not create mBean" : " created mBean " + mBean) - + " for child " + child); - } - } - } - - @Override - protected void validateChange(final ConfiguredObject<?> proxyForValidation, final Set<String> changedAttributes) - { - super.validateChange(proxyForValidation, changedAttributes); - if(changedAttributes.contains(NAME)) - { - String newName = proxyForValidation.getName(); - if(!getName().equals(newName)) - { - throw new IllegalConfigurationException("Changing the name of jmx management plugin is not allowed"); - } - } - } - - private void closeObjectRegistry() - { - if (_objectRegistry != null) - { - try - { - _objectRegistry.close(); - } - finally - { - _objectRegistry = null; - } - } - } - - private ManagedObject createObjectMBeansIfNecessary(ConfiguredObject<?> object) throws JMException - { - ManagedObject mbean = null; - if (supportedConfiguredObject(object)) - { - synchronized (_childrenLock) - { - if (!providerMBeanExists(object, _pluginMBeanProvider)) - { - if (object instanceof VirtualHostNode) - { - object.addChangeListener(_changeListener); - VirtualHostNode<?> virtualHostNode = (VirtualHostNode<?>) object; - - // Virtual host nodes may or may not have a virtual host at this point. - // In the HA case, JE may spontaneously make the node a master causing it to create a virtual host. - // Creation of the virtual host uses the task executor (same thread that executes this code - // so there is no potential for a race here). - VirtualHost<?, ?, ?> host = virtualHostNode.getVirtualHost(); - if (host != null) - { - createVirtualHostMBeanIfNecessary(host, _objectRegistry); - } - } - else if (object instanceof VirtualHost) - { - mbean = createVirtualHostMBeanIfNecessary((VirtualHost<?, ?, ?>) object, _objectRegistry); - } - else if (object instanceof PasswordCredentialManagingAuthenticationProvider) - { - object.addChangeListener(_changeListener); - mbean = new UserManagementMBean((PasswordCredentialManagingAuthenticationProvider<?>) object, _objectRegistry); - registerMBean(object, _pluginMBeanProvider, mbean); - } - } - createAdditionalMBeansFromProvidersIfNecessary(object, _objectRegistry); - } - } - return mbean; - } - - private VirtualHostMBean createVirtualHostMBeanIfNecessary(VirtualHost<?, ?, ?> host, ManagedObjectRegistry _objectRegistry) throws JMException - { - if (!providerMBeanExists(host, _pluginMBeanProvider)) - { - host.addChangeListener(_changeListener); - try - { - VirtualHostMBean mbean = new VirtualHostMBean(host, _objectRegistry); - registerMBean(host, _pluginMBeanProvider, mbean); - return mbean; - } - catch (InstanceAlreadyExistsException e) - { - VirtualHostNode parent = host.getParent(VirtualHostNode.class); - Set<ConfiguredObject<?>> registered = _children.keySet(); - for (ConfiguredObject<?> object: registered) - { - if (object instanceof VirtualHost && object.getParent(VirtualHostNode.class) == parent) - { - LOGGER.warn("Unexpected MBean is found for VirtualHost " + object + " belonging to node " + parent); - } - } - - throw e; - } - } - return null; - } - - private void registerMBean(ConfiguredObject<?> configuredObject, MBeanProvider mBeanProvider, ManagedObject mbean) - { - Map<MBeanProvider, ManagedObject> mbeans = _children.get(configuredObject); - if (mbeans == null) - { - mbeans = new HashMap<MBeanProvider, ManagedObject>(); - _children.put(configuredObject, mbeans); - } - mbeans.put(mBeanProvider, mbean); - } - - private boolean providerMBeanExists(ConfiguredObject<?> configuredObject, MBeanProvider mBeanProvider) - { - Map<MBeanProvider, ManagedObject> mbeans = _children.get(configuredObject); - if (mbeans == null) - { - return false; - } - return mbeans.containsKey(mBeanProvider); - } - - private void destroyObjectMBeans(ConfiguredObject<?> object, boolean removeListener) - { - if (supportedConfiguredObject(object)) - { - synchronized (_childrenLock) - { - if (removeListener) - { - object.removeChangeListener(_changeListener); - } - unregisterObjectMBeans(object); - _children.remove(object); - destroyChildrenMBeans(object); - } - } - } - - private void destroyChildrenMBeans(ConfiguredObject<?> object) - { - for (Iterator<ConfiguredObject<?>> iterator = _children.keySet().iterator(); iterator.hasNext();) - { - ConfiguredObject<?> registeredObject = iterator.next(); - ConfiguredObject<?> parent = registeredObject.getParent(object.getCategoryClass()); - if (parent == object) - { - registeredObject.removeChangeListener(_changeListener); - unregisterObjectMBeans(registeredObject); - iterator.remove(); - } - } - } - - private void createObjectMBeans(ConfiguredObject<?> object) - { - try - { - createObjectMBeansIfNecessary(object); - } - catch (JMException e) - { - LOGGER.error("Cannot create MBean for " + object, e); - } - } - - private boolean supportedConfiguredObject(ConfiguredObject<?> object) - { - return object instanceof VirtualHostNode || object instanceof VirtualHost || object instanceof PasswordCredentialManagingAuthenticationProvider; - } - - private class PluginMBeansProvider implements MBeanProvider - { - @Override - public boolean isChildManageableByMBean(ConfiguredObject<?> object) - { - return supportedConfiguredObject(object); - } - - @Override - public ManagedObject createMBean(ConfiguredObject<?> object, ManagedObjectRegistry registry) throws JMException - { - return createObjectMBeansIfNecessary(object); - } - - @Override - public String getType() - { - return "INTERNAL"; - } - - @Override - public String toString() - { - return DEFAULT_NAME; - } - } - - private class ChangeListener implements ConfigurationChangeListener - { - @Override - public void stateChanged(ConfiguredObject<?> object, State oldState, State newState) - { - if (newState == State.DELETED || newState == State.STOPPED || newState == State.ERRORED) - { - destroyObjectMBeans(object, newState == State.DELETED); - } - else if (newState == State.ACTIVE) - { - createObjectMBeans(object); - } - } - - @Override - public void childAdded(ConfiguredObject<?> object, ConfiguredObject<?> child) - { - createObjectMBeans(child); - } - - @Override - public void childRemoved(ConfiguredObject<?> object, ConfiguredObject<?> child) - { - destroyObjectMBeans(child, true); - } - - @Override - public void attributeSet(ConfiguredObject<?> object, String attributeName, Object oldAttributeValue, Object newAttributeValue) - { - // VH can be created after attribute change, - // for instance, on role change in BDB HA VHN a VH could is recovered/created. - // A call to createObjectMBeans is safe as it checks the existence of MBean before its creation. - - if (ConfiguredObject.DESIRED_STATE.equals(attributeName)) - { - stateChanged(object, State.valueOf(String.valueOf(oldAttributeValue)), State.valueOf(String.valueOf(newAttributeValue))); - } - else - { - createObjectMBeans(object); - } - } - } - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanIntrospector.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanIntrospector.java deleted file mode 100644 index d227b3a02e..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanIntrospector.java +++ /dev/null @@ -1,400 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import org.apache.qpid.management.common.mbeans.annotations.MBeanAttribute; -import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; -import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation; -import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter; - -import javax.management.MBeanAttributeInfo; -import javax.management.MBeanConstructorInfo; -import javax.management.MBeanOperationInfo; -import javax.management.MBeanParameterInfo; -import javax.management.NotCompliantMBeanException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -/** - * This class is a utility class to introspect the MBean class and the management - * interface class for various purposes. - * @author Bhupendra Bhardwaj - * @version 0.1 - */ -class MBeanIntrospector -{ - - private static final String _defaultAttributeDescription = "Management attribute"; - private static final String _defaultOperationDescription = "Management operation"; - private static final String _defaultConstructorDescription = "MBean constructor"; - private static final String _defaultMbeanDescription = "Management interface of the MBean"; - - private MBeanIntrospector() - { - } - - /** - * Introspects the management interface class for MBean attributes. - * @param interfaceClass - * @return MBeanAttributeInfo[] - * @throws javax.management.NotCompliantMBeanException - */ - static MBeanAttributeInfo[] getMBeanAttributesInfo(Class interfaceClass) - throws NotCompliantMBeanException - { - List<MBeanAttributeInfo> attributesList = new ArrayList<MBeanAttributeInfo>(); - - /** - * Using reflection, all methods of the managemetn interface will be analysed, - * and MBeanInfo will be created. - */ - for (Method method : interfaceClass.getMethods()) - { - String name = method.getName(); - Class<?> resultType = method.getReturnType(); - MBeanAttributeInfo attributeInfo = null; - - if (isAttributeGetterMethod(method)) - { - String desc = getAttributeDescription(method); - attributeInfo = new MBeanAttributeInfo(name.substring(3), - resultType.getName(), - desc, - true, - false, - false); - int index = getIndexIfAlreadyExists(attributeInfo, attributesList); - if (index == -1) - { - attributesList.add(attributeInfo); - } - else - { - attributeInfo = new MBeanAttributeInfo(name.substring(3), - resultType.getName(), - desc, - true, - true, - false); - attributesList.set(index, attributeInfo); - } - } - else if (isAttributeSetterMethod(method)) - { - String desc = getAttributeDescription(method); - attributeInfo = new MBeanAttributeInfo(name.substring(3), - method.getParameterTypes()[0].getName(), - desc, - false, - true, - false); - int index = getIndexIfAlreadyExists(attributeInfo, attributesList); - if (index == -1) - { - attributesList.add(attributeInfo); - } - else - { - attributeInfo = new MBeanAttributeInfo(name.substring(3), - method.getParameterTypes()[0].getName(), - desc, - true, - true, - false); - attributesList.set(index, attributeInfo); - } - } - else if (isAttributeBoolean(method)) - { - attributeInfo = new MBeanAttributeInfo(name.substring(2), - resultType.getName(), - getAttributeDescription(method), - true, - false, - true); - attributesList.add(attributeInfo); - } - } - - return attributesList.toArray(new MBeanAttributeInfo[0]); - } - - /** - * Introspects the management interface class for management operations. - * @param interfaceClass - * @return MBeanOperationInfo[] - */ - static MBeanOperationInfo[] getMBeanOperationsInfo(Class interfaceClass) - { - List<MBeanOperationInfo> operationsList = new ArrayList<MBeanOperationInfo>(); - - for (Method method : interfaceClass.getMethods()) - { - if (!isAttributeGetterMethod(method) && - !isAttributeSetterMethod(method) && - !isAttributeBoolean(method)) - { - operationsList.add(getOperationInfo(method)); - } - } - - return operationsList.toArray(new MBeanOperationInfo[0]); - } - - /** - * Checks if the method is an attribute getter method. - * @param method - * @return true if the method is an attribute getter method. - */ - private static boolean isAttributeGetterMethod(Method method) - { - if (!(method.getName().equals("get")) && - method.getName().startsWith("get") && - method.getParameterTypes().length == 0 && - !method.getReturnType().equals(void.class)) - { - return true; - } - - return false; - } - - /** - * Checks if the method is an attribute setter method. - * @param method - * @return true if the method is an attribute setter method. - */ - private static boolean isAttributeSetterMethod(Method method) - { - if (!(method.getName().equals("set")) && - method.getName().startsWith("set") && - method.getParameterTypes().length == 1 && - method.getReturnType().equals(void.class)) - { - return true; - } - - return false; - } - - /** - * Checks if the attribute is a boolean and the method is a isX kind og method. - * @param method - * @return true if the method is an attribute isX type of method - */ - private static boolean isAttributeBoolean(Method method) - { - if (!(method.getName().equals("is")) && - method.getName().startsWith("is") && - method.getParameterTypes().length == 0 && - method.getReturnType().equals(boolean.class)) - { - return true; - } - - return false; - } - - /** - * Helper method to retrieve the attribute index from the list of attributes. - * @param attribute - * @param list - * @return attribute index no. -1 if attribute doesn't exist - * @throws javax.management.NotCompliantMBeanException - */ - private static int getIndexIfAlreadyExists(MBeanAttributeInfo attribute, - List<MBeanAttributeInfo> list) - throws NotCompliantMBeanException - { - String exceptionMsg = "Conflicting attribute methods for attribute " + attribute.getName(); - - for (MBeanAttributeInfo memberAttribute : list) - { - if (attribute.getName().equals(memberAttribute.getName())) - { - if (!attribute.getType().equals(memberAttribute.getType())) - { - throw new NotCompliantMBeanException(exceptionMsg); - } - if (attribute.isReadable() && memberAttribute.isReadable()) - { - if (attribute.isIs() != memberAttribute.isIs()) - { - throw new NotCompliantMBeanException(exceptionMsg); - } - } - - return list.indexOf(memberAttribute); - } - } - - return -1; - } - - /** - * Retrieves the attribute description from annotation - * @param attributeMethod - * @return attribute description - */ - private static String getAttributeDescription(Method attributeMethod) - { - MBeanAttribute anno = attributeMethod.getAnnotation(MBeanAttribute.class); - if (anno != null) - { - return anno.description(); - } - return _defaultAttributeDescription; - } - - /** - * Introspects the method to retrieve the operation information. - * @param operation - * @return MBeanOperationInfo - */ - private static MBeanOperationInfo getOperationInfo(Method operation) - { - MBeanOperationInfo operationInfo = null; - Class<?> returnType = operation.getReturnType(); - - MBeanParameterInfo[] paramsInfo = getParametersInfo(operation.getParameterAnnotations(), - operation.getParameterTypes()); - - String operationDesc = _defaultOperationDescription; - int impact = MBeanOperationInfo.UNKNOWN; - - if (operation.getAnnotation(MBeanOperation.class) != null) - { - operationDesc = operation.getAnnotation(MBeanOperation.class).description(); - impact = operation.getAnnotation(MBeanOperation.class).impact(); - } - operationInfo = new MBeanOperationInfo(operation.getName(), - operationDesc, - paramsInfo, - returnType.getName(), - impact); - - return operationInfo; - } - - /** - * Constructs the parameter info. - * @param paramsAnno - * @param paramTypes - * @return MBeanParameterInfo[] - */ - private static MBeanParameterInfo[] getParametersInfo(Annotation[][] paramsAnno, - Class<?>[] paramTypes) - { - int noOfParams = paramsAnno.length; - - MBeanParameterInfo[] paramsInfo = new MBeanParameterInfo[noOfParams]; - - for (int i = 0; i < noOfParams; i++) - { - MBeanParameterInfo paramInfo = null; - String type = paramTypes[i].getName(); - for (Annotation anno : paramsAnno[i]) - { - String name,desc; - if (MBeanOperationParameter.class.isInstance(anno)) - { - name = MBeanOperationParameter.class.cast(anno).name(); - desc = MBeanOperationParameter.class.cast(anno).description(); - paramInfo = new MBeanParameterInfo(name, type, desc); - } - } - - - if (paramInfo == null) - { - paramInfo = new MBeanParameterInfo("p " + (i + 1), type, "parameter " + (i + 1)); - } - if (paramInfo != null) - { - paramsInfo[i] = paramInfo; - } - } - - return paramsInfo; - } - - /** - * Introspects the MBean class for constructors - * @param implClass - * @return MBeanConstructorInfo[] - */ - static MBeanConstructorInfo[] getMBeanConstructorsInfo(Class implClass) - { - List<MBeanConstructorInfo> constructors = new ArrayList<MBeanConstructorInfo>(); - - for (Constructor cons : implClass.getConstructors()) - { - MBeanConstructorInfo constructorInfo = getMBeanConstructorInfo(cons); - if (constructorInfo != null) - { - constructors.add(constructorInfo); - } - } - - return constructors.toArray(new MBeanConstructorInfo[0]); - } - - /** - * Retrieves the constructor info from given constructor. - * @param cons - * @return MBeanConstructorInfo - */ - private static MBeanConstructorInfo getMBeanConstructorInfo(Constructor cons) - { - String desc = _defaultConstructorDescription; - Annotation anno = cons.getAnnotation(MBeanConstructor.class); - if (anno != null && MBeanConstructor.class.isInstance(anno)) - { - desc = MBeanConstructor.class.cast(anno).value(); - if(desc == null) - { - desc = _defaultConstructorDescription; - } - } - - return new MBeanConstructorInfo(cons.getName(), desc, null); - } - - /** - * Retrieves the description from the annotations of given class - * @param annotatedClass - * @return class description - */ - static String getMBeanDescription(Class annotatedClass) - { - Annotation anno = annotatedClass.getAnnotation(MBeanDescription.class); - if (anno != null && MBeanDescription.class.isInstance(anno)) - { - return MBeanDescription.class.cast(anno).value(); - } - return _defaultMbeanDescription; - } - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanInvocationHandlerImpl.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanInvocationHandlerImpl.java deleted file mode 100644 index 5fe4ac4d24..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanInvocationHandlerImpl.java +++ /dev/null @@ -1,349 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.Arrays; - -import javax.management.Attribute; -import javax.management.JMException; -import javax.management.MBeanInfo; -import javax.management.MBeanOperationInfo; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import javax.management.RuntimeErrorException; -import javax.management.remote.MBeanServerForwarder; -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; - -/** - * This class can be used by the JMXConnectorServer as an InvocationHandler for the mbean operations. It delegates - * JMX access decisions to the SecurityPlugin. - */ -public class MBeanInvocationHandlerImpl implements InvocationHandler -{ - private static final Logger _logger = LoggerFactory.getLogger(MBeanInvocationHandlerImpl.class); - - private final static String DELEGATE = "JMImplementation:type=MBeanServerDelegate"; - private MBeanServer _mbs; - - private final boolean _managementRightsInferAllAccess; - private final Broker<?> _broker; - - MBeanInvocationHandlerImpl(Broker<?> broker) - { - _managementRightsInferAllAccess = Boolean.valueOf(System.getProperty(BrokerProperties.PROPERTY_MANAGEMENT_RIGHTS_INFER_ALL_ACCESS, "true")); - _broker = broker; - } - - public static MBeanServerForwarder newProxyInstance(Broker<?> broker) - { - final InvocationHandler handler = new MBeanInvocationHandlerImpl(broker); - final Class<?>[] interfaces = new Class[] { MBeanServerForwarder.class }; - - Object proxy = Proxy.newProxyInstance(MBeanServerForwarder.class.getClassLoader(), interfaces, handler); - return MBeanServerForwarder.class.cast(proxy); - } - - private boolean invokeDirectly(String methodName, Object[] args, Subject subject) - { - // Allow operations performed locally on behalf of the connector server itself - if (subject == null) - { - return true; - } - - if (args == null || DELEGATE.equals(args[0])) - { - return true; - } - - // Allow querying available object names and mbeans - if (methodName.equals("queryNames") || methodName.equals("queryMBeans")) - { - return true; - } - - if (args[0] instanceof ObjectName) - { - ObjectName mbean = (ObjectName) args[0]; - - if(!ManagedObject.DOMAIN.equalsIgnoreCase(mbean.getDomain())) - { - return true; - } - } - - return false; - } - - public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable - { - final String methodName = method.getName(); - - if (methodName.equals("getMBeanServer")) - { - return _mbs; - } - - if (methodName.equals("setMBeanServer")) - { - if (args[0] == null) - { - throw new IllegalArgumentException("Null MBeanServer"); - } - if (_mbs != null) - { - throw new IllegalArgumentException("MBeanServer object already initialized"); - } - _mbs = (MBeanServer) args[0]; - return null; - } - - // Restrict access to "createMBean" and "unregisterMBean" to any user - if (methodName.equals("createMBean") || methodName.equals("unregisterMBean")) - { - _logger.debug("User trying to create or unregister an MBean"); - throw new SecurityException("Access denied: " + methodName); - } - - // Retrieve Subject from current AccessControlContext - AccessControlContext acc = AccessController.getContext(); - Subject subject = Subject.getSubject(acc); - - try - { - if(invokeDirectly(methodName, args, subject)) - { - return method.invoke(_mbs, args); - } - - try - { - AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); - } - catch(Exception e) - { - throw new SecurityException("Access denied: no authenticated principal", e); - } - - return authoriseAndInvoke(method, args); - } - catch (InvocationTargetException e) - { - Throwable targetException = e.getCause(); - logTargetException(method, args, targetException); - throw targetException; - } - } - - private void logTargetException(Method method, Object[] args, Throwable targetException) - { - Throwable error = null; - if (targetException instanceof RuntimeErrorException) - { - error = ((RuntimeErrorException)targetException).getCause(); - } - else if (targetException instanceof Error) - { - error = targetException; - } - if (error == null) - { - _logger.debug("Exception was thrown on invoking of " + method + " with arguments " + Arrays.toString(args), targetException); - } - else - { - _logger.error("Unexpected error occurred on invoking of " + method + " with arguments " + Arrays.toString(args), targetException); - } - } - - private Object authoriseAndInvoke(final Method method, final Object[] args) throws Exception - { - String methodName; - // Get the component, type and impact, which may be null - String type = getType(method, args); - String virtualHostName = getVirtualHost(method, args); - int impact = getImpact(method, args); - - if (virtualHostName != null) - { - VirtualHost<?,?,?> virtualHost = _broker.findVirtualHostByName(virtualHostName); - if (virtualHost == null) - { - throw new IllegalArgumentException("Virtual host with name '" + virtualHostName + "' is not found."); - } - } - - methodName = getMethodName(method, args); - Operation operation = (isAccessMethod(methodName) || impact == MBeanOperationInfo.INFO) ? Operation.ACCESS : Operation.UPDATE; - - SecurityManager security = _broker.getSecurityManager(); - security.authoriseMethod(operation, type, methodName, virtualHostName); - - if (_managementRightsInferAllAccess) - { - try - { - return Subject.doAs(SecurityManager.getSubjectWithAddedSystemRights(), new PrivilegedExceptionAction<Object>() - { - @Override - public Object run() throws IllegalAccessException, InvocationTargetException - { - return method.invoke(_mbs, args); - } - }); - } - catch (PrivilegedActionException e) - { - throw (Exception) e.getCause(); - } - } - else - { - return method.invoke(_mbs, args); - } - - } - - private String getType(Method method, Object[] args) - { - if (args[0] instanceof ObjectName) - { - ObjectName object = (ObjectName) args[0]; - String type = object.getKeyProperty("type"); - - return type; - } - return null; - } - - private String getVirtualHost(Method method, Object[] args) - { - if (args[0] instanceof ObjectName) - { - ObjectName object = (ObjectName) args[0]; - String vhost = object.getKeyProperty("VirtualHost"); - - if(vhost != null) - { - try - { - //if the name is quoted in the ObjectName, unquote it - vhost = ObjectName.unquote(vhost); - } - catch(IllegalArgumentException e) - { - //ignore, this just means the name is not quoted - //and can be left unchanged - } - } - - return vhost; - } - return null; - } - - private String getMethodName(Method method, Object[] args) - { - String methodName = method.getName(); - - // if arguments are set, try and work out real method name - if (args != null && args.length >= 1 && args[0] instanceof ObjectName) - { - if (methodName.equals("getAttribute")) - { - methodName = "get" + (String) args[1]; - } - else if (methodName.equals("setAttribute")) - { - methodName = "set" + ((Attribute) args[1]).getName(); - } - else if (methodName.equals("invoke")) - { - methodName = (String) args[1]; - } - } - - return methodName; - } - - private int getImpact(Method method, Object[] args) - { - //handle invocation of other methods on mbeans - if ((args[0] instanceof ObjectName) && (method.getName().equals("invoke"))) - { - //get invoked method name - String mbeanMethod = (args.length > 1) ? (String) args[1] : null; - if (mbeanMethod == null) - { - return -1; - } - - try - { - //Get the impact attribute - MBeanInfo mbeanInfo = _mbs.getMBeanInfo((ObjectName) args[0]); - if (mbeanInfo != null) - { - MBeanOperationInfo[] opInfos = mbeanInfo.getOperations(); - for (MBeanOperationInfo opInfo : opInfos) - { - if (opInfo.getName().equals(mbeanMethod)) - { - return opInfo.getImpact(); - } - } - } - } - catch (JMException ex) - { - _logger.error("Unable to determine mbean impact for method : " + mbeanMethod, ex); - } - } - - return -1; - } - - private boolean isAccessMethod(String methodName) - { - //handle standard get/query/is methods from MBeanServer - return (methodName.startsWith("query") || methodName.startsWith("get") || methodName.startsWith("is")); - } - -} - diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanProvider.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanProvider.java deleted file mode 100644 index 16ecde5ad4..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanProvider.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.jmx; - -import javax.management.JMException; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.plugin.Pluggable; -import org.apache.qpid.server.plugin.QpidServiceLoader; - -/** - * A provider of an mbean implementation. - * - * Provider implementations are advertised as services and loaded by a {@link QpidServiceLoader}. - */ -public interface MBeanProvider extends Pluggable -{ - - /** - * Tests whether a <code>child</code> can be managed by the mbean - * provided by this provider. - */ - boolean isChildManageableByMBean(ConfiguredObject<?> child); - - /** - * Creates a mbean for this child. This method should only be called if - * {@link #isChildManageableByMBean(ConfiguredObject)} has previously returned true. - * @param registry managed object registry - * - * @return newly created mbean - */ - ManagedObject createMBean(ConfiguredObject<?> child, ManagedObjectRegistry registry) throws JMException; - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagedObject.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagedObject.java deleted file mode 100644 index 40b778fd93..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagedObject.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import javax.management.JMException; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; - -/** - * This should be implemented by all Managable objects. - */ -public interface ManagedObject -{ - static final String DOMAIN = "org.apache.qpid"; - - /** - * @return the name that uniquely identifies this object instance. It must be - * unique only among objects of this type at this level in the hierarchy so - * the uniqueness should not be too difficult to ensure. - */ - String getObjectInstanceName(); - - String getType(); - - Class<?> getManagementInterface(); - - ManagedObject getParentObject(); - - void register() throws JMException; - - void unregister() throws JMException; - - /** - * Returns the ObjectName required for the mbeanserver registration. - * @return ObjectName - * @throws javax.management.MalformedObjectNameException - */ - ObjectName getObjectName() throws MalformedObjectNameException; -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagedObjectRegistry.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagedObjectRegistry.java deleted file mode 100644 index ce4236661d..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagedObjectRegistry.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import java.io.IOException; - -import javax.management.JMException; - -/** - * Handles the registration (and unregistration and so on) of managed objects. - * - * Managed objects are responsible for exporting attributes, operations and notifications. They will expose - * these outside the JVM therefore it is important not to use implementation objects directly as managed objects. - * Instead, creating inner classes and exposing those is an effective way of exposing internal state in a - * controlled way. - * - * Although we do not explicitly use them while targeting Java 5, the enhanced MXBean approach in Java 6 will - * be the obvious choice for managed objects. - * - */ -public interface ManagedObjectRegistry -{ - void start() throws IOException; - - void registerObject(ManagedObject managedObject) throws JMException; - - void unregisterObject(ManagedObject managedObject) throws JMException; - - void close(); -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporter.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporter.java deleted file mode 100644 index f437b510ee..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporter.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import static javax.management.remote.JMXConnectionNotification.CLOSED; -import static javax.management.remote.JMXConnectionNotification.FAILED; -import static javax.management.remote.JMXConnectionNotification.OPENED; - -import java.rmi.server.RemoteServer; -import java.rmi.server.ServerNotActiveException; -import java.security.PrivilegedAction; - -import javax.management.Notification; -import javax.management.NotificationFilter; -import javax.management.NotificationListener; -import javax.management.remote.JMXConnectionNotification; -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.security.auth.jmx.JMXConnectionPrincipal; - -public class ManagementLogonLogoffReporter implements NotificationListener, NotificationFilter -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ManagementLogonLogoffReporter.class); - private final EventLoggerProvider _eventLoggerProvider; - private final UsernameAccessor _usernameAccessor; - - public ManagementLogonLogoffReporter(EventLoggerProvider eventLoggerProvider, UsernameAccessor usernameAccessor) - { - _eventLoggerProvider = eventLoggerProvider; - _usernameAccessor = usernameAccessor; - } - - @Override - public void handleNotification(final Notification notification, final Object handback) - { - final String connectionId = ((JMXConnectionNotification) notification).getConnectionId(); - final String type = notification.getType(); - - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("Notification connectionId : " + connectionId + " type : " + type); - } - - Subject subject = _usernameAccessor.getSubjectConnectionId(connectionId); - if(subject == null) - { - subject = new Subject(); - } - AuthenticatedPrincipal authenticatedPrincipal = - AuthenticatedPrincipal.getOptionalAuthenticatedPrincipalFromSubject(subject); - - String user; - - if(authenticatedPrincipal != null) - { - user = authenticatedPrincipal.getName(); - } - else - { - // If user is still null, fallback to an unordered list of Principals from the connection id. - final String[] splitConnectionId = connectionId.split(" "); - user = splitConnectionId[1]; - } - - - if(subject.getPrincipals(JMXConnectionPrincipal.class).isEmpty()) - { - try - { - String clientHost = RemoteServer.getClientHost(); - subject = new Subject(false, - subject.getPrincipals(), - subject.getPublicCredentials(), - subject.getPrivateCredentials()); - subject.getPrincipals().add(new JMXConnectionPrincipal(clientHost)); - subject.setReadOnly(); - } - catch(ServerNotActiveException e) - { - } - } - - final String username = user; - Subject.doAs(subject, new PrivilegedAction<Object>() - { - @Override - public Object run() - { - if (JMXConnectionNotification.OPENED.equals(type)) - { - getEventLogger().message(ManagementConsoleMessages.OPEN(username)); - } - else if (JMXConnectionNotification.CLOSED.equals(type) || - JMXConnectionNotification.FAILED.equals(type)) - { - getEventLogger().message(ManagementConsoleMessages.CLOSE(username)); - } - return null; - } - }); - } - - @Override - public boolean isNotificationEnabled(Notification notification) - { - return notification instanceof JMXConnectionNotification && isLogonTypeEvent(notification); - } - - private boolean isLogonTypeEvent(Notification notification) - { - final String type = notification.getType(); - return CLOSED.equals(type) || FAILED.equals(type) || OPENED.equals(type); - } - - public EventLogger getEventLogger() - { - return _eventLoggerProvider.getEventLogger(); - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/QpidRMIServerSocketFactory.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/QpidRMIServerSocketFactory.java deleted file mode 100644 index 29d6fb8df8..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/QpidRMIServerSocketFactory.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.jmx; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.rmi.server.RMIServerSocketFactory; - -class QpidRMIServerSocketFactory implements RMIServerSocketFactory -{ - @Override - public ServerSocket createServerSocket(final int port) throws IOException - { - ServerSocket serverSocket = new ServerSocket(); - serverSocket.setReuseAddress(true); - serverSocket.bind(new InetSocketAddress(port)); - return serverSocket; - } - - @Override - public int hashCode() - { - final int prime = 37; - return prime * QpidRMIServerSocketFactory.class.getName().hashCode(); - } - - @Override - public boolean equals(final Object obj) - { - return obj != null && getClass() == obj.getClass(); - } -}
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/QpidSslRMIServerSocketFactory.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/QpidSslRMIServerSocketFactory.java deleted file mode 100644 index 8af9d87672..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/QpidSslRMIServerSocketFactory.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.Collection; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import javax.rmi.ssl.SslRMIServerSocketFactory; - -import org.apache.qpid.transport.network.security.ssl.SSLUtil; - -public class QpidSslRMIServerSocketFactory extends SslRMIServerSocketFactory -{ - private final SSLContext _sslContext; - private final Collection<String> _enabledCipherSuites; - private final Collection<String> _disabledCipherSuites; - - /** - * SslRMIServerSocketFactory which creates the ServerSocket using the - * supplied SSLContext rather than the system default context normally - * used by the superclass, allowing us to use a configuration-specified - * key store. - * - * @param sslContext previously created sslContext using the desired key store. - * @param enabledCipherSuites - *@param disabledCipherSuites @throws NullPointerException if the provided {@link SSLContext} is null. - */ - public QpidSslRMIServerSocketFactory(SSLContext sslContext, - final Collection<String> enabledCipherSuites, - final Collection<String> disabledCipherSuites) throws NullPointerException - { - super(); - - if(sslContext == null) - { - throw new NullPointerException("The provided SSLContext must not be null"); - } - - _sslContext = sslContext; - _enabledCipherSuites = enabledCipherSuites; - _disabledCipherSuites = disabledCipherSuites; - - //TODO: settings + implementation for SSL client auth, updating equals and hashCode appropriately. - } - - @Override - public ServerSocket createServerSocket(int port) throws IOException - { - final SSLSocketFactory factory = _sslContext.getSocketFactory(); - - ServerSocket serverSocket = new ServerSocket() - { - public Socket accept() throws IOException - { - Socket socket = super.accept(); - - SSLSocket sslSocket = - (SSLSocket) factory.createSocket(socket, - socket.getInetAddress().getHostName(), - socket.getPort(), - true); - sslSocket.setUseClientMode(false); - SSLUtil.removeSSLv3Support(sslSocket); - SSLUtil.updateEnabledCipherSuites(sslSocket, _enabledCipherSuites, _disabledCipherSuites); - return sslSocket; - } - }; - serverSocket.setReuseAddress(true); - serverSocket.bind(new InetSocketAddress(port)); - return serverSocket; - } - - /** - * One QpidSslRMIServerSocketFactory is equal to - * another if their (non-null) SSLContext are equal. - */ - @Override - public boolean equals(Object object) - { - if (!(object instanceof QpidSslRMIServerSocketFactory)) - { - return false; - } - - QpidSslRMIServerSocketFactory that = (QpidSslRMIServerSocketFactory) object; - - return _sslContext.equals(that._sslContext); - } - - @Override - public int hashCode() - { - return _sslContext.hashCode(); - } - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/RegistryProtectingRMIServerSocketFactory.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/RegistryProtectingRMIServerSocketFactory.java deleted file mode 100644 index 11fc4ecdf0..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/RegistryProtectingRMIServerSocketFactory.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.rmi.server.RMIServerSocketFactory; - -/** - * A custom RMIServerSocketFactory class, used to prevent updates to the RMI registry. - * Supplied to the registry at creation, this will prevent RMI-based operations on the - * registry such as attempting to bind a new object, thereby securing it from tampering. - * This is accomplished by always returning null when attempting to determine the address - * of the caller, thus ensuring the registry will refuse the attempt. Calls to bind etc - * made using the object reference will not be affected and continue to operate normally. - */ -class RegistryProtectingRMIServerSocketFactory implements RMIServerSocketFactory -{ - @Override - public ServerSocket createServerSocket(int port) throws IOException - { - NoLocalAddressServerSocket serverSocket = new NoLocalAddressServerSocket(); - serverSocket.setReuseAddress(true); - serverSocket.bind(new InetSocketAddress(port)); - return serverSocket; - } - - @Override - public int hashCode() - { - final int prime = 31; - return prime * RegistryProtectingRMIServerSocketFactory.class.getName().hashCode(); - } - - @Override - public boolean equals(final Object obj) - { - return obj != null && getClass() == obj.getClass(); - } - - private static class NoLocalAddressServerSocket extends ServerSocket - { - NoLocalAddressServerSocket() throws IOException - { - super(); - } - - @Override - public Socket accept() throws IOException - { - Socket s = new NoLocalAddressSocket(); - super.implAccept(s); - return s; - } - } - - private static class NoLocalAddressSocket extends Socket - { - @Override - public InetAddress getInetAddress() - { - return null; - } - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameAccessor.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameAccessor.java deleted file mode 100644 index 18ab02ece1..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameAccessor.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import javax.security.auth.Subject; - -public interface UsernameAccessor -{ - public Subject getSubjectConnectionId(String connectionId); - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameCachingRMIJRMPServer.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameCachingRMIJRMPServer.java deleted file mode 100644 index 4caa14014a..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameCachingRMIJRMPServer.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import static javax.management.remote.JMXConnectionNotification.CLOSED; -import static javax.management.remote.JMXConnectionNotification.FAILED; - -import java.io.IOException; -import java.rmi.server.RMIClientSocketFactory; -import java.rmi.server.RMIServerSocketFactory; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.management.Notification; -import javax.management.NotificationFilter; -import javax.management.NotificationListener; -import javax.management.remote.JMXConnectionNotification; -import javax.management.remote.JMXConnectorServer; -import javax.management.remote.rmi.RMIConnection; -import javax.management.remote.rmi.RMIJRMPServerImpl; -import javax.security.auth.Subject; - -/** - * An implementation of RMIJRMPServerImpl that caches the usernames of users as they log-on - * and makes the same available via {@link UsernameAccessor#getSubjectConnectionId(String)}. - * - * Caller is responsible for installing this object as a {@link NotificationListener} of the - * {@link JMXConnectorServer} so the cache entries are removed as the clients disconnect. - * - */ -public class UsernameCachingRMIJRMPServer extends RMIJRMPServerImpl implements NotificationListener, NotificationFilter, UsernameAccessor -{ - // ConnectionId is guaranteed to be unique per client connection, according to the JMX spec. - private final Map<String, Subject> _connectionIdUsernameMap = new ConcurrentHashMap<String, Subject>(); - - UsernameCachingRMIJRMPServer(int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf, - Map<String, ?> env) throws IOException - { - super(port, csf, ssf, env); - } - - @Override - protected RMIConnection makeClient(String connectionId, Subject subject) throws IOException - { - final RMIConnection makeClient = super.makeClient(connectionId, subject); - _connectionIdUsernameMap.put(connectionId, subject); - return makeClient; - } - - @Override - public Subject getSubjectConnectionId(String connectionId) - { - return _connectionIdUsernameMap.get(connectionId); - } - - @Override - public void handleNotification(Notification notification, Object handback) - { - final String connectionId = ((JMXConnectionNotification) notification).getConnectionId(); - removeConnectionIdFromCache(connectionId); - } - - @Override - public boolean isNotificationEnabled(Notification notification) - { - return isClientDisconnectEvent(notification); - } - - private void removeConnectionIdFromCache(String connectionId) - { - _connectionIdUsernameMap.remove(connectionId); - } - - private boolean isClientDisconnectEvent(Notification notification) - { - final String type = notification.getType(); - return CLOSED.equals(type) || FAILED.equals(type); - } - -}
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/AbstractStatisticsGatheringMBean.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/AbstractStatisticsGatheringMBean.java deleted file mode 100644 index 6223d9d906..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/AbstractStatisticsGatheringMBean.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx.mbeans; - -import javax.management.NotCompliantMBeanException; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Connection; -import org.apache.qpid.server.jmx.AMQManagedObject; -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.model.VirtualHost; - -abstract class AbstractStatisticsGatheringMBean<T extends ConfiguredObject> extends AMQManagedObject -{ - private long _lastStatUpdateTime; - private long _statUpdatePeriod = 5000L; - private long _lastMessagesReceived; - private long _lastMessagesSent; - private long _lastBytesReceived; - private long _lastBytesSent; - private double _messageReceivedRate; - private double _messageSentRate; - private double _bytesReceivedRate; - private double _bytesSentRate; - private double _peakMessageReceivedRate; - private double _peakMessageSentRate; - private double _peakBytesReceivedRate; - private double _peakBytesSentRate; - private final T _configuredObject; - - protected AbstractStatisticsGatheringMBean(Class<?> managementInterface, - String typeName, - ManagedObjectRegistry registry, - T object) throws NotCompliantMBeanException - { - super(managementInterface, typeName, registry); - _configuredObject = object; - initStats(); - } - - protected void initStats() - { - _lastStatUpdateTime = System.currentTimeMillis(); - } - - protected synchronized void updateStats() - { - long time = System.currentTimeMillis(); - final long period = time - _lastStatUpdateTime; - if(period > _statUpdatePeriod) - { - long messagesReceived = getMessagesIn(); - long messagesSent = getMessagesOut(); - long bytesReceived = getBytesIn(); - long bytesSent = getBytesOut(); - - double messageReceivedRate = (double)(messagesReceived - _lastMessagesReceived) / (double)period; - double messageSentRate = (double)(messagesSent - _lastMessagesSent) / (double)period; - double bytesReceivedRate = (double)(bytesReceived - _lastBytesReceived) / (double)period; - double bytesSentRate = (double)(bytesSent - _lastBytesSent) / (double)period; - - _lastMessagesReceived = messagesReceived; - _lastMessagesSent = messagesSent; - _lastBytesReceived = bytesReceived; - _lastBytesSent = bytesSent; - - _messageReceivedRate = messageReceivedRate; - _messageSentRate = messageSentRate; - _bytesReceivedRate = bytesReceivedRate; - _bytesSentRate = bytesSentRate; - - if(messageReceivedRate > _peakMessageReceivedRate) - { - _peakMessageReceivedRate = messageReceivedRate; - } - - if(messageSentRate > _peakMessageSentRate) - { - _peakMessageSentRate = messageSentRate; - } - - if(bytesReceivedRate > _peakBytesReceivedRate) - { - _peakBytesReceivedRate = bytesReceivedRate; - } - - if(bytesSentRate > _peakBytesSentRate) - { - _peakBytesSentRate = bytesSentRate; - } - - } - } - - protected abstract long getBytesOut(); - - protected abstract long getBytesIn(); - - protected abstract long getMessagesOut(); - - protected abstract long getMessagesIn(); - - public synchronized void resetStatistics() throws Exception - { - updateStats(); - //TODO - implement resetStatistics() - } - - public synchronized double getPeakMessageDeliveryRate() - { - updateStats(); - return _peakMessageSentRate; - } - - public synchronized double getPeakDataDeliveryRate() - { - updateStats(); - return _peakBytesSentRate; - } - - public synchronized double getMessageDeliveryRate() - { - updateStats(); - return _messageSentRate; - } - - public synchronized double getDataDeliveryRate() - { - updateStats(); - return _bytesSentRate; - } - - public synchronized long getTotalMessagesDelivered() - { - updateStats(); - return getMessagesOut(); - } - - public synchronized long getTotalDataDelivered() - { - updateStats(); - return getBytesOut(); - } - - protected final T getConfiguredObject() - { - return _configuredObject; - } - - public synchronized double getPeakMessageReceiptRate() - { - updateStats(); - return _peakMessageReceivedRate; - } - - public synchronized double getPeakDataReceiptRate() - { - updateStats(); - return _peakBytesReceivedRate; - } - - public synchronized double getMessageReceiptRate() - { - updateStats(); - return _messageReceivedRate; - } - - public synchronized double getDataReceiptRate() - { - updateStats(); - return _bytesReceivedRate; - } - - public synchronized long getTotalMessagesReceived() - { - updateStats(); - return getMessagesIn(); - } - - public synchronized long getTotalDataReceived() - { - updateStats(); - return getBytesIn(); - } - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ConnectionMBean.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ConnectionMBean.java deleted file mode 100644 index 0787e404fa..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ConnectionMBean.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.jmx.mbeans; - -import java.io.IOException; -import java.util.Collection; -import java.util.Date; -import javax.management.JMException; -import javax.management.ObjectName; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.SimpleType; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.TabularType; - -import org.apache.qpid.management.common.mbeans.ManagedConnection; -import org.apache.qpid.server.jmx.ManagedObject; -import org.apache.qpid.server.model.Connection; -import org.apache.qpid.server.model.Session; -import org.apache.qpid.server.util.ServerScopedRuntimeException; - -public class ConnectionMBean extends AbstractStatisticsGatheringMBean<Connection> implements ManagedConnection -{ - private static final OpenType[] CHANNEL_ATTRIBUTE_TYPES = - { SimpleType.INTEGER, SimpleType.BOOLEAN, SimpleType.STRING, SimpleType.INTEGER, SimpleType.BOOLEAN }; - private static final CompositeType CHANNEL_TYPE; - private static final TabularType CHANNELS_TYPE; - - static - { - try - { - CHANNEL_TYPE = new CompositeType("Channel", "Channel Details", COMPOSITE_ITEM_NAMES_DESC.toArray(new String[COMPOSITE_ITEM_NAMES_DESC.size()]), - COMPOSITE_ITEM_NAMES_DESC.toArray(new String[COMPOSITE_ITEM_NAMES_DESC.size()]), - CHANNEL_ATTRIBUTE_TYPES); - CHANNELS_TYPE = new TabularType("Channels", "Channels", CHANNEL_TYPE, (String[]) TABULAR_UNIQUE_INDEX.toArray(new String[TABULAR_UNIQUE_INDEX.size()])); - } - catch (JMException ex) - { - // This is not expected to ever occur. - throw new ServerScopedRuntimeException("Got JMException in static initializer.", ex); - } - } - - - private final VirtualHostMBean _virtualHostMBean; - - public ConnectionMBean(Connection conn, VirtualHostMBean virtualHostMBean) throws JMException - { - super(ManagedConnection.class, ManagedConnection.TYPE, virtualHostMBean.getRegistry(), conn); - _virtualHostMBean = virtualHostMBean; - register(); - } - - @Override - protected long getBytesOut() - { - return getConfiguredObject().getBytesOut(); - } - - @Override - protected long getBytesIn() - { - return getConfiguredObject().getBytesIn(); - } - - @Override - protected long getMessagesOut() - { - return getConfiguredObject().getMessagesOut(); - } - - @Override - protected long getMessagesIn() - { - return getConfiguredObject().getMessagesIn(); - } - - public String getObjectInstanceName() - { - return ObjectName.quote(getConfiguredObject().getName()); - } - - @Override - public ManagedObject getParentObject() - { - return _virtualHostMBean; - } - - public String getClientId() - { - return (String) getConfiguredObject().getAttribute(Connection.CLIENT_ID); - } - - public String getAuthorizedId() - { - return (String) getConfiguredObject().getAttribute(Connection.PRINCIPAL); - } - - public String getVersion() - { - return (String) getConfiguredObject().getAttribute(Connection.CLIENT_VERSION); - } - - public String getRemoteAddress() - { - return (String) getConfiguredObject().getAttribute(Connection.REMOTE_ADDRESS); - } - - public Date getLastIoTime() - { - return new Date(getConfiguredObject().getLastIoTime()); - } - - public Long getMaximumNumberOfChannels() - { - return (Long) getConfiguredObject().getAttribute(Connection.SESSION_COUNT_LIMIT); - } - - public TabularData channels() throws IOException, JMException - { - TabularDataSupport sessionTable = new TabularDataSupport(CHANNELS_TYPE); - Collection<Session> list = getConfiguredObject().getSessions(); - - for (Session session : list) - { - - Long txnBegins = session.getLocalTransactionBegins(); - Integer channelId = (Integer) session.getAttribute(Session.CHANNEL_ID); - int unacknowledgedSize = (int) session.getUnacknowledgedMessages(); - boolean blocked = (Boolean) session.getAttribute(Session.PRODUCER_FLOW_BLOCKED); - boolean isTransactional = (txnBegins>0l); - - Object[] itemValues = - { - channelId, - isTransactional, - null, // TODO - default queue (which is meaningless) - unacknowledgedSize, - blocked - }; - - CompositeData sessionData = new CompositeDataSupport(CHANNEL_TYPE, - COMPOSITE_ITEM_NAMES_DESC.toArray(new String[COMPOSITE_ITEM_NAMES_DESC.size()]), itemValues); - sessionTable.put(sessionData); - } - - return sessionTable; - } - - public void commitTransactions(int channelId) throws JMException - { - throw buildUnsupportedException(); - } - - public void rollbackTransactions(int channelId) throws JMException - { - throw buildUnsupportedException(); - } - - public void closeConnection() throws Exception - { - getConfiguredObject().delete(); - } - - public boolean isStatisticsEnabled() - { - return true; - } - - public void setStatisticsEnabled(boolean enabled) - { - updateStats(); - } - - private JMException buildUnsupportedException() throws JMException - { - String msg = "Operation not supported"; - JMException jmException = new JMException(msg); - jmException.initCause(new UnsupportedOperationException(msg)); - return jmException; - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ExchangeMBean.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ExchangeMBean.java deleted file mode 100644 index 982b771a32..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ExchangeMBean.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.jmx.mbeans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.management.JMException; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import javax.management.OperationsException; -import javax.management.openmbean.ArrayType; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.SimpleType; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.TabularType; - -import org.apache.qpid.management.common.mbeans.ManagedExchange; -import org.apache.qpid.server.jmx.AMQManagedObject; -import org.apache.qpid.server.jmx.ManagedObject; -import org.apache.qpid.server.model.Binding; -import org.apache.qpid.server.model.Exchange; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.util.ServerScopedRuntimeException; - -public class ExchangeMBean extends AMQManagedObject implements ManagedExchange -{ - - public static final String FANOUT_EXCHANGE_TYPE = "fanout"; - public static final String HEADERS_EXCHANGE_TYPE = "headers"; - - private static final String[] TABULAR_UNIQUE_INDEX_ARRAY = - TABULAR_UNIQUE_INDEX.toArray(new String[TABULAR_UNIQUE_INDEX.size()]); - - private static final String[] COMPOSITE_ITEM_NAMES_ARRAY = - COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]); - - private static final String[] COMPOSITE_ITEM_DESCRIPTIONS_ARRAY = - COMPOSITE_ITEM_DESCRIPTIONS.toArray(new String[COMPOSITE_ITEM_DESCRIPTIONS.size()]); - - private static final OpenType[] BINDING_ITEM_TYPES; - private static final CompositeType BINDING_DATA_TYPE; - private static final OpenType[] HEADERS_BINDING_ITEM_TYPES; - - - private static final CompositeType HEADERS_BINDING_DATA_TYPE; - - private static final String[] HEADERS_COMPOSITE_ITEM_NAMES_ARRAY = - HEADERS_COMPOSITE_ITEM_NAMES.toArray(new String[HEADERS_COMPOSITE_ITEM_NAMES.size()]); - - private static final String[] HEADERS_COMPOSITE_ITEM_DESCS_ARRAY = - HEADERS_COMPOSITE_ITEM_DESC.toArray(new String[HEADERS_COMPOSITE_ITEM_DESC.size()]); - private static final String[] HEADERS_TABULAR_UNIQUE_INDEX_ARRAY = - HEADERS_TABULAR_UNIQUE_INDEX.toArray(new String[HEADERS_TABULAR_UNIQUE_INDEX.size()]); - - static - { - try - { - BINDING_ITEM_TYPES = new OpenType[] {SimpleType.STRING, new ArrayType(1, SimpleType.STRING)}; - - BINDING_DATA_TYPE= new CompositeType("Exchange Binding", "Binding key and Queue names", - COMPOSITE_ITEM_NAMES_ARRAY, - COMPOSITE_ITEM_DESCRIPTIONS_ARRAY, - BINDING_ITEM_TYPES); - - HEADERS_BINDING_ITEM_TYPES = new OpenType[] {SimpleType.INTEGER, - SimpleType.STRING, - new ArrayType(1, SimpleType.STRING)}; - - HEADERS_BINDING_DATA_TYPE = new CompositeType("Exchange Binding", "Queue name and header bindings", - HEADERS_COMPOSITE_ITEM_NAMES_ARRAY, - HEADERS_COMPOSITE_ITEM_DESCS_ARRAY, - HEADERS_BINDING_ITEM_TYPES); - - - } - catch(OpenDataException e) - { - throw new ServerScopedRuntimeException("Unexpected Error creating ArrayType", e); - } - } - - - private final Exchange<?> _exchange; - private final VirtualHostMBean _vhostMBean; - - protected ExchangeMBean(Exchange exchange, VirtualHostMBean virtualHostMBean) - throws JMException - { - super(ManagedExchange.class, ManagedExchange.TYPE, virtualHostMBean.getRegistry()); - _exchange = exchange; - _vhostMBean = virtualHostMBean; - - register(); - } - - public String getObjectInstanceName() - { - return ObjectName.quote(getName()); - } - - @Override - public ManagedObject getParentObject() - { - return _vhostMBean; - } - - public ObjectName getObjectName() throws MalformedObjectNameException - { - String objNameString = super.getObjectName().toString(); - objNameString = objNameString + ",ExchangeType=" + getExchangeType(); - return new ObjectName(objNameString); - } - - - public String getName() - { - return _exchange.getName(); - } - - public String getExchangeType() - { - return _exchange.getType(); - } - - public Integer getTicketNo() - { - return 0; - } - - public boolean isDurable() - { - return _exchange.isDurable(); - } - - public boolean isAutoDelete() - { - return _exchange.getLifetimePolicy() != LifetimePolicy.PERMANENT; - } - - public TabularData bindings() throws IOException, JMException - { - if(HEADERS_EXCHANGE_TYPE.equals(_exchange.getType())) - { - return getHeadersBindings(_exchange.getBindings()); - } - else - { - return getNonHeadersBindings(_exchange.getBindings()); - } - } - - private TabularData getHeadersBindings(Collection<? extends Binding> bindings) throws OpenDataException - { - TabularType bindinglistDataType = - new TabularType("Exchange Bindings", "List of exchange bindings for " + getName(), - HEADERS_BINDING_DATA_TYPE, - HEADERS_TABULAR_UNIQUE_INDEX_ARRAY); - - TabularDataSupport bindingList = new TabularDataSupport(bindinglistDataType); - int count = 1; - for (Binding binding : bindings) - { - - String queueName = binding.getParent(Queue.class).getName(); - - - Map<String,Object> headerMappings = binding.getArguments(); - - final List<String> mappingList = new ArrayList<String>(); - - if(headerMappings != null) - { - for(Map.Entry<String,Object> entry : headerMappings.entrySet()) - { - - mappingList.add(entry.getKey() + "=" + entry.getValue()); - } - } - - - Object[] bindingItemValues = {count++, queueName, mappingList.toArray(new String[0])}; - CompositeData bindingData = new CompositeDataSupport(HEADERS_BINDING_DATA_TYPE, - HEADERS_COMPOSITE_ITEM_NAMES_ARRAY, - bindingItemValues); - bindingList.put(bindingData); - } - - return bindingList; - - } - - private TabularData getNonHeadersBindings(Collection<? extends Binding> bindings) throws OpenDataException - { - - TabularType bindinglistDataType = - new TabularType("Exchange Bindings", "Exchange Bindings for " + getName(), - BINDING_DATA_TYPE, - TABULAR_UNIQUE_INDEX_ARRAY); - - TabularDataSupport bindingList = new TabularDataSupport(bindinglistDataType); - - Map<String, List<String>> bindingMap = new HashMap<String, List<String>>(); - - for (Binding binding : bindings) - { - String key = FANOUT_EXCHANGE_TYPE.equals(_exchange.getType()) ? "*" : binding.getName(); - List<String> queueList = bindingMap.get(key); - if(queueList == null) - { - queueList = new ArrayList<String>(); - bindingMap.put(key, queueList); - } - queueList.add(binding.getParent(Queue.class).getName()); - - } - - for(Map.Entry<String, List<String>> entry : bindingMap.entrySet()) - { - Object[] bindingItemValues = {entry.getKey(), entry.getValue().toArray(new String[0])}; - CompositeData bindingData = new CompositeDataSupport(BINDING_DATA_TYPE, - COMPOSITE_ITEM_NAMES_ARRAY, - bindingItemValues); - bindingList.put(bindingData); - } - - return bindingList; - } - - public void createNewBinding(String queueName, String binding) throws JMException - { - final Map<String,Object> arguments = new HashMap<String, Object>(); - - createNewBinding(queueName, binding, arguments); - } - - @Override - public void createNewBinding(String queueName, String binding, Map<String, Object> arguments) throws JMException - { - if(HEADERS_EXCHANGE_TYPE.equals(_exchange.getType())) - { - arguments = new HashMap<String, Object>(arguments); - final String[] bindings = binding.split(","); - for (int i = 0; i < bindings.length; i++) - { - final String[] keyAndValue = bindings[i].split("="); - if (keyAndValue == null || keyAndValue.length == 0 || keyAndValue.length > 2 || keyAndValue[0].length() == 0) - { - throw new JMException("Format for headers binding should be \"<attribute1>=<value1>,<attribute2>=<value2>\""); - } - - if(keyAndValue.length == 1) - { - //no value was given, only a key. Use an empty value to signal match on key presence alone - arguments.put(keyAndValue[0], ""); - } - else - { - arguments.put(keyAndValue[0], keyAndValue[1]); - } - } - } - - VirtualHost<?,?,?> virtualHost = _exchange.getParent(VirtualHost.class); - Queue<?> queue = virtualHost.getChildByName(Queue.class, queueName); - if (queue == null) - { - throw new OperationsException("No such queue \""+ queueName +"\""); - } - _exchange.createBinding(binding, queue, arguments, Collections.EMPTY_MAP); - } - - public void removeBinding(String queueName, String bindingKey) - throws IOException, JMException - { - VirtualHost<?,?,?> virtualHost = _exchange.getParent(VirtualHost.class); - Queue<?> queue = virtualHost.getChildByName(Queue.class, queueName); - if (queue == null) - { - throw new OperationsException("No such queue \""+ queueName +"\""); - } - - boolean deleted = false; - for(Binding binding : _exchange.getBindings()) - { - if(queue.equals(binding.getParent(Queue.class)) && bindingKey.equals(binding.getName())) - { - binding.delete(); - deleted = true; - } - } - - if (!deleted) - { - throw new OperationsException("No such binding \"" + bindingKey + "\" on queue \"" + queueName + "\""); - } - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/LoggingManagementMBean.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/LoggingManagementMBean.java deleted file mode 100644 index b18da9ba32..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/LoggingManagementMBean.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.jmx.mbeans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.management.JMException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.SimpleType; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.TabularType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.management.common.mbeans.LoggingManagement; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; -import org.apache.qpid.server.jmx.AMQManagedObject; -import org.apache.qpid.server.jmx.ManagedObject; -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.logging.log4j.LoggingFacadeException; -import org.apache.qpid.server.logging.log4j.LoggingManagementFacade; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; - - -/** MBean class for LoggingManagement. It implements all the management features exposed for managing logging. */ -@MBeanDescription("Logging Management Interface") -public class LoggingManagementMBean extends AMQManagedObject implements LoggingManagement -{ - public static final String INHERITED_PSUEDO_LOG_LEVEL = "INHERITED"; - private static final Logger LOGGER = LoggerFactory.getLogger(LoggingManagementMBean.class); - private static final TabularType LOGGER_LEVEL_TABULAR_TYE; - private static final CompositeType LOGGER_LEVEL_COMPOSITE_TYPE; - - private final LoggingManagementFacade _loggingManagementFacade; - private final String[] _allAvailableLogLevels; - - static - { - try - { - OpenType[] loggerLevelItemTypes = new OpenType[]{SimpleType.STRING, SimpleType.STRING}; - - LOGGER_LEVEL_COMPOSITE_TYPE = new CompositeType("LoggerLevelList", "Logger Level Data", - COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]), - COMPOSITE_ITEM_DESCRIPTIONS.toArray(new String[COMPOSITE_ITEM_DESCRIPTIONS.size()]), - loggerLevelItemTypes); - - LOGGER_LEVEL_TABULAR_TYE = new TabularType("LoggerLevel", "List of loggers with levels", - LOGGER_LEVEL_COMPOSITE_TYPE, - TABULAR_UNIQUE_INDEX.toArray(new String[TABULAR_UNIQUE_INDEX.size()])); - } - catch (OpenDataException e) - { - throw new ExceptionInInitializerError(e); - } - } - - public LoggingManagementMBean(LoggingManagementFacade loggingManagementFacade, ManagedObjectRegistry registry) throws JMException - { - super(LoggingManagement.class, LoggingManagement.TYPE, registry); - register(); - _loggingManagementFacade = loggingManagementFacade; - _allAvailableLogLevels = buildAllAvailableLoggerLevelsWithInheritedPsuedoLogLevel(_loggingManagementFacade); - } - - @Override - public String getObjectInstanceName() - { - return LoggingManagement.TYPE; - } - - @Override - public ManagedObject getParentObject() - { - return null; - } - - @Override - public Integer getLog4jLogWatchInterval() - { - return _loggingManagementFacade.getLog4jLogWatchInterval(); - } - - @Override - public String[] getAvailableLoggerLevels() - { - return _allAvailableLogLevels; - } - - @Override - public TabularData viewEffectiveRuntimeLoggerLevels() - { - Map<String, String> levels = _loggingManagementFacade.retrieveRuntimeLoggersLevels(); - return createTabularDataFromLevelsMap(levels); - } - - @Override - public String getRuntimeRootLoggerLevel() - { - return _loggingManagementFacade.retrieveRuntimeRootLoggerLevel(); - } - - @Override - public boolean setRuntimeRootLoggerLevel(String level) - { - try - { - validateLevelNotAllowingInherited(level); - } - catch (IllegalArgumentException iae) - { - LOGGER.warn(level + " is not a known level"); - return false; - } - - _loggingManagementFacade.setRuntimeRootLoggerLevel(level); - return true; - } - - @Override - public boolean setRuntimeLoggerLevel(String logger, String level) - { - String validatedLevel; - try - { - validatedLevel = getValidateLevelAllowingInherited(level); - } - catch (IllegalArgumentException iae) - { - LOGGER.warn(level + " is not a known level"); - return false; - } - - try - { - _loggingManagementFacade.setRuntimeLoggerLevel(logger, validatedLevel); - } - catch (LoggingFacadeException e) - { - LOGGER.error("Cannot set runtime logging level", e); - return false; - } - return true; - } - - @Override - public TabularData viewConfigFileLoggerLevels() - { - Map<String,String> levels; - try - { - levels = _loggingManagementFacade.retrieveConfigFileLoggersLevels(); - } - catch (LoggingFacadeException e) - { - LOGGER.error("Cannot determine logging levels", e); - return null; - } - - return createTabularDataFromLevelsMap(levels); - } - - @Override - public String getConfigFileRootLoggerLevel()throws IOException - { - try - { - return _loggingManagementFacade.retrieveConfigFileRootLoggerLevel().toUpperCase(); - } - catch (LoggingFacadeException e) - { - LOGGER.warn("The log4j configuration get config request was aborted: ", e); - throw new IOException("The log4j configuration get config request was aborted: " + e.getMessage()); - } - } - - @Override - public boolean setConfigFileLoggerLevel(String logger, String level) - { - String validatedLevel; - try - { - validatedLevel = getValidateLevelAllowingInherited(level); - } - catch (IllegalArgumentException iae) - { - LOGGER.warn(level + " is not a known level"); - return false; - } - - try - { - _loggingManagementFacade.setConfigFileLoggerLevel(logger, validatedLevel); - } - catch (LoggingFacadeException e) - { - LOGGER.warn("The log4j configuration set config request was aborted: ", e); - return false; - } - return true; - } - - @Override - public boolean setConfigFileRootLoggerLevel(String level) - { - try - { - validateLevelNotAllowingInherited(level); - } - catch (IllegalArgumentException iae) - { - LOGGER.warn(level + " is not a known level"); - return false; - } - - try - { - _loggingManagementFacade.setConfigFileRootLoggerLevel(level); - return true; - } - catch (LoggingFacadeException e) - { - LOGGER.warn("The log4j configuration set config request was aborted: ", e); - return false; - } - } - - @Override - public void reloadConfigFile() throws IOException - { - try - { - - _loggingManagementFacade.reload(); - } - catch (LoggingFacadeException e) - { - LOGGER.warn("The log4j configuration reload request was aborted: ", e); - throw new IOException("The log4j configuration reload request was aborted: " + e.getMessage()); - } - } - - private String getValidateLevelAllowingInherited(String level) - { - if(level == null - || "null".equalsIgnoreCase(level) - || INHERITED_PSUEDO_LOG_LEVEL.equalsIgnoreCase(level)) - { - //the string "null" or "inherited" signals to inherit from a parent logger, - //using a null Level reference for the logger. - return null; - } - - validateLevelNotAllowingInherited(level); - return level; - } - - private void validateLevelNotAllowingInherited(String level) - { - final List<String> availableLoggerLevels = _loggingManagementFacade.getAvailableLoggerLevels(); - if (level == null || !availableLoggerLevels.contains(level.toUpperCase())) - { - throw new IllegalArgumentException(level + " not known"); - } - } - - private TabularData createTabularDataFromLevelsMap(Map<String, String> levels) - { - TabularData loggerLevelList = new TabularDataSupport(LOGGER_LEVEL_TABULAR_TYE); - for (Map.Entry<String,String> entry : levels.entrySet()) - { - String loggerName = entry.getKey(); - String level = entry.getValue(); - - CompositeData loggerData = createRow(loggerName, level); - loggerLevelList.put(loggerData); - } - return loggerLevelList; - } - - private CompositeData createRow(String loggerName, String level) - { - Object[] itemData = {loggerName, level.toUpperCase()}; - try - { - CompositeData loggerData = new CompositeDataSupport(LOGGER_LEVEL_COMPOSITE_TYPE, - COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]), itemData); - return loggerData; - } - catch (OpenDataException ode) - { - // Should not happen - throw new ConnectionScopedRuntimeException(ode); - } - } - - private String[] buildAllAvailableLoggerLevelsWithInheritedPsuedoLogLevel(LoggingManagementFacade loggingManagementFacade) - { - List<String> levels = loggingManagementFacade.getAvailableLoggerLevels(); - List<String> mbeanLevels = new ArrayList<String>(levels); - mbeanLevels.add(INHERITED_PSUEDO_LOG_LEVEL); - - return mbeanLevels.toArray(new String[mbeanLevels.size()]); - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/QueueMBean.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/QueueMBean.java deleted file mode 100644 index e77085034c..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/QueueMBean.java +++ /dev/null @@ -1,716 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.jmx.mbeans; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.atomic.AtomicLong; - -import javax.management.JMException; -import javax.management.MBeanNotificationInfo; -import javax.management.Notification; -import javax.management.ObjectName; -import javax.management.OperationsException; -import javax.management.monitor.MonitorNotification; -import javax.management.openmbean.ArrayType; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.SimpleType; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.TabularType; - -import org.apache.commons.lang.time.FastDateFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.management.common.mbeans.ManagedQueue; -import org.apache.qpid.server.jmx.AMQManagedObject; -import org.apache.qpid.server.jmx.ManagedObject; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Exchange; -import org.apache.qpid.server.model.ExclusivityPolicy; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.QueueNotificationListener; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.queue.NotificationCheck; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.queue.QueueEntryVisitor; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.util.ServerScopedRuntimeException; - -public class QueueMBean extends AMQManagedObject implements ManagedQueue, QueueNotificationListener -{ - private static final Logger LOGGER = LoggerFactory.getLogger(QueueMBean.class); - - private static final String[] VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC_ARRAY = - VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC.toArray(new String[VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC.size()]); - - private static final OpenType[] MSG_ATTRIBUTE_TYPES; - private static final CompositeType MSG_DATA_TYPE; - private static final TabularType MSG_LIST_DATA_TYPE; - private static final CompositeType MSG_CONTENT_TYPE; - private static final String[] VIEW_MSG_COMPOSITE_ITEM_NAMES_ARRAY = VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.toArray( - new String[VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.size()]); - - static - { - - try - { - MSG_ATTRIBUTE_TYPES = new OpenType[] { - SimpleType.LONG, // For message id - new ArrayType(1, SimpleType.STRING), // For header attributes - SimpleType.LONG, // For size - SimpleType.BOOLEAN, // For redelivered - SimpleType.LONG, // For queue position - SimpleType.INTEGER // For delivery count} - }; - - MSG_DATA_TYPE = new CompositeType("Message", "AMQ Message", - VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC_ARRAY, - VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC_ARRAY, MSG_ATTRIBUTE_TYPES); - - MSG_LIST_DATA_TYPE = new TabularType("Messages", "List of messages", MSG_DATA_TYPE, - VIEW_MSGS_TABULAR_UNIQUE_INDEX.toArray(new String[VIEW_MSGS_TABULAR_UNIQUE_INDEX.size()])); - - OpenType[] msgContentAttrs = new OpenType[] { - SimpleType.LONG, // For message id - SimpleType.STRING, // For MimeType - SimpleType.STRING, // For MimeType - new ArrayType(SimpleType.BYTE, true) // For message content - }; - - - MSG_CONTENT_TYPE = new CompositeType("Message Content", "AMQ Message Content", - VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.toArray(new String[VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.size()]), - VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.toArray(new String[VIEW_MSG_CONTENT_COMPOSITE_ITEM_NAMES_DESC.size()]), - msgContentAttrs); - - } - catch (OpenDataException e) - { - throw new ServerScopedRuntimeException(e); - } - } - - private final Queue<?> _queue; - private final VirtualHostMBean _vhostMBean; - - /** Date/time format used for message expiration and message timestamp formatting */ - public static final String JMSTIMESTAMP_DATETIME_FORMAT = "MM-dd-yy HH:mm:ss.SSS z"; - - private static final FastDateFormat FAST_DATE_FORMAT = FastDateFormat.getInstance(JMSTIMESTAMP_DATETIME_FORMAT); - - public QueueMBean(Queue queue, VirtualHostMBean virtualHostMBean) throws JMException - { - super(ManagedQueue.class, ManagedQueue.TYPE, virtualHostMBean.getRegistry()); - _queue = queue; - _vhostMBean = virtualHostMBean; - register(); - _queue.setNotificationListener(this); - } - - public ManagedObject getParentObject() - { - return _vhostMBean; - } - - public String getObjectInstanceName() - { - return ObjectName.quote(getName()); - } - - public String getName() - { - return _queue.getName(); - } - - public Integer getMessageCount() - { - return _queue.getQueueDepthMessages(); - } - - public Integer getMaximumDeliveryCount() - { - return _queue.getMaximumDeliveryAttempts(); - } - - public Long getReceivedMessageCount() - { - return _queue.getTotalEnqueuedMessages(); - } - - public Long getQueueDepth() - { - return _queue.getQueueDepthBytes(); - } - - public Integer getActiveConsumerCount() - { - return _queue.getConsumerCountWithCredit(); - } - - public Integer getConsumerCount() - { - return _queue.getConsumerCount(); - } - - public String getOwner() - { - return _queue.getOwner(); - } - - @Override - public String getQueueType() - { - return _queue.getType(); - } - - public boolean isDurable() - { - return _queue.isDurable(); - } - - public boolean isAutoDelete() - { - return _queue.getLifetimePolicy() != LifetimePolicy.PERMANENT; - } - - public Long getMaximumMessageAge() - { - return _queue.getAlertThresholdMessageAge(); - } - - public void setMaximumMessageAge(Long age) - { - _queue.setAttribute(Queue.ALERT_THRESHOLD_MESSAGE_AGE, getMaximumMessageAge(), age); - } - - public Long getMaximumMessageSize() - { - return _queue.getAlertThresholdMessageSize(); - } - - public void setMaximumMessageSize(Long size) - { - _queue.setAttribute(Queue.ALERT_THRESHOLD_MESSAGE_SIZE, getMaximumMessageSize(), size); - } - - public Long getMaximumMessageCount() - { - return _queue.getAlertThresholdQueueDepthMessages(); - } - - public void setMaximumMessageCount(Long value) - { - _queue.setAttribute(Queue.ALERT_THRESHOLD_QUEUE_DEPTH_MESSAGES, getMaximumMessageCount(), value); - } - - public Long getMaximumQueueDepth() - { - return _queue.getAlertThresholdQueueDepthBytes(); - } - - public void setMaximumQueueDepth(Long value) - { - _queue.setAttribute(Queue.ALERT_THRESHOLD_QUEUE_DEPTH_BYTES, getMaximumQueueDepth(), value); - } - - public Long getCapacity() - { - return _queue.getQueueFlowControlSizeBytes(); - } - - public void setCapacity(Long value) - { - _queue.setAttribute(Queue.QUEUE_FLOW_CONTROL_SIZE_BYTES, getCapacity(), value); - } - - public Long getFlowResumeCapacity() - { - return _queue.getQueueFlowResumeSizeBytes(); - } - - public void setFlowResumeCapacity(Long value) - { - _queue.setAttribute(Queue.QUEUE_FLOW_RESUME_SIZE_BYTES, getFlowResumeCapacity(), value); - } - - public boolean isFlowOverfull() - { - return _queue.isQueueFlowStopped(); - } - - public boolean isExclusive() - { - final ExclusivityPolicy attribute = _queue.getExclusive(); - return attribute != null && attribute != ExclusivityPolicy.NONE; - } - - public void setExclusive(boolean exclusive) - { - if(exclusive) - { - ExclusivityPolicy currentValue = _queue.getExclusive(); - if(currentValue == null || currentValue == ExclusivityPolicy.NONE) - { - _queue.setAttribute(Queue.EXCLUSIVE, currentValue, ExclusivityPolicy.CONTAINER); - } - } - else - { - ExclusivityPolicy currentValue = _queue.getExclusive(); - if(currentValue != null && currentValue != ExclusivityPolicy.NONE) - { - _queue.setAttribute(Queue.EXCLUSIVE, currentValue, ExclusivityPolicy.NONE); - } - } - - } - - public void setAlternateExchange(String exchangeName) throws OperationsException - { - if (exchangeName == null || "".equals(exchangeName)) - { - _queue.setAttributes(Collections.singletonMap(Queue.ALTERNATE_EXCHANGE, null)); - } - else - { - try - { - - _queue.setAttributes(Collections.<String,Object>singletonMap(Queue.ALTERNATE_EXCHANGE, exchangeName)); - } - catch (IllegalArgumentException e) - { - throw new OperationsException("No such exchange \""+exchangeName+"\""); - } - } - } - - public String getAlternateExchange() - { - Exchange alternateExchange = _queue.getAlternateExchange(); - return alternateExchange == null ? null : alternateExchange.getName(); - } - - public TabularData viewMessages(int fromIndex, int toIndex) - throws IOException, JMException - { - return viewMessages((long)fromIndex, (long)toIndex); - } - - public TabularData viewMessages(long startPosition, long endPosition) - throws IOException, JMException - { - if ((startPosition > endPosition) || (startPosition < 1)) - { - throw new OperationsException("From Index = " + startPosition + ", To Index = " + endPosition - + "\n\"From Index\" should be greater than 0 and less than \"To Index\""); - } - - if ((endPosition - startPosition) > Integer.MAX_VALUE) - { - throw new OperationsException("Specified MessageID interval is too large. Intervals must be less than 2^31 in size"); - } - - - List<QueueEntry> messages = getMessages(startPosition, endPosition); - - TabularDataSupport messageTable = new TabularDataSupport(MSG_LIST_DATA_TYPE); - - - // Create the tabular list of message header contents - long position = startPosition; - - for (QueueEntry queueEntry : messages) - { - ServerMessage serverMsg = queueEntry.getMessage(); - AMQMessageHeader header = serverMsg.getMessageHeader(); - String[] headerAttributes = - {"reply-to = " + header.getReplyTo(), - "propertyFlags = ", - "ApplicationID = " + header.getAppId(), - "ClusterID = ", - "UserId = " + header.getUserId(), - "JMSMessageID = " + header.getMessageId(), - "JMSCorrelationID = " + header.getCorrelationId(), - "JMSDeliveryMode = " + (serverMsg.isPersistent() ? "Persistent" : "Non_Persistent"), - "JMSPriority = " + header.getPriority(), - "JMSType = " + header.getType(), - "JMSExpiration = " + (header.getExpiration() == 0 ? null : FAST_DATE_FORMAT.format(header.getExpiration())), - "JMSTimestamp = " + (header.getTimestamp() == 0 ? null : FAST_DATE_FORMAT.format(header.getTimestamp())) - }; - - Object[] itemValues = new Object[]{ serverMsg.getMessageNumber(), - headerAttributes, - serverMsg.getSize(), - queueEntry.isRedelivered(), - position, - queueEntry.getDeliveryCount()}; - - position++; - - CompositeData messageData = - new CompositeDataSupport(MSG_DATA_TYPE, VIEW_MSGS_COMPOSITE_ITEM_NAMES_DESC_ARRAY, itemValues); - messageTable.put(messageData); - } - - return messageTable; - - } - - public CompositeData viewMessageContent(long messageId) - throws IOException, JMException - { - QueueEntry entry = getMessage(messageId); - if(entry == null) - { - throw new OperationsException("AMQMessage with message id = " + messageId + " is not in the " + _queue.getName()); - } - - ServerMessage serverMsg = entry.getMessage(); - final int bodySize = (int) serverMsg.getSize(); - - byte[] msgContent = new byte[bodySize]; - - ByteBuffer buf = ByteBuffer.wrap(msgContent); - int stored = serverMsg.getContent(buf, 0); - - if(bodySize != stored) - { - LOGGER.error(String.format("An unexpected amount of content was retrieved " + - "(expected %d, got %d bytes) when viewing content for message with ID %d " + - "on queue '%s' in virtual host '%s'", - bodySize, stored, messageId, _queue.getName(), _vhostMBean.getName())); - } - - AMQMessageHeader header = serverMsg.getMessageHeader(); - - String mimeType = null, encoding = null; - if (header != null) - { - mimeType = header.getMimeType(); - - encoding = header.getEncoding(); - } - - - Object[] itemValues = { messageId, mimeType, encoding, msgContent }; - - return new CompositeDataSupport(MSG_CONTENT_TYPE, VIEW_MSG_COMPOSITE_ITEM_NAMES_ARRAY, itemValues); - - - } - - private QueueEntry getMessage(long messageId) - { - GetMessageVisitor visitor = new GetMessageVisitor(messageId); - _queue.visit(visitor); - return visitor.getEntry(); - } - - public void deleteMessageFromTop() throws IOException, JMException - { - VirtualHost vhost = _queue.getParent(VirtualHost.class); - vhost.executeTransaction(new VirtualHost.TransactionalOperation() - { - public void withinTransaction(final VirtualHost.Transaction txn) - { - _queue.visit(new QueueEntryVisitor() - { - - public boolean visit(final QueueEntry entry) - { - if(entry.acquire()) - { - txn.dequeue(entry); - return true; - } - return false; - } - }); - - } - }); - - } - - public Long clearQueue() throws IOException, JMException - { - VirtualHost vhost = _queue.getParent(VirtualHost.class); - final AtomicLong count = new AtomicLong(); - - vhost.executeTransaction(new VirtualHost.TransactionalOperation() - { - public void withinTransaction(final VirtualHost.Transaction txn) - { - _queue.visit(new QueueEntryVisitor() - { - - public boolean visit(final QueueEntry entry) - { - final ServerMessage message = entry.getMessage(); - if(message != null) - { - txn.dequeue(entry); - count.incrementAndGet(); - - } - return false; - } - }); - - } - }); - return count.get(); - } - - public void moveMessages(final long fromMessageId, final long toMessageId, String toQueue) - throws IOException, JMException - { - if ((fromMessageId > toMessageId) || (fromMessageId < 1)) - { - throw new OperationsException("\"From MessageId\" should be greater than 0 and less than \"To MessageId\""); - } - - VirtualHost<?,?,?> vhost = _queue.getParent(VirtualHost.class); - final Queue<?> destinationQueue = vhost.getChildByName(Queue.class, toQueue); - if (destinationQueue == null) - { - throw new OperationsException("No such queue \""+ toQueue +"\""); - } - - vhost.executeTransaction(new VirtualHost.TransactionalOperation() - { - public void withinTransaction(final VirtualHost.Transaction txn) - { - _queue.visit(new QueueEntryVisitor() - { - - public boolean visit(final QueueEntry entry) - { - final ServerMessage message = entry.getMessage(); - if(message != null) - { - final long messageId = message.getMessageNumber(); - - if ((messageId >= fromMessageId) - && (messageId <= toMessageId) - && !(message.isReferenced((TransactionLogResource)destinationQueue))) - { - txn.move(entry, destinationQueue); - } - - } - return false; - } - }); - } - }); - } - - public void deleteMessages(final long fromMessageId, final long toMessageId) - throws IOException, JMException - { - VirtualHost vhost = _queue.getParent(VirtualHost.class); - vhost.executeTransaction(new VirtualHost.TransactionalOperation() - { - public void withinTransaction(final VirtualHost.Transaction txn) - { - _queue.visit(new QueueEntryVisitor() - { - public boolean visit(final QueueEntry entry) - { - final ServerMessage message = entry.getMessage(); - if(message != null) - { - final long messageId = message.getMessageNumber(); - - if ((messageId >= fromMessageId) - && (messageId <= toMessageId)) - { - txn.dequeue(entry); - } - } - return false; - } - }); - } - }); - } - - public void copyMessages(final long fromMessageId, final long toMessageId, String toQueue) - throws IOException, JMException - { - if ((fromMessageId > toMessageId) || (fromMessageId < 1)) - { - throw new OperationsException("\"From MessageId\" should be greater than 0 and less than \"To MessageId\""); - } - - VirtualHost<?,?,?> vhost = _queue.getParent(VirtualHost.class); - final Queue<?> destinationQueue = vhost.getChildByName(Queue.class, toQueue); - if (destinationQueue == null) - { - throw new OperationsException("No such queue \""+ toQueue +"\""); - } - vhost.executeTransaction(new VirtualHost.TransactionalOperation() - { - public void withinTransaction(final VirtualHost.Transaction txn) - { - _queue.visit(new QueueEntryVisitor() - { - - public boolean visit(final QueueEntry entry) - { - final ServerMessage message = entry.getMessage(); - if(message != null) - { - final long messageId = message.getMessageNumber(); - - if ((messageId >= fromMessageId) - && (messageId <= toMessageId) - && !(message.isReferenced((TransactionLogResource)destinationQueue))) - { - txn.copy(entry, destinationQueue); - } - - } - return false; - } - }); - } - }); - } - - private List<QueueEntry> getMessages(final long first, final long last) - { - final List<QueueEntry> messages = new ArrayList<QueueEntry>((int)(last-first)+1); - _queue.visit(new QueueEntryVisitor() - { - private long position = 1; - - public boolean visit(QueueEntry entry) - { - if(position >= first && position <= last) - { - messages.add(entry); - } - position++; - return position > last; - } - }); - return messages; - } - - - protected static class GetMessageVisitor implements QueueEntryVisitor - { - - private final long _messageNumber; - private QueueEntry _entry; - - public GetMessageVisitor(long messageId) - { - _messageNumber = messageId; - } - - public boolean visit(QueueEntry entry) - { - if(entry.getMessage().getMessageNumber() == _messageNumber) - { - _entry = entry; - return true; - } - return false; - } - - public QueueEntry getEntry() - { - return _entry; - } - } - - @Override - public void notifyClients(NotificationCheck notification, Queue queue, String notificationMsg) - { - notificationMsg = notification.name() + " " + notificationMsg; - - Notification note = new Notification(MonitorNotification.THRESHOLD_VALUE_EXCEEDED, this, - incrementAndGetSequenceNumber(), System.currentTimeMillis(), notificationMsg); - - getBroadcaster().sendNotification(note); - } - - /** - * returns Notifications sent by this MBean. - */ - @Override - public MBeanNotificationInfo[] getNotificationInfo() - { - String[] notificationTypes = new String[] { MonitorNotification.THRESHOLD_VALUE_EXCEEDED }; - String name = MonitorNotification.class.getName(); - String description = "Either Message count or Queue depth or Message size has reached threshold high value"; - MBeanNotificationInfo info1 = new MBeanNotificationInfo(notificationTypes, name, description); - - return new MBeanNotificationInfo[] { info1 }; - } - - @Override - public String getDescription() - { - return _queue.getDescription(); - } - - @Override - public void setDescription(String description) - { - _queue.setAttribute(Queue.DESCRIPTION, getDescription(), description); - } - - @Override - public String getMessageGroupKey() - { - return _queue.getMessageGroupKey(); - } - - @Override - public boolean isMessageGroupSharedGroups() - { - return _queue.isMessageGroupSharedGroups(); - } - - @Override - public Long getOldestMessageAge() - { - return _queue.getOldestMessageAge(); - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ServerInformationMBean.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ServerInformationMBean.java deleted file mode 100644 index 75a395bef5..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ServerInformationMBean.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx.mbeans; - -import java.io.IOException; - -import javax.management.JMException; -import javax.management.NotCompliantMBeanException; - -import org.apache.qpid.management.common.mbeans.ServerInformation; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; -import org.apache.qpid.server.jmx.ManagedObject; -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.model.Broker; - -@MBeanDescription("Server Information Interface") -public class ServerInformationMBean extends AbstractStatisticsGatheringMBean<Broker> implements ServerInformation -{ - private final Broker _broker; - - public ServerInformationMBean(ManagedObjectRegistry registry, Broker broker) - throws NotCompliantMBeanException, JMException - { - super(ServerInformation.class, ServerInformation.TYPE, registry, broker); - _broker = broker; - - register(); - } - - @Override - protected long getBytesOut() - { - return getConfiguredObject().getBytesOut(); - } - - @Override - protected long getBytesIn() - { - return getConfiguredObject().getBytesIn(); - } - - @Override - protected long getMessagesOut() - { - return getConfiguredObject().getMessagesOut(); - } - - @Override - protected long getMessagesIn() - { - return getConfiguredObject().getMessagesIn(); - } - - @Override - public String getObjectInstanceName() - { - return ServerInformation.TYPE; - } - - @Override - public Integer getManagementApiMajorVersion() throws IOException - { - return QPID_JMX_API_MAJOR_VERSION; - } - - @Override - public Integer getManagementApiMinorVersion() throws IOException - { - return QPID_JMX_API_MINOR_VERSION; - } - - @Override - public String getBuildVersion() throws IOException - { - return (String) _broker.getAttribute(Broker.BUILD_VERSION); - } - - @Override - public String getProductVersion() throws IOException - { - return (String) _broker.getAttribute(Broker.PRODUCT_VERSION); - } - - @Override - public boolean isStatisticsEnabled() - { - return true; - } - - @Override - public ManagedObject getParentObject() - { - // does not have a parent - return null; - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/Shutdown.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/Shutdown.java deleted file mode 100644 index 979d966c04..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/Shutdown.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx.mbeans; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import javax.management.JMException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.jmx.DefaultManagedObject; -import org.apache.qpid.server.jmx.ManagedObject; -import org.apache.qpid.server.jmx.ManagedObjectRegistry; - -/** - * Implementation of the JMX broker shutdown plugin. - */ -public class Shutdown extends DefaultManagedObject implements ShutdownMBean -{ - - private static final Logger _logger = LoggerFactory.getLogger(Shutdown.class); - - private static final String FORMAT = "yyyy/MM/dd HH:mm:ss"; - private static final int THREAD_COUNT = 1; - private static final ScheduledExecutorService EXECUTOR = new ScheduledThreadPoolExecutor(THREAD_COUNT); - - private final Runnable _shutdown = new SystemExiter(); - - public Shutdown(ManagedObjectRegistry registry) throws JMException - { - super(ShutdownMBean.class, ShutdownMBean.TYPE, registry); - register(); - } - - /** @see ShutdownMBean#shutdown() */ - public void shutdown() - { - _logger.info("Shutting down at user's request"); - shutdownBroker(0); - } - - /** @see ShutdownMBean#shutdown(long) */ - public void shutdown(final long delay) - { - if (delay < 0) - { - _logger.info("Shutting down at user's request"); - shutdownBroker(0); - } - else - { - _logger.info("Scheduled broker shutdown after " + delay + "ms"); - shutdownBroker(delay); - } - } - - /** @see ShutdownMBean#shutdownAt(String) */ - public void shutdownAt(final String when) - { - Date date; - DateFormat df = new SimpleDateFormat(FORMAT); - try - { - date = df.parse(when); - } - catch (ParseException e) - { - _logger.error("Invalid date \"" + when + "\": expecting " + FORMAT, e); - return; - } - _logger.info("Scheduled broker shutdown at " + when); - long now = System.currentTimeMillis(); - long time = date.getTime(); - if (time > now) - { - shutdownBroker(time - now); - } - else - { - shutdownBroker(0); - } - } - - /** - * Submits the {@link SystemExiter} job to shutdown the broker. - */ - private void shutdownBroker(long delay) - { - EXECUTOR.schedule(_shutdown, delay, TimeUnit.MILLISECONDS); - } - - @Override - public ManagedObject getParentObject() - { - return null; - } - - /** - * Shutting down the system in another thread to avoid JMX exceptions being thrown. - */ - class SystemExiter implements Runnable - { - public void run() - { - System.exit(0); - } - } - - /** - * @see ManagedObject#getObjectInstanceName() - */ - public String getObjectInstanceName() - { - return "Shutdown"; - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ShutdownMBean.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ShutdownMBean.java deleted file mode 100644 index ed69c351f7..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ShutdownMBean.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx.mbeans; - -import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation; -import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter; - -import javax.management.MBeanOperationInfo; - -/** - * Shutdown plugin JMX MBean interface. - * - * Shuts the Qpid broker down via JMX. - */ -public interface ShutdownMBean -{ - static final String TYPE = "Shutdown"; - - /** - * Broker will be shut down immediately. - */ - @MBeanOperation(name="shutdown", description="Shut down immediately", impact = MBeanOperationInfo.ACTION) - public void shutdown(); - - /** - * Broker will be shutdown after the specified delay - * - * @param delay the number of ms to wait - */ - @MBeanOperation(name="shutdown", description="Shutdown after the specified delay (ms)", impact = MBeanOperationInfo.ACTION) - public void shutdown(@MBeanOperationParameter(name = "when", description = "delay (ms)") long delay); - - /** - * Broker will be shutdown at the specified date and time. - * - * @param when the date and time to shutdown - */ - @MBeanOperation(name="shutdownAt", description="Shutdown at the specified date and time (yyyy/MM/dd HH:mm:ss)", impact = MBeanOperationInfo.ACTION) - public void shutdownAt(@MBeanOperationParameter(name = "when", - description = "shutdown date/time (yyyy/MM/dd HH:mm:ss)") String when); -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/UserManagementMBean.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/UserManagementMBean.java deleted file mode 100644 index 16907fced4..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/UserManagementMBean.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.jmx.mbeans; - -import java.io.IOException; -import java.util.Map; - -import javax.management.JMException; -import javax.management.ObjectName; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.CompositeType; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.OpenType; -import javax.management.openmbean.SimpleType; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; -import javax.management.openmbean.TabularType; -import javax.security.auth.login.AccountNotFoundException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.management.common.mbeans.UserManagement; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; -import org.apache.qpid.server.jmx.AMQManagedObject; -import org.apache.qpid.server.jmx.ManagedObject; -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.PasswordCredentialManagingAuthenticationProvider; - -@MBeanDescription("User Management Interface") -public class UserManagementMBean extends AMQManagedObject implements UserManagement -{ - private static final Logger _logger = LoggerFactory.getLogger(UserManagementMBean.class); - - private PasswordCredentialManagingAuthenticationProvider _authProvider; - - private String _mbeanName; - private String _type; - - // Setup for the TabularType - private static final TabularType _userlistDataType; // Datatype for representing User Lists - private static final CompositeType _userDataType; // Composite type for representing User - - static - { - OpenType[] userItemTypes = new OpenType[4]; // User item types. - userItemTypes[0] = SimpleType.STRING; // For Username - userItemTypes[1] = SimpleType.BOOLEAN; // For Rights - Read - No longer in use - userItemTypes[2] = SimpleType.BOOLEAN; // For Rights - Write - No longer in use - userItemTypes[3] = SimpleType.BOOLEAN; // For Rights - Admin - No longer is use - - try - { - _userDataType = - new CompositeType("User", "User Data", COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]), - COMPOSITE_ITEM_DESCRIPTIONS.toArray(new String[COMPOSITE_ITEM_DESCRIPTIONS.size()]), userItemTypes); - - _userlistDataType = new TabularType("Users", "List of users", _userDataType, TABULAR_UNIQUE_INDEX.toArray(new String[TABULAR_UNIQUE_INDEX.size()])); - } - catch (OpenDataException e) - { - _logger.error("Tabular data setup for viewing users incorrect.", e); - throw new ExceptionInInitializerError("Tabular data setup for viewing users incorrect"); - } - } - - public UserManagementMBean(PasswordCredentialManagingAuthenticationProvider provider, ManagedObjectRegistry registry) throws JMException - { - super(UserManagement.class, UserManagement.TYPE, registry); - _authProvider = provider; - _mbeanName = UserManagement.TYPE + "-" + _authProvider.getName(); - _type = String.valueOf(_authProvider.getAttribute(AuthenticationProvider.TYPE)); - register(); - } - - @Override - public String getObjectInstanceName() - { - return ObjectName.quote(_mbeanName); - } - - @Override - public boolean setPassword(String username, String password) - { - try - { - _authProvider.setPassword(username, password); - } - catch (AccountNotFoundException e) - { - _logger.warn("Attempt to set password of non-existent user '" + username + "'"); - return false; - } - return true; - } - - @Override - public boolean createUser(String username, String password) - { - return _authProvider.createUser(username, password, null); - } - - @Override - public boolean deleteUser(String username) - { - try - { - _authProvider.deleteUser(username); - } - catch (AccountNotFoundException e) - { - _logger.warn("Attempt to delete user (" + username + ") that doesn't exist"); - return false; - } - - return true; - } - - @Override - public boolean reloadData() - { - try - { - _authProvider.reload(); - return true; - } - catch (IOException e) - { - _logger.error("Unable to reload user data", e); - return false; - } - } - - @Override - public TabularData viewUsers() - { - Map<String, Map<String, String>> users = _authProvider.getUsers(); - - TabularDataSupport userList = new TabularDataSupport(_userlistDataType); - - try - { - // Create the tabular list of message header contents - for (String user : users.keySet()) - { - // Create header attributes list - // Read,Write,Admin items are deprecated and we return always false. - Object[] itemData = {user, false, false, false}; - CompositeData messageData = new CompositeDataSupport(_userDataType, COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]), itemData); - userList.put(messageData); - } - } - catch (OpenDataException e) - { - _logger.warn("Unable to create user list due to :", e); - return null; - } - - return userList; - } - - @Override - public ManagedObject getParentObject() - { - return null; - } - - @Override - public String getAuthenticationProviderType() - { - return _type; - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostMBean.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostMBean.java deleted file mode 100644 index 7ac28cd230..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostMBean.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.jmx.mbeans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import javax.management.JMException; -import javax.management.ObjectName; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.jmx.AMQManagedObject; -import org.apache.qpid.server.jmx.ManagedObject; -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.model.ConfigurationChangeListener; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Connection; -import org.apache.qpid.server.model.Exchange; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.virtualhost.ManagedVirtualHost; - -public class VirtualHostMBean extends AMQManagedObject implements ManagedVirtualHost, ConfigurationChangeListener -{ - private static final Logger LOGGER = LoggerFactory.getLogger(VirtualHostMBean.class); - - private final VirtualHost<?,?,?> _virtualHost; - - private final Map<ConfiguredObject, AMQManagedObject> _children = - new HashMap<ConfiguredObject, AMQManagedObject>(); - private VirtualHostManagerMBean _managerMBean; - - public VirtualHostMBean(VirtualHost virtualHost, ManagedObjectRegistry registry) throws JMException - { - super(ManagedVirtualHost.class, ManagedVirtualHost.TYPE, registry); - _virtualHost = virtualHost; - virtualHost.addChangeListener(this); - - initQueues(); - initExchanges(); - initConnections(); - - //This is the actual JMX bean for this 'VirtualHostMBean', leave it alone. - _managerMBean = new VirtualHostManagerMBean(this); - } - - private void initQueues() - { - synchronized (_children) - { - for(Queue queue : _virtualHost.getQueues()) - { - if(!_children.containsKey(queue)) - { - try - { - _children.put(queue, new QueueMBean(queue, this)); - } - catch(Exception e) - { - LOGGER.error("Cannot create queue mbean for queue " + queue.getName(), e); - } - } - } - } - } - - private void initExchanges() - { - synchronized (_children) - { - for(Exchange exchange : _virtualHost.getExchanges()) - { - if(!_children.containsKey(exchange)) - { - try - { - _children.put(exchange, new ExchangeMBean(exchange, this)); - } - catch(Exception e) - { - LOGGER.error("Cannot create exchange mbean for exchange " + exchange.getName(), e); - } - } - } - } - } - - private void initConnections() - { - synchronized (_children) - { - for(Connection conn : _virtualHost.getConnections()) - { - if(!_children.containsKey(conn)) - { - try - { - _children.put(conn, new ConnectionMBean(conn, this)); - } - catch(Exception e) - { - LOGGER.error("Cannot create connection mbean for connection " + conn.getName(), e); - } - } - } - } - } - - public String getObjectInstanceName() - { - return ObjectName.quote(_virtualHost.getName()); - } - - public String getName() - { - return _virtualHost.getName(); - } - - public void stateChanged(ConfiguredObject object, State oldState, State newState) - { - // no-op - } - - public void childAdded(ConfiguredObject object, ConfiguredObject child) - { - synchronized (_children) - { - try - { - if(child instanceof Queue) - { - QueueMBean queueMB = new QueueMBean((Queue)child, this); - _children.put(child, queueMB); - - } - else if(child instanceof Exchange) - { - ExchangeMBean exchangeMBean = new ExchangeMBean((Exchange)child, this); - _children.put(child, exchangeMBean); - - } - else if(child instanceof Connection) - { - ConnectionMBean connectionMBean = new ConnectionMBean((Connection)child, this); - _children.put(child, connectionMBean); - - } - else - { - LOGGER.debug("Unsupported child : " + child.getName() + " type : " + child.getClass()); - } - - } - catch(Exception e) - { - LOGGER.error("Exception while creating mbean for " + child.getClass().getSimpleName() + " " + child.getName(), e); - } - } - } - - public void childRemoved(ConfiguredObject object, ConfiguredObject child) - { - synchronized (_children) - { - AMQManagedObject mbean = _children.remove(child); - if(mbean != null) - { - try - { - mbean.unregister(); - } - catch(Exception e) - { - LOGGER.error("Exception while unregistering mbean for " + child.getClass().getSimpleName() + " " + child.getName(), e); - } - } - } - } - - @Override - public ManagedObject getParentObject() - { - return null; - } - - protected VirtualHost getVirtualHost() - { - return _virtualHost; - } - - public Collection<QueueMBean> getQueues() - { - Collection<AMQManagedObject> children; - synchronized (_children) - { - children = new ArrayList<AMQManagedObject>(_children.values()); - } - Collection<QueueMBean> queues = new ArrayList<QueueMBean>(); - - for(AMQManagedObject child : children) - { - if(child instanceof QueueMBean) - { - queues.add((QueueMBean) child); - } - } - - return queues; - } - - @Override - public void unregister() throws JMException - { - _virtualHost.removeChangeListener(this); - - synchronized (_children) - { - for (AMQManagedObject mbean : _children.values()) - { - if(mbean != null) - { - try - { - mbean.unregister(); - } - catch(Exception e) - { - LOGGER.error("Exception while unregistering mbean : " + mbean, e); - } - } - } - _children.clear(); - } - _managerMBean.unregister(); - } - - @Override - public void attributeSet(ConfiguredObject object, String attributeName, Object oldAttributeValue, Object newAttributeValue) - { - // no-op - } - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostManagerMBean.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostManagerMBean.java deleted file mode 100644 index f9a51d4158..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostManagerMBean.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.jmx.mbeans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.management.JMException; -import javax.management.MBeanException; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import javax.management.OperationsException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.management.common.mbeans.ManagedBroker; -import org.apache.qpid.management.common.mbeans.ManagedQueue; -import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; -import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter; -import org.apache.qpid.server.jmx.ManagedObject; -import org.apache.qpid.server.model.Exchange; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.NoFactoryForTypeException; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.queue.QueueArgumentsConverter; -import org.apache.qpid.server.virtualhost.ExchangeExistsException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.apache.qpid.server.virtualhost.RequiredExchangeException; -import org.apache.qpid.server.virtualhost.ReservedExchangeNameException; - -@MBeanDescription("This MBean exposes the broker level management features") -public class VirtualHostManagerMBean extends AbstractStatisticsGatheringMBean<VirtualHost> implements ManagedBroker -{ - private static final Logger LOGGER = LoggerFactory.getLogger(VirtualHostManagerMBean.class); - - private static final boolean _moveNonExclusiveQueueOwnerToDescription = Boolean.parseBoolean(System.getProperty("qpid.move_non_exclusive_queue_owner_to_description", Boolean.TRUE.toString())); - - private final VirtualHostMBean _virtualHostMBean; - - @MBeanConstructor("Creates the Broker Manager MBean") - public VirtualHostManagerMBean(VirtualHostMBean virtualHostMBean) throws JMException - { - super(ManagedBroker.class, ManagedBroker.TYPE, virtualHostMBean.getRegistry(), virtualHostMBean.getVirtualHost()); - _virtualHostMBean = virtualHostMBean; - register(); - } - - @Override - protected long getBytesOut() - { - return getConfiguredObject().getBytesOut(); - } - - @Override - protected long getBytesIn() - { - return getConfiguredObject().getBytesIn(); - } - - @Override - protected long getMessagesOut() - { - return getConfiguredObject().getMessagesOut(); - } - - @Override - protected long getMessagesIn() - { - return getConfiguredObject().getMessagesIn(); - } - - @Override - public String getObjectInstanceName() - { - return ObjectName.quote(_virtualHostMBean.getName()); - } - - @Override - public ManagedObject getParentObject() - { - return _virtualHostMBean; - } - - @Override - public String[] getExchangeTypes() throws IOException - { - Collection<String> exchangeTypes = _virtualHostMBean.getVirtualHost().getExchangeTypeNames(); - return exchangeTypes.toArray(new String[exchangeTypes.size()]); - } - - @Override - public List<String> retrieveQueueAttributeNames() throws IOException - { - return ManagedQueue.QUEUE_ATTRIBUTES; - } - - @Override - public List<List<Object>> retrieveQueueAttributeValues( - @MBeanOperationParameter(name = "attributes", description = "Attributes to retrieve") String[] attributes) - throws IOException - { - int attributesLength = attributes.length; - - List<List<Object>> queueAttributesList = new ArrayList<List<Object>>(); - - for(QueueMBean queue : _virtualHostMBean.getQueues()) - { - - if(queue == null) - { - continue; - } - - List<Object> attributeValues = new ArrayList<Object>(attributesLength); - - for(int i=0; i < attributesLength; i++) - { - try - { - attributeValues.add(queue.getAttribute(attributes[i])); - } - catch (Exception e) - { - attributeValues.add("-"); - } - } - - queueAttributesList.add(attributeValues); - } - - return queueAttributesList; - - } - - @Override - public void createNewExchange(String name, String type, boolean durable) - throws IOException, JMException, MBeanException - { - if (!getConfiguredObject().getExchangeTypeNames().contains(type)) - { - throw new OperationsException("No such exchange type \""+type+"\""); - } - - try - { - Map<String,Object> attributes = new HashMap<>(); - attributes.put(Exchange.NAME, name); - attributes.put(Exchange.TYPE, type); - attributes.put(Exchange.DURABLE, durable); - attributes.put(Exchange.LIFETIME_POLICY, LifetimePolicy.PERMANENT); - - getConfiguredObject().createExchange(attributes); - } - catch(ExchangeExistsException e) - { - String message = "Exchange with name '" + name + "' already exists"; - JMException jme = new JMException(message); - throw new MBeanException(jme, "Error in creating exchange " + name); - - } - catch(ReservedExchangeNameException e) - { - throw new UnsupportedOperationException("'" + name + "' is a reserved exchange name"); - } - catch(NoFactoryForTypeException e) - { - JMException jme = new JMException(e.getMessage()); - throw new MBeanException(jme, "Error in creating exchange " + name); - } - catch (IllegalArgumentException iae) - { - JMException jme = new JMException(iae.toString()); - throw new MBeanException(jme, "Error in creating exchange " + name); - } - - - } - - @Override - public void unregisterExchange(String exchangeName) - throws IOException, JMException, MBeanException - { - VirtualHost<?,?,?> virtualHost = _virtualHostMBean.getVirtualHost(); - Exchange<?> exchange = virtualHost.getChildByName(Exchange.class, exchangeName); - - if (exchange == null) - { - throw new OperationsException("No such exchange \""+ exchangeName +"\""); - } - - try - { - exchange.delete(); - } - catch(RequiredExchangeException e) - { - throw new UnsupportedOperationException(e.getMessage(), e); - } - catch (IllegalStateException ex) - { - final JMException jme = new JMException(ex.toString()); - throw new MBeanException(jme, "Error in unregistering exchange " + exchangeName); - } - } - - @Override - public void createNewQueue(String queueName, String owner, boolean durable) - throws IOException, JMException, MBeanException - { - createNewQueue(queueName, owner, durable, Collections.EMPTY_MAP); - } - - @Override - public void createNewQueue(String queueName, String owner, boolean durable, Map<String, Object> originalArguments) - throws IOException, JMException - { - final Map<String, Object> createArgs = processNewQueueArguments(queueName, owner, originalArguments); - - final Map<String, Object> attributes = QueueArgumentsConverter.convertWireArgsToModel(createArgs); - attributes.put(Queue.NAME, queueName); - attributes.put(Queue.DURABLE, durable); - attributes.put(Queue.LIFETIME_POLICY, LifetimePolicy.PERMANENT); - - try - { - getConfiguredObject().createQueue(attributes); - } - catch (QueueExistsException qee) - { - throw new IllegalArgumentException("Queue with name '" + queueName + "' already exists"); - } - } - - - /** - * Some users have been abusing the owner field to store a queue description. As the owner field - * only makes sense if exclusive=true, and it is currently impossible to create an exclusive queue via - * the JMX interface, if the user specifies a owner, then we assume that they actually mean to pass a description. - */ - private Map<String, Object> processNewQueueArguments(String queueName, - String owner, Map<String, Object> arguments) - { - final Map<String, Object> argumentsCopy; - if (_moveNonExclusiveQueueOwnerToDescription && owner != null) - { - argumentsCopy = new HashMap<String, Object>(arguments == null ? new HashMap<String, Object>() : arguments); - if (!argumentsCopy.containsKey(QueueArgumentsConverter.X_QPID_DESCRIPTION)) - { - LOGGER.warn("Non-exclusive owner " + owner + " for new queue " + queueName + " moved to " + QueueArgumentsConverter.X_QPID_DESCRIPTION); - - argumentsCopy.put(QueueArgumentsConverter.X_QPID_DESCRIPTION, owner); - } - else - { - LOGGER.warn("Non-exclusive owner " + owner + " for new queue " + queueName + " ignored."); - } - } - else - { - argumentsCopy = arguments; - } - return argumentsCopy; - } - - @Override - public void deleteQueue( - @MBeanOperationParameter(name = ManagedQueue.TYPE, description = "Queue Name") String queueName) - throws IOException, JMException, MBeanException - { - VirtualHost<?,?,?> virtualHost = _virtualHostMBean.getVirtualHost(); - Queue<?> queue = virtualHost.getChildByName(Queue.class, queueName); - if (queue == null) - { - throw new OperationsException("No such queue \""+ queueName +"\""); - } - queue.delete(); - } - - @Override - public ObjectName getObjectName() throws MalformedObjectNameException - { - return getObjectNameForSingleInstanceMBean(); - } - - public boolean isStatisticsEnabled() - { - return true; - } - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporterTest.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporterTest.java deleted file mode 100644 index 67bee1e268..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporterTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import static javax.management.remote.JMXConnectionNotification.OPENED; -import static javax.management.remote.JMXConnectionNotification.CLOSED; -import static javax.management.remote.JMXConnectionNotification.FAILED; - -import static org.mockito.Matchers.argThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.verify; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; - -import javax.management.remote.JMXConnectionNotification; -import javax.security.auth.Subject; - -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.logging.LogMessage; -import org.apache.qpid.server.logging.MessageLogger; - -import junit.framework.TestCase; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.mockito.ArgumentMatcher; - -import java.util.Collections; - -public class ManagementLogonLogoffReporterTest extends TestCase -{ - private static final String TEST_JMX_UNIQUE_CONNECTION_ID = "jmxconnectionid1 jmxuser,group"; - private static final Subject TEST_USER = new Subject(false, Collections.singleton(new AuthenticatedPrincipal("jmxuser")), Collections.emptySet(), Collections.emptySet()); - - private ManagementLogonLogoffReporter _reporter; - private UsernameAccessor _usernameAccessor; - private MessageLogger _messageLogger; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - _usernameAccessor = mock(UsernameAccessor.class); - _messageLogger = mock(MessageLogger.class); - // Enable messaging so we can valid the generated strings - when(_messageLogger.isMessageEnabled(anyString())).thenReturn(true); - EventLogger eventLogger = new EventLogger(_messageLogger); - EventLoggerProvider provider = mock(EventLoggerProvider.class); - when(provider.getEventLogger()).thenReturn(eventLogger); - _reporter = new ManagementLogonLogoffReporter(provider, _usernameAccessor); - } - - public void testOpenedNotification() - { - when(_usernameAccessor.getSubjectConnectionId(TEST_JMX_UNIQUE_CONNECTION_ID)).thenReturn(TEST_USER); - JMXConnectionNotification openNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, OPENED); - - _reporter.handleNotification(openNotification, null); - - verify(_messageLogger).message(messageMatch("MNG-1007 : Open : User jmxuser", - "qpid.message.managementconsole.open")); - } - - private LogMessage messageMatch(final String message, final String hierarchy) - { - return argThat(new ArgumentMatcher<LogMessage>() - { - @Override - public boolean matches(final Object argument) - { - LogMessage actual = (LogMessage) argument; - return actual.getLogHierarchy().equals(hierarchy) && actual.toString().equals(message); - } - }); - } - - public void testClosedNotification() - { - when(_usernameAccessor.getSubjectConnectionId(TEST_JMX_UNIQUE_CONNECTION_ID)).thenReturn(TEST_USER); - JMXConnectionNotification closeNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, CLOSED); - - _reporter.handleNotification(closeNotification, null); - - verify(_messageLogger).message(messageMatch("MNG-1008 : Close : User jmxuser", "qpid.message.managementconsole.close")); - } - - public void tesNotifiedForLogOnTypeEvents() - { - JMXConnectionNotification openNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, OPENED); - JMXConnectionNotification closeNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, CLOSED); - JMXConnectionNotification failedNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, FAILED); - - assertTrue(_reporter.isNotificationEnabled(openNotification)); - assertTrue(_reporter.isNotificationEnabled(closeNotification)); - assertTrue(_reporter.isNotificationEnabled(failedNotification)); - - JMXConnectionNotification otherNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, "other"); - assertFalse(_reporter.isNotificationEnabled(otherNotification)); - } - - private JMXConnectionNotification createMockNotification(String connectionId, String notificationType) - { - JMXConnectionNotification notification = mock(JMXConnectionNotification.class); - when(notification.getConnectionId()).thenReturn(connectionId); - when(notification.getType()).thenReturn(notificationType); - return notification; - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/NoopManagedObjectRegistry.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/NoopManagedObjectRegistry.java deleted file mode 100644 index a2631bab7f..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/NoopManagedObjectRegistry.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import javax.management.JMException; - -public class NoopManagedObjectRegistry implements ManagedObjectRegistry -{ - public NoopManagedObjectRegistry() - { - } - - public void start() - { - } - - public void registerObject(ManagedObject managedObject) throws JMException - { - } - - public void unregisterObject(ManagedObject managedObject) throws JMException - { - } - - public void close() - { - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ConnectionMBeanTest.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ConnectionMBeanTest.java deleted file mode 100644 index 232094ce9e..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ConnectionMBeanTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.jmx.mbeans; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.Date; - -import javax.management.JMException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; - -import junit.framework.TestCase; - -import org.apache.qpid.management.common.mbeans.ManagedConnection; -import org.apache.qpid.server.jmx.ManagedObject; -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.model.Connection; -import org.apache.qpid.server.model.Session; - -public class ConnectionMBeanTest extends TestCase -{ - private ConnectionMBean _connectionMBean; - private Connection _mockConnection; - private VirtualHostMBean _mockVirtualHostMBean; - private ManagedObjectRegistry _mockManagedObjectRegistry; - - @Override - protected void setUp() throws Exception - { - _mockConnection = mock(Connection.class); - _mockVirtualHostMBean = mock(VirtualHostMBean.class); - - _mockManagedObjectRegistry = mock(ManagedObjectRegistry.class); - when(_mockVirtualHostMBean.getRegistry()).thenReturn(_mockManagedObjectRegistry); - - _connectionMBean = new ConnectionMBean(_mockConnection, _mockVirtualHostMBean); - } - - public void testMBeanRegistersItself() throws Exception - { - ConnectionMBean connectionMBean = new ConnectionMBean(_mockConnection, _mockVirtualHostMBean); - verify(_mockManagedObjectRegistry).registerObject(connectionMBean); - } - - public void testCloseConnection() throws Exception - { - _connectionMBean.closeConnection(); - verify(_mockConnection).delete(); - } - - public void testCommitTransactions() - { - try - { - _connectionMBean.commitTransactions(0); - fail("Exception not thrown"); - } - catch(JMException e) - { - assertTrue("Cause should be an UnsupportedOperationException", e.getCause() instanceof UnsupportedOperationException); - } - } - - public void testRollbackTransactions() - { - try - { - _connectionMBean.rollbackTransactions(0); - fail("Exception not thrown"); - } - catch(JMException e) - { - assertTrue("Cause should be an UnsupportedOperationException", e.getCause() instanceof UnsupportedOperationException); - } - } - - public void testChannelsWithSingleTransactionalSession() throws Exception - { - int channelId = 10; - int unacknowledgedMessages = 2; - long localTransactionBegins = 1; - boolean transactional = true; - boolean blocked = false; - - Session mockSession = createMockedSession(channelId, unacknowledgedMessages, localTransactionBegins, blocked); - - when(_mockConnection.getSessions()).thenReturn(Collections.singletonList(mockSession)); - - TabularData table = _connectionMBean.channels(); - assertEquals("Unexpected number of rows in table", 1, table.size()); - - final CompositeData row = table.get(new Integer[] {channelId} ); - assertChannelRow(row, channelId, unacknowledgedMessages, transactional, blocked); - } - - public void testChannelsWithSingleNonTransactionalSession() throws Exception - { - int channelId = 10; - int unacknowledgedMessages = 2; - long localTransactionBegins = 0; - boolean transactional = false; - boolean blocked = false; - - Session mockSession = createMockedSession(channelId, unacknowledgedMessages, localTransactionBegins, blocked); - - when(_mockConnection.getSessions()).thenReturn(Collections.singletonList(mockSession)); - - TabularData table = _connectionMBean.channels(); - assertEquals("Unexpected number of rows in table", 1, table.size()); - - final CompositeData row = table.get(new Integer[] {channelId} ); - assertChannelRow(row, channelId, unacknowledgedMessages, transactional, blocked); - } - - public void testChannelsWithSessionBlocked() throws Exception - { - int channelId = 10; - int unacknowledgedMessages = 2; - long localTransactionBegins = 0; - boolean transactional = false; - boolean blocked = true; - - Session mockSession = createMockedSession(channelId, unacknowledgedMessages, localTransactionBegins, blocked); - - when(_mockConnection.getSessions()).thenReturn(Collections.singletonList(mockSession)); - - TabularData table = _connectionMBean.channels(); - assertEquals("Unexpected number of rows in table", 1, table.size()); - - final CompositeData row = table.get(new Integer[] {channelId} ); - assertChannelRow(row, channelId, unacknowledgedMessages, transactional, blocked); - } - - public void testParentObjectIsVirtualHost() - { - ManagedObject parent = _connectionMBean.getParentObject(); - assertEquals(_mockVirtualHostMBean, parent); - } - - public void testGetObjectInstanceName() - { - String name = "[1] 127.0.0.1:5555"; - String quotedRemoteAddress = "\"" + name +"\""; - when(_mockConnection.getName()).thenReturn(name); - String objectInstanceName = _connectionMBean.getObjectInstanceName(); - assertEquals(quotedRemoteAddress, objectInstanceName); - } - - public void testGetAuthorizedId() throws Exception - { - assertAttribute("authorizedId", "testAuthorizedId", Connection.PRINCIPAL); - } - - public void testGetClientId() throws Exception - { - assertAttribute("clientId", "testClientId", Connection.CLIENT_ID); - } - - public void testGetVersion() throws Exception - { - assertAttribute("version", "testVersion", Connection.CLIENT_VERSION); - } - - public void testGetRemoteAddress() throws Exception - { - assertAttribute("remoteAddress", "testRemoteAddress", Connection.REMOTE_ADDRESS); - } - - public void testGetLastIoTime() - { - when(_mockConnection.getLastIoTime()).thenReturn(1l); - - - Object actualValue = _connectionMBean.getLastIoTime(); - assertEquals("Unexpected lastIoTime", new Date(1L), actualValue); - } - - public void testGetMaximumNumberOfChannels() throws Exception - { - assertAttribute("maximumNumberOfChannels", 10l, Connection.SESSION_COUNT_LIMIT); - } - - public void testIsStatisticsEnabledAlwaysTrue() throws Exception - { - assertTrue(_connectionMBean.isStatisticsEnabled()); - } - - private void assertAttribute(String jmxAttributeName, Object expectedValue, String underlyingAttributeName) throws Exception - { - when(_mockConnection.getAttribute(underlyingAttributeName)).thenReturn(expectedValue); - MBeanTestUtils.assertMBeanAttribute(_connectionMBean, jmxAttributeName, expectedValue); - } - - private void assertChannelRow(final CompositeData row, int channelId, int unacknowledgedMessages, boolean isTransactional, boolean flowBlocked) - { - assertNotNull("No row for channel id " + channelId, row); - assertEquals("Unexpected channel id", channelId, row.get(ManagedConnection.CHAN_ID)); - assertEquals("Unexpected transactional flag", isTransactional, row.get(ManagedConnection.TRANSACTIONAL)); - assertEquals("Unexpected unacknowledged message count", unacknowledgedMessages, row.get(ManagedConnection.UNACKED_COUNT)); - assertEquals("Unexpected flow blocked", flowBlocked, row.get(ManagedConnection.FLOW_BLOCKED)); - } - - private Session createMockedSession(int channelId, int unacknowledgedMessages, long localTransactionBegins, boolean blocked) - { - Session mockSession = mock(Session.class); - when(mockSession.getLocalTransactionBegins()).thenReturn(localTransactionBegins); - when(mockSession.getUnacknowledgedMessages()).thenReturn((long)unacknowledgedMessages); - - when(mockSession.getStatistics()).thenReturn(Collections.emptyMap()); - when(mockSession.getAttribute(Session.CHANNEL_ID)).thenReturn(channelId); - when(mockSession.getAttribute(Session.PRODUCER_FLOW_BLOCKED)).thenReturn(blocked); - return mockSession; - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ExchangeMBeanTest.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ExchangeMBeanTest.java deleted file mode 100644 index 9dc19c3290..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ExchangeMBeanTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.jmx.mbeans; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMap; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import javax.management.JMException; -import javax.management.OperationsException; - -import junit.framework.TestCase; - -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.model.Binding; -import org.apache.qpid.server.model.Exchange; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; - -public class ExchangeMBeanTest extends TestCase -{ - private static final String EXCHANGE_NAME = "EXCHANGE_NAME"; - private static final String EXCHANGE_TYPE = "EXCHANGE_TYPE"; - private static final String QUEUE1_NAME = "QUEUE1_NAME"; - private static final String QUEUE2_NAME = "QUEUE2_NAME"; - private static final String BINDING1 = "BINDING1"; - private static final String BINDING2 = "BINDING2"; - - private Exchange _mockExchange; - private VirtualHostMBean _mockVirtualHostMBean; - private ManagedObjectRegistry _mockManagedObjectRegistry; - private ExchangeMBean _exchangeMBean; - private Queue _mockQueue1; - private Queue _mockQueue2; - private Exchange _mockHeadersExchange; - - @Override - protected void setUp() throws Exception - { - _mockExchange = mock(Exchange.class); - when(_mockExchange.getName()).thenReturn(EXCHANGE_NAME); - when(_mockExchange.getType()).thenReturn(EXCHANGE_TYPE); - _mockVirtualHostMBean = mock(VirtualHostMBean.class); - - _mockManagedObjectRegistry = mock(ManagedObjectRegistry.class); - when(_mockVirtualHostMBean.getRegistry()).thenReturn(_mockManagedObjectRegistry); - - _mockQueue1 = createMockQueue(QUEUE1_NAME); - _mockQueue2 = createMockQueue(QUEUE2_NAME); - - VirtualHost mockVirtualHost = mock(VirtualHost.class); - when(mockVirtualHost.getQueues()).thenReturn(Arrays.asList(new Queue[] {_mockQueue1, _mockQueue2})); - when(mockVirtualHost.getChildByName(eq(Queue.class), eq(QUEUE1_NAME))).thenReturn(_mockQueue1); - when(mockVirtualHost.getChildByName(eq(Queue.class), eq(QUEUE2_NAME))).thenReturn(_mockQueue2); - - when(_mockExchange.getParent(VirtualHost.class)).thenReturn(mockVirtualHost); - - _exchangeMBean = new ExchangeMBean(_mockExchange, _mockVirtualHostMBean); - - _mockHeadersExchange = mock(Exchange.class); - when(_mockHeadersExchange.getType()).thenReturn(ExchangeMBean.HEADERS_EXCHANGE_TYPE); - when(_mockHeadersExchange.getParent(VirtualHost.class)).thenReturn(mockVirtualHost); - - } - - public void testExchangeName() - { - assertEquals(EXCHANGE_NAME, _exchangeMBean.getName()); - } - - public void testExchangeType() - { - assertEquals(EXCHANGE_TYPE, _exchangeMBean.getExchangeType()); - } - - public void testNonHeadersExchangeCreateNewBinding() throws Exception - { - _exchangeMBean.createNewBinding(QUEUE1_NAME, BINDING1); - verify(_mockExchange).createBinding(BINDING1, _mockQueue1, Collections.EMPTY_MAP, Collections.EMPTY_MAP); - } - - public void testCreateNewBindingWhereQueueIsUnknown() throws Exception - { - try - { - _exchangeMBean.createNewBinding("unknown", BINDING1); - } - catch (OperationsException oe) - { - // PASS - assertEquals("No such queue \"unknown\"", oe.getMessage()); - } - verify(_mockExchange, never()).createBinding(anyString(), any(Queue.class), anyMap(), anyMap()); - } - - public void testCreateNewBindingWithArguments() throws Exception - { - Map<String, Object> arguments = Collections.<String, Object>singletonMap("x-filter-jms-selector", "ID='test'"); - _exchangeMBean.createNewBinding(QUEUE1_NAME, BINDING1, arguments); - verify(_mockExchange).createBinding(BINDING1, _mockQueue1, arguments, Collections.<String, Object>emptyMap()); - } - - public void testRemoveBinding() throws Exception - { - Binding mockBinding1 = createBindingOnQueue(BINDING1, _mockQueue1); - Binding mockBinding2 = createBindingOnQueue(BINDING2, _mockQueue1); - when(_mockExchange.getBindings()).thenReturn(Arrays.asList(new Binding[] {mockBinding1, mockBinding2})); - - _exchangeMBean.removeBinding(QUEUE1_NAME, BINDING1); - verify(mockBinding1).delete(); - } - - public void testRemoveBindingWhereQueueIsUnknown() throws Exception - { - Binding mockBinding1 = createBindingOnQueue(BINDING1, _mockQueue1); - when(_mockExchange.getBindings()).thenReturn(Arrays.asList(new Binding[] {mockBinding1})); - - try - { - _exchangeMBean.removeBinding("unknown", BINDING1); - fail("Exception not thrown"); - } - catch (OperationsException oe) - { - // PASS - assertEquals("No such queue \"unknown\"", oe.getMessage()); - } - verify(mockBinding1, never()).delete(); - } - - public void testRemoveBindingWhereBindingNameIsUnknown() throws Exception - { - Binding mockBinding1 = createBindingOnQueue(BINDING1, _mockQueue1); - when(_mockExchange.getBindings()).thenReturn(Arrays.asList(new Binding[] {mockBinding1})); - - try - { - _exchangeMBean.removeBinding(QUEUE1_NAME, "unknown"); - fail("Exception not thrown"); - } - catch (OperationsException oe) - { - // PASS - assertEquals("No such binding \"unknown\" on queue \"" + QUEUE1_NAME + "\"", oe.getMessage()); - } - verify(mockBinding1, never()).delete(); - } - - public void testHeadersExchangeCreateNewBinding() throws Exception - { - String binding = "key1=binding1,key2=binding2"; - Map<String, Object> expectedBindingMap = new HashMap<String, Object>() - {{ - put("key1", "binding1"); - put("key2", "binding2"); - }}; - _exchangeMBean = new ExchangeMBean(_mockHeadersExchange, _mockVirtualHostMBean); - - _exchangeMBean.createNewBinding(QUEUE1_NAME, binding); - verify(_mockHeadersExchange).createBinding(binding, _mockQueue1, expectedBindingMap, Collections.EMPTY_MAP); - } - - public void testHeadersExchangeCreateNewBindingWithFieldWithoutValue() throws Exception - { - String binding = "key1=binding1,key2="; - Map<String, Object> expectedBindingMap = new HashMap<String, Object>() - {{ - put("key1", "binding1"); - put("key2", ""); - }}; - _exchangeMBean = new ExchangeMBean(_mockHeadersExchange, _mockVirtualHostMBean); - - _exchangeMBean.createNewBinding(QUEUE1_NAME, binding); - verify(_mockHeadersExchange).createBinding(binding, _mockQueue1, expectedBindingMap, Collections.EMPTY_MAP); - } - - public void testHeadersExchangeCreateNewBindingMalformed() throws Exception - { - String binding = "=binding1,="; - _exchangeMBean = new ExchangeMBean(_mockHeadersExchange, _mockVirtualHostMBean); - - try - { - _exchangeMBean.createNewBinding(QUEUE1_NAME, binding); - fail("Exception not thrown"); - } - catch (JMException e) - { - assertEquals("Format for headers binding should be \"<attribute1>=<value1>,<attribute2>=<value2>\"", e.getMessage()); - } - } - - private Binding createBindingOnQueue(String bindingName, Queue queue) - { - Binding mockBinding = mock(Binding.class); - when(mockBinding.getParent(Queue.class)).thenReturn(queue); - when(mockBinding.getName()).thenReturn(bindingName); - return mockBinding; - } - - private Queue createMockQueue(String queueName) - { - Queue mockQueue = mock(Queue.class); - when(mockQueue.getName()).thenReturn(queueName); - return mockQueue; - } - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/LoggingManagementMBeanTest.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/LoggingManagementMBeanTest.java deleted file mode 100644 index 0f33e78d03..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/LoggingManagementMBeanTest.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.server.jmx.mbeans; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.Matchers.anyString; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; - -import junit.framework.TestCase; - -import org.apache.qpid.management.common.mbeans.LoggingManagement; -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.logging.log4j.LoggingManagementFacade; - -public class LoggingManagementMBeanTest extends TestCase -{ - private static final String TEST_LEVEL1 = "LEVEL1"; - private static final String TEST_LEVEL2 = "LEVEL2"; - - private LoggingManagementMBean _loggingMBean; - private LoggingManagementFacade _mockLoggingFacade; - private ManagedObjectRegistry _mockManagedObjectRegistry; - - @Override - protected void setUp() throws Exception - { - _mockLoggingFacade = mock(LoggingManagementFacade.class); - final List<String> listOfLevels = new ArrayList<String>() - {{ - add(TEST_LEVEL1); - add(TEST_LEVEL2); - }}; - when(_mockLoggingFacade.getAvailableLoggerLevels()).thenReturn(listOfLevels); - - _mockManagedObjectRegistry = mock(ManagedObjectRegistry.class); - - _loggingMBean = new LoggingManagementMBean(_mockLoggingFacade, _mockManagedObjectRegistry); - } - - public void testMBeanRegistersItself() throws Exception - { - LoggingManagementMBean connectionMBean = new LoggingManagementMBean(_mockLoggingFacade, _mockManagedObjectRegistry); - verify(_mockManagedObjectRegistry).registerObject(connectionMBean); - } - - public void testLog4jLogWatchInterval() throws Exception - { - final Integer value = 5000; - when(_mockLoggingFacade.getLog4jLogWatchInterval()).thenReturn(value); - - assertEquals("Unexpected watch interval",value, _loggingMBean.getLog4jLogWatchInterval()); - } - - public void testGetAvailableLoggerLevels() throws Exception - { - String[] actualLevels = _loggingMBean.getAvailableLoggerLevels(); - assertEquals(3, actualLevels.length); - assertEquals(TEST_LEVEL1, actualLevels[0]); - assertEquals(TEST_LEVEL2, actualLevels[1]); - assertEquals(LoggingManagementMBean.INHERITED_PSUEDO_LOG_LEVEL, actualLevels[2]); - } - - public void testViewEffectiveRuntimeLoggerLevels() throws Exception - { - Map<String, String> loggerLevels = new TreeMap<String, String>(); - loggerLevels.put("a.b.D", TEST_LEVEL2); - loggerLevels.put("a.b.C", TEST_LEVEL1); - loggerLevels.put("a.b.c.E", TEST_LEVEL2); - - when(_mockLoggingFacade.retrieveRuntimeLoggersLevels()).thenReturn(loggerLevels ); - - TabularData table = _loggingMBean.viewEffectiveRuntimeLoggerLevels(); - assertEquals(3, table.size()); - - final CompositeData row1 = table.get(new String[] {"a.b.C"} ); - final CompositeData row2 = table.get(new String[] {"a.b.D"} ); - final CompositeData row3 = table.get(new String[] {"a.b.c.E"} ); - assertChannelRow(row1, "a.b.C", TEST_LEVEL1); - assertChannelRow(row2, "a.b.D", TEST_LEVEL2); - assertChannelRow(row3, "a.b.c.E", TEST_LEVEL2); - } - - public void testGetRuntimeRootLoggerLevel() throws Exception - { - when(_mockLoggingFacade.retrieveRuntimeRootLoggerLevel()).thenReturn(TEST_LEVEL1); - - assertEquals(TEST_LEVEL1, _loggingMBean.getRuntimeRootLoggerLevel()); - } - - public void testSetRuntimeRootLoggerLevel() throws Exception - { - _loggingMBean.setRuntimeRootLoggerLevel(TEST_LEVEL1); - verify(_mockLoggingFacade).setRuntimeRootLoggerLevel(TEST_LEVEL1); - } - - public void testSetRuntimeRootLoggerLevelWhenLoggingLevelUnknown() throws Exception - { - boolean result = _loggingMBean.setRuntimeRootLoggerLevel("unknown"); - assertFalse(result); - verify(_mockLoggingFacade, never()).setRuntimeRootLoggerLevel("unknown"); - } - - public void testSetRuntimeRootLoggerLevelWhenLoggingLevelInherited() throws Exception - { - boolean result = _loggingMBean.setRuntimeRootLoggerLevel(LoggingManagementMBean.INHERITED_PSUEDO_LOG_LEVEL); - assertFalse(result); - verify(_mockLoggingFacade, never()).setRuntimeRootLoggerLevel(anyString()); - } - - public void testSetRuntimeLoggerLevel() throws Exception - { - _loggingMBean.setRuntimeLoggerLevel("a.b.c.D", TEST_LEVEL1); - verify(_mockLoggingFacade).setRuntimeLoggerLevel("a.b.c.D", TEST_LEVEL1); - } - - public void testSetRuntimeLoggerLevelWhenLoggingLevelUnknown() throws Exception - { - boolean result = _loggingMBean.setRuntimeLoggerLevel("a.b.c.D", "unknown"); - assertFalse(result); - verify(_mockLoggingFacade, never()).setRuntimeLoggerLevel(anyString(), anyString()); - } - - public void testSetRuntimeLoggerLevelWhenLoggingLevelInherited() throws Exception - { - boolean result = _loggingMBean.setRuntimeLoggerLevel("a.b.c.D", LoggingManagementMBean.INHERITED_PSUEDO_LOG_LEVEL); - assertTrue(result); - verify(_mockLoggingFacade).setRuntimeLoggerLevel("a.b.c.D", null); - } - - public void testViewEffectiveConfigFileLoggerLevels() throws Exception - { - Map<String, String> loggerLevels = new TreeMap<String, String>(); - loggerLevels.put("a.b.D", "level2"); - loggerLevels.put("a.b.C", TEST_LEVEL1); - loggerLevels.put("a.b.c.E", "level2"); - - when(_mockLoggingFacade.retrieveConfigFileLoggersLevels()).thenReturn(loggerLevels ); - - TabularData table = _loggingMBean.viewConfigFileLoggerLevels(); - assertEquals(3, table.size()); - - final CompositeData row1 = table.get(new String[] {"a.b.C"} ); - final CompositeData row2 = table.get(new String[] {"a.b.D"} ); - final CompositeData row3 = table.get(new String[] {"a.b.c.E"} ); - assertChannelRow(row1, "a.b.C", TEST_LEVEL1); - assertChannelRow(row2, "a.b.D", TEST_LEVEL2); - assertChannelRow(row3, "a.b.c.E", TEST_LEVEL2); - } - - public void testGetConfigFileRootLoggerLevel() throws Exception - { - when(_mockLoggingFacade.retrieveConfigFileRootLoggerLevel()).thenReturn(TEST_LEVEL1); - - assertEquals(TEST_LEVEL1, _loggingMBean.getConfigFileRootLoggerLevel()); - } - - public void testSetConfigFileRootLoggerLevel() throws Exception - { - when(_mockLoggingFacade.getAvailableLoggerLevels()).thenReturn(Collections.singletonList(TEST_LEVEL1)); - _loggingMBean.setConfigFileRootLoggerLevel(TEST_LEVEL1); - verify(_mockLoggingFacade).setConfigFileRootLoggerLevel(TEST_LEVEL1); - } - - public void testSetConfigFileRootLoggerLevelWhenLoggingLevelUnknown() throws Exception - { - when(_mockLoggingFacade.getAvailableLoggerLevels()).thenReturn(Collections.singletonList(TEST_LEVEL1)); - boolean result = _loggingMBean.setConfigFileRootLoggerLevel("unknown"); - assertFalse(result); - verify(_mockLoggingFacade, never()).setConfigFileRootLoggerLevel("unknown"); - } - - public void testSetConfigFileRootLoggerLevelWhenLoggingLevelInherited() throws Exception - { - when(_mockLoggingFacade.getAvailableLoggerLevels()).thenReturn(Collections.singletonList(TEST_LEVEL1)); - boolean result = _loggingMBean.setConfigFileRootLoggerLevel(LoggingManagementMBean.INHERITED_PSUEDO_LOG_LEVEL); - assertFalse(result); - verify(_mockLoggingFacade, never()).setConfigFileRootLoggerLevel(anyString()); - } - - public void testSetConfigFileLoggerLevel() throws Exception - { - when(_mockLoggingFacade.getAvailableLoggerLevels()).thenReturn(Collections.singletonList(TEST_LEVEL1)); - _loggingMBean.setConfigFileLoggerLevel("a.b.c.D", TEST_LEVEL1); - verify(_mockLoggingFacade).setConfigFileLoggerLevel("a.b.c.D", TEST_LEVEL1); - } - - public void testSetConfigFileLoggerLevelWhenLoggingLevelUnknown() throws Exception - { - when(_mockLoggingFacade.getAvailableLoggerLevels()).thenReturn(Collections.singletonList(TEST_LEVEL1)); - boolean result = _loggingMBean.setConfigFileLoggerLevel("a.b.c.D", "unknown"); - assertFalse(result); - verify(_mockLoggingFacade, never()).setConfigFileLoggerLevel("a.b.c.D", "unknown"); - } - - public void testSetConfigFileLoggerLevelWhenLoggingLevelInherited() throws Exception - { - when(_mockLoggingFacade.getAvailableLoggerLevels()).thenReturn(Collections.singletonList(TEST_LEVEL1)); - boolean result = _loggingMBean.setConfigFileLoggerLevel("a.b.c.D", LoggingManagementMBean.INHERITED_PSUEDO_LOG_LEVEL); - assertTrue(result); - verify(_mockLoggingFacade).setConfigFileLoggerLevel("a.b.c.D", null); - } - - public void testReloadConfigFile() throws Exception - { - _loggingMBean.reloadConfigFile(); - - verify(_mockLoggingFacade).reload(); - } - - private void assertChannelRow(final CompositeData row, String logger, String level) - { - assertNotNull("No row for " + logger, row); - assertEquals("Unexpected logger name", logger, row.get(LoggingManagement.LOGGER_NAME)); - assertEquals("Unexpected level", level, row.get(LoggingManagement.LOGGER_LEVEL)); - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/MBeanTestUtils.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/MBeanTestUtils.java deleted file mode 100644 index 5f913e5f33..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/MBeanTestUtils.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx.mbeans; - -import junit.framework.TestCase; - -import org.apache.commons.beanutils.PropertyUtils; -import org.apache.qpid.server.jmx.DefaultManagedObject; - -public class MBeanTestUtils -{ - - public static void assertMBeanAttribute(DefaultManagedObject managedObject, String jmxAttributeName, Object expectedValue) throws Exception - { - Object actualValue = PropertyUtils.getSimpleProperty(managedObject, jmxAttributeName); - TestCase.assertEquals("Attribute " + jmxAttributeName + " has unexpected value", expectedValue, actualValue); - } - - public static void setMBeanAttribute(DefaultManagedObject managedObject, String jmxAttributeName, Object newValue) throws Exception - { - PropertyUtils.setSimpleProperty(managedObject, jmxAttributeName, newValue); - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/QueueMBeanTest.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/QueueMBeanTest.java deleted file mode 100644 index 671920c33d..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/QueueMBeanTest.java +++ /dev/null @@ -1,494 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.server.jmx.mbeans; - -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isNull; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.Collections; - -import javax.management.ListenerNotFoundException; -import javax.management.Notification; -import javax.management.NotificationListener; -import javax.management.OperationsException; -import javax.management.openmbean.CompositeDataSupport; - -import org.mockito.ArgumentMatcher; -import org.mockito.Matchers; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import org.apache.qpid.management.common.mbeans.ManagedQueue; -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.jmx.mbeans.QueueMBean.GetMessageVisitor; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Exchange; -import org.apache.qpid.server.model.ExclusivityPolicy; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.queue.NotificationCheck; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.test.utils.QpidTestCase; - -public class QueueMBeanTest extends QpidTestCase -{ - private static final String QUEUE_NAME = "QUEUE_NAME"; - private static final String QUEUE_DESCRIPTION = "QUEUE_DESCRIPTION"; - private static final String QUEUE_TYPE = "QUEUE_TYPE"; - private static final String QUEUE_ALTERNATE_EXCHANGE = "QUEUE_ALTERNATE_EXCHANGE"; - - private Queue _mockQueue; - private VirtualHostMBean _mockVirtualHostMBean; - private ManagedObjectRegistry _mockManagedObjectRegistry; - private QueueMBean _queueMBean; - - @Override - protected void setUp() throws Exception - { - super.setUp(); - _mockQueue = mock(Queue.class); - when(_mockQueue.getName()).thenReturn(QUEUE_NAME); - _mockVirtualHostMBean = mock(VirtualHostMBean.class); - - _mockManagedObjectRegistry = mock(ManagedObjectRegistry.class); - when(_mockVirtualHostMBean.getRegistry()).thenReturn(_mockManagedObjectRegistry); - - _queueMBean = new QueueMBean(_mockQueue, _mockVirtualHostMBean); - } - - public void testQueueName() - { - assertEquals(QUEUE_NAME, _queueMBean.getName()); - } - - /********** Statistics **********/ - - public void testGetMessageCount() throws Exception - { - when(_mockQueue.getQueueDepthMessages()).thenReturn(1000); - assertStatistic("messageCount", 1000); - } - - public void testGetReceivedMessageCount() throws Exception - { - when(_mockQueue.getTotalEnqueuedMessages()).thenReturn(1000l); - assertStatistic("receivedMessageCount", 1000l); - } - - public void testQueueDepth() throws Exception - { - when(_mockQueue.getQueueDepthBytes()).thenReturn(4096l); - assertStatistic("queueDepth", 4096l); - } - - public void testActiveConsumerCount() throws Exception - { - when(_mockQueue.getConsumerCountWithCredit()).thenReturn(3); - assertStatistic("activeConsumerCount", 3); - } - - public void testConsumerCount() throws Exception - { - when(_mockQueue.getConsumerCount()).thenReturn(3); - assertStatistic("consumerCount", 3); - } - - public void testOldestMessageAge() throws Exception - { - when(_mockQueue.getOldestMessageAge()).thenReturn(3l); - assertStatistic("oldestMessageAge", 3l); - } - - /********** Simple Attributes **********/ - - public void testGetQueueDescription() throws Exception - { - when(_mockQueue.getDescription()).thenReturn(QUEUE_DESCRIPTION); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "description", QUEUE_DESCRIPTION); - } - - public void testSetQueueDescription() throws Exception - { - when(_mockQueue.getDescription()).thenReturn("descriptionold"); - - MBeanTestUtils.setMBeanAttribute(_queueMBean, "description", "descriptionnew"); - - verify(_mockQueue).setAttribute(Queue.DESCRIPTION, "descriptionold", "descriptionnew"); - } - - public void testQueueType() throws Exception - { - when(_mockQueue.getType()).thenReturn(QUEUE_TYPE); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "queueType", QUEUE_TYPE); - } - - public void testMaximumDeliveryCount() throws Exception - { - when(_mockQueue.getMaximumDeliveryAttempts()).thenReturn(5); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "maximumDeliveryCount", 5); - } - - public void testOwner() throws Exception - { - when(_mockQueue.getOwner()).thenReturn("testOwner"); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "owner", "testOwner"); - } - - public void testIsDurable() throws Exception - { - when(_mockQueue.isDurable()).thenReturn(true); - assertTrue(_queueMBean.isDurable()); - } - - public void testIsNotDurable() throws Exception - { - when(_mockQueue.isDurable()).thenReturn(false); - assertFalse(_queueMBean.isDurable()); - } - - public void testIsAutoDelete() throws Exception - { - when(_mockQueue.getLifetimePolicy()).thenReturn(LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS); - assertTrue(_queueMBean.isAutoDelete()); - } - - public void testIsNotAutoDelete() throws Exception - { - when(_mockQueue.getLifetimePolicy()).thenReturn(LifetimePolicy.PERMANENT); - assertFalse(_queueMBean.isAutoDelete()); - } - - public void testGetMaximumMessageAge() throws Exception - { - when(_mockQueue.getAlertThresholdMessageAge()).thenReturn(10000l); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "maximumMessageAge", 10000l); - } - - public void testSetMaximumMessageAge() throws Exception - { - when(_mockQueue.getAlertThresholdMessageAge()).thenReturn(1000l); - - MBeanTestUtils.setMBeanAttribute(_queueMBean, "maximumMessageAge", 10000l); - - verify(_mockQueue).setAttribute(Queue.ALERT_THRESHOLD_MESSAGE_AGE, 1000l, 10000l); - } - - public void testGetMaximumMessageSize() throws Exception - { - when(_mockQueue.getAlertThresholdMessageSize()).thenReturn(1024l); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "maximumMessageSize", 1024l); - } - - public void testSetMaximumMessageSize() throws Exception - { - when(_mockQueue.getAlertThresholdMessageSize()).thenReturn(1024l); - - MBeanTestUtils.setMBeanAttribute(_queueMBean, "maximumMessageSize", 2048l); - - verify(_mockQueue).setAttribute(Queue.ALERT_THRESHOLD_MESSAGE_SIZE, 1024l, 2048l); - } - - public void testGetMaximumMessageCount() throws Exception - { - when(_mockQueue.getAlertThresholdQueueDepthMessages()).thenReturn(5000l); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "maximumMessageCount", 5000l); - } - - public void testSetMaximumMessageCount() throws Exception - { - when(_mockQueue.getAlertThresholdQueueDepthMessages()).thenReturn(4000l); - - MBeanTestUtils.setMBeanAttribute(_queueMBean, "maximumMessageCount", 5000l); - - verify(_mockQueue).setAttribute(Queue.ALERT_THRESHOLD_QUEUE_DEPTH_MESSAGES, 4000l, 5000l); - } - - public void testGetMaximumQueueDepth() throws Exception - { - when(_mockQueue.getAlertThresholdQueueDepthBytes()).thenReturn(1048576l); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "maximumQueueDepth", 1048576l); - } - - public void testSetMaximumQueueDepth() throws Exception - { - when(_mockQueue.getAlertThresholdQueueDepthBytes()).thenReturn(1048576l); - - MBeanTestUtils.setMBeanAttribute(_queueMBean, "maximumQueueDepth", 2097152l); - - verify(_mockQueue).setAttribute(Queue.ALERT_THRESHOLD_QUEUE_DEPTH_BYTES, 1048576l, 2097152l); - } - - public void testGetCapacity() throws Exception - { - when(_mockQueue.getQueueFlowControlSizeBytes()).thenReturn(1048576l); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "capacity", 1048576l); - } - - public void testSetCapacity() throws Exception - { - when(_mockQueue.getQueueFlowControlSizeBytes()).thenReturn(1048576l); - - MBeanTestUtils.setMBeanAttribute(_queueMBean, "capacity", 2097152l); - - verify(_mockQueue).setAttribute(Queue.QUEUE_FLOW_CONTROL_SIZE_BYTES, 1048576l, 2097152l); - } - - public void testGetFlowResumeCapacity() throws Exception - { - when(_mockQueue.getQueueFlowResumeSizeBytes()).thenReturn(1048576l); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "flowResumeCapacity", 1048576l); - } - - public void testSetFlowResumeCapacity() throws Exception - { - when(_mockQueue.getQueueFlowResumeSizeBytes()).thenReturn(1048576l); - - MBeanTestUtils.setMBeanAttribute(_queueMBean, "flowResumeCapacity", 2097152l); - - verify(_mockQueue).setAttribute(Queue.QUEUE_FLOW_RESUME_SIZE_BYTES, 1048576l, 2097152l); - } - - - /********** Other attributes **********/ - - - public void testIsExclusive() throws Exception - { - when(_mockQueue.getExclusive()).thenReturn(ExclusivityPolicy.CONTAINER); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "exclusive", true); - } - - public void testIsNotExclusive() throws Exception - { - when(_mockQueue.getExclusive()).thenReturn(ExclusivityPolicy.NONE); - MBeanTestUtils.assertMBeanAttribute(_queueMBean, "exclusive", false); - } - - public void testSetExclusive() throws Exception - { - when(_mockQueue.getExclusive()).thenReturn(ExclusivityPolicy.NONE); - - MBeanTestUtils.setMBeanAttribute(_queueMBean, "exclusive", Boolean.TRUE); - - verify(_mockQueue).setAttribute(Queue.EXCLUSIVE, ExclusivityPolicy.NONE, ExclusivityPolicy.CONTAINER); - - } - - public void testGetAlternateExchange() - { - Exchange mockAlternateExchange = mock(Exchange.class); - when(mockAlternateExchange.getName()).thenReturn(QUEUE_ALTERNATE_EXCHANGE); - - when(_mockQueue.getAlternateExchange()).thenReturn(mockAlternateExchange); - - assertEquals(QUEUE_ALTERNATE_EXCHANGE, _queueMBean.getAlternateExchange()); - } - - public void testGetAlternateExchangeWhenQueueHasNone() - { - when(_mockQueue.getAlternateExchange()).thenReturn(null); - - assertNull(_queueMBean.getAlternateExchange()); - } - - public void testSetAlternateExchange() throws Exception - { - Exchange mockExchange1 = mock(Exchange.class); - when(mockExchange1.getName()).thenReturn("exchange1"); - - Exchange mockExchange2 = mock(Exchange.class); - when(mockExchange2.getName()).thenReturn("exchange2"); - - Exchange mockExchange3 = mock(Exchange.class); - when(mockExchange3.getName()).thenReturn("exchange3"); - - VirtualHost mockVirtualHost = mock(VirtualHost.class); - when(mockVirtualHost.getExchanges()).thenReturn(Arrays.asList(new Exchange[] {mockExchange1, mockExchange2, mockExchange3})); - when(_mockQueue.getParent(VirtualHost.class)).thenReturn(mockVirtualHost); - - _queueMBean.setAlternateExchange("exchange2"); - verify(_mockQueue).setAttributes(Collections.<String,Object>singletonMap(Queue.ALTERNATE_EXCHANGE, "exchange2")); - } - - public void testSetAlternateExchangeWithUnknownExchangeName() throws Exception - { - Exchange mockExchange = mock(Exchange.class); - when(mockExchange.getName()).thenReturn("exchange1"); - - VirtualHost mockVirtualHost = mock(VirtualHost.class); - when(mockVirtualHost.getExchanges()).thenReturn(Collections.singletonList(mockExchange)); - when(_mockQueue.getParent(VirtualHost.class)).thenReturn(mockVirtualHost); - doThrow(new IllegalArgumentException()).when(_mockQueue).setAttributes( - eq(Collections.<String, Object>singletonMap(Queue.ALTERNATE_EXCHANGE, "notknown"))); - try - { - _queueMBean.setAlternateExchange("notknown"); - fail("Exception not thrown"); - } - catch(OperationsException oe) - { - // PASS - } - } - - public void testRemoveAlternateExchange() throws Exception - { - _queueMBean.setAlternateExchange(""); - verify(_mockQueue).setAttributes(Collections.singletonMap(Queue.ALTERNATE_EXCHANGE, null)); - } - - /********** Operations **********/ - - /********** Notifications **********/ - - public void testNotificationListenerCalled() throws Exception - { - NotificationListener listener = mock(NotificationListener.class); - _queueMBean.addNotificationListener(listener, null, null); - - NotificationCheck notification = mock(NotificationCheck.class); - String notificationMsg = "Test notification message"; - - _queueMBean.notifyClients(notification, _mockQueue, notificationMsg); - verify(listener).handleNotification(isNotificationWithMessage(notificationMsg), - isNull()); - } - - public void testAddRemoveNotificationListener() throws Exception - { - NotificationListener listener1 = mock(NotificationListener.class); - _queueMBean.addNotificationListener(listener1, null, null); - _queueMBean.removeNotificationListener(listener1); - } - - public void testRemoveUnknownNotificationListener() throws Exception - { - NotificationListener listener1 = mock(NotificationListener.class); - try - { - _queueMBean.removeNotificationListener(listener1); - fail("Exception not thrown"); - } - catch (ListenerNotFoundException e) - { - // PASS - } - } - - private Notification isNotificationWithMessage(final String expectedMessage) - { - return argThat( new ArgumentMatcher<Notification>() - { - @Override - public boolean matches(Object argument) - { - Notification actual = (Notification) argument; - return actual.getMessage().endsWith(expectedMessage); - } - }); - } - - private void assertStatistic(String jmxAttributeName, Object expectedValue) throws Exception - { - MBeanTestUtils.assertMBeanAttribute(_queueMBean, jmxAttributeName, expectedValue); - } - - public void testViewMessageContent() throws Exception - { - viewMessageContentTestImpl(16L, 1000, 1000); - } - - public void testViewMessageContentWithMissingPayload() throws Exception - { - viewMessageContentTestImpl(16L, 1000, 0); - } - - private void viewMessageContentTestImpl(final long messageNumber, - final int messageSize, - final int messageContentSize) throws Exception - { - final byte[] content = new byte[messageContentSize]; - - //mock message and queue entry to return a given message size, and have a given content - final ServerMessage<?> serverMessage = mock(ServerMessage.class); - when(serverMessage.getMessageNumber()).thenReturn(messageNumber); - when(serverMessage.getSize()).thenReturn((long)messageSize); - doAnswer(new Answer<Object>() - { - public Object answer(InvocationOnMock invocation) - { - Object[] args = invocation.getArguments(); - - //verify the arg types / expected values - assertEquals(2, args.length); - assertTrue(args[0] instanceof ByteBuffer); - assertTrue(args[1] instanceof Integer); - - ByteBuffer dest = (ByteBuffer) args[0]; - int offset = (Integer) args[1]; - assertEquals(0, offset); - - dest.put(content); - return messageContentSize; - } - }).when(serverMessage).getContent(Matchers.any(ByteBuffer.class), Matchers.anyInt()); - - final QueueEntry entry = mock(QueueEntry.class); - when(entry.getMessage()).thenReturn(serverMessage); - - //mock the queue.visit() method to ensure we match the mock message - doAnswer(new Answer<Object>() - { - public Object answer(InvocationOnMock invocation) - { - Object[] args = invocation.getArguments(); - GetMessageVisitor visitor = (GetMessageVisitor) args[0]; - visitor.visit(entry); - return null; - } - }).when(_mockQueue).visit(Matchers.any(GetMessageVisitor.class)); - - //now retrieve the content and verify its size - CompositeDataSupport comp = (CompositeDataSupport) _queueMBean.viewMessageContent(messageNumber); - assertNotNull(comp); - byte[] data = (byte[]) comp.get(ManagedQueue.CONTENT); - assertEquals(messageSize, data.length); - } - - public void testGetMessageGroupKey() - { - when(_mockQueue.getMessageGroupKey()).thenReturn(getTestName()); - assertEquals("Unexpected message group key", getTestName(), _queueMBean.getMessageGroupKey()); - } - - public void testIsSharedMessageGroup() - { - when(_mockQueue.isMessageGroupSharedGroups()).thenReturn(true); - assertEquals("Unexpected message group sharing", true, _queueMBean.isMessageGroupSharedGroups()); - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ServerInformationMBeanTest.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ServerInformationMBeanTest.java deleted file mode 100644 index d83f2b98b5..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ServerInformationMBeanTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx.mbeans; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.model.Broker; - -import junit.framework.TestCase; - -public class ServerInformationMBeanTest extends TestCase -{ - private ManagedObjectRegistry _mockManagedObjectRegistry; - private Broker _mockBroker; - private ServerInformationMBean _mbean; - - @Override - protected void setUp() throws Exception - { - _mockManagedObjectRegistry = mock(ManagedObjectRegistry.class); - _mockBroker = mock(Broker.class); - - _mbean = new ServerInformationMBean(_mockManagedObjectRegistry, _mockBroker); - } - - public void testMBeanRegistersItself() throws Exception - { - ServerInformationMBean mbean = new ServerInformationMBean(_mockManagedObjectRegistry, _mockBroker); - verify(_mockManagedObjectRegistry).registerObject(mbean); - } - - /********** Statistics **********/ - - public void testGetMessageCount() throws Exception - { - when(_mockBroker.getBytesOut()).thenReturn(16384l); - assertStatistic("totalDataDelivered", 16384l); - } - - /********** Attributes **********/ - - public void testBuildVersion() throws Exception - { - assertAttribute("buildVersion", "0.0.1", Broker.BUILD_VERSION); - } - - public void testProductVersion() throws Exception - { - assertAttribute("productVersion", "0.0.1", Broker.PRODUCT_VERSION); - } - - /********** Other Attributes **********/ - - public void testIsStatisticsEnabled() throws Exception - { - assertTrue("isStatisticsEnabled", _mbean.isStatisticsEnabled()); - } - - private void assertStatistic(String jmxAttributeName, Object expectedValue) throws Exception - { - MBeanTestUtils.assertMBeanAttribute(_mbean, jmxAttributeName, expectedValue); - } - - private void assertAttribute(String jmxAttributeName, Object expectedValue, String underlyingAttributeName) throws Exception - { - when(_mockBroker.getAttribute(underlyingAttributeName)).thenReturn(expectedValue); - MBeanTestUtils.assertMBeanAttribute(_mbean, jmxAttributeName, expectedValue); - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/UserManagementMBeanTest.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/UserManagementMBeanTest.java deleted file mode 100644 index 5a21bdab7d..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/UserManagementMBeanTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.jmx.mbeans; - -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.Collections; -import java.util.Map; - -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; -import javax.security.auth.login.AccountNotFoundException; - -import junit.framework.TestCase; - -import org.apache.qpid.management.common.mbeans.UserManagement; -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.model.PasswordCredentialManagingAuthenticationProvider; - -public class UserManagementMBeanTest extends TestCase -{ - private UserManagementMBean _userManagement; - private ManagedObjectRegistry _mockRegistry; - private PasswordCredentialManagingAuthenticationProvider _mockProvider; - - private static final String TEST_USERNAME = "testuser"; - private static final String TEST_PASSWORD = "password"; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _mockProvider = mock(PasswordCredentialManagingAuthenticationProvider.class); - _mockRegistry = mock(ManagedObjectRegistry.class); - _userManagement = new UserManagementMBean(_mockProvider, _mockRegistry); - } - - public void testMBeanRegistersItself() throws Exception - { - UserManagementMBean userManagementMBean = new UserManagementMBean(_mockProvider, _mockRegistry); - verify(_mockRegistry).registerObject(userManagementMBean); - } - - public void testDeleteUser() throws Exception - { - boolean deleteSuccess = _userManagement.deleteUser(TEST_USERNAME); - assertTrue("Expected successful delete", deleteSuccess); - - verify(_mockProvider).deleteUser(TEST_USERNAME); - } - - public void testDeleteUserWhereUserDoesNotExist() throws Exception - { - doThrow(AccountNotFoundException.class).when(_mockProvider).deleteUser(TEST_USERNAME); - - boolean deleteSuccess = _userManagement.deleteUser(TEST_USERNAME); - assertFalse("Expected unsuccessful delete", deleteSuccess); - } - - public void testCreateUser() throws Exception - { - when(_mockProvider.createUser(TEST_USERNAME, TEST_PASSWORD, null)).thenReturn(true); - - boolean createSuccess = _userManagement.createUser(TEST_USERNAME, TEST_PASSWORD); - assertTrue(createSuccess); - } - - public void testCreateUserWhereUserAlreadyExists() - { - when(_mockProvider.createUser(TEST_USERNAME, TEST_PASSWORD, null)).thenReturn(false); - - boolean createSuccess = _userManagement.createUser(TEST_USERNAME, TEST_PASSWORD); - assertFalse(createSuccess); - } - - public void testSetPassword() throws Exception - { - boolean setPasswordSuccess = _userManagement.setPassword(TEST_USERNAME, TEST_PASSWORD); - assertTrue(setPasswordSuccess); - - assertTrue("Set password should return true to flag successful change", setPasswordSuccess); - - verify(_mockProvider).setPassword(TEST_USERNAME, TEST_PASSWORD); - } - - public void testSetPasswordWhereUserDoesNotExist() throws Exception - { - doThrow(AccountNotFoundException.class).when(_mockProvider).setPassword(TEST_USERNAME, TEST_PASSWORD); - - boolean setPasswordSuccess = _userManagement.setPassword(TEST_USERNAME, TEST_PASSWORD); - - assertFalse("Set password should return false to flag unsuccessful change", setPasswordSuccess); - } - - public void testReload() throws Exception - { - boolean reloadSuccess = _userManagement.reloadData(); - - assertTrue("Reload should return true to flag successful update", reloadSuccess); - - verify(_mockProvider).reload(); - } - - public void testReloadFails() throws Exception - { - doThrow(IOException.class).when(_mockProvider).reload(); - - boolean reloadSuccess = _userManagement.reloadData(); - - assertFalse("Expected reload to fail", reloadSuccess); - } - - public void testViewUsers() throws Exception - { - Map<String,String> args = Collections.emptyMap(); - when(_mockProvider.getUsers()).thenReturn(Collections.singletonMap(TEST_USERNAME, args)); - - TabularData userList = _userManagement.viewUsers(); - - assertNotNull(userList); - assertEquals("Unexpected number of users in user list", 1, userList.size()); - assertTrue(userList.containsKey(new Object[]{TEST_USERNAME})); - - // Check the deprecated read, write and admin items continue to exist but return false. - CompositeData userRec = userList.get(new Object[]{TEST_USERNAME}); - assertTrue(userRec.containsKey(UserManagement.RIGHTS_READ_ONLY)); - assertEquals(false, userRec.get(UserManagement.RIGHTS_READ_ONLY)); - assertEquals(false, userRec.get(UserManagement.RIGHTS_READ_WRITE)); - assertTrue(userRec.containsKey(UserManagement.RIGHTS_READ_WRITE)); - assertTrue(userRec.containsKey(UserManagement.RIGHTS_ADMIN)); - assertEquals(false, userRec.get(UserManagement.RIGHTS_ADMIN)); - } -} diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/VirtualHostManagerMBeanTest.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/VirtualHostManagerMBeanTest.java deleted file mode 100644 index c8c27d386c..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/VirtualHostManagerMBeanTest.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx.mbeans; - -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.doThrow; - -import java.util.Collections; -import java.util.Map; - -import javax.management.OperationsException; - -import junit.framework.TestCase; -import org.mockito.ArgumentCaptor; -import org.mockito.ArgumentMatcher; - -import org.apache.qpid.server.jmx.ManagedObjectRegistry; -import org.apache.qpid.server.model.Exchange; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.queue.QueueArgumentsConverter; -import org.apache.qpid.server.virtualhost.QueueExistsException; - -public class VirtualHostManagerMBeanTest extends TestCase -{ - private static final String TEST_QUEUE_NAME = "QUEUE_NAME"; - private static final String TEST_EXCHANGE_NAME = "EXCHANGE_NAME"; - private static final String TEST_OWNER = "OWNER"; - private static final String TEST_DESCRIPTION = "DESCRIPTION"; - private static final String TEST_EXCHANGE_TYPE = "EXCHANGE_TYPE"; - - private static final Map<String, Object> EMPTY_ARGUMENT_MAP = Collections.emptyMap(); - public static final String QUEUE_1_NAME = "queue1"; - public static final String EXCHANGE_1_NAME = "exchange1"; - - private VirtualHost _mockVirtualHost; - private ManagedObjectRegistry _mockManagedObjectRegistry; - private VirtualHostManagerMBean _virtualHostManagerMBean; - - @Override - protected void setUp() throws Exception - { - _mockVirtualHost = mock(VirtualHost.class); - when(_mockVirtualHost.getExchangeTypeNames()).thenReturn(Collections.singletonList(TEST_EXCHANGE_TYPE)); - - _mockManagedObjectRegistry = mock(ManagedObjectRegistry.class); - - _virtualHostManagerMBean = new VirtualHostManagerMBean(new VirtualHostMBean(_mockVirtualHost, _mockManagedObjectRegistry)); - } - - public void testCreateQueueWithNoOwner() throws Exception - { - _virtualHostManagerMBean.createNewQueue(TEST_QUEUE_NAME, null, true); - ArgumentCaptor<Map> argsCaptor = ArgumentCaptor.forClass(Map.class); - - verify(_mockVirtualHost).createQueue(argsCaptor.capture()); - - Map actualAttributes = argsCaptor.getValue(); - assertEquals(TEST_QUEUE_NAME, actualAttributes.get(Queue.NAME)); - assertEquals(Boolean.TRUE,actualAttributes.get(Queue.DURABLE)); - assertEquals(null,actualAttributes.get(Queue.OWNER)); - - } - - /** - * Some users have been abusing the owner parameter as a description. Decision has been taken to map this parameter - * through to the description field (if the description field is passed, the owner is discarded). - */ - public void testCreateQueueWithOwnerMappedThroughToDescription() throws Exception - { - _virtualHostManagerMBean.createNewQueue(TEST_QUEUE_NAME, TEST_OWNER, true); - ArgumentCaptor<Map> argsCaptor = ArgumentCaptor.forClass(Map.class); - - verify(_mockVirtualHost).createQueue(argsCaptor.capture()); - - Map actualAttributes = argsCaptor.getValue(); - assertEquals(TEST_QUEUE_NAME,actualAttributes.get(Queue.NAME)); - assertEquals(Boolean.TRUE,actualAttributes.get(Queue.DURABLE)); - assertEquals(null,actualAttributes.get(Queue.OWNER)); - assertEquals(TEST_OWNER, actualAttributes.get(Queue.DESCRIPTION)); - } - - public void testCreateQueueWithOwnerAndDescriptionDiscardsOwner() throws Exception - { - Map<String, Object> arguments = Collections.singletonMap(QueueArgumentsConverter.X_QPID_DESCRIPTION, (Object)TEST_DESCRIPTION); - _virtualHostManagerMBean.createNewQueue(TEST_QUEUE_NAME, TEST_OWNER, true, arguments); - - ArgumentCaptor<Map> argsCaptor = ArgumentCaptor.forClass(Map.class); - - verify(_mockVirtualHost).createQueue(argsCaptor.capture()); - - Map actualAttributes = argsCaptor.getValue(); - assertEquals(TEST_QUEUE_NAME,actualAttributes.get(Queue.NAME)); - assertEquals(Boolean.TRUE,actualAttributes.get(Queue.DURABLE)); - assertEquals(null,actualAttributes.get(Queue.OWNER)); - assertEquals(TEST_DESCRIPTION, actualAttributes.get(Queue.DESCRIPTION)); - } - - public void testCreateQueueThatAlreadyExists() throws Exception - { - doThrow(new QueueExistsException("mocked exception", null)).when(_mockVirtualHost).createQueue(any(Map.class)); - - try - { - _virtualHostManagerMBean.createNewQueue(TEST_QUEUE_NAME, TEST_OWNER, true); - fail("Exception not thrown"); - } - catch (IllegalArgumentException iae) - { - // PASS - } - - } - - public void testDeleteQueue() throws Exception - { - Queue mockQueue = mock(Queue.class); - when(mockQueue.getName()).thenReturn(QUEUE_1_NAME); - when(_mockVirtualHost.getQueues()).thenReturn(Collections.singletonList(mockQueue)); - when(_mockVirtualHost.getChildByName(eq(Queue.class), eq(QUEUE_1_NAME))).thenReturn(mockQueue); - - _virtualHostManagerMBean.deleteQueue(QUEUE_1_NAME); - verify(mockQueue).delete(); - } - - public void testDeleteQueueWhenQueueDoesNotExist() throws Exception - { - Queue mockQueue = mock(Queue.class); - when(mockQueue.getName()).thenReturn(QUEUE_1_NAME); - when(_mockVirtualHost.getQueues()).thenReturn(Collections.singletonList(mockQueue)); - when(_mockVirtualHost.getChildByName(eq(Queue.class), eq(QUEUE_1_NAME))).thenReturn(mockQueue); - - try - { - _virtualHostManagerMBean.deleteQueue("unknownqueue"); - fail("Exception not thrown"); - } - catch(OperationsException oe) - { - // PASS - assertEquals("No such queue \"unknownqueue\"", oe.getMessage()); - } - verify(mockQueue, never()).deleteAndReturnCount(); - } - - public void testCreateNewDurableExchange() throws Exception - { - _virtualHostManagerMBean.createNewExchange(TEST_EXCHANGE_NAME, TEST_EXCHANGE_TYPE, true); - - verify(_mockVirtualHost).createExchange(matchesMap(TEST_EXCHANGE_NAME, true, LifetimePolicy.PERMANENT, TEST_EXCHANGE_TYPE)); - } - - public void testCreateNewExchangeWithUnknownExchangeType() throws Exception - { - String exchangeType = "notknown"; - try - { - _virtualHostManagerMBean.createNewExchange(TEST_EXCHANGE_NAME, exchangeType, true); - fail("Exception not thrown"); - } - catch (OperationsException oe) - { - // PASS - } - verify(_mockVirtualHost, never()).createExchange(matchesMap(TEST_EXCHANGE_NAME, - true, - LifetimePolicy.PERMANENT, - exchangeType)); - } - - public void testUnregisterExchange() throws Exception - { - Exchange mockExchange = mock(Exchange.class); - when(mockExchange.getName()).thenReturn(EXCHANGE_1_NAME); - when(_mockVirtualHost.getExchanges()).thenReturn(Collections.singletonList(mockExchange)); - when(_mockVirtualHost.getChildByName(eq(Exchange.class), eq(EXCHANGE_1_NAME))).thenReturn(mockExchange); - - - _virtualHostManagerMBean.unregisterExchange(EXCHANGE_1_NAME); - verify(mockExchange).delete(); - } - - public void testUnregisterExchangeWhenExchangeDoesNotExist() throws Exception - { - Exchange mockExchange = mock(Exchange.class); - when(mockExchange.getName()).thenReturn(EXCHANGE_1_NAME); - when(_mockVirtualHost.getExchanges()).thenReturn(Collections.singletonList(mockExchange)); - when(_mockVirtualHost.getChildByName(eq(Exchange.class), eq(EXCHANGE_1_NAME))).thenReturn(mockExchange); - - try - { - _virtualHostManagerMBean.unregisterExchange("unknownexchange"); - fail("Exception not thrown"); - } - catch(OperationsException oe) - { - // PASS - assertEquals("No such exchange \"unknownexchange\"", oe.getMessage()); - } - - verify(mockExchange, never()).deleteWithChecks(); - } - - private static Map<String,Object> matchesMap(final String name, - final boolean durable, - final LifetimePolicy lifetimePolicy, - final String exchangeType) - { - return argThat(new MapMatcher(name, durable, lifetimePolicy, exchangeType)); - } - - private static class MapMatcher extends ArgumentMatcher<Map<String,Object>> - { - - private final String _name; - private final boolean _durable; - private final LifetimePolicy _lifetimePolicy; - private final String _exchangeType; - - public MapMatcher(final String name, - final boolean durable, - final LifetimePolicy lifetimePolicy, - final String exchangeType) - { - _name = name; - _durable = durable; - _lifetimePolicy = lifetimePolicy; - _exchangeType = exchangeType; - - } - - @Override - public boolean matches(final Object o) - { - Map<String,Object> map = (Map<String,Object>)o; - - return _name.equals(map.get(Exchange.NAME)) - && _durable == (Boolean) map.get(Exchange.DURABLE) - && _lifetimePolicy == map.get(Exchange.LIFETIME_POLICY) - && _exchangeType.equals(map.get(Exchange.TYPE)); - } - } - -} diff --git a/qpid/java/broker-plugins/memory-store/pom.xml b/qpid/java/broker-plugins/memory-store/pom.xml deleted file mode 100644 index f6427a338d..0000000000 --- a/qpid/java/broker-plugins/memory-store/pom.xml +++ /dev/null @@ -1,78 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-memory-store</artifactId> - <name>Qpid Memory Message Store Broker Plug-in</name> - <description>Memory message store broker plug-in</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <!-- test dependencies --> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-test-utils</artifactId> - <version>${project.version}</version> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <type>test-jar</type> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <resources> - <resource> - <directory>src/main/resources</directory> - </resource> - <resource> - <directory>src/main/java</directory> - <includes> - <include>resources/</include> - </includes> - </resource> - </resources> - </build> - -</project> diff --git a/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemoryConfigurationStore.java b/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemoryConfigurationStore.java deleted file mode 100644 index 81344c880f..0000000000 --- a/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemoryConfigurationStore.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store; - - -import org.apache.qpid.server.model.ConfiguredObject; - -/** A simple message store that stores the messages in a thread-safe structure in memory. */ -public class MemoryConfigurationStore extends AbstractMemoryStore -{ - public static final String TYPE = "Memory"; - - public MemoryConfigurationStore(final Class<? extends ConfiguredObject> rootClass) - { - super(rootClass); - } -} diff --git a/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemorySystemConfigImpl.java b/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemorySystemConfigImpl.java deleted file mode 100644 index a15de21ce7..0000000000 --- a/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemorySystemConfigImpl.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.store; - -import java.util.Map; - -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.model.AbstractSystemConfig; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerShutdownProvider; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.SystemConfigFactoryConstructor; - - -@ManagedObject( category = false, type = MemorySystemConfigImpl.SYSTEM_CONFIG_TYPE ) -public class MemorySystemConfigImpl extends AbstractSystemConfig<MemorySystemConfigImpl> -{ - public static final String SYSTEM_CONFIG_TYPE = "Memory"; - - @SystemConfigFactoryConstructor - public MemorySystemConfigImpl(final TaskExecutor taskExecutor, - final EventLogger eventLogger, - final LogRecorder logRecorder, - final Map<String,Object> attributes, - final BrokerShutdownProvider brokerShutdownProvider) - { - super(taskExecutor, eventLogger, logRecorder, attributes, brokerShutdownProvider); - } - - @Override - protected DurableConfigurationStore createStoreObject() - { - return new MemoryConfigurationStore(Broker.class); - } -} diff --git a/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhost/memory/MemoryVirtualHost.java b/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhost/memory/MemoryVirtualHost.java deleted file mode 100644 index 5c86f734d0..0000000000 --- a/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhost/memory/MemoryVirtualHost.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.virtualhost.memory; - -import java.util.Map; - -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.store.MemoryMessageStore; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.virtualhost.AbstractVirtualHost; - -@ManagedObject(category = false, type = MemoryVirtualHost.VIRTUAL_HOST_TYPE) -public class MemoryVirtualHost extends AbstractVirtualHost<MemoryVirtualHost> -{ - public static final String VIRTUAL_HOST_TYPE = "Memory"; - - @ManagedObjectFactoryConstructor - public MemoryVirtualHost(final Map<String, Object> attributes, - final VirtualHostNode<?> virtualHostNode) - { - super(attributes, virtualHostNode); - } - - - @Override - protected MessageStore createMessageStore() - { - return new MemoryMessageStore(); - } -} diff --git a/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhostnode/memory/MemoryVirtualHostNode.java b/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhostnode/memory/MemoryVirtualHostNode.java deleted file mode 100644 index 10c30cf87a..0000000000 --- a/qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhostnode/memory/MemoryVirtualHostNode.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.virtualhostnode.memory; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.server.store.MemoryConfigurationStore; -import org.apache.qpid.server.virtualhostnode.AbstractStandardVirtualHostNode; - -@ManagedObject(type=MemoryVirtualHostNode.VIRTUAL_HOST_NODE_TYPE, category=false, validChildTypes = "org.apache.qpid.server.virtualhostnode.memory.MemoryVirtualHostNode#getSupportedChildTypes()") -public class MemoryVirtualHostNode extends AbstractStandardVirtualHostNode<MemoryVirtualHostNode> -{ - public static final String VIRTUAL_HOST_NODE_TYPE = "Memory"; - - @ManagedObjectFactoryConstructor - public MemoryVirtualHostNode(Map<String, Object> attributes, Broker<?> parent) - { - super(attributes, parent); - } - - @Override - protected void writeLocationEventLog() - { - } - - @Override - protected DurableConfigurationStore createConfigurationStore() - { - return new MemoryConfigurationStore(VirtualHost.class); - } - - public static Map<String, Collection<String>> getSupportedChildTypes() - { - return Collections.singletonMap(VirtualHost.class.getSimpleName(), getSupportedVirtualHostTypes(true)); - } -} diff --git a/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/add.js b/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/add.js deleted file mode 100644 index aa7bd8c582..0000000000 --- a/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/add.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dijit/registry", - "dojo/text!virtualhost/memory/add.html", - "dijit/form/ValidationTextBox", - "dojo/domReady!"], - function (xhr, parser, dom, domConstruct, json, registry, template) - { - return { - show: function (data) - { - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode); - } - }; - } -); diff --git a/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/edit.js b/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/edit.js deleted file mode 100644 index cfe7ebee8c..0000000000 --- a/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/edit.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -define(["dojo/domReady!"], - function () - { - return { - show: function(data) - { - } - }; - } -); diff --git a/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/show.js b/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/show.js deleted file mode 100644 index a431b63b86..0000000000 --- a/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/show.js +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define([], - function () - { - function Memory(data) - { - } - - Memory.prototype.update = function(data) - { - } - - return Memory; - } -); diff --git a/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhostnode/memory/add.js b/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhostnode/memory/add.js deleted file mode 100644 index 51ec19ea1b..0000000000 --- a/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhostnode/memory/add.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dijit/registry", - "dojo/text!virtualhostnode/memory/add.html", - "dijit/form/ValidationTextBox", - "dojo/domReady!"], - function (xhr, parser, dom, domConstruct, json, registry, template) - { - return { - show: function (data) - { - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode); - } - }; - } -); diff --git a/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhostnode/memory/show.js b/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhostnode/memory/show.js deleted file mode 100644 index 4c858c612a..0000000000 --- a/qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhostnode/memory/show.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -define([], - function () - { - function Memory(data) - { - this.parent = data.parent; - this.parent.editNodeButton.set("disabled",true); - this.parent.editNodeButton.domNode.style.display = "none"; - } - - Memory.prototype.update = function(data) - { - this.parent.editNodeButton.set("disabled", true); - this.parent.editNodeButton.domNode.style.display = "none"; - } - - return Memory; - } -); diff --git a/qpid/java/broker-plugins/memory-store/src/main/java/resources/virtualhost/memory/add.html b/qpid/java/broker-plugins/memory-store/src/main/java/resources/virtualhost/memory/add.html deleted file mode 100644 index 7b9172257b..0000000000 --- a/qpid/java/broker-plugins/memory-store/src/main/java/resources/virtualhost/memory/add.html +++ /dev/null @@ -1,22 +0,0 @@ -<!-- - ~ Licensed to the Apache Software Foundation (ASF) under one - ~ or more contributor license agreements. See the NOTICE file - ~ distributed with this work for additional information - ~ regarding copyright ownership. The ASF licenses this file - ~ to you under the Apache License, Version 2.0 (the - ~ "License"); you may not use this file except in compliance - ~ with the License. You may obtain a copy of the License at - ~ - ~ http://www.apache.org/licenses/LICENSE-2.0 - ~ - ~ Unless required by applicable law or agreed to in writing, - ~ software distributed under the License is distributed on an - ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - ~ KIND, either express or implied. See the License for the - ~ specific language governing permissions and limitations - ~ under the License. - --> -<div> - <div class="clear"></div> - <div class="infoMessage">The virtual host will have the same name as the node.</div> -</div> diff --git a/qpid/java/broker-plugins/memory-store/src/main/java/resources/virtualhostnode/memory/add.html b/qpid/java/broker-plugins/memory-store/src/main/java/resources/virtualhostnode/memory/add.html deleted file mode 100644 index 1422d9e366..0000000000 --- a/qpid/java/broker-plugins/memory-store/src/main/java/resources/virtualhostnode/memory/add.html +++ /dev/null @@ -1,23 +0,0 @@ -<!-- - - - - Licensed to the Apache Software Foundation (ASF) under one - - or more contributor license agreements. See the NOTICE file - - distributed with this work for additional information - - regarding copyright ownership. The ASF licenses this file - - to you under the Apache License, Version 2.0 (the - - "License"); you may not use this file except in compliance - - with the License. You may obtain a copy of the License at - - - - http://www.apache.org/licenses/LICENSE-2.0 - - - - Unless required by applicable law or agreed to in writing, - - software distributed under the License is distributed on an - - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - - KIND, either express or implied. See the License for the - - specific language governing permissions and limitations - - under the License. - - - --> -<div> - <div class="clear"></div> -</div> diff --git a/qpid/java/broker-plugins/websocket/pom.xml b/qpid/java/broker-plugins/websocket/pom.xml deleted file mode 100644 index eb92e9da36..0000000000 --- a/qpid/java/broker-plugins/websocket/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-java-build</artifactId> - <version>0.32-SNAPSHOT</version> - <relativePath>../../pom.xml</relativePath> - </parent> - - <artifactId>qpid-broker-plugins-websocket</artifactId> - <name>Qpid WebSocket Broker Plug-in</name> - <description>WebSocket broker plug-in</description> - - <dependencies> - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - - - <dependency> - <groupId>org.apache.qpid</groupId> - <artifactId>qpid-broker-codegen</artifactId> - <version>${project.version}</version> - <optional>true</optional> - </dependency> - - <dependency> - <groupId>org.apache.geronimo.specs</groupId> - <artifactId>geronimo-servlet_3.0_spec</artifactId> - <version>${geronimo-servlet-version}</version> - </dependency> - - <dependency> - <groupId>org.eclipse.jetty</groupId> - <artifactId>jetty-server</artifactId> - <version>${jetty-version}</version> - <exclusions> - <exclusion> - <groupId>org.eclipse.jetty.orbit</groupId> - <artifactId>javax.servlet</artifactId> - </exclusion> - </exclusions> - </dependency> - - <dependency> - <groupId>org.eclipse.jetty</groupId> - <artifactId>jetty-websocket</artifactId> - <version>${jetty-version}</version> - </dependency> - - </dependencies> - - <build> - </build> - -</project> diff --git a/qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketProvider.java b/qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketProvider.java deleted file mode 100644 index 896a7119f7..0000000000 --- a/qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketProvider.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.transport.websocket; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.security.Principal; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Set; - -import javax.net.ssl.SSLContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.eclipse.jetty.server.Connector; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.server.nio.SelectChannelConnector; -import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.eclipse.jetty.websocket.WebSocket; -import org.eclipse.jetty.websocket.WebSocketHandler; - -import org.apache.qpid.protocol.ProtocolEngine; -import org.apache.qpid.protocol.ProtocolEngineFactory; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.protocol.MultiVersionProtocolEngineFactory; -import org.apache.qpid.server.transport.AcceptingTransport; -import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.network.NetworkConnection; -import org.apache.qpid.transport.network.security.ssl.SSLUtil; - -class WebSocketProvider implements AcceptingTransport -{ - public static final String AMQP_WEBSOCKET_SUBPROTOCOL = "AMQPWSB10"; - public static final String X509_CERTIFICATES = "javax.servlet.request.X509Certificate"; - private final Transport _transport; - private final SSLContext _sslContext; - private final AmqpPort<?> _port; - private final Set<Protocol> _supported; - private final Protocol _defaultSupportedProtocolReply; - private final ProtocolEngineFactory _factory; - private Server _server; - - WebSocketProvider(final Transport transport, - final SSLContext sslContext, - final AmqpPort<?> port, - final Set<Protocol> supported, - final Protocol defaultSupportedProtocolReply) - { - _transport = transport; - _sslContext = sslContext; - _port = port; - _supported = supported; - _defaultSupportedProtocolReply = defaultSupportedProtocolReply; - _factory = new MultiVersionProtocolEngineFactory( - _port.getParent(Broker.class), - _supported, - _defaultSupportedProtocolReply, - _port, - _transport); - - } - - @Override - public void start() - { - _server = new Server(); - - Connector connector = null; - - - if (_transport == Transport.WS) - { - connector = new SelectChannelConnector(); - } - else if (_transport == Transport.WSS) - { - SslContextFactory factory = new SslContextFactory(); - factory.setSslContext(_sslContext); - factory.addExcludeProtocols(SSLUtil.SSLV3_PROTOCOL); - factory.setNeedClientAuth(_port.getNeedClientAuth()); - factory.setWantClientAuth(_port.getWantClientAuth()); - connector = new SslSelectChannelConnector(factory); - } - else - { - throw new IllegalArgumentException("Unexpected transport on port " + _port.getName() + ":" + _transport); - } - - String bindingAddress = null; - - bindingAddress = _port.getBindingAddress(); - - if (bindingAddress != null && !bindingAddress.trim().equals("") && !bindingAddress.trim().equals("*")) - { - connector.setHost(bindingAddress.trim()); - } - - connector.setPort(_port.getPort()); - _server.addConnector(connector); - - WebSocketHandler wshandler = new WebSocketHandler() - { - @Override - public WebSocket doWebSocketConnect(final HttpServletRequest request, final String protocol) - { - - Principal principal = null; - if(Collections.list(request.getAttributeNames()).contains(X509_CERTIFICATES)) - { - X509Certificate[] certificates = - (X509Certificate[]) request.getAttribute(X509_CERTIFICATES); - if(certificates != null && certificates.length != 0) - { - - principal = certificates[0].getSubjectDN(); - } - } - - SocketAddress remoteAddress = new InetSocketAddress(request.getRemoteHost(), request.getRemotePort()); - SocketAddress localAddress = new InetSocketAddress(request.getLocalName(), request.getLocalPort()); - return AMQP_WEBSOCKET_SUBPROTOCOL.equals(protocol) ? new AmqpWebSocket(_transport, localAddress, remoteAddress, principal) : null; - } - }; - - _server.setHandler(wshandler); - _server.setSendServerVersion(false); - wshandler.setHandler(new AbstractHandler() - { - @Override - public void handle(final String target, - final Request baseRequest, - final HttpServletRequest request, - final HttpServletResponse response) - throws IOException, ServletException - { - if (response.isCommitted() || baseRequest.isHandled()) - { - return; - } - baseRequest.setHandled(true); - response.setStatus(HttpServletResponse.SC_FORBIDDEN); - - - } - }); - try - { - _server.start(); - } - catch(RuntimeException e) - { - throw e; - } - catch (Exception e) - { - throw new ServerScopedRuntimeException(e); - } - - } - - @Override - public void close() - { - - } - - private class AmqpWebSocket implements WebSocket,WebSocket.OnBinaryMessage - { - private final SocketAddress _localAddress; - private final SocketAddress _remoteAddress; - private final Principal _userPrincipal; - private Connection _connection; - private final Transport _transport; - private ProtocolEngine _engine; - - private AmqpWebSocket(final Transport transport, - final SocketAddress localAddress, - final SocketAddress remoteAddress, - final Principal userPrincipal) - { - _transport = transport; - _localAddress = localAddress; - _remoteAddress = remoteAddress; - _userPrincipal = userPrincipal; - } - - @Override - public void onMessage(final byte[] data, final int offset, final int length) - { - _engine.received(ByteBuffer.wrap(data, offset, length).slice()); - } - - @Override - public void onOpen(final Connection connection) - { - _connection = connection; - - _engine = _factory.newProtocolEngine(_remoteAddress); - - final ConnectionWrapper connectionWrapper = - new ConnectionWrapper(connection, _localAddress, _remoteAddress); - connectionWrapper.setPeerPrincipal(_userPrincipal); - _engine.setNetworkConnection(connectionWrapper, connectionWrapper.getSender()); - - } - - @Override - public void onClose(final int closeCode, final String message) - { - _engine.closed(); - } - } - - private class ConnectionWrapper implements NetworkConnection, ByteBufferSender - { - private final WebSocket.Connection _connection; - private final SocketAddress _localAddress; - private final SocketAddress _remoteAddress; - private Principal _principal; - private int _maxWriteIdle; - private int _maxReadIdle; - - public ConnectionWrapper(final WebSocket.Connection connection, - final SocketAddress localAddress, - final SocketAddress remoteAddress) - { - _connection = connection; - _localAddress = localAddress; - _remoteAddress = remoteAddress; - } - - @Override - public ByteBufferSender getSender() - { - return this; - } - - @Override - public void start() - { - - } - - @Override - public void send(final ByteBuffer msg) - { - try - { - _connection.sendMessage(msg.array(),msg.arrayOffset()+msg.position(),msg.remaining()); - } - catch (IOException e) - { - close(); - } - } - - @Override - public void flush() - { - - } - - @Override - public void close() - { - _connection.close(); - } - - @Override - public SocketAddress getRemoteAddress() - { - return _remoteAddress; - } - - @Override - public SocketAddress getLocalAddress() - { - return _localAddress; - } - - @Override - public void setMaxWriteIdle(final int sec) - { - _maxWriteIdle = sec; - } - - @Override - public void setMaxReadIdle(final int sec) - { - _maxReadIdle = sec; - } - - @Override - public Principal getPeerPrincipal() - { - return _principal; - } - - @Override - public int getMaxReadIdle() - { - return _maxReadIdle; - } - - @Override - public int getMaxWriteIdle() - { - return _maxWriteIdle; - } - - void setPeerPrincipal(final Principal peerPrincipal) - { - _principal = peerPrincipal; - } - } -} diff --git a/qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketTransportProvider.java b/qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketTransportProvider.java deleted file mode 100644 index c7578adb91..0000000000 --- a/qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketTransportProvider.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.transport.websocket; - -import java.util.Set; - -import javax.net.ssl.SSLContext; - -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.transport.AcceptingTransport; -import org.apache.qpid.server.transport.TransportProvider; - -class WebSocketTransportProvider implements TransportProvider -{ - public WebSocketTransportProvider() - { - } - - @Override - public AcceptingTransport createTransport(final Set<Transport> transports, - final SSLContext sslContext, - final AmqpPort<?> port, - final Set<Protocol> supported, - final Protocol defaultSupportedProtocolReply) - { - return new WebSocketProvider(transports.iterator().next(), - sslContext, - port, - supported, - defaultSupportedProtocolReply); - } -} diff --git a/qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketTransportProviderFactory.java b/qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketTransportProviderFactory.java deleted file mode 100644 index e3db7e3686..0000000000 --- a/qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketTransportProviderFactory.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.transport.websocket; - -import java.util.Arrays; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Set; - -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.TransportProviderFactory; -import org.apache.qpid.server.transport.TransportProvider; - -@PluggableService -public class WebSocketTransportProviderFactory implements TransportProviderFactory -{ - - private static final String TYPE = "Websocket"; - - @Override - public Set<Set<Transport>> getSupportedTransports() - { - return new HashSet<Set<Transport>>(Arrays.asList(EnumSet.of(Transport.WS), - EnumSet.of(Transport.WSS))); - } - - @Override - public TransportProvider getTransportProvider(final Set<Transport> transports) - { - return new WebSocketTransportProvider(); - } - - @Override - public String getType() - { - return TYPE; - } -} |
