index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/useradmin/UserAdmin.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.useradmin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.apache.aries.jmx.codec.AuthorizationData;
import org.apache.aries.jmx.codec.GroupData;
import org.apache.aries.jmx.codec.PropertyData;
import org.apache.aries.jmx.codec.RoleData;
import org.apache.aries.jmx.codec.UserData;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.jmx.JmxConstants;
import org.osgi.jmx.service.useradmin.UserAdminMBean;
import org.osgi.service.useradmin.Authorization;
import org.osgi.service.useradmin.Group;
import org.osgi.service.useradmin.Role;
import org.osgi.service.useradmin.User;
/**
* <p>
* <tt>UserAdmin</tt> represents {@link UserAdminMBean} implementation.
* </p>
*
* @see UserAdminMBean
*
* @version $Rev$ $Date$
*/
public class UserAdmin implements UserAdminMBean {
/**
* @see org.osgi.service.useradmin.UserAdmin service reference;
*/
private org.osgi.service.useradmin.UserAdmin userAdmin;
/**
* Constructs new UserAdmin MBean.
*
* @param userAdmin
* {@link UserAdmin} service reference.
*/
public UserAdmin(org.osgi.service.useradmin.UserAdmin userAdmin) {
this.userAdmin = userAdmin;
}
/**
* Validate Role against roleType.
*
* @see Role#USER
* @see Role#GROUP
* @see Role#USER_ANYONE
*
* @param role
* Role instance.
* @param roleType
* role type.
*/
private void validateRoleType(Role role, int roleType) throws IOException {
if (role.getType() != roleType) {
throw new IOException("Unexpected role type. Expected " + roleType + " but got " + role.getType());
}
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#addCredential(java.lang.String, byte[], java.lang.String)
*/
public void addCredential(String key, byte[] value, String username) throws IOException {
addCredential(key, (Object)value, username);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#addCredentialString(String, String, String)
*/
public void addCredentialString(String key, String value, String username) throws IOException {
addCredential(key, (Object)value, username);
}
private void addCredential(String key, Object value, String username) throws IOException {
if (username == null) {
throw new IOException("User name cannot be null");
}
if (key == null) {
throw new IOException("Credential key cannot be null");
}
Role role = userAdmin.getRole(username);
if (role == null) {
throw new IOException("Operation fails user with provided username = [" + username + "] doesn't exist");
}
validateRoleType(role, Role.USER);
Dictionary<String, Object> credentials = ((User) role).getCredentials();
if (credentials != null) {
credentials.put(key, value);
}
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#addMember(java.lang.String, java.lang.String)
*/
public boolean addMember(String groupname, String rolename) throws IOException {
if (groupname == null) {
throw new IOException("Group name cannot be null");
}
if (rolename == null) {
throw new IOException("Role name cannot be null");
}
Role group = userAdmin.getRole(groupname);
Role member = userAdmin.getRole(rolename);
if (group == null) {
throw new IOException("Operation fails role with provided groupname = [" + groupname + "] doesn't exist");
}
validateRoleType(group, Role.GROUP);
return ((Group) group).addMember(member);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#addPropertyString(String, String, String)
*/
public void addPropertyString(String key, String value, String rolename) throws IOException {
addRoleProperty(key, value, rolename);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#addProperty(java.lang.String, byte[], java.lang.String)
*/
public void addProperty(String key, byte[] value, String rolename) throws IOException {
addRoleProperty(key, value, rolename);
}
/**
* @see UserAdminMBean#addProperty(String, byte[], String)
* @see UserAdminMBean#addProperty(String, String, String)
*/
private void addRoleProperty(String key, Object value, String rolename) throws IOException {
if (rolename == null) {
throw new IOException("Role name cannot be null");
}
if (key == null) {
throw new IOException("Property key cannot be null");
}
Role role = userAdmin.getRole(rolename);
if (role == null) {
throw new IOException("Operation fails role with provided rolename = [" + rolename + "] doesn't exist");
}
Dictionary<String, Object> properties = role.getProperties();
if (properties != null) {
properties.put(key, value);
}
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#addRequiredMember(java.lang.String, java.lang.String)
*/
public boolean addRequiredMember(String groupname, String rolename) throws IOException {
if (groupname == null) {
throw new IOException("Group name cannot be null");
}
if (rolename == null) {
throw new IOException("Role name cannot be null");
}
Role group = userAdmin.getRole(groupname);
Role member = userAdmin.getRole(rolename);
if (group == null) {
throw new IOException("Operation fails role with provided groupname = [" + groupname + "] doesn't exist");
}
validateRoleType(group, Role.GROUP);
return ((Group) group).addRequiredMember(member);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#createGroup(java.lang.String)
*/
public void createGroup(String name) throws IOException {
if (name == null) {
throw new IOException("Group name cannot be null");
}
userAdmin.createRole(name, Role.GROUP);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#createRole(java.lang.String)
*/
public void createRole(String name) throws IOException {
throw new IOException("Deprecated: use createGroup or createUser");
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#createUser(java.lang.String)
*/
public void createUser(String name) throws IOException {
if (name == null) {
throw new IOException("User name cannot be null");
}
userAdmin.createRole(name, Role.USER);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getAuthorization(java.lang.String)
*/
public CompositeData getAuthorization(String username) throws IOException {
if (username== null) {
throw new IOException("User name cannot be null");
}
Role role = userAdmin.getRole(username);
if (role == null) {
return null;
}
validateRoleType(role, Role.USER);
Authorization auth = userAdmin.getAuthorization((User) role);
if (auth == null) {
return null;
}
return new AuthorizationData(auth).toCompositeData();
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getCredentials(java.lang.String)
*/
public TabularData getCredentials(String username) throws IOException {
if (username == null) {
throw new IOException("User name cannot be null");
}
Role role = userAdmin.getRole(username);
if (role == null) {
return null;
}
validateRoleType(role, Role.USER);
Dictionary<String, Object> credentials = ((User) role).getCredentials();
if (credentials == null) {
return null;
}
TabularData data = new TabularDataSupport(JmxConstants.PROPERTIES_TYPE);
for (Enumeration<String> keys = credentials.keys(); keys.hasMoreElements();) {
String key = keys.nextElement();
data.put(PropertyData.newInstance(key, credentials.get(key)).toCompositeData());
}
return data;
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getGroup(java.lang.String)
*/
public CompositeData getGroup(String groupname) throws IOException {
if (groupname == null) {
throw new IOException("Group name cannot be null");
}
Role role = userAdmin.getRole(groupname);
if (role == null) {
return null;
}
validateRoleType(role, Role.GROUP);
return new GroupData((Group) role).toCompositeData();
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getGroups(java.lang.String)
*/
public String[] getGroups(String filter) throws IOException {
Role[] roles = null;
try {
roles = userAdmin.getRoles(filter);
} catch (InvalidSyntaxException ise) {
IOException ioex = new IOException("Operation fails illegal filter provided: " + filter);
ioex.initCause(ise);
throw ioex;
}
if (roles == null) {
return null;
}
return getRoleByType(roles, Role.GROUP);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getImpliedRoles(java.lang.String)
*/
public String[] getImpliedRoles(String username) throws IOException {
if (username == null) {
throw new IOException("User name cannot be null");
}
Role role = userAdmin.getRole(username);
if (role != null) {
validateRoleType(role, Role.USER);
Authorization auth = userAdmin.getAuthorization((User) role);
if (auth != null) {
return auth.getRoles();
}
}
return null;
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getMembers(java.lang.String)
*/
public String[] getMembers(String groupname) throws IOException {
if (groupname == null) {
throw new IOException("Group name cannot be null");
}
Role role = userAdmin.getRole(groupname);
if (role != null) {
validateRoleType(role, Role.GROUP);
Role[] roles = ((Group) role).getMembers();
if (roles != null) {
String[] members = new String[roles.length];
for (int i = 0; i < roles.length; i++) {
members[i] = roles[i].getName();
}
return members;
}
}
return null;
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getProperties(java.lang.String)
*/
public TabularData getProperties(String rolename) throws IOException {
if (rolename == null) {
throw new IOException("Role name cannot be null");
}
Role role = userAdmin.getRole(rolename);
if (role == null) {
return null;
}
Dictionary<String, Object> properties = role.getProperties();
if (properties == null) {
return null;
}
TabularData data = new TabularDataSupport(JmxConstants.PROPERTIES_TYPE);
for (Enumeration<String> keys = properties.keys(); keys.hasMoreElements();) {
String key = keys.nextElement();
data.put(PropertyData.newInstance(key, properties.get(key)).toCompositeData());
}
return data;
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getRequiredMembers(java.lang.String)
*/
public String[] getRequiredMembers(String groupname) throws IOException {
if (groupname == null) {
throw new IOException("Group name cannot be null");
}
Role role = userAdmin.getRole(groupname);
if (role != null) {
validateRoleType(role, Role.GROUP);
Role[] roles = ((Group) role).getRequiredMembers();
if (roles != null) {
String[] reqMembers = new String[roles.length];
for (int i = 0; i < roles.length; i++) {
reqMembers[i] = roles[i].getName();
}
return reqMembers;
}
}
return null;
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getRole(java.lang.String)
*/
public CompositeData getRole(String name) throws IOException {
if (name == null) {
throw new IOException("Role name cannot be null");
}
Role role = userAdmin.getRole(name);
if (role == null) {
return null;
}
return new RoleData(role).toCompositeData();
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getRoles(java.lang.String)
*/
public String[] getRoles(String filter) throws IOException {
Role[] roles = null;
try {
roles = userAdmin.getRoles(filter);
} catch (InvalidSyntaxException ise) {
IOException ioex = new IOException("Operation fails illegal filter provided: " + filter);
ioex.initCause(ise);
throw ioex;
}
if (roles == null) {
return null;
}
return getRoleByType(roles, Role.ROLE);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getUser(java.lang.String)
*/
public CompositeData getUser(String username) throws IOException {
if (username == null) {
throw new IOException("User name cannot be null");
}
Role role = userAdmin.getRole(username);
if (role == null) {
return null;
}
validateRoleType(role, Role.USER);
return new UserData((User) role).toCompositeData();
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getUserWithProperty(String, String)
*/
public String getUserWithProperty(String key, String value) throws IOException {
if (key == null) {
throw new IOException("Property key cannot be null");
}
User user = userAdmin.getUser(key, value);
if (user == null) {
return null;
}
return user.getName();
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#getUsers(java.lang.String)
*/
public String[] getUsers(String filter) throws IOException {
Role[] roles = null;
try {
roles = userAdmin.getRoles(filter);
} catch (InvalidSyntaxException ise) {
IOException ioex = new IOException("Operation fails illegal filter provided: " + filter);
ioex.initCause(ise);
throw ioex;
}
if (roles == null) {
return null;
}
return getRoleByType(roles, Role.USER);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#listGroups()
*/
public String[] listGroups() throws IOException {
Role[] roles = null;
try {
roles = userAdmin.getRoles(null);
} catch (InvalidSyntaxException e) {
// shouldn't happened we are not using filter
}
if (roles == null) {
return null;
}
return getRoleByType(roles, Role.GROUP);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#listRoles()
*/
public String[] listRoles() throws IOException {
Role[] roles = null;
try {
roles = userAdmin.getRoles(null);
} catch (InvalidSyntaxException e) {
// shouldn't happened we are not using filter
}
if (roles == null) {
return null;
}
return getRoleByType(roles, Role.ROLE);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#listUsers()
*/
public String[] listUsers() throws IOException {
Role[] roles = null;
try {
roles = userAdmin.getRoles(null);
} catch (InvalidSyntaxException e) {
// shouldn't happened we are not using filter
}
if (roles == null) {
return null;
}
return getRoleByType(roles, Role.USER);
}
/**
* Gets role names by type from provided roles array.
*
* @param roles
* array of Role's.
* @param roleType
* role Type.
* @return array of role names.
*/
private String[] getRoleByType(Role[] roles, int roleType) {
List<String> rs = new ArrayList<String>();
for (Role role : roles) {
if (roleType == Role.ROLE) {
rs.add(role.getName());
continue;
}
if (role.getType() == roleType) {
rs.add(role.getName());
}
}
return rs.toArray(new String[rs.size()]);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeCredential(java.lang.String, java.lang.String)
*/
public void removeCredential(String key, String username) throws IOException {
if (username == null) {
throw new IOException("User name cannot be null");
}
if (key == null) {
throw new IOException("Credential key cannot be null");
}
Role role = userAdmin.getRole(username);
if (role == null) {
throw new IOException("Operation fails can't find user with username = [" + username + "] doesn't exist");
}
validateRoleType(role, Role.USER);
((User) role).getCredentials().remove(key);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeGroup(java.lang.String)
*/
public boolean removeGroup(String name) throws IOException {
if (name == null) {
throw new IOException("Group name cannot be null");
}
return userAdmin.removeRole(name);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeMember(java.lang.String, java.lang.String)
*/
public boolean removeMember(String groupname, String rolename) throws IOException {
if (groupname == null) {
throw new IOException("Group name cannot be null");
}
if (rolename == null) {
throw new IOException("Role name cannot be null");
}
Role group = userAdmin.getRole(groupname);
Role member = userAdmin.getRole(rolename);
if (group == null) {
throw new IOException("Operation fails role with provided groupname = [" + groupname + "] doesn't exist");
}
validateRoleType(group, Role.GROUP);
return ((Group) group).removeMember(member);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeProperty(java.lang.String, java.lang.String)
*/
public void removeProperty(String key, String rolename) throws IOException {
if (rolename == null) {
throw new IOException("Role name cannot be null");
}
Role role = userAdmin.getRole(rolename);
if (role == null) {
throw new IOException("Operation fails role with provided rolename = [" + rolename + "] doesn't exist");
}
role.getProperties().remove(key);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeRole(java.lang.String)
*/
public boolean removeRole(String name) throws IOException {
if (name == null) {
throw new IOException("Role name cannot be null");
}
return userAdmin.removeRole(name);
}
/**
* @see org.osgi.jmx.service.useradmin.UserAdminMBean#removeUser(java.lang.String)
*/
public boolean removeUser(String name) throws IOException {
if (name == null) {
throw new IOException("User name cannot be null");
}
return userAdmin.removeRole(name);
}
}
| 8,100 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/util/TypeUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.util;
import static org.osgi.jmx.JmxConstants.BIGDECIMAL;
import static org.osgi.jmx.JmxConstants.BIGINTEGER;
import static org.osgi.jmx.JmxConstants.BOOLEAN;
import static org.osgi.jmx.JmxConstants.BYTE;
import static org.osgi.jmx.JmxConstants.CHARACTER;
import static org.osgi.jmx.JmxConstants.DOUBLE;
import static org.osgi.jmx.JmxConstants.FLOAT;
import static org.osgi.jmx.JmxConstants.INTEGER;
import static org.osgi.jmx.JmxConstants.LONG;
import static org.osgi.jmx.JmxConstants.P_BOOLEAN;
import static org.osgi.jmx.JmxConstants.P_BYTE;
import static org.osgi.jmx.JmxConstants.P_CHAR;
import static org.osgi.jmx.JmxConstants.P_DOUBLE;
import static org.osgi.jmx.JmxConstants.P_FLOAT;
import static org.osgi.jmx.JmxConstants.P_INT;
import static org.osgi.jmx.JmxConstants.P_LONG;
import static org.osgi.jmx.JmxConstants.P_SHORT;
import static org.osgi.jmx.JmxConstants.SHORT;
import static org.osgi.jmx.JmxConstants.STRING;
import static org.osgi.jmx.JmxConstants.VERSION;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import org.osgi.framework.Version;
/**
* This class provides common utilities related to type conversions for the MBean implementations
*
* @version $Rev$ $Date$
*/
public class TypeUtils {
private TypeUtils() {
super();
}
public static Map<String, Class<? extends Object>> primitiveTypes = new HashMap<String, Class<? extends Object>>();
public static Map<String, Class<? extends Object>> wrapperTypes = new HashMap<String, Class<? extends Object>>();
public static Map<String, Class<? extends Object>> mathTypes = new HashMap<String, Class<? extends Object>>();
public static Map<Class<? extends Object>, Class<? extends Object>> primitiveToWrapper = new HashMap<Class<? extends Object>, Class<? extends Object>>();
public static Map<String, Class<? extends Object>> types = new HashMap<String, Class<? extends Object>>();
static {
primitiveTypes.put(P_FLOAT, Float.TYPE);
primitiveTypes.put(P_INT, Integer.TYPE);
primitiveTypes.put(P_LONG, Long.TYPE);
primitiveTypes.put(P_DOUBLE, Double.TYPE);
primitiveTypes.put(P_BYTE, Byte.TYPE);
primitiveTypes.put(P_SHORT, Short.TYPE);
primitiveTypes.put(P_CHAR, Character.TYPE);
primitiveTypes.put(P_BOOLEAN, Boolean.TYPE);
primitiveToWrapper.put(Float.TYPE, Float.class);
primitiveToWrapper.put(Integer.TYPE, Integer.class);
primitiveToWrapper.put(Long.TYPE, Long.class);
primitiveToWrapper.put(Double.TYPE, Double.class);
primitiveToWrapper.put(Byte.TYPE, Byte.class);
primitiveToWrapper.put(Short.TYPE, Short.class);
primitiveToWrapper.put(Boolean.TYPE, Boolean.class);
wrapperTypes.put(INTEGER, Integer.class);
wrapperTypes.put(FLOAT, Float.class);
wrapperTypes.put(LONG, Long.class);
wrapperTypes.put(DOUBLE, Double.class);
wrapperTypes.put(BYTE, Byte.class);
wrapperTypes.put(SHORT, Short.class);
wrapperTypes.put(BOOLEAN, Boolean.class);
wrapperTypes.put(CHARACTER, Character.class);
wrapperTypes.put(VERSION, Version.class);
mathTypes.put(BIGDECIMAL, BigDecimal.class);
mathTypes.put(BIGINTEGER, BigInteger.class);
types.put(STRING, String.class);
types.putAll(primitiveTypes);
types.putAll(wrapperTypes);
types.putAll(mathTypes);
}
/**
* Converts a <code>Dictionary</code> object to a <code>Map</code>
*
* @param dictionary
* @return
*/
public static Map<String, String> fromDictionary(Dictionary<String, String> dictionary) {
Map<String, String> result = new HashMap<String, String>();
Enumeration<String> keys = dictionary.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
result.put(key, dictionary.get(key));
}
return result;
}
/**
* Converts primitive long[] array to Long[]
*
* @param array
* @return
*/
public static Long[] toLong(long[] array) {
Long[] toArray = (array == null) ? new Long[0] : new Long[array.length];
for (int i = 0; i < toArray.length; i++) {
toArray[i] = array[i];
}
return toArray;
}
/**
* Converts Long[] array to primitive
*
* @param array
* @return
*/
public static long[] toPrimitive(Long[] array) {
long[] toArray = (array == null) ? new long[0] : new long[array.length];
for (int i = 0; i < toArray.length; i++) {
toArray[i] = array[i];
}
return toArray;
}
/**
* Converts a String value to an Object of the specified type
*
* @param type
* one of types listed in {@link #types}
* @param value
* @return instance of class <code>type</code>
* @throws IllegalArgumentException
* if type or value are null or if the Class type does not support a valueOf() or cannot be converted to
* a wrapper type
*/
@SuppressWarnings("unchecked")
public static <T> T fromString(Class<T> type, String value) {
if (type == null || !types.containsValue(type)) {
throw new IllegalArgumentException("Cannot convert to type argument : " + type);
}
if (value == null || value.length() < 1) {
throw new IllegalArgumentException("Argument value cannot be null or empty");
}
T result = null;
try {
if (type.equals(String.class)) {
result = (T) value;
} else if (type.equals(Character.class) || type.equals(Character.TYPE)) {
result = (T) Character.valueOf(value.charAt(0));
} else if (wrapperTypes.containsValue(type) || mathTypes.containsValue(type)) {
Constructor<? extends Object> constructor = type.getConstructor(String.class);
result = (T) constructor.newInstance(value);
} else if (primitiveToWrapper.containsKey(type)) { // attempt to promote to wrapper and resolve to the base
// type
Class<? extends Object> promotedType = primitiveToWrapper.get(type);
char[] simpleTypeName = type.getName().toCharArray();
simpleTypeName[0] = Character.toUpperCase(simpleTypeName[0]);
String parseMethodName = "parse" + new String(simpleTypeName);
Method parseMethod = promotedType.getDeclaredMethod(parseMethodName, String.class);
result = (T) parseMethod.invoke(null, value);
}
} catch (SecurityException e) {
throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
} catch (InstantiationException e) {
throw new IllegalArgumentException("Cannot convert value [" + value + "] to type [" + type + "]", e);
}
return result;
}
}
| 8,101 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/util/ObjectNameUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.util;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
public class ObjectNameUtils {
private ObjectNameUtils() {}
public static String createFullObjectName(BundleContext context, String namePrefix) {
return namePrefix +
",framework=" + context.getBundle(0).getSymbolicName() +
",uuid=" + context.getProperty(Constants.FRAMEWORK_UUID);
}
}
| 8,102 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/util/FrameworkUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.util;
import static org.osgi.jmx.framework.BundleStateMBean.ACTIVE;
import static org.osgi.jmx.framework.BundleStateMBean.INSTALLED;
import static org.osgi.jmx.framework.BundleStateMBean.RESOLVED;
import static org.osgi.jmx.framework.BundleStateMBean.STARTING;
import static org.osgi.jmx.framework.BundleStateMBean.STOPPING;
import static org.osgi.jmx.framework.BundleStateMBean.UNINSTALLED;
import static org.osgi.jmx.framework.BundleStateMBean.UNKNOWN;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.aries.util.ManifestHeaderUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.packageadmin.RequiredBundle;
/**
* This class contains common utilities related to Framework operations for the MBean implementations
*
* @version $Rev$ $Date$
*/
public class FrameworkUtils {
private FrameworkUtils() {
super();
}
/**
*
* Returns the Bundle object for a given id
*
* @param bundleContext
* @param bundleId
* @return
* @throws IllegalArgumentException
* if no Bundle is found with matching bundleId
*/
public static Bundle resolveBundle(BundleContext bundleContext, long bundleId) throws IOException {
if (bundleContext == null) {
throw new IllegalArgumentException("Argument bundleContext cannot be null");
}
Bundle bundle = bundleContext.getBundle(bundleId);
if (bundle == null) {
throw new IOException("Bundle with id [" + bundleId + "] not found");
}
return bundle;
}
/**
* Returns an array of bundleIds
*
* @param bundles
* array of <code>Bundle</code> objects
* @return bundleIds in sequence
*/
public static long[] getBundleIds(Bundle[] bundles) {
long[] result;
if (bundles == null) {
result = new long[0];
} else {
result = new long[bundles.length];
for (int i = 0; i < bundles.length; i++) {
result[i] = bundles[i].getBundleId();
}
}
return result;
}
public static long[] getBundleIds(List<Bundle> bundles) {
long[] result;
if (bundles == null) {
result = new long[0];
} else {
result = new long[bundles.size()];
for (int i = 0; i < bundles.size(); i++) {
result[i] = bundles.get(i).getBundleId();
}
}
return result;
}
/**
*
* Returns the ServiceReference object with matching service.id
*
* @param bundleContext
* @param serviceId
* @return ServiceReference with matching service.id property
* @throws IllegalArgumentException if bundleContext is null
* @throws IOException if no service is found with the given id
*/
public static ServiceReference resolveService(BundleContext bundleContext, long serviceId) throws IOException {
if (bundleContext == null) {
throw new IllegalArgumentException("Argument bundleContext cannot be null");
}
ServiceReference result = null;
try {
ServiceReference[] references = bundleContext.getAllServiceReferences(null, "(" + Constants.SERVICE_ID
+ "=" + serviceId + ")");
if (references == null || references.length < 1) {
throw new IOException("Service with id [" + serviceId + "] not found");
} else {
result = references[0];
}
} catch (InvalidSyntaxException e) {
IOException ioex = new IOException("Failure when resolving service ");
ioex.initCause(e);
throw ioex;
}
return result;
}
/**
* Returns an array of service.id values
*
* @param serviceReferences
* array of <code>ServiceReference</code> objects
* @return service.id values in sequence
*/
public static long[] getServiceIds(ServiceReference[] serviceReferences) {
long result[] = (serviceReferences == null) ? new long[0] : new long[serviceReferences.length];
for (int i = 0; i < result.length; i++) {
result[i] = (Long) serviceReferences[i].getProperty(Constants.SERVICE_ID);
}
return result;
}
/**
* Returns the packages exported by the specified bundle
*
* @param bundle
* @param packageAdmin
* @return
* @throws IllegalArgumentException
* if bundle or packageAdmin are null
*/
public static String[] getBundleExportedPackages(Bundle bundle, PackageAdmin packageAdmin)
throws IllegalArgumentException {
if (bundle == null) {
throw new IllegalArgumentException("Argument bundle cannot be null");
}
if (packageAdmin == null) {
throw new IllegalArgumentException("Argument packageAdmin cannot be null");
}
String[] exportedPackages;
ExportedPackage[] exported = packageAdmin.getExportedPackages(bundle);
if (exported != null) {
exportedPackages = new String[exported.length];
for (int i = 0; i < exported.length; i++) {
exportedPackages[i] = exported[i].getName() + ";" + exported[i].getVersion().toString();
}
} else {
exportedPackages = new String[0];
}
return exportedPackages;
}
/**
* Returns the bundle ids of any resolved fragments
*
* @param bundle
* @param packageAdmin
* @return
* @throws IllegalArgumentException
* if bundle or packageAdmin are null
*/
public static long[] getFragmentIds(Bundle bundle, PackageAdmin packageAdmin) throws IllegalArgumentException {
if (bundle == null) {
throw new IllegalArgumentException("Argument bundle cannot be null");
}
if (packageAdmin == null) {
throw new IllegalArgumentException("Argument packageAdmin cannot be null");
}
long[] fragmentIds;
Bundle[] fragments = packageAdmin.getFragments(bundle);
if (fragments != null) {
fragmentIds = getBundleIds(fragments);
} else {
fragmentIds = new long[0];
}
return fragmentIds;
}
/**
* Returns the bundle ids of any resolved hosts
*
* @param fragment
* @param packageAdmin
* @return
* @throws IllegalArgumentException
* if fragment or packageAdmin are null
*/
public static long[] getHostIds(Bundle fragment, PackageAdmin packageAdmin) throws IllegalArgumentException {
if (fragment == null) {
throw new IllegalArgumentException("Argument bundle cannot be null");
}
if (packageAdmin == null) {
throw new IllegalArgumentException("Argument packageAdmin cannot be null");
}
long[] hostIds;
Bundle[] hosts = packageAdmin.getHosts(fragment);
if (hosts != null) {
hostIds = getBundleIds(hosts);
} else {
hostIds = new long[0];
}
return hostIds;
}
/**
* Returns the resolved package imports for the given bundle
*
* @param localBundleContext
* BundleContext object of this bundle/caller
* @param bundle
* target Bundle object to query imported packages for
* @param packageAdmin
*
* @return
* @throws IllegalArgumentException
* if fragment or packageAdmin are null
*/
public static String[] getBundleImportedPackages(BundleContext localBundleContext, Bundle bundle,
PackageAdmin packageAdmin) throws IllegalArgumentException {
if (bundle == null) {
throw new IllegalArgumentException("Argument bundle cannot be null");
}
if (packageAdmin == null) {
throw new IllegalArgumentException("Argument packageAdmin cannot be null");
}
List<String> result = new ArrayList<String>();
for (ExportedPackage ep : getBundleImportedPackagesRaw(localBundleContext, bundle, packageAdmin)) {
result.add(ep.getName()+";"+ep.getVersion());
}
return result.toArray(new String[0]);
}
@SuppressWarnings("unchecked")
private static Collection<ExportedPackage> getBundleImportedPackagesRaw(BundleContext localBundleContext, Bundle bundle, PackageAdmin packageAdmin) throws IllegalArgumentException
{
List<ExportedPackage> result = new ArrayList<ExportedPackage>();
Dictionary<String, String> bundleHeaders = bundle.getHeaders();
String dynamicImportHeader = bundleHeaders.get(Constants.DYNAMICIMPORT_PACKAGE);
// if DynamicImport-Package used, then do full iteration
// else means no dynamic import or has dynamic import but no wildcard "*" in it.
if (dynamicImportHeader != null && dynamicImportHeader.contains("*")) {
Bundle[] bundles = localBundleContext.getBundles();
for (Bundle candidate : bundles) {
if (candidate.equals(bundle)) {
continue;
}
ExportedPackage[] candidateExports = packageAdmin.getExportedPackages(candidate);
if (candidateExports != null) {
for (ExportedPackage exportedPackage : candidateExports) {
Bundle[] userBundles = exportedPackage.getImportingBundles();
if (userBundles != null && arrayContains(userBundles, bundle)) {
result.add(exportedPackage);
}
}// end for candidateExports
}
}// end for bundles
} else { // only query ExportPackage for package names declared as imported
List<String> importPackages = new ArrayList<String>();
String importPackageHeader = bundleHeaders.get(Constants.IMPORT_PACKAGE);
if (importPackageHeader != null && importPackageHeader.length() > 0) {
importPackages.addAll(extractHeaderDeclaration(importPackageHeader));
}
if (dynamicImportHeader != null) {
importPackages.addAll(extractHeaderDeclaration(dynamicImportHeader));
}
for (String packageName : importPackages) {
ExportedPackage[] candidateExports = packageAdmin.getExportedPackages(packageName);
if (candidateExports != null) {
for (ExportedPackage exportedPackage : candidateExports) {
Bundle[] userBundles = exportedPackage.getImportingBundles();
if (userBundles != null && arrayContains(userBundles, bundle)) {
result.add(exportedPackage);
}
}// end for candidateExports
}
}
}
return result;
}
/**
* Returns the service.id values for services registered by the given bundle
*
* @param bundle
* @return
* @throws IllegalArgumentException
* if bundle is null
* @throws IlleglStateException
* if bundle has been uninstalled
*/
public static long[] getRegisteredServiceIds(Bundle bundle) throws IllegalArgumentException, IllegalStateException {
if (bundle == null) {
throw new IllegalArgumentException("Argument bundle cannot be null");
}
long[] serviceIds;
ServiceReference[] serviceReferences = bundle.getRegisteredServices();
if (serviceReferences != null) {
serviceIds = new long[serviceReferences.length];
for (int i = 0; i < serviceReferences.length; i++) {
serviceIds[i] = (Long) serviceReferences[i].getProperty(Constants.SERVICE_ID);
}
} else {
serviceIds = new long[0];
}
return serviceIds;
}
/**
* Returns the service.id values of services being used by the given bundle
*
* @param bundle
* @return
* @throws IllegalArgumentException
* if bundle is null
* @throws IlleglStateException
* if bundle has been uninstalled
*/
public static long[] getServicesInUseByBundle(Bundle bundle) throws IllegalArgumentException, IllegalStateException {
if (bundle == null) {
throw new IllegalArgumentException("Argument bundle cannot be null");
}
long[] serviceIds;
ServiceReference[] serviceReferences = bundle.getServicesInUse();
if (serviceReferences != null) {
serviceIds = new long[serviceReferences.length];
for (int i = 0; i < serviceReferences.length; i++) {
serviceIds[i] = (Long) serviceReferences[i].getProperty(Constants.SERVICE_ID);
}
} else {
serviceIds = new long[0];
}
return serviceIds;
}
/**
* Returns the status of pending removal
*
* @param bundle
* @return true if the bundle is pending removal
* @throws IllegalArgumentException
* if bundle or packageAdmin are null
*/
public static boolean isBundlePendingRemoval(Bundle bundle, PackageAdmin packageAdmin)
throws IllegalArgumentException {
if (bundle == null) {
throw new IllegalArgumentException("Argument bundle cannot be null");
}
if (packageAdmin == null) {
throw new IllegalArgumentException("Argument packageAdmin cannot be null");
}
boolean result = false;
ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(bundle);
if (exportedPackages != null) {
for (ExportedPackage exportedPackage : exportedPackages) {
if (exportedPackage.isRemovalPending()) {
result = true;
break;
}
}
}
if (!result) {
RequiredBundle[] requiredBundles = packageAdmin.getRequiredBundles(bundle.getSymbolicName());
if (requiredBundles != null) {
for (RequiredBundle requiredBundle : requiredBundles) {
Bundle required = requiredBundle.getBundle();
if (required == bundle) {
result = requiredBundle.isRemovalPending();
break;
}
}
}
}
return result;
}
/**
* Checks if the given bundle is currently required by other bundles
*
* @param bundle
* @param packageAdmin
* @return
* @throws IllegalArgumentException
* if bundle or packageAdmin are null
*/
public static boolean isBundleRequiredByOthers(Bundle bundle, PackageAdmin packageAdmin)
throws IllegalArgumentException {
if (bundle == null) {
throw new IllegalArgumentException("Argument bundle cannot be null");
}
if (packageAdmin == null) {
throw new IllegalArgumentException("Argument packageAdmin cannot be null");
}
boolean result = false;
// Check imported packages (statically or dynamically)
ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(bundle);
if (exportedPackages != null) {
for (ExportedPackage exportedPackage : exportedPackages) {
Bundle[] importingBundles = exportedPackage.getImportingBundles();
if (importingBundles != null && importingBundles.length > 0) {
result = true;
break;
}
}
}
if (!result) {
// Check required bundles
RequiredBundle[] requiredBundles = packageAdmin.getRequiredBundles(bundle.getSymbolicName());
if (requiredBundles != null) {
for (RequiredBundle requiredBundle : requiredBundles) {
Bundle required = requiredBundle.getBundle();
if (required == bundle) {
Bundle[] requiring = requiredBundle.getRequiringBundles();
if (requiring != null && requiring.length > 0) {
result = true;
break;
}
}
}
}
}
if (!result) {
// Check fragment bundles
Bundle[] fragments = packageAdmin.getFragments(bundle);
if (fragments != null && fragments.length > 0) {
result = true;
}
}
return result;
}
/**
* Returns an array of ids of bundles the given bundle depends on
*
* @param localBundleContext
* BundleContext object of this bundle/caller
* @param bundle
* target Bundle object to query dependencies for
* @param packageAdmin
*
* @return
* @throws IllegalArgumentException
* if bundle or packageAdmin are null
*/
@SuppressWarnings("unchecked")
public static long[] getBundleDependencies(BundleContext localBundleContext,
Bundle bundle,
PackageAdmin packageAdmin) throws IllegalArgumentException {
if (bundle == null) {
throw new IllegalArgumentException("Argument bundle cannot be null");
}
if (packageAdmin == null) {
throw new IllegalArgumentException("Argument packageAdmin cannot be null");
}
Set<Bundle> dependencies = new HashSet<Bundle>();
for (ExportedPackage ep : getBundleImportedPackagesRaw(localBundleContext, bundle, packageAdmin)) {
dependencies.add(ep.getExportingBundle());
}
// Handle required bundles
Dictionary<String, String> bundleHeaders = bundle.getHeaders();
String requireBundleHeader = bundleHeaders.get(Constants.REQUIRE_BUNDLE);
if (requireBundleHeader != null) { // only check if Require-Bundle is used
List<String> bundleSymbolicNames = extractHeaderDeclaration(requireBundleHeader);
for (String bundleSymbolicName: bundleSymbolicNames) {
RequiredBundle[] candidateRequiredBundles = packageAdmin.getRequiredBundles(bundleSymbolicName);
if (candidateRequiredBundles != null) {
for (RequiredBundle candidateRequiredBundle : candidateRequiredBundles) {
Bundle[] bundlesRequiring = candidateRequiredBundle.getRequiringBundles();
if (bundlesRequiring != null && arrayContains(bundlesRequiring, bundle)) {
dependencies.add(candidateRequiredBundle.getBundle());
}
}
}
}
}
// Handle fragment bundles
Bundle[] hosts = packageAdmin.getHosts(bundle);
if (hosts != null) {
for (Bundle host : hosts) {
dependencies.add(host);
}
}
return getBundleIds(dependencies.toArray(new Bundle[dependencies.size()]));
}
/**
* Returns an array of ids of bundles that depend on the given bundle
*
* @param bundle
* @param packageAdmin
* @return
* @throws IllegalArgumentException
* if bundle or packageAdmin are null
*/
public static long[] getDependentBundles(Bundle bundle, PackageAdmin packageAdmin) throws IllegalArgumentException {
if (bundle == null) {
throw new IllegalArgumentException("Argument bundle cannot be null");
}
if (packageAdmin == null) {
throw new IllegalArgumentException("Argument packageAdmin cannot be null");
}
Set<Bundle> dependencies = new HashSet<Bundle>();
// Handle imported packages (statically or dynamically)
ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(bundle);
if (exportedPackages != null) {
for (ExportedPackage exportedPackage : exportedPackages) {
Bundle[] importingBundles = exportedPackage.getImportingBundles();
if (importingBundles != null) {
for (Bundle importingBundle : importingBundles) {
dependencies.add(importingBundle);
}
}
}
}
// Handle required bundles
RequiredBundle[] requiredBundles = packageAdmin.getRequiredBundles(bundle.getSymbolicName());
if (requiredBundles != null) {
for (RequiredBundle requiredBundle : requiredBundles) {
Bundle required = requiredBundle.getBundle();
if (required == bundle) {
Bundle[] requiringBundles = requiredBundle.getRequiringBundles();
if (requiringBundles != null) {
for (Bundle requiringBundle : requiringBundles) {
dependencies.add(requiringBundle);
}
}
}
}
}
// Handle fragment bundles
Bundle[] fragments = packageAdmin.getFragments(bundle);
if (fragments != null) {
for (Bundle fragment : fragments) {
dependencies.add(fragment);
}
}
return getBundleIds(dependencies.toArray(new Bundle[dependencies.size()]));
}
/**
* Returns a String representation of the bundles state
*
* @param bundle
* @return
*/
public static String getBundleState(Bundle bundle) {
String state = UNKNOWN;
switch (bundle.getState()) {
case Bundle.INSTALLED:
state = INSTALLED;
break;
case Bundle.RESOLVED:
state = RESOLVED;
break;
case Bundle.STARTING:
state = STARTING;
break;
case Bundle.ACTIVE:
state = ACTIVE;
break;
case Bundle.STOPPING:
state = STOPPING;
break;
case Bundle.UNINSTALLED:
state = UNINSTALLED;
}
return state;
}
/*
* Checks if an object exists in the given array (based on object equality)
*/
public static boolean arrayContains(Object[] array, Object value) {
boolean result = false;
if (array != null && value != null) {
for (Object element : array) {
if (value.equals(element)) {
result = true;
break;
}
}
}
return result;
}
/*
* Will parse a header value, strip out trailing attributes and return a list of declarations
*/
public static List<String> extractHeaderDeclaration(String headerStatement) {
List<String> result = new ArrayList<String>();
for (String headerDeclaration : ManifestHeaderUtils.split(headerStatement, ",")) {
String name = headerDeclaration.contains(";") ? headerDeclaration.substring(0, headerDeclaration
.indexOf(";")) : headerDeclaration;
result.add(name);
}
return result;
}
}
| 8,103 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/util | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/util/shared/RegistrableStandardEmitterMBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.util.shared;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.StandardMBean;
/**
* The <code>StandardMBean</code> does not appear to delegate correctly to the underlying MBean implementation. Due to
* issues surrounding the <code>MBeanRegistration</code> callback methods and <code>NotificationEmmitter</code> methods,
* this subclass was introduced to force the delegation
*
* @version $Rev$ $Date$
*/
public class RegistrableStandardEmitterMBean extends StandardMBean implements MBeanRegistration, NotificationEmitter {
public <T> RegistrableStandardEmitterMBean(T impl, Class<T> intf) throws NotCompliantMBeanException {
super(impl, intf);
}
/**
* @see javax.management.StandardMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
MBeanInfo mbeanInfo = super.getMBeanInfo();
if (mbeanInfo != null) {
MBeanNotificationInfo[] notificationInfo;
Object impl = getImplementation();
if (impl instanceof NotificationEmitter) {
notificationInfo = ((NotificationEmitter) (impl)).getNotificationInfo();
} else {
notificationInfo = new MBeanNotificationInfo[0];
}
mbeanInfo = new MBeanInfo(mbeanInfo.getClassName(), mbeanInfo.getDescription(), mbeanInfo.getAttributes(),
mbeanInfo.getConstructors(), mbeanInfo.getOperations(), notificationInfo);
}
return mbeanInfo;
}
/**
* @see javax.management.MBeanRegistration#postDeregister()
*/
public void postDeregister() {
Object impl = getImplementation();
if (impl instanceof MBeanRegistration) {
((MBeanRegistration) impl).postDeregister();
}
}
/**
* @see javax.management.MBeanRegistration#postRegister(java.lang.Boolean)
*/
public void postRegister(Boolean registrationDone) {
Object impl = getImplementation();
if (impl instanceof MBeanRegistration) {
((MBeanRegistration) impl).postRegister(registrationDone);
}
}
/**
* @see javax.management.MBeanRegistration#preDeregister()
*/
public void preDeregister() throws Exception {
Object impl = getImplementation();
if (impl instanceof MBeanRegistration) {
((MBeanRegistration) impl).preDeregister();
}
}
/**
* @see javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName)
*/
public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
ObjectName result = name;
Object impl = getImplementation();
if (impl instanceof MBeanRegistration) {
result = ((MBeanRegistration) impl).preRegister(server, name);
}
return result;
}
/**
* @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener,
* javax.management.NotificationFilter, java.lang.Object)
*/
public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
throws ListenerNotFoundException {
Object impl = getImplementation();
if (impl instanceof NotificationEmitter) {
((NotificationEmitter) (impl)).removeNotificationListener(listener, filter, handback);
}
}
/**
* @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener,
* javax.management.NotificationFilter, java.lang.Object)
*/
public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
throws IllegalArgumentException {
Object impl = getImplementation();
if (impl instanceof NotificationEmitter) {
((NotificationEmitter) (impl)).addNotificationListener(listener, filter, handback);
}
}
/**
* @see javax.management.NotificationBroadcaster#getNotificationInfo()
*/
public MBeanNotificationInfo[] getNotificationInfo() {
MBeanNotificationInfo[] result;
Object impl = getImplementation();
if (impl instanceof NotificationEmitter) {
result = ((NotificationEmitter) (impl)).getNotificationInfo();
} else {
result = new MBeanNotificationInfo[0];
}
return result;
}
/**
* @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)
*/
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
Object impl = getImplementation();
if (impl instanceof NotificationEmitter) {
((NotificationEmitter) (impl)).removeNotificationListener(listener);
}
}
}
| 8,104 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/BundleStateMBeanHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.osgi.jmx.framework.BundleStateMBean.OBJECTNAME;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.MBeanHandler;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.apache.aries.jmx.util.ObjectNameUtils;
import org.apache.aries.jmx.util.shared.RegistrableStandardEmitterMBean;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.jmx.framework.BundleStateMBean;
import org.osgi.service.log.LogService;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;
/**
* <p>
* Implementation of <code>MBeanHandler</code> which manages the <code>BundleState</code>
* MBean implementation
* @see MBeanHandler
* </p>
*
* @version $Rev$ $Date$
*/
public class BundleStateMBeanHandler implements MBeanHandler {
private JMXAgentContext agentContext;
private StateConfig stateConfig;
private Logger logger;
private String name;
private StandardMBean mbean;
private BundleState bundleStateMBean;
private BundleContext bundleContext;
private ServiceReference packageAdminRef;
private ServiceReference startLevelRef;
public BundleStateMBeanHandler(JMXAgentContext agentContext, StateConfig stateConfig) {
this.agentContext = agentContext;
this.stateConfig = stateConfig;
this.bundleContext = agentContext.getBundleContext();
this.logger = agentContext.getLogger();
this.name = ObjectNameUtils.createFullObjectName(bundleContext, OBJECTNAME);
}
/**
* @see org.apache.aries.jmx.MBeanHandler#open()
*/
public void open() {
packageAdminRef = bundleContext.getServiceReference(PackageAdmin.class.getName());
PackageAdmin packageAdmin = (PackageAdmin) bundleContext.getService(packageAdminRef);
startLevelRef = bundleContext.getServiceReference(StartLevel.class.getName());
StartLevel startLevel = (StartLevel) bundleContext.getService(startLevelRef);
bundleStateMBean = new BundleState(bundleContext, packageAdmin, startLevel, stateConfig, logger);
try {
mbean = new RegistrableStandardEmitterMBean(bundleStateMBean, BundleStateMBean.class);
} catch (NotCompliantMBeanException e) {
logger.log(LogService.LOG_ERROR, "Failed to instantiate MBean for " + BundleStateMBean.class.getName(), e);
}
agentContext.registerMBean(this);
}
/**
* @see org.apache.aries.jmx.MBeanHandler#getMbean()
*/
public StandardMBean getMbean() {
return mbean;
}
/**
* @see org.apache.aries.jmx.MBeanHandler#getName()
*/
public String getName() {
return name;
}
/**
* @see org.apache.aries.jmx.MBeanHandler#close()
*/
public void close() {
agentContext.unregisterMBean(this);
if (packageAdminRef != null) {
try {
bundleContext.ungetService(packageAdminRef);
} catch (RuntimeException e) {
logger.log(LogService.LOG_WARNING, "Exception occured during cleanup", e);
}
packageAdminRef = null;
}
if (startLevelRef != null) {
try {
bundleContext.ungetService(startLevelRef);
} catch (RuntimeException e) {
logger.log(LogService.LOG_WARNING, "Exception occured during cleanup", e);
}
startLevelRef = null;
}
// ensure dispatcher is shutdown even if postDeRegister is not honored
if (bundleStateMBean != null) {
bundleStateMBean.shutDownDispatcher();
}
}
}
| 8,105 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/BundleState.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleDependencies;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleExportedPackages;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleImportedPackages;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleState;
import static org.apache.aries.jmx.util.FrameworkUtils.getDependentBundles;
import static org.apache.aries.jmx.util.FrameworkUtils.getFragmentIds;
import static org.apache.aries.jmx.util.FrameworkUtils.getHostIds;
import static org.apache.aries.jmx.util.FrameworkUtils.getRegisteredServiceIds;
import static org.apache.aries.jmx.util.FrameworkUtils.getServicesInUseByBundle;
import static org.apache.aries.jmx.util.FrameworkUtils.isBundlePendingRemoval;
import static org.apache.aries.jmx.util.FrameworkUtils.isBundleRequiredByOthers;
import static org.apache.aries.jmx.util.FrameworkUtils.resolveBundle;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.management.AttributeChangeNotification;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.apache.aries.jmx.JMXThreadFactory;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.codec.BundleData;
import org.apache.aries.jmx.codec.BundleData.Header;
import org.apache.aries.jmx.codec.BundleEventData;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
import org.osgi.jmx.framework.BundleStateMBean;
import org.osgi.service.log.LogService;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;
/**
* Implementation of <code>BundleStateMBean</code> which emits JMX <code>Notification</code> on <code>Bundle</code>
* state changes.
*
* @version $Rev$ $Date$
*/
public class BundleState extends NotificationBroadcasterSupport implements BundleStateMBean, MBeanRegistration {
protected Logger logger;
protected BundleContext bundleContext;
protected PackageAdmin packageAdmin;
protected StartLevel startLevel;
protected StateConfig stateConfig;
protected ExecutorService eventDispatcher;
protected BundleListener bundleListener;
private AtomicInteger notificationSequenceNumber = new AtomicInteger(1);
private AtomicInteger attributeChangeNotificationSequenceNumber = new AtomicInteger(1);
private Lock lock = new ReentrantLock();
private AtomicInteger registrations = new AtomicInteger(0);
// notification type description
public static String BUNDLE_EVENT = "org.osgi.bundle.event";
public BundleState(BundleContext bundleContext, PackageAdmin packageAdmin, StartLevel startLevel, StateConfig stateConfig, Logger logger) {
this.bundleContext = bundleContext;
this.packageAdmin = packageAdmin;
this.startLevel = startLevel;
this.stateConfig = stateConfig;
this.logger = logger;
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getExportedPackages(long)
*/
public String[] getExportedPackages(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return getBundleExportedPackages(bundle, packageAdmin);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getFragments(long)
*/
public long[] getFragments(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return getFragmentIds(bundle, packageAdmin);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getHeaders(long)
*/
public TabularData getHeaders(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
Dictionary<String, String> bundleHeaders = bundle.getHeaders();
return getHeaders(bundleHeaders);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getHeaders(long, java.lang.String)
*/
public TabularData getHeaders(long bundleId, String locale) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
Dictionary<String, String> bundleHeaders = bundle.getHeaders(locale);
return getHeaders(bundleHeaders);
}
private TabularData getHeaders(Dictionary<String, String> bundleHeaders) {
List<Header> headers = new ArrayList<Header>();
Enumeration<String> keys = bundleHeaders.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
headers.add(new Header(key, bundleHeaders.get(key)));
}
TabularData headerTable = new TabularDataSupport(HEADERS_TYPE);
for (Header header : headers) {
headerTable.put(header.toCompositeData());
}
return headerTable;
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getHeader(long, java.lang.String)
*/
public String getHeader(long bundleId, String key) throws IOException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return bundle.getHeaders().get(key);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getHeader(long, java.lang.String, java.lang.String)
*/
public String getHeader(long bundleId, String key, String locale) throws IOException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return bundle.getHeaders(locale).get(key);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getHosts(long)
*/
public long[] getHosts(long fragmentId) throws IOException, IllegalArgumentException {
Bundle fragment = resolveBundle(bundleContext, fragmentId);
return getHostIds(fragment, packageAdmin);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getImportedPackages(long)
*/
public String[] getImportedPackages(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return getBundleImportedPackages(bundleContext, bundle, packageAdmin);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getLastModified(long)
*/
public long getLastModified(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return bundle.getLastModified();
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getLocation(long)
*/
public String getLocation(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return bundle.getLocation();
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getRegisteredServices(long)
*/
public long[] getRegisteredServices(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return getRegisteredServiceIds(bundle);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getRequiredBundles(long)
*/
public long[] getRequiredBundles(long bundleIdentifier) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleIdentifier);
return getBundleDependencies(bundleContext, bundle, packageAdmin);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getRequiringBundles(long)
*/
public long[] getRequiringBundles(long bundleIdentifier) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleIdentifier);
return getDependentBundles(bundle, packageAdmin);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getServicesInUse(long)
*/
public long[] getServicesInUse(long bundleIdentifier) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleIdentifier);
return getServicesInUseByBundle(bundle);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getStartLevel(long)
*/
public int getStartLevel(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return startLevel.getBundleStartLevel(bundle);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getState(long)
*/
public String getState(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return getBundleState(bundle);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getSymbolicName(long)
*/
public String getSymbolicName(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return bundle.getSymbolicName();
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#getVersion(long)
*/
public String getVersion(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return bundle.getVersion().toString();
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#isFragment(long)
*/
public boolean isFragment(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return (PackageAdmin.BUNDLE_TYPE_FRAGMENT == packageAdmin.getBundleType(bundle));
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#isActivationPolicyUsed(long)
*/
public boolean isActivationPolicyUsed(long bundleId) throws IOException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return startLevel.isBundleActivationPolicyUsed(bundle);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#isPersistentlyStarted(long)
*/
public boolean isPersistentlyStarted(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return startLevel.isBundlePersistentlyStarted(bundle);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#isRemovalPending(long)
*/
public boolean isRemovalPending(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return isBundlePendingRemoval(bundle, packageAdmin);
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#isRequired(long)
*/
public boolean isRequired(long bundleId) throws IOException, IllegalArgumentException {
Bundle bundle = resolveBundle(bundleContext, bundleId);
return isBundleRequiredByOthers(bundle, packageAdmin);
}
public CompositeData getBundle(long id) throws IOException {
Bundle bundle = bundleContext.getBundle(id);
if (bundle == null)
return null;
BundleData data = new BundleData(bundleContext, bundle, packageAdmin, startLevel);
return data.toCompositeData();
}
public long[] getBundleIds() throws IOException {
Bundle[] bundles = bundleContext.getBundles();
long[] ids = new long[bundles.length];
for (int i=0; i < bundles.length; i++) {
ids[i] = bundles[i].getBundleId();
}
// The IDs are sorted here. It's not required by the spec but it's nice
// to have an ordered list returned.
Arrays.sort(ids);
return ids;
}
/**
* @see org.osgi.jmx.framework.BundleStateMBean#listBundles()
*/
public TabularData listBundles() throws IOException {
return listBundles(BundleStateMBean.BUNDLE_TYPE.keySet());
}
public TabularData listBundles(String ... items) throws IOException {
return listBundles(Arrays.asList(items));
}
private TabularData listBundles(Collection<String> items) throws IOException {
Bundle[] containerBundles = bundleContext.getBundles();
List<BundleData> bundleDatas = new ArrayList<BundleData>();
if (containerBundles != null) {
for (Bundle containerBundle : containerBundles) {
bundleDatas.add(new BundleData(bundleContext, containerBundle, packageAdmin, startLevel));
}
}
TabularData bundleTable = new TabularDataSupport(BUNDLES_TYPE);
for (BundleData bundleData : bundleDatas) {
bundleTable.put(bundleData.toCompositeData(items));
}
return bundleTable;
}
/**
* @see javax.management.NotificationBroadcasterSupport#getNotificationInfo()
*/
public MBeanNotificationInfo[] getNotificationInfo() {
MBeanNotificationInfo eventInfo = new MBeanNotificationInfo(
new String[] { BUNDLE_EVENT },
Notification.class.getName(),
"A BundleEvent issued from the Framework describing a bundle lifecycle change");
MBeanNotificationInfo attributeChangeInfo = new MBeanNotificationInfo(
new String [] {AttributeChangeNotification.ATTRIBUTE_CHANGE },
AttributeChangeNotification.class.getName(),
"An attribute of this MBean has changed");
return new MBeanNotificationInfo[] { eventInfo, attributeChangeInfo };
}
/**
* @see javax.management.MBeanRegistration#postDeregister()
*/
public void postDeregister() {
if (registrations.decrementAndGet() < 1) {
shutDownDispatcher();
}
}
/**
* @see javax.management.MBeanRegistration#postRegister(java.lang.Boolean)
*/
public void postRegister(Boolean registrationDone) {
if (registrationDone && registrations.incrementAndGet() == 1) {
eventDispatcher = Executors.newSingleThreadExecutor(new JMXThreadFactory("JMX OSGi Bundle State Event Dispatcher"));
bundleContext.addBundleListener(bundleListener);
}
}
/**
* @see javax.management.MBeanRegistration#preDeregister()
*/
public void preDeregister() throws Exception {
// No action
}
/**
* @see javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName)
*/
public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
lock.lock();
try {
if (bundleListener == null) {
bundleListener = new BundleListener() {
public void bundleChanged(BundleEvent event) {
if (stateConfig != null && !stateConfig.isBundleChangeNotificationEnabled()) {
return;
}
try {
final Notification notification = new Notification(EVENT, OBJECTNAME,
notificationSequenceNumber.getAndIncrement());
notification.setUserData(new BundleEventData(event).toCompositeData());
// also send notifications to the bundleIDs attribute listeners, if a bundle was added or removed
final AttributeChangeNotification attributeChangeNotification =
getAttributeChangeNotification(event);
eventDispatcher.submit(new Runnable() {
public void run() {
sendNotification(notification);
if (attributeChangeNotification != null)
sendNotification(attributeChangeNotification);
}
});
} catch (RejectedExecutionException re) {
logger.log(LogService.LOG_WARNING, "Task rejected for JMX Notification dispatch of event ["
+ event + "] - Dispatcher may have been shutdown");
} catch (Exception e) {
logger.log(LogService.LOG_WARNING,
"Exception occured on JMX Notification dispatch for event [" + event + "]", e);
}
}
};
}
} finally {
lock.unlock();
}
return name;
}
protected AttributeChangeNotification getAttributeChangeNotification(BundleEvent event) throws IOException {
if (stateConfig != null && !stateConfig.isAttributeChangeNotificationEnabled()) {
return null;
}
int eventType = event.getType();
switch (eventType) {
case BundleEvent.INSTALLED:
case BundleEvent.UNINSTALLED:
long bundleID = event.getBundle().getBundleId();
long[] ids = getBundleIds();
List<Long> without = new ArrayList<Long>();
for (long id : ids) {
if (id != bundleID)
without.add(id);
}
List<Long> with = new ArrayList<Long>(without);
with.add(bundleID);
// Sorting is not mandatory, but its nice for the user, note that getBundleIds() also returns a sorted array
Collections.sort(with);
List<Long> oldList = eventType == BundleEvent.INSTALLED ? without : with;
List<Long> newList = eventType == BundleEvent.INSTALLED ? with : without;
long[] oldIDs = new long[oldList.size()];
for (int i = 0; i < oldIDs.length; i++) {
oldIDs[i] = oldList.get(i);
}
long[] newIDs = new long[newList.size()];
for (int i = 0; i < newIDs.length; i++) {
newIDs[i] = newList.get(i);
}
return new AttributeChangeNotification(OBJECTNAME, attributeChangeNotificationSequenceNumber.getAndIncrement(),
System.currentTimeMillis(), "BundleIds changed", "BundleIds", "Array of long", oldIDs, newIDs);
default:
return null;
}
}
/*
* Shuts down the notification dispatcher
* [ARIES-259] MBeans not getting unregistered reliably
*/
protected void shutDownDispatcher() {
if (bundleListener != null) {
try {
bundleContext.removeBundleListener(bundleListener);
}
catch (Exception e) {
// ignore
}
}
if (eventDispatcher != null) {
eventDispatcher.shutdown();
}
}
/*
* Returns the ExecutorService used to dispatch Notifications
*/
protected ExecutorService getEventDispatcher() {
return eventDispatcher;
}
}
| 8,106 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/StateConfig.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import org.osgi.framework.BundleContext;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;
/**
* Configuration for {@link BundleState} and {@link ServiceState}.
*
* @version $Rev$ $Date$
*/
public class StateConfig implements ManagedService {
private static final String PID = StateConfig.class.getName();
private static final String ATTRIBUTE_CHANGE_NOTIFICATION_ENABLED = "attributeChangeNotificationEnabled";
private static final boolean DEFAULT_ATTRIBUTE_CHANGE_NOTIFICATION_ENABLED = true;
private static final String SERVICE_CHANGE_NOTIFICATION_ENABLED = "serviceChangeNotificationEnabled";
private static final boolean DEFAULT_SERVICE_CHANGE_NOTIFICATION_ENABLED = true;
private static final String BUNDLE_CHANGE_NOTIFICATION_ENABLED = "bundleChangeNotificationEnabled";
private static final boolean DEFAULT_BUNDLE_CHANGE_NOTIFICATION_ENABLED = true;
private volatile boolean attributeChangeNotificationEnabled = DEFAULT_ATTRIBUTE_CHANGE_NOTIFICATION_ENABLED;
private volatile boolean serviceChangeNotificationEnabled = DEFAULT_SERVICE_CHANGE_NOTIFICATION_ENABLED;
private volatile boolean bundleChangeNotificationEnabled = DEFAULT_BUNDLE_CHANGE_NOTIFICATION_ENABLED;
void setAttributeChangeNotificationEnabled(boolean attributeChangeNotificationEnabled) {
this.attributeChangeNotificationEnabled = attributeChangeNotificationEnabled;
}
void setServiceChangeNotificationEnabled(boolean serviceChangeNotificationEnabled) {
this.serviceChangeNotificationEnabled = serviceChangeNotificationEnabled;
}
void setBundleChangeNotificationEnabled(boolean bundleChangeNotificationEnabled) {
this.bundleChangeNotificationEnabled = bundleChangeNotificationEnabled;
}
/**
* Registers this service and returns an instance.
*
* @param context the bundle context
* @return the service instance
* @throws IOException
*/
public static StateConfig register(BundleContext context) throws IOException {
Dictionary<String, Object> serviceProps = new Hashtable<String, Object>();
serviceProps.put("service.pid", PID);
StateConfig stateConfig = new StateConfig();
context.registerService(ManagedService.class, stateConfig, serviceProps);
return stateConfig;
}
@Override
public void updated(Dictionary<String, ?> dictionary) throws ConfigurationException {
attributeChangeNotificationEnabled = getBoolean(dictionary, ATTRIBUTE_CHANGE_NOTIFICATION_ENABLED,
DEFAULT_ATTRIBUTE_CHANGE_NOTIFICATION_ENABLED);
serviceChangeNotificationEnabled = getBoolean(dictionary, SERVICE_CHANGE_NOTIFICATION_ENABLED,
DEFAULT_SERVICE_CHANGE_NOTIFICATION_ENABLED);
bundleChangeNotificationEnabled = getBoolean(dictionary, BUNDLE_CHANGE_NOTIFICATION_ENABLED,
DEFAULT_BUNDLE_CHANGE_NOTIFICATION_ENABLED);
}
/**
* Whether or not JMX attribute change notifications should be triggered when attributes change.
*
* @return <code>true</code> if attribute change notifications are enabled
*/
public boolean isAttributeChangeNotificationEnabled() {
return attributeChangeNotificationEnabled;
}
/**
* Whether or not JMX OSGi service change notifications should be triggered when OSGi service change.
*
* @return <code>true</code> if OSGi service change notifications are enabled
*/
public boolean isServiceChangeNotificationEnabled() {
return serviceChangeNotificationEnabled;
}
/**
* Whether or not JMX bundle change notifications should be triggered when bundle change.
*
* @return <code>true</code> if bundle change notifications are enabled
*/
public boolean isBundleChangeNotificationEnabled() {
return bundleChangeNotificationEnabled;
}
private static boolean getBoolean(Dictionary<String, ?> dictionary, String propertyName, boolean defaultValue) {
Object object = (dictionary != null) ? dictionary.get(propertyName) : null;
if (object == null) {
return defaultValue;
} else if (object instanceof Boolean) {
return (Boolean) object;
} else {
String string = object.toString();
return !string.isEmpty() ? Boolean.parseBoolean(string) : defaultValue;
}
}
}
| 8,107 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/ServiceStateMBeanHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.osgi.jmx.framework.ServiceStateMBean.OBJECTNAME;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.MBeanHandler;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.apache.aries.jmx.util.ObjectNameUtils;
import org.apache.aries.jmx.util.shared.RegistrableStandardEmitterMBean;
import org.osgi.framework.BundleContext;
import org.osgi.jmx.framework.ServiceStateMBean;
import org.osgi.service.log.LogService;
/**
* <p>
* Implementation of <code>MBeanHandler</code> which manages the <code>ServiceState</code>
* MBean implementation
* @see MBeanHandler
* </p>
*
* @version $Rev$ $Date$
*/
public class ServiceStateMBeanHandler implements MBeanHandler {
private JMXAgentContext agentContext;
private StateConfig stateConfig;
private String name;
private StandardMBean mbean;
private ServiceState serviceStateMBean;
private BundleContext bundleContext;
private Logger logger;
public ServiceStateMBeanHandler(JMXAgentContext agentContext, StateConfig stateConfig) {
this.agentContext = agentContext;
this.stateConfig = stateConfig;
this.bundleContext = agentContext.getBundleContext();
this.logger = agentContext.getLogger();
this.name = ObjectNameUtils.createFullObjectName(bundleContext, OBJECTNAME);
}
/**
* @see org.apache.aries.jmx.MBeanHandler#open()
*/
public void open() {
serviceStateMBean = new ServiceState(bundleContext, stateConfig, logger);
try {
mbean = new RegistrableStandardEmitterMBean(serviceStateMBean, ServiceStateMBean.class);
} catch (NotCompliantMBeanException e) {
logger.log(LogService.LOG_ERROR, "Failed to instantiate MBean for " + ServiceStateMBean.class.getName(), e);
}
agentContext.registerMBean(this);
}
/**
* @see org.apache.aries.jmx.MBeanHandler#getMbean()
*/
public StandardMBean getMbean() {
return mbean;
}
/**
* @see org.apache.aries.jmx.MBeanHandler#getName()
*/
public String getName() {
return name;
}
/**
* @see org.apache.aries.jmx.MBeanHandler#close()
*/
public void close() {
agentContext.unregisterMBean(this);
// ensure dispatcher is shutdown even if postDeRegister is not honored
if (serviceStateMBean != null) {
serviceStateMBean.shutDownDispatcher();
}
}
}
| 8,108 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/PackageStateMBeanHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.MBeanHandler;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.apache.aries.jmx.util.ObjectNameUtils;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.jmx.framework.PackageStateMBean;
import org.osgi.service.log.LogService;
import org.osgi.service.packageadmin.PackageAdmin;
/**
* <p>
* <tt>PackageStateMBeanHandler</tt> represents MBeanHandler which
* holding information about {@link PackageStateMBean}.</p>
*
* @see MBeanHandler
*
* @version $Rev$ $Date$
*/
public class PackageStateMBeanHandler implements MBeanHandler {
private JMXAgentContext agentContext;
private String name;
private StandardMBean mbean;
private BundleContext context;
private Logger logger;
/**
* Constructs new PackageStateMBeanHandler.
*/
public PackageStateMBeanHandler(JMXAgentContext agentContext) {
this.agentContext = agentContext;
this.context = agentContext.getBundleContext();
this.logger = agentContext.getLogger();
this.name = ObjectNameUtils.createFullObjectName(context, PackageStateMBean.OBJECTNAME);
}
/**
* @see org.apache.aries.jmx.MBeanHandler#getMbean()
*/
public StandardMBean getMbean() {
return mbean;
}
/**
* @see org.apache.aries.jmx.MBeanHandler#open()
*/
public void open() {
ServiceReference adminRef = context.getServiceReference(PackageAdmin.class.getCanonicalName());
PackageAdmin packageAdmin = (PackageAdmin) context.getService(adminRef);
PackageStateMBean packageState = new PackageState(context, packageAdmin);
try {
mbean = new StandardMBean(packageState, PackageStateMBean.class);
} catch (NotCompliantMBeanException e) {
logger.log(LogService.LOG_ERROR, "Not compliant MBean", e);
}
agentContext.registerMBean(this);
}
/**
* @see org.apache.aries.jmx.MBeanHandler#close()
*/
public void close() {
agentContext.unregisterMBean(this);
}
/**
* @see org.apache.aries.jmx.MBeanHandler#getName()
*/
public String getName() {
return name;
}
}
| 8,109 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/Framework.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.management.openmbean.CompositeData;
import org.apache.aries.jmx.codec.BatchActionResult;
import org.apache.aries.jmx.codec.BatchInstallResult;
import org.apache.aries.jmx.codec.BatchResolveResult;
import org.apache.aries.jmx.util.FrameworkUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.wiring.FrameworkWiring;
import org.osgi.jmx.framework.FrameworkMBean;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;
/**
* <p>
* <tt>Framework</tt> represents {@link FrameworkMBean} implementation.
* </p>
* @see FrameworkMBean
*
* @version $Rev$ $Date$
*/
public class Framework implements FrameworkMBean {
private StartLevel startLevel;
private PackageAdmin packageAdmin;
private BundleContext context;
/**
* Constructs new FrameworkMBean.
*
* @param context bundle context of jmx bundle.
* @param startLevel @see {@link StartLevel} service reference.
* @param packageAdmin @see {@link PackageAdmin} service reference.
*/
public Framework(BundleContext context, StartLevel startLevel, PackageAdmin packageAdmin) {
this.context = context;
this.startLevel = startLevel;
this.packageAdmin = packageAdmin;
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#getDependencyClosureBundles(long[])
*/
public long[] getDependencyClosure(long[] bundles) throws IOException {
FrameworkWiring fw = context.getBundle(0).adapt(FrameworkWiring.class);
List<Bundle> bl = new ArrayList<Bundle>();
for (int i=0; i < bundles.length; i++) {
bl.add(context.getBundle(bundles[i]));
}
Collection<Bundle> rc = fw.getDependencyClosure(bl);
Iterator<Bundle> it = rc.iterator();
long[] result = new long[rc.size()];
for (int i = 0; i < result.length; i++) {
result[i] = it.next().getBundleId();
}
return result;
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#getFrameworkStartLevel()
*/
public int getFrameworkStartLevel() throws IOException {
return startLevel.getStartLevel();
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#getInitialBundleStartLevel()
*/
public int getInitialBundleStartLevel() throws IOException {
return startLevel.getInitialBundleStartLevel();
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#getProperty(java.lang.String)
*/
public String getProperty(String key) {
return context.getProperty(key);
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#getRemovalPendingBundles()
*/
public long[] getRemovalPendingBundles() throws IOException {
FrameworkWiring fw = context.getBundle(0).adapt(FrameworkWiring.class);
Collection<Bundle> rc = fw.getRemovalPendingBundles();
Iterator<Bundle> it = rc.iterator();
long[] result = new long[rc.size()];
for (int i = 0; i < result.length; i++) {
result[i] = it.next().getBundleId();
}
return result;
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#installBundle(java.lang.String)
*/
public long installBundle(String location) throws IOException {
try {
Bundle bundle = context.installBundle(location);
return bundle.getBundleId();
} catch (Exception e) {
IOException ioex = new IOException("Installation of a bundle with location " + location + " failed with the message: " + e.getMessage());
ioex.initCause(e);
throw ioex;
}
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#installBundleFromURL(String, String)
*/
public long installBundleFromURL(String location, String url) throws IOException {
InputStream inputStream = null;
try {
inputStream = createStream(url);
Bundle bundle = context.installBundle(location, inputStream);
return bundle.getBundleId();
} catch (Exception e) {
IOException ioex = new IOException("Installation of a bundle with location " + location + " failed with the message: " + e.getMessage());
ioex.initCause(e);
throw ioex;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ioe) {
}
}
}
}
public InputStream createStream(String url) throws IOException {
return new URL(url).openStream();
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#installBundles(java.lang.String[])
*/
public CompositeData installBundles(String[] locations) throws IOException {
if(locations == null){
return new BatchInstallResult("Failed to install bundles locations can't be null").toCompositeData();
}
long[] ids = new long[locations.length];
for (int i = 0; i < locations.length; i++) {
try {
long id = installBundle(locations[i]);
ids[i] = id;
} catch (Throwable t) {
long[] completed = new long[i];
System.arraycopy(ids, 0, completed, 0, i);
String[] remaining = new String[locations.length - i - 1];
System.arraycopy(locations, i + 1, remaining, 0, remaining.length);
return new BatchInstallResult(completed, t.toString(), remaining, locations[i]).toCompositeData();
}
}
return new BatchInstallResult(ids).toCompositeData();
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#installBundlesFromURL(String[], String[])
*/
public CompositeData installBundlesFromURL(String[] locations, String[] urls) throws IOException {
if(locations == null || urls == null){
return new BatchInstallResult("Failed to install bundles arguments can't be null").toCompositeData();
}
if(locations.length != urls.length){
return new BatchInstallResult("Failed to install bundles size of arguments should be same").toCompositeData();
}
long[] ids = new long[locations.length];
for (int i = 0; i < locations.length; i++) {
try {
long id = installBundleFromURL(locations[i], urls[i]);
ids[i] = id;
} catch (Throwable t) {
long[] completed = new long[i];
System.arraycopy(ids, 0, completed, 0, i);
String[] remaining = new String[locations.length - i - 1];
System.arraycopy(locations, i + 1, remaining, 0, remaining.length);
return new BatchInstallResult(completed, t.toString(), remaining, locations[i]).toCompositeData();
}
}
return new BatchInstallResult(ids).toCompositeData();
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#refreshBundle(long)
*/
public void refreshBundle(long bundleIdentifier) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
packageAdmin.refreshPackages(new Bundle[] { bundle });
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#refreshBundleAndWait(long)
*/
public boolean refreshBundleAndWait(long bundleIdentifier) throws IOException {
Bundle[] bundleArray = new Bundle[1];
refreshBundlesAndWait(new long[] {bundleIdentifier}, bundleArray);
return isResolved(bundleArray[0].getState());
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#refreshBundles(long[])
*/
public void refreshBundles(long[] bundleIdentifiers) throws IOException {
Bundle[] bundles = null;
if(bundleIdentifiers != null) {
bundles = new Bundle[bundleIdentifiers.length];
for (int i = 0; i < bundleIdentifiers.length; i++) {
try {
bundles[i] = FrameworkUtils.resolveBundle(context, bundleIdentifiers[i]);
} catch (Exception e) {
IOException ex = new IOException("Unable to find bundle with id " + bundleIdentifiers[i]);
ex.initCause(e);
throw ex;
}
}
}
packageAdmin.refreshPackages(bundles);
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#refreshBundlesAndWait(long[])
*/
public CompositeData refreshBundlesAndWait(long[] bundleIdentifiers) throws IOException {
Bundle [] bundles = bundleIdentifiers != null ? new Bundle[bundleIdentifiers.length] : null;
refreshBundlesAndWait(bundleIdentifiers, bundles);
return constructResolveResult(bundles);
}
private void refreshBundlesAndWait(long[] bundleIdentifiers, Bundle[] bundles) throws IOException {
final CountDownLatch latch = new CountDownLatch(1);
FrameworkListener listener = new FrameworkListener() {
public void frameworkEvent(FrameworkEvent event) {
if (FrameworkEvent.PACKAGES_REFRESHED == event.getType()) {
latch.countDown();
}
}
};
try {
context.addFrameworkListener(listener);
try {
if (bundles != null) {
for (int i=0; i < bundleIdentifiers.length; i++) {
bundles[i] = FrameworkUtils.resolveBundle(context, bundleIdentifiers[i]);
}
}
packageAdmin.refreshPackages(bundles);
if (latch.await(30, TimeUnit.SECONDS))
return;
else
throw new IOException("Refresh operation timed out");
} catch (InterruptedException e) {
IOException ex = new IOException();
ex.initCause(e);
throw ex;
}
} finally {
context.removeFrameworkListener(listener);
}
}
private CompositeData constructResolveResult(Bundle[] bundles) {
if (bundles == null)
bundles = context.getBundles();
boolean result = true;
List<Long> successList = new ArrayList<Long>();
for (Bundle bundle : bundles) {
int state = bundle.getState();
if (isResolved(state)) {
successList.add(bundle.getBundleId());
} else
result = false;
}
return new BatchResolveResult(result, successList.toArray(new Long[] {})).toCompositeData();
}
private boolean isResolved(int state) {
return (state & (Bundle.RESOLVED | Bundle.STARTING | Bundle.ACTIVE)) > 0;
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#resolveBundle(long)
*/
public boolean resolveBundle(long bundleIdentifier) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
return packageAdmin.resolveBundles(new Bundle[] { bundle });
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#resolveBundles(long[])
*/
public boolean resolveBundles(long[] bundleIdentifiers) throws IOException {
Bundle[] bundles = null;
if (bundleIdentifiers != null)
bundles = new Bundle[bundleIdentifiers.length];
return resolveBundles(bundleIdentifiers, bundles);
}
private boolean resolveBundles(long[] bundleIdentifiers, Bundle[] bundles) throws IOException {
if (bundleIdentifiers != null) {
for (int i = 0; i < bundleIdentifiers.length; i++) {
try {
bundles[i] = FrameworkUtils.resolveBundle(context, bundleIdentifiers[i]);
} catch (Exception e) {
IOException ex = new IOException("Unable to find bundle with id " + bundleIdentifiers[i]);
ex.initCause(e);
throw ex;
}
}
}
return packageAdmin.resolveBundles(bundles);
}
public CompositeData resolve(long[] bundleIdentifiers) throws IOException {
Bundle[] bundles = null;
if (bundleIdentifiers != null)
bundles = new Bundle[bundleIdentifiers.length];
resolveBundles(bundleIdentifiers, bundles);
return constructResolveResult(bundles);
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#restartFramework()
*/
public void restartFramework() throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(context, 0);
try {
bundle.update();
} catch (Exception be) {
IOException ioex = new IOException("Framework restart failed with message: " + be.getMessage());
ioex.initCause(be);
throw ioex;
}
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#setBundleStartLevel(long, int)
*/
public void setBundleStartLevel(long bundleIdentifier, int newlevel) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
try {
startLevel.setBundleStartLevel(bundle, newlevel);
} catch (IllegalArgumentException e) {
IOException ioex = new IOException("Setting the start level for bundle with id " + bundle.getBundleId() + " to level " + newlevel + " failed with message: " + e.getMessage());
ioex.initCause(e);
throw ioex;
}
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#setBundleStartLevels(long[], int[])
*/
public CompositeData setBundleStartLevels(long[] bundleIdentifiers, int[] newlevels) throws IOException {
if (bundleIdentifiers == null || newlevels == null) {
return new BatchActionResult("Failed to setBundleStartLevels arguments can't be null").toCompositeData();
}
if (bundleIdentifiers != null && newlevels != null && bundleIdentifiers.length != newlevels.length) {
return new BatchActionResult("Failed to setBundleStartLevels size of arguments should be same").toCompositeData();
}
for (int i = 0; i < bundleIdentifiers.length; i++) {
try {
setBundleStartLevel(bundleIdentifiers[i], newlevels[i]);
} catch (Throwable t) {
return createFailedBatchActionResult(bundleIdentifiers, i, t);
}
}
return new BatchActionResult(bundleIdentifiers).toCompositeData();
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#setFrameworkStartLevel(int)
*/
public void setFrameworkStartLevel(int newlevel) throws IOException {
try {
startLevel.setStartLevel(newlevel);
} catch (Exception e) {
IOException ioex = new IOException("Setting the framework start level to " + newlevel + " failed with message: " + e.getMessage());
ioex.initCause(e);
throw ioex;
}
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#setInitialBundleStartLevel(int)
*/
public void setInitialBundleStartLevel(int newlevel) throws IOException {
try {
startLevel.setInitialBundleStartLevel(newlevel);
} catch (Exception e) {
IOException ioex = new IOException("Setting the initial start level to " + newlevel + " failed with message: " + e.getMessage());
ioex.initCause(e);
throw ioex;
}
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#shutdownFramework()
*/
public void shutdownFramework() throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(context, 0);
try {
bundle.stop();
} catch (Exception be) {
IOException ioex = new IOException("Stopping the framework failed with message: " + be.getMessage());
ioex.initCause(be);
throw ioex;
}
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#startBundle(long)
*/
public void startBundle(long bundleIdentifier) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
try {
bundle.start();
} catch (Exception be) {
IOException ioex = new IOException("Start of bundle with id " + bundleIdentifier + " failed with message: " + be.getMessage());
ioex.initCause(be);
throw ioex;
}
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#startBundles(long[])
*/
public CompositeData startBundles(long[] bundleIdentifiers) throws IOException {
if (bundleIdentifiers == null) {
return new BatchActionResult("Failed to start bundles, bundle id's can't be null").toCompositeData();
}
for (int i = 0; i < bundleIdentifiers.length; i++) {
try {
startBundle(bundleIdentifiers[i]);
} catch (Throwable t) {
return createFailedBatchActionResult(bundleIdentifiers, i, t);
}
}
return new BatchActionResult(bundleIdentifiers).toCompositeData();
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#stopBundle(long)
*/
public void stopBundle(long bundleIdentifier) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
try {
bundle.stop();
} catch (Exception e) {
IOException ioex = new IOException("Stop of bundle with id " + bundleIdentifier + " failed with message: " + e.getMessage());
ioex.initCause(e);
throw ioex;
}
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#stopBundles(long[])
*/
public CompositeData stopBundles(long[] bundleIdentifiers) throws IOException {
if (bundleIdentifiers == null) {
return new BatchActionResult("Failed to stop bundles, bundle id's can't be null").toCompositeData();
}
for (int i = 0; i < bundleIdentifiers.length; i++) {
try {
stopBundle(bundleIdentifiers[i]);
} catch (Throwable t) {
return createFailedBatchActionResult(bundleIdentifiers, i, t);
}
}
return new BatchActionResult(bundleIdentifiers).toCompositeData();
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#uninstallBundle(long)
*/
public void uninstallBundle(long bundleIdentifier) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
try {
bundle.uninstall();
} catch (Exception be) {
IOException ioex = new IOException("Uninstall of bundle with id " + bundleIdentifier + " failed with message: " + be.getMessage());
ioex.initCause(be);
throw ioex;
}
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#uninstallBundles(long[])
*/
public CompositeData uninstallBundles(long[] bundleIdentifiers) throws IOException {
if (bundleIdentifiers == null) {
return new BatchActionResult("Failed uninstall bundles, bundle id's can't be null").toCompositeData();
}
for (int i = 0; i < bundleIdentifiers.length; i++) {
try {
uninstallBundle(bundleIdentifiers[i]);
} catch (Throwable t) {
return createFailedBatchActionResult(bundleIdentifiers, i, t);
}
}
return new BatchActionResult(bundleIdentifiers).toCompositeData();
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#updateBundle(long)
*/
public void updateBundle(long bundleIdentifier) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
try {
bundle.update();
} catch (Exception be) {
IOException ioex = new IOException("Update of bundle with id " + bundleIdentifier + " failed with message: " + be.getMessage());
ioex.initCause(be);
throw ioex;
}
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#updateBundleFromURL(long, String)
*/
public void updateBundleFromURL(long bundleIdentifier, String url) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);
InputStream inputStream = null;
try {
inputStream = createStream(url);
bundle.update(inputStream);
} catch (Exception be) {
IOException ioex = new IOException("Update of bundle with id " + bundleIdentifier + " from url " + url + " failed with message: " + be.getMessage());
ioex.initCause(be);
throw ioex;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ioe) {
}
}
}
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#updateBundles(long[])
*/
public CompositeData updateBundles(long[] bundleIdentifiers) throws IOException {
if (bundleIdentifiers == null) {
return new BatchActionResult("Failed to update bundles, bundle id's can't be null").toCompositeData();
}
for (int i = 0; i < bundleIdentifiers.length; i++) {
try {
updateBundle(bundleIdentifiers[i]);
} catch (Throwable t) {
return createFailedBatchActionResult(bundleIdentifiers, i, t);
}
}
return new BatchActionResult(bundleIdentifiers).toCompositeData();
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#updateBundlesFromURL(long[], String[])
*/
public CompositeData updateBundlesFromURL(long[] bundleIdentifiers, String[] urls) throws IOException {
if(bundleIdentifiers == null || urls == null){
return new BatchActionResult("Failed to update bundles arguments can't be null").toCompositeData();
}
if(bundleIdentifiers != null && urls != null && bundleIdentifiers.length != urls.length){
return new BatchActionResult("Failed to update bundles size of arguments should be same").toCompositeData();
}
for (int i = 0; i < bundleIdentifiers.length; i++) {
try {
updateBundleFromURL(bundleIdentifiers[i], urls[i]);
} catch (Throwable t) {
return createFailedBatchActionResult(bundleIdentifiers, i, t);
}
}
return new BatchActionResult(bundleIdentifiers).toCompositeData();
}
/**
* @see org.osgi.jmx.framework.FrameworkMBean#updateFramework()
*/
public void updateFramework() throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(context, 0);
try {
bundle.update();
} catch (Exception be) {
IOException ioex = new IOException("Update of framework bundle failed with message: " + be.getMessage());
ioex.initCause(be);
throw ioex;
}
}
/**
* Create {@link BatchActionResult}, when the operation fail.
*
* @param bundleIdentifiers bundle ids for operation.
* @param i index of loop pointing on which operation fails.
* @param t Throwable thrown by failed operation.
* @return created BatchActionResult instance.
*/
private CompositeData createFailedBatchActionResult(long[] bundleIdentifiers, int i, Throwable t) {
long[] completed = new long[i];
System.arraycopy(bundleIdentifiers, 0, completed, 0, i);
long[] remaining = new long[bundleIdentifiers.length - i - 1];
System.arraycopy(bundleIdentifiers, i + 1, remaining, 0, remaining.length);
return new BatchActionResult(completed, t.toString(), remaining, bundleIdentifiers[i]).toCompositeData();
}
}
| 8,110 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/ServiceState.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleIds;
import static org.apache.aries.jmx.util.FrameworkUtils.resolveService;
import static org.osgi.jmx.JmxConstants.PROPERTIES_TYPE;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.management.AttributeChangeNotification;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.apache.aries.jmx.JMXThreadFactory;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.codec.PropertyData;
import org.apache.aries.jmx.codec.ServiceData;
import org.apache.aries.jmx.codec.ServiceEventData;
import org.osgi.framework.AllServiceListener;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.jmx.framework.ServiceStateMBean;
import org.osgi.service.log.LogService;
/**
* Implementation of <code>ServiceStateMBean</code> which emits JMX <code>Notification</code> for framework
* <code>ServiceEvent</code> events and changes to the <code>ServiceIds</code> attribute.
*
* @version $Rev$ $Date$
*/
public class ServiceState extends NotificationBroadcasterSupport implements ServiceStateMBean, MBeanRegistration {
protected Logger logger;
private BundleContext bundleContext;
private StateConfig stateConfig;
protected ExecutorService eventDispatcher;
protected AllServiceListener serviceListener;
private AtomicInteger notificationSequenceNumber = new AtomicInteger(1);
private AtomicInteger attributeChangeNotificationSequenceNumber = new AtomicInteger(1);
private AtomicInteger registrations = new AtomicInteger(0);
private Lock lock = new ReentrantLock();
// notification type description
public static String SERVICE_EVENT = "org.osgi.service.event";
public ServiceState(BundleContext bundleContext, StateConfig stateConfig, Logger logger) {
if (bundleContext == null) {
throw new IllegalArgumentException("Argument bundleContext cannot be null");
}
this.bundleContext = bundleContext;
this.stateConfig = stateConfig;
this.logger = logger;
}
/**
* @see org.osgi.jmx.framework.ServiceStateMBean#getBundleIdentifier(long)
*/
public long getBundleIdentifier(long serviceId) throws IOException {
ServiceReference reference = resolveService(bundleContext, serviceId);
return reference.getBundle().getBundleId();
}
/**
* @see org.osgi.jmx.framework.ServiceStateMBean#getObjectClass(long)
*/
public String[] getObjectClass(long serviceId) throws IOException {
ServiceReference reference = resolveService(bundleContext, serviceId);
return (String[]) reference.getProperty(Constants.OBJECTCLASS);
}
/**
* @see org.osgi.jmx.framework.ServiceStateMBean#getProperties(long)
*/
public TabularData getProperties(long serviceId) throws IOException {
ServiceReference reference = resolveService(bundleContext, serviceId);
TabularData propertiesTable = new TabularDataSupport(PROPERTIES_TYPE);
for (String propertyKey : reference.getPropertyKeys()) {
propertiesTable.put(PropertyData.newInstance(propertyKey, reference.getProperty(propertyKey))
.toCompositeData());
}
return propertiesTable;
}
/**
* @see org.osgi.jmx.framework.ServiceStateMBean#getProperty(long, java.lang.String)
*/
public CompositeData getProperty(long serviceId, String key) throws IOException {
ServiceReference reference = resolveService(bundleContext, serviceId);
return PropertyData.newInstance(key, reference.getProperty(key)).toCompositeData();
}
/**
* @see org.osgi.jmx.framework.ServiceStateMBean#getUsingBundles(long)
*/
public long[] getUsingBundles(long serviceId) throws IOException {
ServiceReference reference = resolveService(bundleContext, serviceId);
Bundle[] usingBundles = reference.getUsingBundles();
return getBundleIds(usingBundles);
}
/**
* @see org.osgi.jmx.framework.ServiceStateMBean#getService(long)
*/
public CompositeData getService(long serviceId) throws IOException {
return new ServiceData(resolveService(bundleContext, serviceId)).toCompositeData();
}
/**
* @see org.osgi.jmx.framework.ServiceStateMBean#listServices()
*/
public TabularData listServices() throws IOException {
return listServices(null, null);
}
/**
* @see org.osgi.jmx.framework.ServiceStateMBean#listServices(java.lang.String, java.lang.String)
*/
public TabularData listServices(String clazz, String filter) throws IOException {
return listServices(clazz, filter, ServiceStateMBean.SERVICE_TYPE.keySet());
}
/**
* @see org.osgi.jmx.framework.ServiceStateMBean#listServices(java.lang.String, java.lang.String, java.lang.String...)
*/
public TabularData listServices(String clazz, String filter, String ... serviceTypeItems) throws IOException {
return listServices(clazz, filter, Arrays.asList(serviceTypeItems));
}
private TabularData listServices(String clazz, String filter, Collection<String> serviceTypeItems) throws IOException {
TabularData servicesTable = new TabularDataSupport(SERVICES_TYPE);
ServiceReference[] allServiceReferences = null;
try {
allServiceReferences = bundleContext.getAllServiceReferences(clazz, filter);
} catch (InvalidSyntaxException e) {
throw new IllegalStateException("Failed to retrieve all service references", e);
}
if (allServiceReferences != null) {
for (ServiceReference reference : allServiceReferences) {
servicesTable.put(new ServiceData(reference).toCompositeData(serviceTypeItems));
}
}
return servicesTable;
}
/**
* @see javax.management.NotificationBroadcasterSupport#getNotificationInfo()
*/
public MBeanNotificationInfo[] getNotificationInfo() {
MBeanNotificationInfo eventInfo = new MBeanNotificationInfo(
new String[] { SERVICE_EVENT },
Notification.class.getName(),
"A ServiceEvent issued from the Framework describing a service lifecycle change");
MBeanNotificationInfo attributeChangeInfo = new MBeanNotificationInfo(
new String[] { AttributeChangeNotification.ATTRIBUTE_CHANGE },
AttributeChangeNotification.class.getName(),
"An attribute of this MBean has changed");
return new MBeanNotificationInfo[] { eventInfo, attributeChangeInfo };
}
/**
* @see org.osgi.jmx.framework.ServiceStateMBean#getServiceIds()
*/
public long[] getServiceIds() throws IOException {
try {
ServiceReference<?>[] refs = bundleContext.getAllServiceReferences(null, null);
long[] ids = new long[refs.length];
for (int i=0; i < refs.length; i++) {
ServiceReference<?> ref = refs[i];
long id = (Long) ref.getProperty(Constants.SERVICE_ID);
ids[i] = id;
}
// The IDs are sorted here. It's not required by the spec but it's nice
// to have an ordered list returned.
Arrays.sort(ids);
return ids;
} catch (InvalidSyntaxException e) {
IOException ioe = new IOException();
ioe.initCause(e);
throw ioe;
}
}
/**
* @see javax.management.MBeanRegistration#postDeregister()
*/
public void postDeregister() {
if (registrations.decrementAndGet() < 1) {
shutDownDispatcher();
}
}
/**
* @see javax.management.MBeanRegistration#postRegister(java.lang.Boolean)
*/
public void postRegister(Boolean registrationDone) {
if (registrationDone && registrations.incrementAndGet() == 1) {
eventDispatcher = Executors.newSingleThreadExecutor(new JMXThreadFactory("JMX OSGi Service State Event Dispatcher"));
bundleContext.addServiceListener(serviceListener);
}
}
public void preDeregister() throws Exception {
// No action
}
/**
* @see javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName)
*/
public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
lock.lock();
try {
if (serviceListener == null) {
serviceListener = new AllServiceListener() {
public void serviceChanged(ServiceEvent serviceevent) {
if (stateConfig != null && !stateConfig.isServiceChangeNotificationEnabled()) {
return;
}
try {
// Create a notification for the event
final Notification notification = new Notification(EVENT, OBJECTNAME,
notificationSequenceNumber.getAndIncrement());
notification.setUserData(new ServiceEventData(serviceevent).toCompositeData());
// also send notifications to the serviceIDs attribute listeners, if a service was added or removed
final AttributeChangeNotification attributeChangeNotification =
getAttributeChangeNotification(serviceevent);
eventDispatcher.submit(new Runnable() {
public void run() {
sendNotification(notification);
if (attributeChangeNotification != null)
sendNotification(attributeChangeNotification);
}
});
} catch (RejectedExecutionException re) {
logger.log(LogService.LOG_WARNING, "Task rejected for JMX Notification dispatch of event ["
+ serviceevent + "] - Dispatcher may have been shutdown");
} catch (Exception e) {
logger.log(LogService.LOG_WARNING,
"Exception occured on JMX Notification dispatch for event [" + serviceevent + "]",
e);
}
}
};
}
} finally {
lock.unlock();
}
return name;
}
protected AttributeChangeNotification getAttributeChangeNotification(ServiceEvent serviceevent) throws IOException {
if (stateConfig != null && !stateConfig.isAttributeChangeNotificationEnabled()) {
return null;
}
int eventType = serviceevent.getType();
switch (eventType) {
case ServiceEvent.REGISTERED:
case ServiceEvent.UNREGISTERING:
long serviceID = (Long) serviceevent.getServiceReference().getProperty(Constants.SERVICE_ID);
long[] ids = getServiceIds();
List<Long> without = new ArrayList<Long>(ids.length);
for (long id : ids) {
if (id != serviceID)
without.add(id);
}
List<Long> with = new ArrayList<Long>(without);
with.add(serviceID);
// Sorting is not mandatory, but its nice for the user, note that getServiceIds() also returns a sorted array
Collections.sort(with);
List<Long> oldList = eventType == ServiceEvent.REGISTERED ? without : with;
List<Long> newList = eventType == ServiceEvent.REGISTERED ? with : without;
long[] oldIDs = new long[oldList.size()];
for (int i = 0; i < oldIDs.length; i++) {
oldIDs[i] = oldList.get(i);
}
long[] newIDs = new long[newList.size()];
for (int i = 0; i < newIDs.length; i++) {
newIDs[i] = newList.get(i);
}
return new AttributeChangeNotification(OBJECTNAME, attributeChangeNotificationSequenceNumber.getAndIncrement(),
System.currentTimeMillis(), "ServiceIds changed", "ServiceIds", "Array of long", oldIDs, newIDs);
default:
return null;
}
}
/*
* Shuts down the notification dispatcher
* [ARIES-259] MBeans not getting unregistered reliably
*/
protected void shutDownDispatcher() {
if (serviceListener != null) {
try {
bundleContext.removeServiceListener(serviceListener);
}
catch (Exception e) {
// ignore
}
}
if (eventDispatcher != null) {
eventDispatcher.shutdown();
}
}
/*
* Returns the ExecutorService used to dispatch Notifications
*/
protected ExecutorService getEventDispatcher() {
return eventDispatcher;
}
}
| 8,111 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/PackageState.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.management.openmbean.TabularData;
import org.apache.aries.jmx.codec.PackageData;
import org.apache.aries.jmx.util.FrameworkUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Version;
import org.osgi.jmx.framework.PackageStateMBean;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
/**
* <p>
* <tt>PackageState</tt> represents implementation of PackageStateMBean.
* </p>
*
* @see PackageStateMBean
*
* @version $Rev$ $Date$
*/
public class PackageState implements PackageStateMBean {
/**
* {@link PackageAdmin} service reference.
*/
private PackageAdmin packageAdmin;
private BundleContext context;
/**
* Constructs new PackagesState MBean.
*
* @param context bundle context.
* @param packageAdmin {@link PackageAdmin} service reference.
*/
public PackageState(BundleContext context, PackageAdmin packageAdmin) {
this.context = context;
this.packageAdmin = packageAdmin;
}
/**
* @see org.osgi.jmx.framework.PackageStateMBean#getExportingBundles(String, String)
*/
public long[] getExportingBundles(String packageName, String version) throws IOException {
if (packageName == null || packageName.length() < 1) {
throw new IOException("Package name cannot be null or empty");
}
ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(packageName);
if (exportedPackages != null) {
Version ver = Version.parseVersion(version);
List<Bundle> exportingBundles = new ArrayList<Bundle>();
for (ExportedPackage exportedPackage : exportedPackages) {
if (exportedPackage.getVersion().equals(ver)) {
Bundle bundle = exportedPackage.getExportingBundle();
exportingBundles.add(bundle);
}
}
return FrameworkUtils.getBundleIds(exportingBundles);
}
return null;
}
/**
* @see org.osgi.jmx.framework.PackageStateMBean#getImportingBundles(String, String, long)
*/
public long[] getImportingBundles(String packageName, String version, long exportingBundle) throws IOException {
if (packageName == null || packageName.length() < 1) {
throw new IOException("Package name cannot be null or empty");
}
ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(packageName);
if (exportedPackages != null) {
Version ver = Version.parseVersion(version);
for (ExportedPackage exportedPackage : exportedPackages) {
if (exportedPackage.getVersion().equals(ver)
&& exportedPackage.getExportingBundle().getBundleId() == exportingBundle) {
Bundle[] bundles = exportedPackage.getImportingBundles();
if (bundles != null) {
return FrameworkUtils.getBundleIds(bundles);
}
}
}
}
return null;
}
/**
* @see org.osgi.jmx.framework.PackageStateMBean#isRemovalPending(String, String, long)
*/
public boolean isRemovalPending(String packageName, String version, long exportingBundle) throws IOException {
if (packageName == null || packageName.length() < 1) {
throw new IOException("Package name cannot be null or empty");
}
ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(packageName);
if (exportedPackages != null) {
Version ver = Version.parseVersion(version);
for (ExportedPackage exportedPackage : exportedPackages) {
if (exportedPackage.getVersion().equals(ver)
&& exportedPackage.getExportingBundle().getBundleId() == exportingBundle
&& exportedPackage.isRemovalPending()) {
return true;
}
}
}
return false;
}
/**
* @see org.osgi.jmx.framework.PackageStateMBean#listPackages()
*/
public TabularData listPackages() throws IOException {
Set<PackageData> packages = new HashSet<PackageData>();
for (Bundle bundle : context.getBundles()) {
ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(bundle);
if (exportedPackages != null) {
for (ExportedPackage exportedPackage : exportedPackages) {
packages.add(new PackageData(exportedPackage));
}
}
}
return PackageData.tableFrom(packages);
}
}
| 8,112 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/FrameworkMBeanHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.MBeanHandler;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.apache.aries.jmx.util.ObjectNameUtils;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.jmx.framework.FrameworkMBean;
import org.osgi.service.log.LogService;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;
/**
* <p>
* <tt>FrameworkMBeanHandler</tt> represents MBeanHandler which
* holding information about {@link FrameworkMBean}.</p>
*
* @see MBeanHandler
*
* @version $Rev$ $Date$
*/
public class FrameworkMBeanHandler implements MBeanHandler {
private JMXAgentContext agentContext;
private String name;
private StandardMBean mbean;
private BundleContext context;
private Logger logger;
/**
* Constructs new FrameworkMBeanHandler.
*
* @param agentContext agent context
*/
public FrameworkMBeanHandler(JMXAgentContext agentContext) {
this.agentContext = agentContext;
this.context = agentContext.getBundleContext();
this.logger = agentContext.getLogger();
this.name = ObjectNameUtils.createFullObjectName(context, FrameworkMBean.OBJECTNAME);
}
/**
* @see org.apache.aries.jmx.MBeanHandler#getMbean()
*/
public StandardMBean getMbean() {
return mbean;
}
/**
* @see org.apache.aries.jmx.MBeanHandler#open()
*/
public void open() {
ServiceReference adminRef = context.getServiceReference(PackageAdmin.class.getCanonicalName());
PackageAdmin packageAdmin = (PackageAdmin) context.getService(adminRef);
ServiceReference startLevelRef = context.getServiceReference(StartLevel.class.getCanonicalName());
StartLevel startLevel = (StartLevel) context.getService(startLevelRef);
FrameworkMBean framework = new Framework(context, startLevel, packageAdmin);
try {
mbean = new StandardMBean(framework, FrameworkMBean.class);
} catch (NotCompliantMBeanException e) {
logger.log(LogService.LOG_ERROR, "Not compliant MBean", e);
}
agentContext.registerMBean(this);
}
/**
* @see org.apache.aries.jmx.MBeanHandler#close()
*/
public void close() {
agentContext.unregisterMBean(this);
}
/**
* @see org.apache.aries.jmx.MBeanHandler#getName()
*/
public String getName() {
return name;
}
}
| 8,113 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/wiring/BundleWiringStateMBeanHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework.wiring;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.MBeanHandler;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.apache.aries.jmx.util.ObjectNameUtils;
import org.apache.aries.jmx.util.shared.RegistrableStandardEmitterMBean;
import org.osgi.framework.BundleContext;
import org.osgi.jmx.framework.wiring.BundleWiringStateMBean;
import org.osgi.service.log.LogService;
public class BundleWiringStateMBeanHandler implements MBeanHandler {
private JMXAgentContext agentContext;
private final String name;
private final BundleContext bundleContext;
private final Logger logger;
private StandardMBean mbean;
private BundleWiringState revisionsStateMBean;
public BundleWiringStateMBeanHandler(JMXAgentContext agentContext) {
this.agentContext = agentContext;
this.bundleContext = agentContext.getBundleContext();
this.logger = agentContext.getLogger();
this.name = ObjectNameUtils.createFullObjectName(bundleContext, BundleWiringStateMBean.OBJECTNAME);
}
/* (non-Javadoc)
* @see org.apache.aries.jmx.MBeanHandler#open()
*/
public void open() {
revisionsStateMBean = new BundleWiringState(bundleContext, logger);
try {
mbean = new RegistrableStandardEmitterMBean(revisionsStateMBean, BundleWiringStateMBean.class);
} catch (NotCompliantMBeanException e) {
logger.log(LogService.LOG_ERROR, "Failed to instantiate MBean for " + BundleWiringStateMBean.class.getName(), e);
}
agentContext.registerMBean(this);
}
/* (non-Javadoc)
* @see org.apache.aries.jmx.MBeanHandler#getMbean()
*/
public StandardMBean getMbean() {
return mbean;
}
/* (non-Javadoc)
* @see org.apache.aries.jmx.MBeanHandler#close()
*/
public void close() {
agentContext.unregisterMBean(this);
}
/* (non-Javadoc)
* @see org.apache.aries.jmx.MBeanHandler#getName()
*/
public String getName() {
return name;
}
}
| 8,114 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/wiring/BundleWiringState.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework.wiring;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.codec.BundleWiringData;
import org.apache.aries.jmx.util.FrameworkUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleRevisions;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.jmx.framework.wiring.BundleWiringStateMBean;
public class BundleWiringState implements BundleWiringStateMBean {
private final BundleContext bundleContext;
private final Logger logger;
public BundleWiringState(BundleContext bundleContext, Logger logger) {
this.bundleContext = bundleContext;
this.logger = logger;
}
/* (non-Javadoc)
* @see org.osgi.jmx.framework.BundleRevisionsStateMBean#getCurrentRevisionDeclaredRequirements(long, java.lang.String)
*/
public CompositeData[] getCurrentRevisionDeclaredRequirements(long bundleId, String namespace) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(bundleContext, bundleId);
BundleRevision revision = bundle.adapt(BundleRevision.class);
return BundleWiringData.getRequirementsCompositeData(revision.getDeclaredRequirements(namespace));
}
/* (non-Javadoc)
* @see org.osgi.jmx.framework.BundleRevisionsStateMBean#getCurrentRevisionDeclaredCapabilities(long, java.lang.String)
*/
public CompositeData[] getCurrentRevisionDeclaredCapabilities(long bundleId, String namespace) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(bundleContext, bundleId);
BundleRevision revision = bundle.adapt(BundleRevision.class);
return BundleWiringData.getCapabilitiesCompositeData(revision.getDeclaredCapabilities(namespace));
}
/* (non-Javadoc)
* @see org.osgi.jmx.framework.BundleRevisionsStateMBean#getCurrentWiring(long, java.lang.String)
*/
public CompositeData getCurrentWiring(long bundleId, String namespace) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(bundleContext, bundleId);
BundleRevision currentRevision = bundle.adapt(BundleRevision.class);
Map<BundleRevision, Integer> revisionIDMap = getCurrentRevisionTransitiveRevisionsClosure(bundleId, namespace);
return getRevisionWiring(currentRevision, 0, namespace, revisionIDMap);
}
/* (non-Javadoc)
* @see org.osgi.jmx.framework.BundleRevisionsStateMBean#getCurrentWiringClosure(long)
*/
public TabularData getCurrentWiringClosure(long rootBundleId, String namespace) throws IOException {
Map<BundleRevision, Integer> revisionIDMap = getCurrentRevisionTransitiveRevisionsClosure(rootBundleId, namespace);
TabularData td = new TabularDataSupport(BundleWiringStateMBean.BUNDLES_WIRING_TYPE);
for (Map.Entry<BundleRevision, Integer> entry : revisionIDMap.entrySet()) {
td.put(getRevisionWiring(entry.getKey(), entry.getValue(), namespace, revisionIDMap));
}
return td;
}
// The current revision being passed in always gets assigned revision ID 0
// All the other revision IDs unique, but don't increase monotonous.
private Map<BundleRevision, Integer> getCurrentRevisionTransitiveRevisionsClosure(long rootBundleId, String namespace) throws IOException {
Bundle rootBundle = FrameworkUtils.resolveBundle(bundleContext, rootBundleId);
BundleRevision rootRevision = rootBundle.adapt(BundleRevision.class);
return getRevisionTransitiveClosure(rootRevision, namespace);
}
private Map<BundleRevision, Integer> getRevisionTransitiveClosure(BundleRevision rootRevision, String namespace) {
Map<BundleRevision, Integer> revisionIDMap = new HashMap<BundleRevision, Integer>();
populateTransitiveRevisions(namespace, rootRevision, revisionIDMap);
// Set the root revision ID to 0,
// TODO check if there is already a revision with ID 0 and if so swap them. Quite a small chance that this will be needed
revisionIDMap.put(rootRevision, 0);
return revisionIDMap;
}
private void populateTransitiveRevisions(String namespace, BundleRevision rootRevision, Map<BundleRevision, Integer> allRevisions) {
allRevisions.put(rootRevision, System.identityHashCode(rootRevision));
BundleWiring wiring = rootRevision.getWiring();
if (wiring == null)
return;
List<BundleWire> requiredWires = wiring.getRequiredWires(namespace);
for (BundleWire wire : requiredWires) {
BundleRevision revision = wire.getCapability().getRevision();
if (!allRevisions.containsKey(revision)) {
populateTransitiveRevisions(namespace, revision, allRevisions);
}
}
List<BundleWire> providedWires = wiring.getProvidedWires(namespace);
for (BundleWire wire : providedWires) {
BundleRevision revision = wire.getRequirement().getRevision();
if (!allRevisions.containsKey(revision)) {
populateTransitiveRevisions(namespace, revision, allRevisions);
}
}
}
private CompositeData getRevisionWiring(BundleRevision revision, int revisionID, String namespace, Map<BundleRevision, Integer> revisionIDMap) {
BundleWiring wiring = revision.getWiring();
List<BundleCapability> capabilities = wiring.getCapabilities(namespace);
List<BundleRequirement> requirements = wiring.getRequirements(namespace);
List<BundleWire> providedWires = wiring.getProvidedWires(namespace);
List<BundleWire> requiredWires = wiring.getRequiredWires(namespace);
BundleWiringData data = new BundleWiringData(wiring.getBundle().getBundleId(), revisionID, capabilities, requirements, providedWires, requiredWires, revisionIDMap);
return data.toCompositeData();
}
/* (non-Javadoc)
* @see org.osgi.jmx.framework.BundleRevisionsStateMBean#getRevisionsDeclaredRequirements(long, java.lang.String, boolean)
*/
public TabularData getRevisionsDeclaredRequirements(long bundleId, String namespace) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(bundleContext, bundleId);
BundleRevisions revisions = bundle.adapt(BundleRevisions.class);
TabularData td = new TabularDataSupport(BundleWiringStateMBean.REVISIONS_REQUIREMENTS_TYPE);
for (BundleRevision revision : revisions.getRevisions()) {
td.put(BundleWiringData.getRevisionRequirements(
System.identityHashCode(revision),
revision.getDeclaredRequirements(namespace)));
}
return td;
}
/* (non-Javadoc)
* @see org.osgi.jmx.framework.BundleRevisionsStateMBean#getRevisionsDeclaredCapabilities(long, java.lang.String, boolean)
*/
public TabularData getRevisionsDeclaredCapabilities(long bundleId, String namespace) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(bundleContext, bundleId);
BundleRevisions revisions = bundle.adapt(BundleRevisions.class);
TabularData td = new TabularDataSupport(BundleWiringStateMBean.REVISIONS_CAPABILITIES_TYPE);
for (BundleRevision revision : revisions.getRevisions()) {
td.put(BundleWiringData.getRevisionCapabilities(
System.identityHashCode(revision),
revision.getDeclaredCapabilities(namespace)));
}
return td;
}
/* (non-Javadoc)
* @see org.osgi.jmx.framework.BundleRevisionsStateMBean#getRevisionsWiring(long, java.lang.String)
*/
public TabularData getRevisionsWiring(long bundleId, String namespace) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(bundleContext, bundleId);
BundleRevisions revisions = bundle.adapt(BundleRevisions.class);
TabularData td = new TabularDataSupport(BundleWiringStateMBean.BUNDLES_WIRING_TYPE);
for (BundleRevision revision : revisions.getRevisions()) {
Map<BundleRevision, Integer> revisionIDMap = getRevisionTransitiveClosure(revision, namespace);
td.put(getRevisionWiring(revision, System.identityHashCode(revision), namespace, revisionIDMap));
}
return td;
}
/* (non-Javadoc)
* @see org.osgi.jmx.framework.BundleRevisionsStateMBean#getWiringClosure(long, java.lang.String)
*/
public TabularData getRevisionsWiringClosure(long rootBundleId, String namespace) throws IOException {
Bundle bundle = FrameworkUtils.resolveBundle(bundleContext, rootBundleId);
BundleRevisions revisions = bundle.adapt(BundleRevisions.class);
Map<BundleRevision, Integer> revisionIDMap = new HashMap<BundleRevision, Integer>();
for (BundleRevision revision : revisions.getRevisions()) {
populateTransitiveRevisions(namespace, revision, revisionIDMap);
}
// Set the root current revision ID to 0,
// TODO check if there is already a revision with ID 0 and if so swap them. Quite a small chance that this will be needed
BundleRevision revision = bundle.adapt(BundleRevision.class);
revisionIDMap.put(revision, 0);
TabularData td = new TabularDataSupport(BundleWiringStateMBean.BUNDLES_WIRING_TYPE);
for (Map.Entry<BundleRevision, Integer> entry : revisionIDMap.entrySet()) {
td.put(getRevisionWiring(entry.getKey(), entry.getValue(), namespace, revisionIDMap));
}
return td;
}
}
| 8,115 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchInstallResult.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import java.util.HashMap;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.osgi.jmx.framework.FrameworkMBean;
/**
* <p>
* <tt>BatchInstallResult</tt> represents codec for resulting CompositeData of
* FrameworkMBean installBundles methods.
* It converting batch install results to CompositeData {@link #toCompositeData()}
* and from CompositeData to this BatchInstallResult {@link #from(CompositeData)}.
* It provides also constructors to build BatchInstallResult.
* Structure of compositeData as defined in compositeType @see {@link FrameworkMBean#BATCH_INSTALL_RESULT_TYPE}.
* </p>
* @see BatchResult
*
* @version $Rev$ $Date$
*/
public class BatchInstallResult extends BatchResult {
/**
* @see FrameworkMBean#REMAINING_LOCATION_ITEM
* @see FrameworkMBean#REMAINING
*/
private String[] remainingLocationItems;
/**
* @see FrameworkMBean#BUNDLE_IN_ERROR_LOCATION_ITEM
* @see FrameworkMBean#BUNDLE_IN_ERROR
*/
private String bundleInError;
/**
* Constructs new BatchInstallResult with completedItems array.
* Newly created object represents successful batch result.
* @param completedItems containing the list of bundles completing the batch operation.
*/
public BatchInstallResult(long[] completedItems) {
this.completed = completedItems;
success = true;
}
/**
* Constructs new BatchInstallResult with error message.
* Newly created object represents failed batch result.
* @param error containing the error message of the batch operation.
*/
public BatchInstallResult(String error){
this.error = error;
success = false;
}
/**
* Constructs new BatchInstallResult.
* Newly created object represents failed batch result.
*
* @param completedItems containing the list of bundles completing the batch operation.
* @param error containing the error message of the batch operation.
* @param remainingLocationItems remaining bundles unprocessed by the
* failing batch operation.
* @param bundleInError containing the bundle which caused the error during the batch
* operation.
*/
public BatchInstallResult(long[] completedItems, String error, String[] remainingLocationItems, String bundleInError) {
this(completedItems, error, remainingLocationItems, false, bundleInError);
}
/**
* Constructs new BatchInstallResult.
*
* @param completedItems containing the list of bundles completing the batch operation.
* @param error containing the error message of the batch operation.
* @param remainingLocationItems remaining bundles unprocessed by the
* failing batch operation.
* @param success indicates if this operation was successful.
* @param bundleInError containing the bundle which caused the error during the batch
* operation.
*/
public BatchInstallResult(long[] completedItems, String error, String[] remainingLocationItems, boolean success,
String bundleInError) {
this.bundleInError = bundleInError;
this.completed = completedItems;
this.error = error;
this.remainingLocationItems = remainingLocationItems;
this.success = success;
}
/**
* Translates BatchInstallResult to CompositeData represented by
* compositeType {@link FrameworkMBean#BATCH_INSTALL_RESULT_TYPE}.
*
* @return translated BatchInstallResult to compositeData.
*/
public CompositeData toCompositeData() {
try {
Map<String, Object> items = new HashMap<String, Object>();
items.put(FrameworkMBean.BUNDLE_IN_ERROR, bundleInError);
items.put(FrameworkMBean.COMPLETED, toLongArray(completed));
items.put(FrameworkMBean.ERROR, error);
items.put(FrameworkMBean.REMAINING, remainingLocationItems);
items.put(FrameworkMBean.SUCCESS, success);
return new CompositeDataSupport(FrameworkMBean.BATCH_INSTALL_RESULT_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData" + e);
}
}
/**
* Static factory method to create BatchInstallResult from CompositeData object.
*
* @param data {@link CompositeData} instance.
* @return BatchInstallResult instance.
*/
public static BatchInstallResult from(CompositeData data) {
if(data == null){
return null;
}
String bundleInError = (String) data.get(FrameworkMBean.BUNDLE_IN_ERROR);
long[] completedItems = toLongPrimitiveArray((Long[]) data.get(FrameworkMBean.COMPLETED));
String[] remainingLocationItems = (String[]) data.get(FrameworkMBean.REMAINING);
String error = (String) data.get(FrameworkMBean.ERROR);
boolean success = (Boolean) data.get(FrameworkMBean.SUCCESS);
return new BatchInstallResult(completedItems, error, remainingLocationItems, success, bundleInError);
}
/**
* Gets remaining location items.
* @return array of String with locations.
*/
public String[] getRemainingLocationItems() {
return remainingLocationItems;
}
/**
* Gets bundle in error location.
* @return the bundleInError.
*/
public String getBundleInError() {
return bundleInError;
}
}
| 8,116 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchResolveResult.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import java.util.HashMap;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.osgi.jmx.framework.FrameworkMBean;
public class BatchResolveResult {
private final boolean success;
private final Long[] successfulBundles;
public BatchResolveResult(boolean success, Long[] successfulBundles) {
this.success = success;
this.successfulBundles = successfulBundles;
}
public CompositeData toCompositeData() {
try {
Map<String, Object> items = new HashMap<String, Object>();
items.put(FrameworkMBean.COMPLETED, successfulBundles);
items.put(FrameworkMBean.SUCCESS, success);
return new CompositeDataSupport(FrameworkMBean.BATCH_RESOLVE_RESULT_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData", e);
}
}
}
| 8,117 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/BundleWiringData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.jmx.framework.wiring.BundleWiringStateMBean;
public class BundleWiringData {
private final long bundleId;
private final int revisionId;
private final List<BundleCapability> capabilities;
private final List<BundleRequirement> requirements;
private final List<BundleWire> providedWires;
private final List<BundleWire> requiredWires;
private final Map<BundleRevision, Integer> revisionIDMap;
public BundleWiringData(long bundleId, int revisionId, List<BundleCapability> capabilities, List<BundleRequirement> requirements,
List<BundleWire> providedWires, List<BundleWire> requiredWires, Map<BundleRevision, Integer> revisionIDMap) {
this.bundleId = bundleId;
this.revisionId = revisionId;
this.capabilities = capabilities;
this.requirements = requirements;
this.providedWires = providedWires;
this.requiredWires = requiredWires;
this.revisionIDMap = revisionIDMap;
}
public CompositeData toCompositeData() {
try {
Map<String, Object> items = new HashMap<String, Object>();
items.put(BundleWiringStateMBean.BUNDLE_ID, bundleId);
items.put(BundleWiringStateMBean.BUNDLE_REVISION_ID, revisionId);
items.put(BundleWiringStateMBean.REQUIREMENTS, getRequirements(requirements));
items.put(BundleWiringStateMBean.CAPABILITIES, getCapabilities(capabilities));
items.put(BundleWiringStateMBean.REQUIRED_WIRES, getRequiredWires());
items.put(BundleWiringStateMBean.PROVIDED_WIRES, getProvidedWires());
return new CompositeDataSupport(BundleWiringStateMBean.BUNDLE_WIRING_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData", e);
}
}
private static CompositeData[] getCapabilities(List<BundleCapability> capabilityList) throws OpenDataException {
CompositeData[] capData = new CompositeData[capabilityList.size()];
for (int i=0; i < capabilityList.size(); i++) {
BundleCapability capability = capabilityList.get(i);
capData[i] = getCapReqCompositeData(BundleWiringStateMBean.BUNDLE_CAPABILITY_TYPE,
capability.getNamespace(), capability.getAttributes().entrySet(), capability.getDirectives().entrySet());
}
return capData;
}
private static CompositeData[] getRequirements(List<BundleRequirement> requirementList) throws OpenDataException {
CompositeData [] reqData = new CompositeData[requirementList.size()];
for (int i=0; i < requirementList.size(); i++) {
BundleRequirement requirement = requirementList.get(i);
reqData[i] = getCapReqCompositeData(BundleWiringStateMBean.BUNDLE_REQUIREMENT_TYPE,
requirement.getNamespace(), requirement.getAttributes().entrySet(), requirement.getDirectives().entrySet());
}
return reqData;
}
public static CompositeData getRevisionCapabilities(int revisionId, List<BundleCapability> bundleCapabilities) {
try {
Map<String, Object> items = new HashMap<String, Object>();
items.put(BundleWiringStateMBean.BUNDLE_REVISION_ID, revisionId);
items.put(BundleWiringStateMBean.CAPABILITIES, getCapabilities(bundleCapabilities));
return new CompositeDataSupport(BundleWiringStateMBean.REVISION_CAPABILITIES_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData", e);
}
}
public static CompositeData getRevisionRequirements(int revisionId, List<BundleRequirement> bundleRequirements) {
try {
Map<String, Object> items = new HashMap<String, Object>();
items.put(BundleWiringStateMBean.BUNDLE_REVISION_ID, revisionId);
items.put(BundleWiringStateMBean.REQUIREMENTS, getRequirements(bundleRequirements));
return new CompositeDataSupport(BundleWiringStateMBean.REVISION_REQUIREMENTS_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData", e);
}
}
public static CompositeData[] getCapabilitiesCompositeData(List<BundleCapability> bundleCapabilities) {
try {
CompositeData[] data = new CompositeData[bundleCapabilities.size()];
for (int i=0; i < bundleCapabilities.size(); i++) {
BundleCapability requirement = bundleCapabilities.get(i);
CompositeData cd = BundleWiringData.getCapReqCompositeData(BundleWiringStateMBean.BUNDLE_CAPABILITY_TYPE,
requirement.getNamespace(), requirement.getAttributes().entrySet(), requirement.getDirectives().entrySet());
data[i] = cd;
}
return data;
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData", e);
}
}
public static CompositeData[] getRequirementsCompositeData(List<BundleRequirement> bundleRequirements) {
try {
CompositeData[] data = new CompositeData[bundleRequirements.size()];
for (int i=0; i < bundleRequirements.size(); i++) {
BundleRequirement requirement = bundleRequirements.get(i);
CompositeData cd = BundleWiringData.getCapReqCompositeData(BundleWiringStateMBean.BUNDLE_REQUIREMENT_TYPE,
requirement.getNamespace(), requirement.getAttributes().entrySet(), requirement.getDirectives().entrySet());
data[i] = cd;
}
return data;
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData", e);
}
}
private static CompositeData getCapReqCompositeData(CompositeType type, String namespace, Set<Map.Entry<String,Object>> attributeSet, Set<Map.Entry<String,String>> directiveSet) throws OpenDataException {
Map<String, Object> reqItems = new HashMap<String, Object>();
TabularData attributes = new TabularDataSupport(BundleWiringStateMBean.ATTRIBUTES_TYPE);
for (Map.Entry<String, Object> entry : attributeSet) {
PropertyData<?> pd = PropertyData.newInstance(entry.getKey(), entry.getValue());
attributes.put(pd.toCompositeData());
}
reqItems.put(BundleWiringStateMBean.ATTRIBUTES, attributes);
TabularData directives = new TabularDataSupport(BundleWiringStateMBean.DIRECTIVES_TYPE);
for (Map.Entry<String, String> entry : directiveSet) {
CompositeData directive = new CompositeDataSupport(BundleWiringStateMBean.DIRECTIVE_TYPE,
new String[] { BundleWiringStateMBean.KEY, BundleWiringStateMBean.VALUE },
new Object[] { entry.getKey(), entry.getValue() });
directives.put(directive);
}
reqItems.put(BundleWiringStateMBean.DIRECTIVES, directives);
reqItems.put(BundleWiringStateMBean.NAMESPACE, namespace);
CompositeData req = new CompositeDataSupport(type, reqItems);
return req;
}
private CompositeData[] getProvidedWires() throws OpenDataException {
return getWiresCompositeData(providedWires);
}
private CompositeData[] getRequiredWires() throws OpenDataException {
return getWiresCompositeData(requiredWires);
}
private CompositeData[] getWiresCompositeData(List<BundleWire> wires) throws OpenDataException {
CompositeData[] reqWiresData = new CompositeData[wires.size()];
for (int i=0; i < wires.size(); i++) {
BundleWire requiredWire = wires.get(i);
Map<String, Object> wireItems = new HashMap<String, Object>();
BundleCapability capability = requiredWire.getCapability();
wireItems.put(BundleWiringStateMBean.PROVIDER_BUNDLE_ID, capability.getRevision().getBundle().getBundleId());
wireItems.put(BundleWiringStateMBean.PROVIDER_BUNDLE_REVISION_ID, revisionIDMap.get(capability.getRevision()));
wireItems.put(BundleWiringStateMBean.BUNDLE_CAPABILITY,
getCapReqCompositeData(BundleWiringStateMBean.BUNDLE_CAPABILITY_TYPE,
capability.getNamespace(), capability.getAttributes().entrySet(), capability.getDirectives().entrySet()));
BundleRequirement requirement = requiredWire.getRequirement();
wireItems.put(BundleWiringStateMBean.REQUIRER_BUNDLE_ID, requirement.getRevision().getBundle().getBundleId());
wireItems.put(BundleWiringStateMBean.REQUIRER_BUNDLE_REVISION_ID, revisionIDMap.get(requirement.getRevision()));
wireItems.put(BundleWiringStateMBean.BUNDLE_REQUIREMENT,
getCapReqCompositeData(BundleWiringStateMBean.BUNDLE_REQUIREMENT_TYPE,
requirement.getNamespace(), requirement.getAttributes().entrySet(), requirement.getDirectives().entrySet()));
CompositeData wireData = new CompositeDataSupport(BundleWiringStateMBean.BUNDLE_WIRE_TYPE, wireItems);
reqWiresData[i] = wireData;
}
return reqWiresData;
}
}
| 8,118 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/RoleData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.osgi.jmx.JmxConstants;
import org.osgi.jmx.service.useradmin.UserAdminMBean;
import org.osgi.service.useradmin.Role;
/**
* <p>
* <tt>RoleData</tt> represents Role Type @see {@link UserAdminMBean#ROLE_TYPE}.It is a codec
* for the <code>CompositeData</code> representing a Role.
* </p>
*
* @version $Rev$ $Date$
*/
public class RoleData {
/**
* role name.
*/
protected String name;
/**
* role type.
*/
protected int type;
/**
* role propeties.
*/
protected List<PropertyData<? extends Object>> properties = new ArrayList<PropertyData<? extends Object>>();
/**
* Constructs new RoleData from Role object.
* @param role {@link Role} instance.
*/
public RoleData(Role role){
this(role.getName(), role.getType(), role.getProperties());
}
/**
* Constructs new RoleData.
* @param name role name.
* @param type role type.
*/
public RoleData(String name, int type) {
this(name, type, null);
}
/**
* Constructs new RoleData.
* @param name role name.
* @param type role type.
* @param properties role properties.
*/
@SuppressWarnings("rawtypes")
public RoleData(String name, int type, Dictionary properties) {
this.name = name;
this.type = type;
if (properties != null) {
for (Enumeration e = properties.keys(); e.hasMoreElements(); ) {
String key = e.nextElement().toString();
this.properties.add(PropertyData.newInstance(key, properties.get(key)));
}
}
}
/**
* Translates RoleData to CompositeData represented by
* compositeType {@link UserAdminMBean#ROLE_TYPE}.
*
* @return translated RoleData to compositeData.
*/
public CompositeData toCompositeData() {
try {
Map<String, Object> items = new HashMap<String, Object>();
items.put(UserAdminMBean.NAME, name);
items.put(UserAdminMBean.TYPE, type);
// items.put(UserAdminMBean.PROPERTIES, getPropertiesTable());
return new CompositeDataSupport(UserAdminMBean.ROLE_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData" + e);
}
}
protected TabularData getPropertiesTable() {
return getPropertiesTable(properties);
}
protected static TabularData getPropertiesTable(List<PropertyData<? extends Object>> data) {
TabularData propertiesTable = new TabularDataSupport(JmxConstants.PROPERTIES_TYPE);
for (PropertyData<? extends Object> propertyData : data) {
propertiesTable.put(propertyData.toCompositeData());
}
return propertiesTable;
}
/**
* Static factory method to create RoleData from CompositeData object.
*
* @param data {@link CompositeData} instance.
* @return RoleData instance.
*/
public static RoleData from(CompositeData data) {
if(data == null){
return null;
}
String name = (String) data.get(UserAdminMBean.NAME);
int type = (Integer) data.get(UserAdminMBean.TYPE);
// Dictionary<String, Object> props = propertiesFrom((TabularData) data.get(UserAdminMBean.PROPERTIES));
return new RoleData(name, type, null /* props */);
}
/**
* Creates TabularData from Dictionary.
*
* @param props Dictionary instance.
* @return TabularData instance.
*/
protected static TabularData toTabularData(Dictionary<String, Object> props){
if(props == null){
return null;
}
TabularData data = new TabularDataSupport(JmxConstants.PROPERTIES_TYPE);
for (Enumeration<String> keys = props.keys(); keys.hasMoreElements();) {
String key = keys.nextElement();
data.put(PropertyData.newInstance(key, props.get(key)).toCompositeData());
}
return data;
}
/**
* Creates properties from TabularData object.
*
* @param data {@link TabularData} instance.
* @return translated tabular data to properties {@link Dictionary}.
*/
protected static Dictionary<String, Object> propertiesFrom(TabularData data){
if(data == null){
return null;
}
Dictionary<String, Object> props = new Hashtable<String, Object>();
for(CompositeData compositeData : (Collection<CompositeData>)data.values()){
PropertyData property = PropertyData.from(compositeData);
props.put(property.getKey(), property.getValue());
}
return props;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the type
*/
public int getType() {
return type;
}
} | 8,119 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/AuthorizationData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import java.util.HashMap;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.osgi.jmx.service.useradmin.UserAdminMBean;
import org.osgi.service.useradmin.Authorization;
/**
* <p>
* <tt>AuthorizationData</tt> represents Authorization Type @see {@link UserAdminMBean#AUTORIZATION_TYPE}.It is a codec
* for the <code>CompositeData</code> representing an Authorization .
* </p>
*
*
* @version $Rev$ $Date$
*/
public class AuthorizationData {
/**
* authorization context name.
*/
private String name;
/**
* roles implied by authorization context.
*/
private String[] roles;
/**
* Constructs new AuthorizationData from Authorization.
* @param auth {@link Authorization} instance.
*/
public AuthorizationData(Authorization auth){
this.name = auth.getName();
this.roles = auth.getRoles();
}
/**
* Constructs new AuthorizationData.
*
* @param name of authorization context.
* @param roles implied by authorization context.
*/
public AuthorizationData(String name, String[] roles){
this.name = name;
this.roles = roles;
}
/**
* Translates AuthorizationData to CompositeData represented by
* compositeType {@link UserAdminMBean#AUTORIZATION_TYPE}.
*
* @return translated AuthorizationData to compositeData.
*/
public CompositeData toCompositeData() {
try {
Map<String, Object> items = new HashMap<String, Object>();
items.put(UserAdminMBean.NAME, name);
items.put(UserAdminMBean.ROLES, roles);
return new CompositeDataSupport(UserAdminMBean.AUTORIZATION_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData" + e);
}
}
/**
* Static factory method to create AuthorizationData from CompositeData object.
*
* @param data {@link CompositeData} instance.
* @return AuthorizationData instance.
*/
public static AuthorizationData from(CompositeData data) {
if(data == null){
return null;
}
String name = (String) data.get(UserAdminMBean.NAME);
String[] roles = (String[]) data.get(UserAdminMBean.ROLES);
return new AuthorizationData(name, roles);
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the roles
*/
public String[] getRoles() {
return roles;
}
} | 8,120 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/PackageData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.osgi.framework.Bundle;
import org.osgi.jmx.framework.PackageStateMBean;
import org.osgi.service.packageadmin.ExportedPackage;
/**
* <p>
* <tt>PackageData</tt>represents PackageType @see {@link PackageStateMBean#PACKAGE_TYPE}.
* It is a codec for the composite data representing an OSGi ExportedPackage.
* </p>
*
* @version $Rev$ $Date$
*/
@SuppressWarnings("deprecation")
public class PackageData {
/**
* {@link PackageStateMBean#EXPORTING_BUNDLES}
*/
long[] exportingBundles;
/**
* {@link PackageStateMBean#IMPORTING_BUNDLES}
*/
long[] importingBundles;
/**
* {@link PackageStateMBean#NAME}
*/
String name;
/**
* {@link PackageStateMBean#REMOVAL_PENDING}
*/
boolean removalPending;
/**
* {@link PackageStateMBean#VERSION}
*/
String version;
/**
* Constructs new PackageData with provided ExportedPackage.
* @param exportedPackage @see {@link ExportedPackage}.
*/
public PackageData(ExportedPackage exportedPackage) {
this(new long[]{exportedPackage.getExportingBundle().getBundleId()}, toBundleIds(exportedPackage.getImportingBundles()),
exportedPackage.getName(), exportedPackage.isRemovalPending(), exportedPackage.getVersion().toString());
}
/**
* Constructs new PackageData.
*
* @param exportingBundles the bundle the package belongs to.
* @param importingBundles the importing bundles of the package.
* @param name the package name.
* @param removalPending whether the package is pending removal.
* @param version package version.
*/
public PackageData(long[] exportingBundles, long[] importingBundles, String name, boolean removalPending, String version) {
this.exportingBundles = exportingBundles;
this.importingBundles = importingBundles;
this.name = name;
this.removalPending = removalPending;
this.version = version;
}
/**
* Translates PackageData to CompositeData represented by
* compositeType {@link PackageStateMBean#PACKAGE_TYPE}.
*
* @return translated PackageData to compositeData.
*/
public CompositeData toCompositeData() {
try {
Map<String, Object> items = new HashMap<String, Object>();
items.put(PackageStateMBean.EXPORTING_BUNDLES, toLongArray(exportingBundles));
items.put(PackageStateMBean.IMPORTING_BUNDLES, toLongArray(importingBundles));
items.put(PackageStateMBean.NAME, name);
items.put(PackageStateMBean.REMOVAL_PENDING, removalPending);
items.put(PackageStateMBean.VERSION, version);
return new CompositeDataSupport(PackageStateMBean.PACKAGE_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData" + e);
}
}
/**
* Static factory method to create PackageData from CompositeData object.
*
* @param data {@link CompositeData} instance.
* @return PackageData instance.
*/
public static PackageData from(CompositeData data) {
if(data == null){
return null;
}
long[] exportingBundle = toLongPrimitiveArray((Long[])data.get(PackageStateMBean.EXPORTING_BUNDLES));
long[] importingBundles = toLongPrimitiveArray((Long[]) data.get(PackageStateMBean.IMPORTING_BUNDLES));
String name = (String) data.get(PackageStateMBean.NAME);
boolean removalPending = (Boolean) data.get(PackageStateMBean.REMOVAL_PENDING);
String version = (String) data.get(PackageStateMBean.VERSION);
return new PackageData(exportingBundle,importingBundles,name, removalPending,version);
}
/**
* Creates {@link TabularData} for set of PackageData's.
*
* @param packages set of PackageData's
* @return {@link TabularData} instance.
*/
public static TabularData tableFrom(Set<PackageData> packages){
TabularData table = new TabularDataSupport(PackageStateMBean.PACKAGES_TYPE);
for(PackageData pkg : packages){
table.put(pkg.toCompositeData());
}
return table;
}
/**
* Converts array of bundles to array of bundle id's.
*
* @param bundles array of Bundle's.
* @return array of bundle id's.
*/
public static long[] toBundleIds(Bundle[] bundles) {
if (bundles != null) {
long[] importingBundles = new long[bundles.length];
for (int i = 0; i < bundles.length; i++) {
importingBundles[i] = bundles[i].getBundleId();
}
return importingBundles;
}
return null;
}
/**
* Converts primitive array of strings to Long array.
*
* @param primitiveArray primitive long array.
* @return Long array.
*/
protected Long[] toLongArray(long[] primitiveArray) {
if (primitiveArray == null) {
return null;
}
Long[] converted = new Long[primitiveArray.length];
for (int i = 0; i < primitiveArray.length; i++) {
converted[i] = primitiveArray[i];
}
return converted;
}
/**
* Converts Long array to primitive array of long.
*
* @param wrapperArray Long array.
* @return primitive long array.
*/
protected static long[] toLongPrimitiveArray(Long[] wrapperArray) {
if (wrapperArray == null) {
return null;
}
long[] converted = new long[wrapperArray.length];
for (int i = 0; i < wrapperArray.length; i++) {
converted[i] = wrapperArray[i];
}
return converted;
}
/**
* @return the exportingBundles
*/
public long[] getExportingBundles() {
return exportingBundles;
}
/**
* @return the importingBundles
*/
public long[] getImportingBundles() {
return importingBundles;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the removalPending
*/
public boolean isRemovalPending() {
return removalPending;
}
/**
* @return the version
*/
public String getVersion() {
return version;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PackageData that = (PackageData) o;
// exportingBundle must be always there
if (exportingBundles[0] != that.exportingBundles[0]) return false;
if (!name.equals(that.name)) return false;
if (!version.equals(that.version)) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (exportingBundles[0] ^ (exportingBundles[0] >>> 32));
result = 31 * result + name.hashCode();
result = 31 * result + version.hashCode();
return result;
}
}
| 8,121 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchActionResult.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import java.util.HashMap;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.osgi.jmx.framework.FrameworkMBean;
/**
* <p>
* <tt>BatchInstallResult</tt> represents codec for resulting CompositeData of batch operations
* made on bundle via FrameworkMBean.
* It's converting batch install results to CompositeData {@link #toCompositeData()}
* and from CompositeData to this BatchActionResult {@link #from(CompositeData)}.
* It provides also constructors to build BatchActionResult.
* Structure of compositeData is as defined in compositeType @see {@link FrameworkMBean#BATCH_ACTION_RESULT_TYPE}.
* </p>
* @see BatchResult
*
* @version $Rev$ $Date$
*/
public class BatchActionResult extends BatchResult{
/**
* @see FrameworkMBean#REMAINING_ID_ITEM
* @see FrameworkMBean#REMAINING_LOCATION_ITEM
*/
private long[] remainingItems;
/**
* @see FrameworkMBean#BUNDLE_IN_ERROR_ID_ITEM
* @see FrameworkMBean#BUNDLE_IN_ERROR
*/
private long bundleInError;
/**
* Constructs new BatchActionResult with completedItems array.
* Newly created object represents successful batch result.
* @param completedItems containing the list of bundles completing the batch operation.
*/
public BatchActionResult(long[] completedItems){
this.completed = completedItems;
success = true;
}
/**
* Constructs new BatchActionResult with error message.
* Newly created object represents failed batch result.
* @param error containing the error message of the batch operation.
*/
public BatchActionResult(String error){
this.error = error;
success = false;
}
/**
* Constructs new BatchActionResult.
* Newly created object represents failed batch result.
*
* @param completedItems containing the list of bundles completing the batch operation.
* @param error containing the error message of the batch operation.
* @param remainingItems remaining bundles unprocessed by the
* failing batch operation.
* @param bundleInError containing the bundle which caused the error during the batch
* operation.
*/
public BatchActionResult(long[] completedItems, String error, long[] remainingItems, long bundleInError){
this(completedItems,error,remainingItems,false,bundleInError);
}
/**
* Constructs new BatchActionResult.
*
* @param completedItems containing the list of bundles completing the batch operation.
* @param error containing the error message of the batch operation.
* @param remainingItems remaining bundles unprocessed by the
* failing batch operation.
* @param success indicates if this operation was successful.
* @param bundleInError containing the bundle which caused the error during the batch
* operation.
*/
public BatchActionResult(long[] completedItems, String error, long[] remainingItems, boolean success, long bundleInError){
this.bundleInError = bundleInError;
this.completed = completedItems;
this.error = error;
this.remainingItems = remainingItems;
this.success = success;
}
/**
* Translates BatchActionResult to CompositeData represented by
* compositeType {@link FrameworkMBean#BATCH_ACTION_RESULT_TYPE}.
*
* @return translated BatchActionResult to compositeData.
*/
public CompositeData toCompositeData(){
try {
Map<String, Object> items = new HashMap<String, Object>();
items.put(FrameworkMBean.BUNDLE_IN_ERROR, bundleInError);
items.put(FrameworkMBean.COMPLETED, toLongArray(completed));
items.put(FrameworkMBean.ERROR, error);
items.put(FrameworkMBean.REMAINING, toLongArray(remainingItems));
items.put(FrameworkMBean.SUCCESS, success);
return new CompositeDataSupport(FrameworkMBean.BATCH_ACTION_RESULT_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData" + e);
}
}
/**
* Static factory method to create BatchActionResult from CompositeData object.
*
* @param data {@link CompositeData} instance.
* @return BatchActionResult instance.
*/
public static BatchActionResult from(CompositeData data){
if(data == null){
return null;
}
long bundleInError = (Long) data.get(FrameworkMBean.BUNDLE_IN_ERROR);
// need to convert primitive array to wrapper type array
// compositeData accept only wrapper type array
long[] completedItems = toLongPrimitiveArray((Long[])data.get(FrameworkMBean.COMPLETED));
long[] remainingItems = toLongPrimitiveArray((Long[]) data.get(FrameworkMBean.REMAINING));
String error = (String) data.get(FrameworkMBean.ERROR);
Boolean success = (Boolean) data.get(FrameworkMBean.SUCCESS);
return new BatchActionResult(completedItems, error, remainingItems, success, bundleInError);
}
/**
* Gets remaining items id's.
* @return the remainingItems.
*/
public long[] getRemainingItems() {
return remainingItems;
}
/**
* Gets bundle in error id.
* @return the bundleInError.
*/
public long getBundleInError() {
return bundleInError;
}
}
| 8,122 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/BundleData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleDependencies;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleExportedPackages;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleImportedPackages;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleState;
import static org.apache.aries.jmx.util.FrameworkUtils.getDependentBundles;
import static org.apache.aries.jmx.util.FrameworkUtils.getFragmentIds;
import static org.apache.aries.jmx.util.FrameworkUtils.getHostIds;
import static org.apache.aries.jmx.util.FrameworkUtils.getRegisteredServiceIds;
import static org.apache.aries.jmx.util.FrameworkUtils.getServicesInUseByBundle;
import static org.apache.aries.jmx.util.FrameworkUtils.isBundlePendingRemoval;
import static org.apache.aries.jmx.util.FrameworkUtils.isBundleRequiredByOthers;
import static org.apache.aries.jmx.util.TypeUtils.toLong;
import static org.apache.aries.jmx.util.TypeUtils.toPrimitive;
import static org.osgi.jmx.framework.BundleStateMBean.BUNDLE_TYPE;
import static org.osgi.jmx.framework.BundleStateMBean.EXPORTED_PACKAGES;
import static org.osgi.jmx.framework.BundleStateMBean.FRAGMENT;
import static org.osgi.jmx.framework.BundleStateMBean.FRAGMENTS;
import static org.osgi.jmx.framework.BundleStateMBean.HEADERS;
import static org.osgi.jmx.framework.BundleStateMBean.HEADERS_TYPE;
import static org.osgi.jmx.framework.BundleStateMBean.HEADER_TYPE;
import static org.osgi.jmx.framework.BundleStateMBean.HOSTS;
import static org.osgi.jmx.framework.BundleStateMBean.IDENTIFIER;
import static org.osgi.jmx.framework.BundleStateMBean.IMPORTED_PACKAGES;
import static org.osgi.jmx.framework.BundleStateMBean.KEY;
import static org.osgi.jmx.framework.BundleStateMBean.LAST_MODIFIED;
import static org.osgi.jmx.framework.BundleStateMBean.LOCATION;
import static org.osgi.jmx.framework.BundleStateMBean.PERSISTENTLY_STARTED;
import static org.osgi.jmx.framework.BundleStateMBean.REGISTERED_SERVICES;
import static org.osgi.jmx.framework.BundleStateMBean.REMOVAL_PENDING;
import static org.osgi.jmx.framework.BundleStateMBean.REQUIRED;
import static org.osgi.jmx.framework.BundleStateMBean.REQUIRED_BUNDLES;
import static org.osgi.jmx.framework.BundleStateMBean.REQUIRING_BUNDLES;
import static org.osgi.jmx.framework.BundleStateMBean.SERVICES_IN_USE;
import static org.osgi.jmx.framework.BundleStateMBean.START_LEVEL;
import static org.osgi.jmx.framework.BundleStateMBean.STATE;
import static org.osgi.jmx.framework.BundleStateMBean.SYMBOLIC_NAME;
import static org.osgi.jmx.framework.BundleStateMBean.VALUE;
import static org.osgi.jmx.framework.BundleStateMBean.VERSION;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.JMRuntimeException;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.jmx.framework.BundleStateMBean;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;
/**
* <p>
* <tt>BundleData</tt> represents BundleData Type @see {@link BundleStateMBean#BUNDLE_TYPE}. It is a codec for the
* <code>CompositeData</code> representing an OSGi BundleData.
* </p>
*
* @version $Rev$ $Date$
*/
@SuppressWarnings("deprecation")
public class BundleData {
/**
* @see BundleStateMBean#EXPORTED_PACKAGES_ITEM
*/
private String[] exportedPackages;
/**
* @see BundleStateMBean#FRAGMENT_ITEM
*/
private boolean fragment;
/**
* @see BundleStateMBean#FRAGMENTS_ITEM
*/
private long[] fragments;
/**
* @see BundleStateMBean#HEADER_TYPE
*/
private List<Header> headers = new ArrayList<Header>();
/**
* @see BundleStateMBean#HOSTS_ITEM
*/
private long[] hosts;
/**
* @see BundleStateMBean#IDENTIFIER_ITEM
*/
private long identifier;
/**
* @see BundleStateMBean#IMPORTED_PACKAGES_ITEM
*/
private String[] importedPackages;
/**
* @see BundleStateMBean#LAST_MODIFIED_ITEM
*/
private long lastModified;
/**
* @see BundleStateMBean#LOCATION_ITEM
*/
private String location;
/**
* @see BundleStateMBean#PERSISTENTLY_STARTED_ITEM
*/
private boolean persistentlyStarted;
/**
* @see BundleStateMBean#REGISTERED_SERVICES_ITEM
*/
private long[] registeredServices;
/**
* @see BundleStateMBean#REMOVAL_PENDING_ITEM
*/
private boolean removalPending;
/**
* @see BundleStateMBean#REQUIRED_ITEM
*/
private boolean required;
/**
* @see BundleStateMBean#REQUIRED_BUNDLES_ITEM
*/
private long[] requiredBundles;
/**
* @see BundleStateMBean#REQUIRING_BUNDLES_ITEM
*/
private long[] requiringBundles;
/**
* @see BundleStateMBean#SERVICES_IN_USE_ITEM
*/
private long[] servicesInUse;
/**
* @see BundleStateMBean#START_LEVEL_ITEM
*/
private int bundleStartLevel;
/**
* @see BundleStateMBean#STATE_ITEM
*/
private String state;
/**
* @see BundleStateMBean#SYMBOLIC_NAME_ITEM
*/
private String symbolicName;
/**
* @see BundleStateMBean#VERSION_ITEM
*/
private String version;
private BundleData() {
super();
}
public BundleData(BundleContext localBundleContext, Bundle bundle, PackageAdmin packageAdmin, StartLevel startLevel) {
if (bundle == null) {
throw new IllegalArgumentException("Argument bundle cannot be null");
}
if (packageAdmin == null || startLevel == null) {
throw new IllegalArgumentException("Arguments PackageAdmin / startLevel cannot be null");
}
this.exportedPackages = getBundleExportedPackages(bundle, packageAdmin);
this.fragment = (PackageAdmin.BUNDLE_TYPE_FRAGMENT == packageAdmin.getBundleType(bundle));
this.fragments = getFragmentIds(bundle, packageAdmin);
Dictionary<String, String> bundleHeaders = bundle.getHeaders();
Enumeration<String> keys = bundleHeaders.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
headers.add(new Header(key, bundleHeaders.get(key)));
}
this.hosts = getHostIds(bundle, packageAdmin);
this.identifier = bundle.getBundleId();
this.importedPackages = getBundleImportedPackages(localBundleContext, bundle, packageAdmin);
this.lastModified = bundle.getLastModified();
this.location = bundle.getLocation();
this.persistentlyStarted = startLevel.isBundlePersistentlyStarted(bundle);
this.registeredServices = getRegisteredServiceIds(bundle);
this.removalPending = isBundlePendingRemoval(bundle, packageAdmin);
this.required = isBundleRequiredByOthers(bundle, packageAdmin);
this.requiredBundles = getBundleDependencies(localBundleContext, bundle, packageAdmin);
this.requiringBundles = getDependentBundles(bundle, packageAdmin);
this.servicesInUse = getServicesInUseByBundle(bundle);
this.bundleStartLevel = startLevel.getBundleStartLevel(bundle);
this.state = getBundleState(bundle);
this.symbolicName = bundle.getSymbolicName();
this.version = bundle.getVersion().toString();
}
/**
* Returns CompositeData representing a BundleData complete state typed by {@link BundleStateMBean#BUNDLE_TYPE}
*
* @return
*/
public CompositeData toCompositeData() {
return toCompositeData(BundleStateMBean.BUNDLE_TYPE.keySet());
}
public CompositeData toCompositeData(Collection<String> itemNames) {
Map<String, Object> items = new HashMap<String, Object>();
items.put(IDENTIFIER, this.identifier);
if (itemNames.contains(EXPORTED_PACKAGES))
items.put(EXPORTED_PACKAGES, this.exportedPackages);
if (itemNames.contains(FRAGMENT))
items.put(FRAGMENT, this.fragment);
if (itemNames.contains(FRAGMENTS))
items.put(FRAGMENTS, toLong(this.fragments));
if (itemNames.contains(HOSTS))
items.put(HOSTS, toLong(this.hosts));
if (itemNames.contains(IMPORTED_PACKAGES))
items.put(IMPORTED_PACKAGES, this.importedPackages);
if (itemNames.contains(LAST_MODIFIED))
items.put(LAST_MODIFIED, this.lastModified);
if (itemNames.contains(LOCATION))
items.put(LOCATION, this.location);
if (itemNames.contains(PERSISTENTLY_STARTED))
items.put(PERSISTENTLY_STARTED, this.persistentlyStarted);
if (itemNames.contains(REGISTERED_SERVICES))
items.put(REGISTERED_SERVICES, toLong(this.registeredServices));
if (itemNames.contains(REMOVAL_PENDING))
items.put(REMOVAL_PENDING, this.removalPending);
if (itemNames.contains(REQUIRED))
items.put(REQUIRED, this.required);
if (itemNames.contains(REQUIRED_BUNDLES))
items.put(REQUIRED_BUNDLES, toLong(this.requiredBundles));
if (itemNames.contains(REQUIRING_BUNDLES))
items.put(REQUIRING_BUNDLES, toLong(this.requiringBundles));
if (itemNames.contains(SERVICES_IN_USE))
items.put(SERVICES_IN_USE, toLong(this.servicesInUse));
if (itemNames.contains(START_LEVEL))
items.put(START_LEVEL, this.bundleStartLevel);
if (itemNames.contains(STATE))
items.put(STATE, this.state);
if (itemNames.contains(SYMBOLIC_NAME))
items.put(SYMBOLIC_NAME, this.symbolicName);
if (itemNames.contains(VERSION))
items.put(VERSION, this.version);
if (itemNames.contains(HEADERS)) {
TabularData headerTable = new TabularDataSupport(HEADERS_TYPE);
for (Header header : this.headers) {
headerTable.put(header.toCompositeData());
}
items.put(HEADERS, headerTable);
}
String[] allItemNames = BUNDLE_TYPE.keySet().toArray(new String [] {});
Object[] itemValues = new Object[allItemNames.length];
for (int i=0; i < allItemNames.length; i++) {
itemValues[i] = items.get(allItemNames[i]);
}
try {
return new CompositeDataSupport(BUNDLE_TYPE, allItemNames, itemValues);
} catch (OpenDataException e) {
throw new IllegalStateException("Failed to create CompositeData for BundleData [" + this.identifier
+ "]", e);
}
}
/**
* Constructs a <code>BundleData</code> object from the given <code>CompositeData</code>
*
* @param compositeData
* @return
* @throws IlleglArgumentException
* if compositeData is null or not of type {@link BundleStateMBean#BUNDLE_TYPE}
*/
@SuppressWarnings("unchecked")
public static BundleData from(CompositeData compositeData) throws IllegalArgumentException {
if (compositeData == null) {
throw new IllegalArgumentException("Argument compositeData cannot be null");
}
if (!compositeData.getCompositeType().equals(BUNDLE_TYPE)) {
throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
}
BundleData bundleData = new BundleData();
bundleData.exportedPackages = (String[]) compositeData.get(EXPORTED_PACKAGES);
bundleData.fragment = (Boolean) compositeData.get(FRAGMENT);
bundleData.fragments = toPrimitive((Long[]) compositeData.get(FRAGMENTS));
bundleData.hosts = toPrimitive((Long[]) compositeData.get(HOSTS));
bundleData.identifier = (Long) compositeData.get(IDENTIFIER);
bundleData.importedPackages = (String[]) compositeData.get(IMPORTED_PACKAGES);
bundleData.lastModified = (Long) compositeData.get(LAST_MODIFIED);
bundleData.location = (String) compositeData.get(LOCATION);
bundleData.persistentlyStarted = (Boolean) compositeData.get(PERSISTENTLY_STARTED);
bundleData.registeredServices = toPrimitive((Long[]) compositeData.get(REGISTERED_SERVICES));
bundleData.removalPending = (Boolean) compositeData.get(REMOVAL_PENDING);
bundleData.required = (Boolean) compositeData.get(REQUIRED);
bundleData.requiredBundles = toPrimitive((Long[]) compositeData.get(REQUIRED_BUNDLES));
bundleData.requiringBundles = toPrimitive((Long[]) compositeData.get(REQUIRING_BUNDLES));
bundleData.servicesInUse = toPrimitive((Long[]) compositeData.get(SERVICES_IN_USE));
bundleData.bundleStartLevel = (Integer) compositeData.get(START_LEVEL);
bundleData.state = (String) compositeData.get(STATE);
bundleData.symbolicName = (String) compositeData.get(SYMBOLIC_NAME);
bundleData.version = (String) compositeData.get(VERSION);
TabularData headerTable = (TabularData) compositeData.get(HEADERS);
Collection<CompositeData> headerData = (Collection<CompositeData>) headerTable.values();
for (CompositeData headerRow : headerData) {
bundleData.headers.add(Header.from(headerRow));
}
return bundleData;
}
public String[] getExportedPackages() {
return exportedPackages;
}
public boolean isFragment() {
return fragment;
}
public long[] getFragments() {
return fragments;
}
public List<Header> getHeaders() {
return headers;
}
public long[] getHosts() {
return hosts;
}
public long getIdentifier() {
return identifier;
}
public String[] getImportedPackages() {
return importedPackages;
}
public long getLastModified() {
return lastModified;
}
public String getLocation() {
return location;
}
public boolean isPersistentlyStarted() {
return persistentlyStarted;
}
public long[] getRegisteredServices() {
return registeredServices;
}
public boolean isRemovalPending() {
return removalPending;
}
public boolean isRequired() {
return required;
}
public long[] getRequiredBundles() {
return requiredBundles;
}
public long[] getRequiringBundles() {
return requiringBundles;
}
public long[] getServicesInUse() {
return servicesInUse;
}
public int getBundleStartLevel() {
return bundleStartLevel;
}
public String getState() {
return state;
}
public String getSymbolicName() {
return symbolicName;
}
public String getVersion() {
return version;
}
/*
* Represents key/value pair in BundleData headers
*/
public static class Header {
private String key;
private String value;
public String getKey() {
return key;
}
public String getValue() {
return value;
}
private Header() {
super();
}
public Header(String key, String value) {
this.key = key;
this.value = value;
}
public CompositeData toCompositeData() throws JMRuntimeException {
CompositeData result = null;
Map<String, Object> items = new HashMap<String, Object>();
items.put(KEY, key);
items.put(VALUE, value);
try {
result = new CompositeDataSupport(HEADER_TYPE, items);
} catch (OpenDataException e) {
throw new JMRuntimeException("Failed to create CompositeData for header [" + key + ":" + value + "] - "
+ e.getMessage());
}
return result;
}
public static Header from(CompositeData compositeData) {
if (compositeData == null) {
throw new IllegalArgumentException("Argument compositeData cannot be null");
}
if (!compositeData.getCompositeType().equals(HEADER_TYPE)) {
throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
}
Header header = new Header();
header.key = (String) compositeData.get(KEY);
header.value = (String) compositeData.get(VALUE);
return header;
}
}
}
| 8,123 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/BatchResult.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import org.osgi.jmx.framework.FrameworkMBean;
/**
* <p>
* <tt>BatchResult</tt> represents abstract class for BatchResults.
* It contains common data structure of batch result:
* <ul>
* <li>completed containing the list of bundles completing the batch operation.</li>
* <li>error containing the error message of the batch operation.</li>
* <li>success indicates if this operation was successful.</li>
* </ul>
* </p>
*
*
* @version $Rev$ $Date$
*/
public abstract class BatchResult {
/**
* @see FrameworkMBean#COMPLETED_ITEM
* @see FrameworkMBean#COMPLETED
*/
protected long[] completed;
/**
* @see FrameworkMBean#ERROR_ITEM
* @see FrameworkMBean#ERROR
*/
protected String error;
/**
* @see FrameworkMBean#SUCCESS_ITEM
* @see FrameworkMBean#SUCCESS
*/
protected boolean success;
/**
* Gets completed item id's.
* @return completed items id's.
*/
public long[] getCompleted() {
return completed;
}
/**
* Gets error message.
* @return error message.
*/
public String getError() {
return error;
}
/**
* Gets success value.
* @return true if success false if not.
*/
public boolean isSuccess() {
return success;
}
/**
* Converts primitive array of strings to Long array.
*
* @param primitiveArray primitive long array.
* @return Long array.
*/
protected Long[] toLongArray(long[] primitiveArray) {
if (primitiveArray == null) {
return null;
}
Long[] converted = new Long[primitiveArray.length];
for (int i = 0; i < primitiveArray.length; i++) {
converted[i] = primitiveArray[i];
}
return converted;
}
/**
* Converts Long array to primitive array of long.
*
* @param wrapperArray Long array.
* @return primitive long array.
*/
protected static long[] toLongPrimitiveArray(Long[] wrapperArray) {
if (wrapperArray == null) {
return null;
}
long[] converted = new long[wrapperArray.length];
for (int i = 0; i < wrapperArray.length; i++) {
converted[i] = wrapperArray[i];
}
return converted;
}
} | 8,124 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/GroupData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.osgi.jmx.service.useradmin.UserAdminMBean;
import org.osgi.service.useradmin.Group;
import org.osgi.service.useradmin.Role;
/**
* <p>
* <tt>GroupData</tt> represents Group Type @see {@link UserAdminMBean#GROUP_TYPE}.It is a codec
* for the <code>CompositeData</code> representing a Group.
* </p>
* </p>
*
* @version $Rev$ $Date$
*/
public class GroupData extends UserData {
/**
* @see UserAdminMBean#MEMBERS_ITEM
* @see UserAdminMBean#MEMBERS
*/
private String[] members;
/**
* @see UserAdminMBean#REQUIRED_MEMBERS
* @see UserAdminMBean#REQUIRED_MEMBERS_ITEM
*/
private String[] requiredMembers;
/**
* Constructs new GroupData from Group object.
* @param group {@link Group} instance.
*/
public GroupData(Group group) {
super(group.getName(), Role.GROUP, group.getProperties(), group.getCredentials());
this.members = toArray(group.getMembers());
this.requiredMembers = toArray(group.getRequiredMembers());
}
/**
* Constructs new GroupData.
*
* @param name group name.
* @param members basic members.
* @param requiredMembers required members.
*/
public GroupData(String name, String[] members, String[] requiredMembers) {
this(name, null, null, members, requiredMembers);
}
/**
* Constructs new GroupData.
*
* @param name group name.
* @param properties group properties.
* @param credentials group credentials.
* @param members basic members.
* @param requiredMembers required members.
*/
@SuppressWarnings("rawtypes")
public GroupData(String name, Dictionary properties, Dictionary credentials, String[] members, String[] requiredMembers) {
super(name, Role.GROUP, properties, credentials);
this.members = (members == null) ? new String[0] : members;
this.requiredMembers = (requiredMembers == null) ? new String[0] : requiredMembers;
}
/**
* Translates GroupData to CompositeData represented by compositeType {@link UserAdminMBean#GROUP_TYPE}.
*
* @return translated GroupData to compositeData.
*/
public CompositeData toCompositeData() {
try {
Map<String, Object> items = new HashMap<String, Object>();
items.put(UserAdminMBean.NAME, name);
items.put(UserAdminMBean.TYPE, type);
// items.put(UserAdminMBean.PROPERTIES, getPropertiesTable());
// items.put(UserAdminMBean.CREDENTIALS, getCredentialsTable());
items.put(UserAdminMBean.MEMBERS, members);
items.put(UserAdminMBean.REQUIRED_MEMBERS, requiredMembers);
return new CompositeDataSupport(UserAdminMBean.GROUP_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData" + e);
}
}
/**
* Static factory method to create GroupData from CompositeData object.
*
* @param data
* {@link CompositeData} instance.
* @return GroupData instance.
*/
public static GroupData from(CompositeData data) {
if (data == null) {
return null;
}
String name = (String) data.get(UserAdminMBean.NAME);
// Dictionary<String, Object> props = propertiesFrom((TabularData) data.get(UserAdminMBean.PROPERTIES));
// Dictionary<String, Object> credentials = propertiesFrom((TabularData) data.get(UserAdminMBean.CREDENTIALS));
String[] members = (String[]) data.get(UserAdminMBean.MEMBERS);
String[] requiredMembers = (String[]) data.get(UserAdminMBean.REQUIRED_MEMBERS);
return new GroupData(name, null, null,/* props, credentials, */ members, requiredMembers);
}
/**
* @return the members
*/
public String[] getMembers() {
return members;
}
/**
* @return the requiredMembers
*/
public String[] getRequiredMembers() {
return requiredMembers;
}
private static String[] toArray(Role[] roles) {
List<String> members = new ArrayList<String>();
if (roles != null) {
for (Role role : roles) {
members.add(role.getName());
}
}
return members.toArray(new String[members.size()]);
}
} | 8,125 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/ServiceData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleIds;
import static org.apache.aries.jmx.util.TypeUtils.toLong;
import static org.apache.aries.jmx.util.TypeUtils.toPrimitive;
import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_IDENTIFIER;
import static org.osgi.jmx.framework.ServiceStateMBean.IDENTIFIER;
import static org.osgi.jmx.framework.ServiceStateMBean.OBJECT_CLASS;
import static org.osgi.jmx.framework.ServiceStateMBean.PROPERTIES;
import static org.osgi.jmx.framework.ServiceStateMBean.SERVICE_TYPE;
import static org.osgi.jmx.framework.ServiceStateMBean.USING_BUNDLES;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.jmx.JmxConstants;
import org.osgi.jmx.framework.ServiceStateMBean;
/**
* <p>
* <tt>ServiceData</tt> represents Service Type @see {@link ServiceStateMBean#SERVICE_TYPE}. It is a codec for the
* <code>CompositeData</code> representing an OSGi <code>ServiceReference</code>.
* </p>
*
* @version $Rev$ $Date$
*/
public class ServiceData {
/**
* @see ServiceStateMBean#IDENTIFIER_ITEM
*/
private long serviceId;
/**
* @see ServiceStateMBean#BUNDLE_IDENTIFIER_ITEM
*/
private long bundleId;
/**
* @see ServiceStateMBean#OBJECT_CLASS_ITEM
*/
private String[] serviceInterfaces;
/**
* @see ServiceStateMBean#PROPERTIES_ITEM
*/
private List<PropertyData<? extends Object>> properties = new ArrayList<PropertyData<? extends Object>>();
/**
* @see ServiceStateMBean#USING_BUNDLES_ITEM
*/
private long[] usingBundles;
private ServiceData() {
super();
}
public ServiceData(ServiceReference<?> serviceReference) throws IllegalArgumentException {
if (serviceReference == null) {
throw new IllegalArgumentException("Argument serviceReference cannot be null");
}
this.serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID);
this.bundleId = serviceReference.getBundle().getBundleId();
this.serviceInterfaces = (String[]) serviceReference.getProperty(Constants.OBJECTCLASS);
this.usingBundles = getBundleIds(serviceReference.getUsingBundles());
for (String propertyKey: serviceReference.getPropertyKeys()) {
this.properties.add(PropertyData.newInstance(propertyKey, serviceReference.getProperty(propertyKey)));
}
}
/**
* Returns CompositeData representing a ServiceReference typed by {@link ServiceStateMBean#SERVICE_TYPE}.
* @return
*/
public CompositeData toCompositeData() {
return toCompositeData(ServiceStateMBean.SERVICE_TYPE.keySet());
}
public CompositeData toCompositeData(Collection<String> itemNames) {
Map<String, Object> items = new HashMap<String, Object>();
items.put(IDENTIFIER, this.serviceId);
if (itemNames.contains(BUNDLE_IDENTIFIER))
items.put(BUNDLE_IDENTIFIER, this.bundleId);
if (itemNames.contains(OBJECT_CLASS))
items.put(OBJECT_CLASS, this.serviceInterfaces);
TabularData propertiesTable = new TabularDataSupport(JmxConstants.PROPERTIES_TYPE);
for (PropertyData<? extends Object> propertyData : this.properties) {
propertiesTable.put(propertyData.toCompositeData());
}
items.put(PROPERTIES, propertiesTable);
if (itemNames.contains(USING_BUNDLES))
items.put(USING_BUNDLES, toLong(this.usingBundles));
String[] allItemNames = SERVICE_TYPE.keySet().toArray(new String [] {});
Object[] itemValues = new Object[allItemNames.length];
for (int i=0; i < allItemNames.length; i++) {
itemValues[i] = items.get(allItemNames[i]);
}
try {
return new CompositeDataSupport(SERVICE_TYPE, allItemNames, itemValues);
} catch (OpenDataException e) {
throw new IllegalStateException("Failed to create CompositeData for ServiceReference with "
+ Constants.SERVICE_ID + " [" + this.serviceId + "]", e);
}
}
/**
* Constructs a <code>ServiceData</code> object from the given <code>CompositeData</code>
*
* @param compositeData
* @return
* @throws IlleglArugmentException
* if compositeData is null or not of type {@link ServiceStateMBean#SERVICE_TYPE}.
*/
public static ServiceData from(CompositeData compositeData) {
if (compositeData == null) {
throw new IllegalArgumentException("Argument compositeData cannot be null");
}
if (!compositeData.getCompositeType().equals(SERVICE_TYPE)) {
throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
}
ServiceData serviceData = new ServiceData();
serviceData.serviceId = (Long) compositeData.get(IDENTIFIER);
serviceData.bundleId = (Long) compositeData.get(BUNDLE_IDENTIFIER);
serviceData.serviceInterfaces = (String[]) compositeData.get(OBJECT_CLASS);
serviceData.usingBundles = toPrimitive((Long[]) compositeData.get(USING_BUNDLES));
TabularData propertiesTable = (TabularData) compositeData.get(PROPERTIES);
Collection<CompositeData> propertyData = (Collection<CompositeData>) propertiesTable.values();
for (CompositeData propertyRow: propertyData) {
serviceData.properties.add(PropertyData.from(propertyRow));
}
return serviceData;
}
public long getServiceId() {
return serviceId;
}
public long getBundleId() {
return bundleId;
}
public String[] getServiceInterfaces() {
return serviceInterfaces;
}
public List<PropertyData<? extends Object>> getProperties() {
return properties;
}
public long[] getUsingBundles() {
return usingBundles;
}
}
| 8,126 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/BundleEventData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import static org.osgi.jmx.framework.BundleStateMBean.BUNDLE_EVENT_TYPE;
import static org.osgi.jmx.framework.BundleStateMBean.EVENT;
import static org.osgi.jmx.framework.BundleStateMBean.IDENTIFIER;
import static org.osgi.jmx.framework.BundleStateMBean.LOCATION;
import static org.osgi.jmx.framework.BundleStateMBean.SYMBOLIC_NAME;
import java.util.HashMap;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleEvent;
import org.osgi.jmx.framework.BundleStateMBean;
/**
* <p>
* <tt>BundleEventData</tt> represents BundleEvent Type @see {@link BundleStateMBean#BUNDLE_EVENT_TYPE}. It is a codec
* for the <code>CompositeData</code> representing an OSGi BundleEvent.
* </p>
*
* @version $Rev$ $Date$
*/
public class BundleEventData {
/**
* @see BundleStateMBean#IDENTIFIER_ITEM
*/
private long bundleId;
/**
* @see BundleStateMBean#LOCATION_ITEM
*/
private String location;
/**
* @see BundleStateMBean#SYMBOLIC_NAME_ITEM
*/
private String bundleSymbolicName;
/**
* @see BundleStateMBean#EVENT_ITEM
*/
private int eventType;
private BundleEventData() {
super();
}
public BundleEventData(BundleEvent bundleEvent) {
this.eventType = bundleEvent.getType();
Bundle bundle = bundleEvent.getBundle();
this.bundleId = bundle.getBundleId();
this.location = bundle.getLocation();
this.bundleSymbolicName = bundle.getSymbolicName();
}
/**
* Returns CompositeData representing a BundleEvent typed by {@link BundleStateMBean#BUNDLE_EVENT_TYPE}
*
* @return
*/
public CompositeData toCompositeData() {
CompositeData result = null;
Map<String, Object> items = new HashMap<String, Object>();
items.put(IDENTIFIER, this.bundleId);
items.put(SYMBOLIC_NAME, this.bundleSymbolicName);
items.put(LOCATION, this.location);
items.put(EVENT, this.eventType);
try {
result = new CompositeDataSupport(BUNDLE_EVENT_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Failed to create CompositeData for BundleEvent for Bundle ["
+ this.bundleId + "]", e);
}
return result;
}
/**
* Returns a <code>BundleEventData</code> representation of the given compositeData
*
* @param compositeData
* @return
* @throws IllegalArgumentException
* if the compositeData is null or incorrect type
*/
public static BundleEventData from(CompositeData compositeData) throws IllegalArgumentException {
BundleEventData eventData = new BundleEventData();
if (compositeData == null) {
throw new IllegalArgumentException("Argument compositeData cannot be null");
}
if (!compositeData.getCompositeType().equals(BUNDLE_EVENT_TYPE)) {
throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
}
eventData.bundleId = (Long) compositeData.get(IDENTIFIER);
eventData.bundleSymbolicName = (String) compositeData.get(SYMBOLIC_NAME);
eventData.eventType = (Integer) compositeData.get(EVENT);
eventData.location = (String) compositeData.get(LOCATION);
return eventData;
}
public long getBundleId() {
return bundleId;
}
public String getLocation() {
return location;
}
public String getBundleSymbolicName() {
return bundleSymbolicName;
}
public int getEventType() {
return eventType;
}
}
| 8,127 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/UserData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.TabularData;
import org.osgi.jmx.service.useradmin.UserAdminMBean;
import org.osgi.service.useradmin.User;
/**
* <p>
* <tt>UserData</tt> represents User Type @see {@link UserAdminMBean#USER_TYPE}.It is a codec
* for the <code>CompositeData</code> representing a User.
* </p>
* @see RoleData
*
* @version $Rev$ $Date$
*/
public class UserData extends RoleData {
/**
* user credentials.
*/
protected List<PropertyData<? extends Object>> credentials = new ArrayList<PropertyData<? extends Object>>();
/**
* Constructs new UserData from {@link User} object.
*
* @param user {@link User} instance.
*/
public UserData(User user){
this(user.getName(), user.getType(), user.getProperties(), user.getCredentials());
}
/**
* Constructs new UserData.
*
* @param name user name.
* @param type role type.
*/
public UserData(String name, int type){
super(name, type);
}
/**
* Constructs new UserData.
*
* @param name user name.
* @param type role type.
* @param properties user properties.
* @param credentials user credentials.
*/
public UserData(String name, int type, Dictionary properties, Dictionary credentials) {
super(name, type, properties);
if (credentials != null) {
for (Enumeration e = credentials.keys(); e.hasMoreElements(); ) {
String key = e.nextElement().toString();
this.credentials.add(PropertyData.newInstance(key, credentials.get(key)));
}
}
}
/**
* Translates UserData to CompositeData represented by
* compositeType {@link UserAdminMBean#USER_TYPE}.
*
* @return translated UserData to compositeData.
*/
public CompositeData toCompositeData() {
try {
Map<String, Object> items = new HashMap<String, Object>();
items.put(UserAdminMBean.NAME, name);
items.put(UserAdminMBean.TYPE, type);
// items.put(UserAdminMBean.PROPERTIES, getPropertiesTable());
// items.put(UserAdminMBean.CREDENTIALS, getCredentialsTable());
return new CompositeDataSupport(UserAdminMBean.USER_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Can't create CompositeData" + e);
}
}
protected TabularData getCredentialsTable() {
return getPropertiesTable(credentials);
}
/**
* Static factory method to create UserData from CompositeData object.
*
* @param data {@link CompositeData} instance.
* @return UserData instance.
*/
public static UserData from(CompositeData data) {
if(data == null){
return null;
}
String name = (String) data.get(UserAdminMBean.NAME);
int type = (Integer)data.get(UserAdminMBean.TYPE);
// Dictionary<String, Object> props = propertiesFrom((TabularData) data.get(UserAdminMBean.PROPERTIES));
// Dictionary<String, Object> credentials = propertiesFrom((TabularData) data.get(UserAdminMBean.CREDENTIALS));
return new UserData(name, type, null, null /* props, credentials */);
}
}
| 8,128 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/PropertyData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import static org.apache.aries.jmx.util.TypeUtils.fromString;
import static org.apache.aries.jmx.util.TypeUtils.primitiveTypes;
import static org.apache.aries.jmx.util.TypeUtils.types;
import static org.osgi.jmx.JmxConstants.ARRAY_OF;
import static org.osgi.jmx.JmxConstants.KEY;
import static org.osgi.jmx.JmxConstants.PROPERTY_TYPE;
import static org.osgi.jmx.JmxConstants.P_BOOLEAN;
import static org.osgi.jmx.JmxConstants.P_BYTE;
import static org.osgi.jmx.JmxConstants.P_CHAR;
import static org.osgi.jmx.JmxConstants.P_DOUBLE;
import static org.osgi.jmx.JmxConstants.P_FLOAT;
import static org.osgi.jmx.JmxConstants.P_INT;
import static org.osgi.jmx.JmxConstants.P_LONG;
import static org.osgi.jmx.JmxConstants.TYPE;
import static org.osgi.jmx.JmxConstants.VALUE;
import static org.osgi.jmx.JmxConstants.VECTOR_OF;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.osgi.jmx.JmxConstants;
/**
* <p>
* <tt>PropertyData</tt> represents Property Type @see {@link JmxConstants#PROPERTY_TYPE}. It is a codec for the
* <code>CompositeData</code> representing a Property with an associated Type and Value.
* </p>
*
* @version $Rev$ $Date$
*/
public class PropertyData<T> {
/**
* @see JmxConstants#KEY_ITEM
*/
private String key;
/**
* @see JmxConstants#SCALAR
*/
private T value;
/**
* @see JmxConstants#VALUE_ITEM
*/
private String encodedValue;
/**
* @see JmxConstants#TYPE_ITEM
*/
private String encodedType;
private PropertyData() {
super();
}
@SuppressWarnings("unchecked")
private PropertyData(String key, T value, String preservedBaseType) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException("Argument key cannot be null");
}
if (value == null) {
throw new IllegalArgumentException("Argument value cannot be null");
}
this.key = key;
this.value = value;
Class<T> type = (Class<T>) value.getClass();
if (type.isArray()) {
this.encodedType = ARRAY_OF + type.getComponentType().getSimpleName();
StringBuilder builder = new StringBuilder();
int length = Array.getLength(value);
boolean useDelimiter = false;
for (int i = 0; i < length; i++) {
if (useDelimiter) {
builder.append(",");
} else {
useDelimiter = true;
}
builder.append(Array.get(value, i));
}
this.encodedValue = builder.toString();
} else if (type.equals(Vector.class)) {
Vector<?> vector = (Vector<?>) value;
Class<? extends Object> componentType = Object.class;
if (vector.size() > 0) {
componentType = vector.firstElement().getClass();
}
this.encodedType = VECTOR_OF + componentType.getSimpleName();
StringBuilder builder = new StringBuilder();
Vector<?> valueVector = (Vector<?>) value;
boolean useDelimiter = false;
for (Object val : valueVector) {
if (useDelimiter) {
builder.append(",");
} else {
useDelimiter = true;
}
builder.append(val);
}
this.encodedValue = builder.toString();
} else if (List.class.isAssignableFrom(type)) {
// Lists are encoded as Arrays...
List<?> list = (List<?>) value;
Class<?> componentType = Object.class;
if (list.size() > 0)
componentType = list.get(0).getClass();
this.encodedType = ARRAY_OF + componentType.getSimpleName();
StringBuilder builder = new StringBuilder();
boolean useDelimiter = false;
for (Object o : list) {
if (useDelimiter) {
builder.append(",");
} else {
useDelimiter = true;
}
builder.append(o);
}
this.encodedValue = builder.toString();
} else {
this.encodedType = (preservedBaseType == null) ? type.getSimpleName() : preservedBaseType;
this.encodedValue = value.toString();
}
}
/**
* Static factory method for <code>PropertyData</code> instance parameterized by value's type
* @param <T>
* @param key
* @param value an instance of {@link JmxConstants#SCALAR}
* @return
* @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
*/
public static <T> PropertyData<T> newInstance(String key, T value) throws IllegalArgumentException {
return new PropertyData<T>(key, value, null);
}
/**
* Static factory method for <code>PropertyData</code> instance which preserves encoded type
* information for primitive int type
* @param key
* @param value
* @return
* @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
*/
public static PropertyData<Integer> newInstance(String key, int value) throws IllegalArgumentException {
return new PropertyData<Integer>(key, value, P_INT);
}
/**
* Static factory method for <code>PropertyData</code> instance which preserves encoded type
* information for primitive long type
* @param key
* @param value
* @return
* @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
*/
public static PropertyData<Long> newInstance(String key, long value) throws IllegalArgumentException {
return new PropertyData<Long>(key, value, P_LONG);
}
/**
* Static factory method for <code>PropertyData</code> instance which preserves encoded type
* information for primitive float type
* @param key
* @param value
* @return
* @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
*/
public static PropertyData<Float> newInstance(String key, float value) throws IllegalArgumentException {
return new PropertyData<Float>(key, value, P_FLOAT);
}
/**
* Static factory method for <code>PropertyData</code> instance which preserves encoded type
* information for primitive double type
* @param key
* @param value
* @return
* @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
*/
public static PropertyData<Double> newInstance(String key, double value) throws IllegalArgumentException {
return new PropertyData<Double>(key, value, P_DOUBLE);
}
/**
* Static factory method for <code>PropertyData</code> instance which preserves encoded type
* information for primitive byte type
* @param key
* @param value
* @return
* @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
*/
public static PropertyData<Byte> newInstance(String key, byte value) throws IllegalArgumentException {
return new PropertyData<Byte>(key, value, P_BYTE);
}
/**
* Static factory method for <code>PropertyData</code> instance which preserves encoded type
* information for primitive char type
* @param key
* @param value
* @return
* @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
*/
public static PropertyData<Character> newInstance(String key, char value) throws IllegalArgumentException {
return new PropertyData<Character>(key, value, P_CHAR);
}
/**
* Static factory method for <code>PropertyData</code> instance which preserves encoded type
* information for primitive boolean type
* @param key
* @param value
* @return
* @throws IllegalArgumentException if key or value are null or value's type cannot be encoded
*/
public static PropertyData<Boolean> newInstance(String key, boolean value) throws IllegalArgumentException {
return new PropertyData<Boolean>(key, value, P_BOOLEAN);
}
/**
* Returns CompositeData representing a Property typed by {@link JmxConstants#PROPERTY_TYPE}.
* @return
*/
public CompositeData toCompositeData() {
CompositeData result = null;
Map<String, Object> items = new HashMap<String, Object>();
items.put(KEY, this.key);
items.put(VALUE, this.encodedValue);
items.put(TYPE, this.encodedType);
try {
result = new CompositeDataSupport(PROPERTY_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Failed to create CompositeData for Property [" + this.key + ":" + this.value + "]", e);
}
return result;
}
/**
* Constructs a <code>PropertyData</code> object from the given <code>CompositeData</code>
* @param compositeData
* @return
* @throws IlleglArgumentException if compositeData is null or not of type {@link JmxConstants#PROPERTY_TYPE}
*/
@SuppressWarnings("unchecked")
public static <T> PropertyData<T> from(CompositeData compositeData) throws IllegalArgumentException {
if ( compositeData == null ) {
throw new IllegalArgumentException("Argument compositeData cannot be null");
}
if (!compositeData.getCompositeType().equals(PROPERTY_TYPE)) {
throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
}
PropertyData propertyData = new PropertyData();
propertyData.key = (String) compositeData.get(KEY);
propertyData.encodedType = (String) compositeData.get(TYPE);
propertyData.encodedValue = (String) compositeData.get(VALUE);
if (propertyData.encodedType == null || propertyData.encodedType.length() < 1) {
throw new IllegalArgumentException ("Cannot determine type from compositeData : " + compositeData);
}
StringTokenizer values = new StringTokenizer(propertyData.encodedValue, ",");
int valuesLength = values.countTokens();
if (propertyData.encodedType.startsWith(ARRAY_OF)) {
String[] arrayTypeParts = propertyData.encodedType.split("\\s");
if (arrayTypeParts.length < 3) {
throw new IllegalArgumentException("Cannot parse Array type from type item : " + propertyData.encodedType);
}
String arrayTypeName = arrayTypeParts[2].trim();
if (!types.containsKey(arrayTypeName)) {
throw new IllegalArgumentException ("Cannot determine type from value : " + arrayTypeName);
}
Class<? extends Object> arrayType = types.get(arrayTypeName);
propertyData.value = Array.newInstance(arrayType, valuesLength);
int index = 0;
while (values.hasMoreTokens()) {
Array.set(propertyData.value, index++, fromString(arrayType, values.nextToken()));
}
} else if (propertyData.encodedType.startsWith(VECTOR_OF)) {
String[] vectorTypeParts = propertyData.encodedType.split("\\s");
if (vectorTypeParts.length < 3) {
throw new IllegalArgumentException("Cannot parse Array type from type item : " + propertyData.encodedType);
}
String vectorTypeName = vectorTypeParts[2].trim();
if (!types.containsKey(vectorTypeName)) {
throw new IllegalArgumentException ("Cannot determine type from value : " + vectorTypeName);
}
Class<? extends Object> vectorType = types.get(vectorTypeName);
Vector vector = new Vector();
while (values.hasMoreTokens()) {
vector.add(fromString(vectorType, values.nextToken()));
}
propertyData.value = vector;
} else {
if (!types.containsKey(propertyData.encodedType)) {
throw new IllegalArgumentException ("Cannot determine type from value : " + propertyData.encodedType);
}
Class<? extends Object> valueType = types.get(propertyData.encodedType);
propertyData.value = fromString(valueType, propertyData.encodedValue);
}
return propertyData;
}
public String getKey() {
return key;
}
public T getValue() {
return value;
}
public String getEncodedType() {
return encodedType;
}
public String getEncodedValue() {
return encodedValue;
}
public boolean isEncodingPrimitive() {
return primitiveTypes.containsKey(encodedType);
}
}
| 8,129 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/codec/ServiceEventData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_IDENTIFIER;
import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_LOCATION;
import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_SYMBOLIC_NAME;
import static org.osgi.jmx.framework.ServiceStateMBean.EVENT;
import static org.osgi.jmx.framework.ServiceStateMBean.IDENTIFIER;
import static org.osgi.jmx.framework.ServiceStateMBean.OBJECT_CLASS;
import static org.osgi.jmx.framework.ServiceStateMBean.SERVICE_EVENT_TYPE;
import java.util.HashMap;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.jmx.framework.ServiceStateMBean;
/**
<p>
* <tt>ServiceEventData</tt> represents ServiceEvent Type @see {@link ServiceStateMBean#SERVICE_EVENT_TYPE}.
* It is a codec for the <code>CompositeData</code> representing an OSGi ServiceEvent.
* </p>
*
* @version $Rev$ $Date$
*/
public class ServiceEventData {
/**
* @see ServiceStateMBean#IDENTIFIER_ITEM
*/
private long serviceId;
/**
* @see ServiceStateMBean#OBJECT_CLASS_ITEM
*/
private String[] serviceInterfaces;
/**
* @see ServiceStateMBean#BUNDLE_IDENTIFIER_ITEM
*/
private long bundleId;
/**
* @see ServiceStateMBean#BUNDLE_LOCATION_ITEM
*/
private String bundleLocation;
/**
* @see ServiceStateMBean#BUNDLE_SYMBOLIC_NAME_ITEM
*/
private String bundleSymbolicName;
/**
* @see ServiceStateMBean#EVENT_ITEM
*/
private int eventType;
private ServiceEventData(){
super();
}
public ServiceEventData(ServiceEvent serviceEvent) {
@SuppressWarnings("rawtypes")
ServiceReference serviceReference = serviceEvent.getServiceReference();
this.serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID);
this.serviceInterfaces = (String[]) serviceReference.getProperty(Constants.OBJECTCLASS);
this.eventType = serviceEvent.getType();
Bundle bundle = serviceReference.getBundle();
if (bundle != null) {
this.bundleId = bundle.getBundleId();
this.bundleLocation = bundle.getLocation();
this.bundleSymbolicName = bundle.getSymbolicName();
}
}
/**
* Returns CompositeData representing a ServiceEvent typed by {@link ServiceStateMBean#SERVICE_EVENT_TYPE}.
* @return
*/
public CompositeData toCompositeData() {
CompositeData result = null;
Map<String, Object> items = new HashMap<String, Object>();
items.put(IDENTIFIER, this.serviceId);
items.put(OBJECT_CLASS, this.serviceInterfaces);
items.put(BUNDLE_IDENTIFIER, this.bundleId);
items.put(BUNDLE_LOCATION, this.bundleLocation);
items.put(BUNDLE_SYMBOLIC_NAME, this.bundleSymbolicName);
items.put(EVENT, this.eventType);
try {
result = new CompositeDataSupport(SERVICE_EVENT_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Failed to create CompositeData for ServiceEvent for Service [" + this.serviceId + "]", e);
}
return result;
}
/**
* Returns a <code>ServiceEventData</code> representation of the given compositeData
* @param compositeData
* @return
* @throws IllegalArgumentException if the compositeData is null or incorrect type
*/
public static ServiceEventData from(CompositeData compositeData) throws IllegalArgumentException {
ServiceEventData serviceEventData = new ServiceEventData();
if ( compositeData == null ) {
throw new IllegalArgumentException("Argument compositeData cannot be null");
}
if (!compositeData.getCompositeType().equals(SERVICE_EVENT_TYPE)) {
throw new IllegalArgumentException("Invalid CompositeType [" + compositeData.getCompositeType() + "]");
}
serviceEventData.serviceId = (Long) compositeData.get(IDENTIFIER);
serviceEventData.serviceInterfaces = (String[]) compositeData.get(OBJECT_CLASS);
serviceEventData.bundleId = (Long) compositeData.get(BUNDLE_IDENTIFIER);
serviceEventData.bundleLocation = (String) compositeData.get(BUNDLE_LOCATION);
serviceEventData.bundleSymbolicName = (String) compositeData.get(BUNDLE_SYMBOLIC_NAME);
serviceEventData.eventType = (Integer) compositeData.get(EVENT);
return serviceEventData;
}
public long getServiceId() {
return serviceId;
}
public String[] getServiceInterfaces() {
return serviceInterfaces;
}
public long getBundleId() {
return bundleId;
}
public String getBundleLocation() {
return bundleLocation;
}
public String getBundleSymbolicName() {
return bundleSymbolicName;
}
public int getEventType() {
return eventType;
}
}
| 8,130 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/provisioning/ProvisioningService.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.provisioning;
import static org.osgi.jmx.JmxConstants.PROPERTIES_TYPE;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.zip.ZipInputStream;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.apache.aries.jmx.codec.PropertyData;
import org.osgi.jmx.service.provisioning.ProvisioningServiceMBean;
/**
* Implementation of <code>ProvisioningServiceMBean</code>
*
* @version $Rev$ $Date$
*/
public class ProvisioningService implements ProvisioningServiceMBean {
private org.osgi.service.provisioning.ProvisioningService provisioningService;
/**
* Constructs new ProvisioningService instance
* @param provisioningService instance of org.osgi.service.provisioning.ProvisioningService service
*/
public ProvisioningService(org.osgi.service.provisioning.ProvisioningService provisioningService){
this.provisioningService = provisioningService;
}
/**
* @see org.osgi.jmx.service.provisioning.ProvisioningServiceMBean#addInformationFromZip(java.lang.String)
*/
public void addInformationFromZip(String zipURL) throws IOException {
if (zipURL == null || zipURL.length() < 1) {
throw new IOException("Argument zipURL cannot be null or empty");
}
InputStream is = createStream(zipURL);
ZipInputStream zis = new ZipInputStream(is);
try {
provisioningService.addInformation(zis);
} finally {
zis.close();
}
}
/**
* @see org.osgi.jmx.service.provisioning.ProvisioningServiceMBean#addInformation(javax.management.openmbean.TabularData)
*/
public void addInformation(TabularData info) throws IOException {
Dictionary<String, Object> provisioningInfo = extractProvisioningDictionary(info);
provisioningService.addInformation(provisioningInfo);
}
/**
* @see org.osgi.jmx.service.provisioning.ProvisioningServiceMBean#listInformation()
*/
@SuppressWarnings("unchecked")
public TabularData listInformation() throws IOException {
TabularData propertiesTable = new TabularDataSupport(PROPERTIES_TYPE);
Dictionary<String, Object> information = (Dictionary<String, Object>) provisioningService.getInformation();
if (information != null) {
Enumeration<String> keys = information.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
propertiesTable.put(PropertyData.newInstance(key, information.get(key)).toCompositeData());
}
}
return propertiesTable;
}
/**
* @see org.osgi.jmx.service.provisioning.ProvisioningServiceMBean#setInformation(javax.management.openmbean.TabularData)
*/
public void setInformation(TabularData info) throws IOException {
Dictionary<String, Object> provisioningInfo = extractProvisioningDictionary(info);
provisioningService.setInformation(provisioningInfo);
}
@SuppressWarnings("unchecked")
protected Dictionary<String, Object> extractProvisioningDictionary(TabularData info) {
Dictionary<String, Object> provisioningInfo = new Hashtable<String, Object>();
if (info != null) {
Collection<CompositeData> compositeData = (Collection<CompositeData>) info.values();
for (CompositeData row: compositeData) {
PropertyData<? extends Class> propertyData = PropertyData.from(row);
provisioningInfo.put(propertyData.getKey(), propertyData.getValue());
}
}
return provisioningInfo;
}
protected InputStream createStream(String url) throws IOException {
return new URL(url).openStream();
}
}
| 8,131 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/provisioning/ProvisioningServiceMBeanHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.provisioning;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
import org.apache.aries.jmx.AbstractCompendiumHandler;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.MBeanHandler;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.osgi.jmx.service.provisioning.ProvisioningServiceMBean;
import org.osgi.service.log.LogService;
/**
* <p>
* Implementation of <code>MBeanHandler</code> which manages the <code>ProvisioningServiceMBean</code> implementation
*
* @see MBeanHandler
*
* @version $Rev$ $Date$
*/
public class ProvisioningServiceMBeanHandler extends AbstractCompendiumHandler {
/**
* Constructs new ProvisioningServiceMBeanHandler instance
*
* @param agentContext
* JMXAgentContext instance
*/
public ProvisioningServiceMBeanHandler(JMXAgentContext agentContext) {
super(agentContext, "org.osgi.service.provisioning.ProvisioningService");
}
/**
* @see org.apache.aries.jmx.AbstractCompendiumHandler#constructInjectMBean(java.lang.Object)
*/
@Override
protected StandardMBean constructInjectMBean(Object targetService) {
ProvisioningService psMBean = new ProvisioningService(
(org.osgi.service.provisioning.ProvisioningService) targetService);
StandardMBean mbean = null;
try {
mbean = new StandardMBean(psMBean, ProvisioningServiceMBean.class);
} catch (NotCompliantMBeanException e) {
Logger logger = agentContext.getLogger();
logger.log(LogService.LOG_ERROR, "Failed to instantiate MBean for "
+ ProvisioningServiceMBean.class.getName(), e);
}
return mbean;
}
/**
* @see org.apache.aries.jmx.AbstractCompendiumHandler#getBaseName()
*/
protected String getBaseName() {
return ProvisioningServiceMBean.OBJECTNAME;
}
}
| 8,132 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgentImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.agent;
import java.util.IdentityHashMap;
import java.util.Map;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.MBeanHandler;
import org.apache.aries.jmx.MBeanServiceTracker;
import org.apache.aries.jmx.cm.ConfigurationAdminMBeanHandler;
import org.apache.aries.jmx.framework.BundleStateMBeanHandler;
import org.apache.aries.jmx.framework.FrameworkMBeanHandler;
import org.apache.aries.jmx.framework.PackageStateMBeanHandler;
import org.apache.aries.jmx.framework.ServiceStateMBeanHandler;
import org.apache.aries.jmx.framework.StateConfig;
import org.apache.aries.jmx.framework.wiring.BundleWiringStateMBeanHandler;
import org.apache.aries.jmx.permissionadmin.PermissionAdminMBeanHandler;
import org.apache.aries.jmx.provisioning.ProvisioningServiceMBeanHandler;
import org.apache.aries.jmx.useradmin.UserAdminMBeanHandler;
import org.osgi.framework.BundleContext;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
/**
* <p>
* Represent agent for MBeanServers registered in ServiceRegistry. Providing registration and unregistration methods.
* </p>
*
* @see JMXAgent
*
* @version $Rev$ $Date$
*/
public class JMXAgentImpl implements JMXAgent {
@SuppressWarnings("rawtypes")
private ServiceTracker mbeanServiceTracker;
/**
* {@link MBeanHandler} store.
*/
private Map<MBeanServer, Boolean> mbeanServers;
private Map<MBeanHandler, Boolean> mbeansHandlers;
private StateConfig stateConfig;
private BundleContext context;
private Logger logger;
/**
* Constructs new JMXAgent.
*
* @param stateConfig
* @param logger @see org.apache.aries.jmx.Logger
*/
public JMXAgentImpl(BundleContext context, StateConfig stateConfig, Logger logger) {
this.context = context;
this.stateConfig = stateConfig;
this.logger = logger;
this.mbeanServers = new IdentityHashMap<MBeanServer, Boolean>();
this.mbeansHandlers = new IdentityHashMap<MBeanHandler, Boolean>();
}
/**
* @see org.apache.aries.jmx.agent.JMXAgent#start()
*/
public synchronized void start() {
logger.log(LogService.LOG_INFO, "Starting JMX OSGi agent");
// Initialize static handlers
// Those handlers do not track dependencies
JMXAgentContext agentContext = new JMXAgentContext(context, this, logger);
MBeanHandler frameworkHandler = new FrameworkMBeanHandler(agentContext);
mbeansHandlers.put(frameworkHandler, Boolean.FALSE);
frameworkHandler.open();
MBeanHandler bundleStateHandler = new BundleStateMBeanHandler(agentContext, stateConfig);
mbeansHandlers.put(bundleStateHandler, Boolean.FALSE);
bundleStateHandler.open();
MBeanHandler revisionsStateHandler = new BundleWiringStateMBeanHandler(agentContext);
mbeansHandlers.put(revisionsStateHandler, Boolean.FALSE);
revisionsStateHandler.open();
MBeanHandler serviceStateHandler = new ServiceStateMBeanHandler(agentContext, stateConfig);
mbeansHandlers.put(serviceStateHandler, Boolean.FALSE);
serviceStateHandler.open();
MBeanHandler packageStateHandler = new PackageStateMBeanHandler(agentContext);
mbeansHandlers.put(packageStateHandler, Boolean.FALSE);
packageStateHandler.open();
MBeanHandler permissionAdminHandler = new PermissionAdminMBeanHandler(agentContext);
mbeansHandlers.put(permissionAdminHandler, Boolean.FALSE);
permissionAdminHandler.open();
MBeanHandler userAdminHandler = new UserAdminMBeanHandler(agentContext);
mbeansHandlers.put(userAdminHandler, Boolean.FALSE);
userAdminHandler.open();
MBeanHandler configAdminHandler = new ConfigurationAdminMBeanHandler(agentContext);
mbeansHandlers.put(configAdminHandler, Boolean.FALSE);
configAdminHandler.open();
MBeanHandler provServiceHandler = new ProvisioningServiceMBeanHandler(agentContext);
mbeansHandlers.put(provServiceHandler, Boolean.FALSE);
provServiceHandler.open();
// Track mbean servers
mbeanServiceTracker = new MBeanServiceTracker(agentContext);
mbeanServiceTracker.open();
}
/**
* @see org.apache.aries.jmx.agent.JMXAgent#registerMBeans(javax.management.MBeanServer)
*/
public synchronized void registerMBeans(final MBeanServer server) {
for (MBeanHandler mbeanHandler : mbeansHandlers.keySet()) {
if (mbeansHandlers.get(mbeanHandler) == Boolean.TRUE) {
String name = mbeanHandler.getName();
StandardMBean mbean = mbeanHandler.getMbean();
if (mbean != null) {
try {
logger.log(LogService.LOG_INFO, "Registering " + mbean.getMBeanInterface().getName()
+ " to MBeanServer " + server + " with name " + name);
server.registerMBean(mbean, new ObjectName(name));
} catch (InstanceAlreadyExistsException e) {
logger.log(LogService.LOG_ERROR, "MBean is already registered", e);
} catch (MBeanRegistrationException e) {
logger.log(LogService.LOG_ERROR, "Can't register MBean", e);
} catch (NotCompliantMBeanException e) {
logger.log(LogService.LOG_ERROR, "MBean is not compliant MBean", e);
} catch (MalformedObjectNameException e) {
logger.log(LogService.LOG_ERROR, "Try to register with no valid objectname", e);
} catch (NullPointerException e) {
logger.log(LogService.LOG_ERROR, "Name of objectname can't be null", e);
}
}
}
}
mbeanServers.put(server, Boolean.TRUE);
}
/**
* @see org.apache.aries.jmx.agent.JMXAgent#unregisterMBeans(javax.management.MBeanServer)
*/
public synchronized void unregisterMBeans(final MBeanServer server) {
for (MBeanHandler mBeanHandler : mbeansHandlers.keySet()) {
if (mbeansHandlers.get(mBeanHandler) == Boolean.TRUE) {
try {
String name = mBeanHandler.getName();
StandardMBean mbean = mBeanHandler.getMbean();
if (mbean != null) {
logger.log(LogService.LOG_INFO, "Unregistering " + mbean.getMBeanInterface().getName()
+ " to MBeanServer " + server + " with name " + name);
server.unregisterMBean(new ObjectName(name));
}
} catch (MBeanRegistrationException e) {
logger.log(LogService.LOG_ERROR, "Can't unregister MBean", e);
} catch (InstanceNotFoundException e) {
logger.log(LogService.LOG_ERROR, "MBean doesn't exist in the repository", e);
} catch (MalformedObjectNameException e) {
logger.log(LogService.LOG_ERROR, "Try to unregister with no valid objectname", e);
} catch (NullPointerException e) {
logger.log(LogService.LOG_ERROR, "Name of objectname can't be null ", e);
} catch (Exception e) {
logger.log(LogService.LOG_ERROR, "Cannot unregister MBean: " + mBeanHandler, e);
}
}
}
mbeanServers.remove(server);
}
/**
* @see org.apache.aries.jmx.agent.JMXAgent#registerMBean(org.apache.aries.jmx.MBeanHandler)
*/
public synchronized void registerMBean(final MBeanHandler mBeanHandler) {
for (MBeanServer server : mbeanServers.keySet()) {
String name = mBeanHandler.getName();
StandardMBean mbean = mBeanHandler.getMbean();
try {
logger.log(LogService.LOG_INFO, "Registering " + mbean.getMBeanInterface().getName()
+ " to MBeanServer " + server + " with name " + name);
server.registerMBean(mbean, new ObjectName(name));
} catch (InstanceAlreadyExistsException e) {
logger.log(LogService.LOG_ERROR, "MBean is already registered", e);
} catch (MBeanRegistrationException e) {
logger.log(LogService.LOG_ERROR, "Can't register MBean", e);
} catch (NotCompliantMBeanException e) {
logger.log(LogService.LOG_ERROR, "MBean is not compliant MBean, Stopping registration", e);
return;
} catch (MalformedObjectNameException e) {
logger.log(LogService.LOG_ERROR, "Try to register with no valid objectname, Stopping registration", e);
return;
} catch (NullPointerException e) {
logger.log(LogService.LOG_ERROR, "Name of objectname can't be null, Stopping registration", e);
return;
}
}
mbeansHandlers.put(mBeanHandler, Boolean.TRUE);
}
/**
* @see org.apache.aries.jmx.agent.JMXAgent#unregisterMBean(org.apache.aries.jmx.MBeanHandler)
*/
public synchronized void unregisterMBean(final MBeanHandler mBeanHandler) {
for (MBeanServer server : mbeanServers.keySet()) {
String name = mBeanHandler.getName();
try {
logger.log(LogService.LOG_INFO, "Unregistering mbean " + " to MBeanServer " + server + " with name "
+ name);
server.unregisterMBean(new ObjectName(name));
} catch (MBeanRegistrationException e) {
logger.log(LogService.LOG_ERROR, "Can't register MBean", e);
} catch (InstanceNotFoundException e) {
logger.log(LogService.LOG_ERROR, "MBean doesn't exist in the repository", e);
} catch (MalformedObjectNameException e) {
logger.log(LogService.LOG_ERROR, "Try to register with no valid objectname, Stopping registration", e);
return;
} catch (NullPointerException e) {
logger.log(LogService.LOG_ERROR, "Name of objectname can't be null, Stopping registration", e);
return;
}
}
mbeansHandlers.put(mBeanHandler, Boolean.FALSE);
}
/**
* @see org.apache.aries.jmx.agent.JMXAgent#stop()
*/
public void stop() {
logger.log(LogService.LOG_INFO, "Stopping JMX OSGi agent");
synchronized (this) {
mbeanServiceTracker.close();
for (MBeanHandler mBeanHandler : mbeansHandlers.keySet()) {
mBeanHandler.close();
}
}
}
}
| 8,133 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgentContext.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.agent;
import javax.management.MBeanServer;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.MBeanHandler;
import org.osgi.framework.BundleContext;
/**
* <p>This class <tt>JMXAgentContext</tt> represents context of JMXAgent.
* Delegates registration and unregistration methods to {@link JMXAgent}.</p>
* @see JMXAgent
*
* @version $Rev$ $Date$
*/
public class JMXAgentContext {
private JMXAgent agent;
private BundleContext bundleContext;
private Logger logger;
/**
* Constructs new JMXAgentContext.
* @param bundleContext bundle context @see {@link BundleContext}.
* @param agent {@link JMXAgent}.
* @param log logger represents by @see {@link Logger}.
*/
public JMXAgentContext(BundleContext bundleContext, JMXAgent agent, Logger log) {
this.bundleContext = bundleContext;
this.agent = agent;
this.logger = log;
}
/**
* Delegates invocation to JMX agent.
* @see org.apache.aries.jmx.agent.JMXAgent#registerMBeans(MBeanServer)
*
*/
public void registerMBeans(final MBeanServer server) {
agent.registerMBeans(server);
}
/**
* Delegates invocation to JMX agent.
* @see org.apache.aries.jmx.agent.JMXAgent#unregisterMBeans(MBeanServer)
*/
public void unregisterMBeans(final MBeanServer server) {
agent.unregisterMBeans(server);
}
/**
* Delegates invocation to JMX agent.
* @see org.apache.aries.jmx.agent.JMXAgent#registerMBean(MBeanHandler)
*/
public void registerMBean(final MBeanHandler mbeanData) {
agent.registerMBean(mbeanData);
}
/**
* Delegates invocation to JMX agent.
* @see org.apache.aries.jmx.agent.JMXAgent#unregisterMBean(MBeanHandler)
*/
public void unregisterMBean(final MBeanHandler mBeanHandler) {
agent.unregisterMBean(mBeanHandler);
}
/**
* Gets bundle context.
* @return bundle context.
*/
public BundleContext getBundleContext() {
return bundleContext;
}
/**
* Gets a logger represents by @see {@link Logger}.
* @return LogService tracker.
*/
public Logger getLogger() {
return logger;
}
}
| 8,134 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/agent/JMXAgent.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.agent;
import javax.management.MBeanServer;
import org.apache.aries.jmx.MBeanHandler;
/**
* <p>This <tt>JMXAgent</tt> class represent agent for MBeanServers registered in ServiceRegistry.
* It's responsible for registration and unregistration MBeans with available MBeanServers.
* </p>
*
* @version $Rev$ $Date$
*/
public interface JMXAgent {
/**
* This method starts JMX agent.
* Creates and starting all MBean Handlers and MBeanServiceTracker.
*/
void start();
/**
* Registers MBeans with provided MBeanServer.
* @param server MBeanServer with which MBeans are going to be registered
*/
void registerMBeans(final MBeanServer server);
/**
* Unregisters MBeans with provided MBeanServer.
* @param server MBeanServer with which MBeans are going to be unregistered.
*/
void unregisterMBeans(final MBeanServer server);
/**
* Registers MBean with all available MBeanServers.
* @param mBeanHandler handler which contains MBean info.
*/
void registerMBean(final MBeanHandler mBeanHandler);
/**
* Unregisters MBean with all available MBeanServers.
* @param mBeanHandler handler which contains MBean info.
*/
void unregisterMBean(final MBeanHandler mBeanHandler);
/**
* Stops JMXAgent.
* This method stops MBeanServiceTracker and all MBean handlers.
*/
void stop();
} | 8,135 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/permissionadmin/PermissionAdmin.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.permissionadmin;
import java.io.IOException;
import org.osgi.jmx.service.permissionadmin.PermissionAdminMBean;
import org.osgi.service.permissionadmin.PermissionInfo;
/**
* <p>
* <tt>PermissionAdmin</tt> represents implementation of PermissionAdminMBean.
* </p>
* @see PermissionAdminMBean
*
* @version $Rev$ $Date$
*/
public class PermissionAdmin implements PermissionAdminMBean {
/**
* {@link org.osgi.service.permissionadmin.PermissionAdmin} service.
*/
private org.osgi.service.permissionadmin.PermissionAdmin permAdmin;
/**
* Constructs new PermissionAdmin MBean.
*
* @param permAdmin {@link org.osgi.service.permissionadmin.PermissionAdmin} service reference.
*/
public PermissionAdmin(org.osgi.service.permissionadmin.PermissionAdmin permAdmin) {
this.permAdmin = permAdmin;
}
/**
* @see org.osgi.jmx.service.permissionadmin.PermissionAdminMBean#getPermissions(java.lang.String)
*/
public String[] getPermissions(String location) throws IOException {
if (location == null) {
throw new IOException("Location cannot be null");
}
PermissionInfo[] permissions = permAdmin.getPermissions(location);
if (permissions != null) {
String[] encoded = new String[permissions.length];
for (int i = 0; i < permissions.length; i++) {
PermissionInfo info = permissions[i];
encoded[i] = info.getEncoded();
}
return encoded;
}
return null;
}
/**
* @see org.osgi.jmx.service.permissionadmin.PermissionAdminMBean#listDefaultPermissions()
*/
public String[] listDefaultPermissions() throws IOException {
PermissionInfo[] permissions = permAdmin.getDefaultPermissions();
if (permissions != null) {
String[] encoded = new String[permissions.length];
for (int i = 0; i < permissions.length; i++) {
PermissionInfo info = permissions[i];
encoded[i] = info.getEncoded();
}
return encoded;
}
return null;
}
/**
* @see org.osgi.jmx.service.permissionadmin.PermissionAdminMBean#listLocations()
*/
public String[] listLocations() throws IOException {
return permAdmin.getLocations();
}
/**
* @see org.osgi.jmx.service.permissionadmin.PermissionAdminMBean#setDefaultPermissions(java.lang.String[])
*/
public void setDefaultPermissions(String[] encodedPermissions) throws IOException {
PermissionInfo[] permissions = toPermissionInfo(encodedPermissions);
permAdmin.setDefaultPermissions(permissions);
}
/**
* @see org.osgi.jmx.service.permissionadmin.PermissionAdminMBean#setPermissions(java.lang.String,
* java.lang.String[])
*/
public void setPermissions(String location, String[] encodedPermissions) throws IOException {
if (location == null) {
throw new IOException("Location cannot be null");
}
PermissionInfo[] permissions = toPermissionInfo(encodedPermissions);
permAdmin.setPermissions(location, permissions);
}
private static PermissionInfo[] toPermissionInfo(String[] encodedPermissions) throws IOException {
if (encodedPermissions == null) {
return null;
}
PermissionInfo[] permissions = new PermissionInfo[encodedPermissions.length];
for (int i = 0; i < encodedPermissions.length; i++) {
try {
permissions[i] = new PermissionInfo(encodedPermissions[i]);
} catch (Exception e) {
IOException ex = new IOException("Invalid encoded permission: " + encodedPermissions[i]);
ex.initCause(e);
throw ex;
}
}
return permissions;
}
}
| 8,136 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/permissionadmin/PermissionAdminMBeanHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.permissionadmin;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
import org.apache.aries.jmx.AbstractCompendiumHandler;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.MBeanHandler;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.osgi.jmx.service.permissionadmin.PermissionAdminMBean;
import org.osgi.service.log.LogService;
/**
* <p>
* <tt>PermissionAdminMBeanHandler</tt> represents MBeanHandler which
* holding information about {@link PermissionAdminMBean}.</p>
* @see MBeanHandler
*
* @version $Rev$ $Date$
*/
public class PermissionAdminMBeanHandler extends AbstractCompendiumHandler {
/**
* Constructs new PermissionAdminMBeanHandler.
*
* @param agentContext JMXAgentContext instance.
*/
public PermissionAdminMBeanHandler(JMXAgentContext agentContext) {
super(agentContext, "org.osgi.service.permissionadmin.PermissionAdmin");
}
/**
* @see org.apache.aries.jmx.AbstractCompendiumHandler#constructInjectMBean(java.lang.Object)
*/
@Override
protected StandardMBean constructInjectMBean(Object targetService) {
PermissionAdminMBean paMBean = new PermissionAdmin((org.osgi.service.permissionadmin.PermissionAdmin) targetService);
StandardMBean mbean = null;
try {
mbean = new StandardMBean(paMBean, PermissionAdminMBean.class);
} catch (NotCompliantMBeanException e) {
Logger logger = agentContext.getLogger();
logger.log(LogService.LOG_ERROR, "Not compliant MBean", e);
}
return mbean;
}
/**
* @see org.apache.aries.jmx.AbstractCompendiumHandler#getBaseName()
*/
protected String getBaseName() {
return PermissionAdminMBean.OBJECTNAME;
}
} | 8,137 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/cm/ConfigurationAdminMBeanHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.cm;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
import org.apache.aries.jmx.AbstractCompendiumHandler;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.MBeanHandler;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.osgi.jmx.service.cm.ConfigurationAdminMBean;
import org.osgi.service.log.LogService;
/**
* <p>
* Implementation of <code>MBeanHandler</code> which manages the <code>ConfigurationAdminMBean</code> implementation
*
* @see MBeanHandler </p>
*
* @version $Rev$ $Date$
*/
public class ConfigurationAdminMBeanHandler extends AbstractCompendiumHandler {
/**
* Constructs new ConfigurationAdminMBeanHandler instance
*
* @param agentContext
* JMXAgentContext instance
*/
public ConfigurationAdminMBeanHandler(JMXAgentContext agentContext) {
super(agentContext, "org.osgi.service.cm.ConfigurationAdmin");
}
/**
* @see org.apache.aries.jmx.AbstractCompendiumHandler#constructInjectMBean(java.lang.Object)
*/
@Override
protected StandardMBean constructInjectMBean(Object targetService) {
ConfigurationAdminMBean caMBean = new org.apache.aries.jmx.cm.ConfigurationAdmin(
(org.osgi.service.cm.ConfigurationAdmin) targetService);
StandardMBean mbean = null;
try {
mbean = new StandardMBean(caMBean, ConfigurationAdminMBean.class);
} catch (NotCompliantMBeanException e) {
Logger logger = agentContext.getLogger();
logger.log(LogService.LOG_ERROR, "Failed to instantiate MBean for "
+ ConfigurationAdminMBean.class.getName(), e);
}
return mbean;
}
/**
* @see org.apache.aries.jmx.AbstractCompendiumHandler#getBaseName()
*/
protected String getBaseName() {
return ConfigurationAdminMBean.OBJECTNAME;
}
}
| 8,138 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/cm/ConfigurationAdmin.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.cm;
import static org.osgi.jmx.JmxConstants.PROPERTIES_TYPE;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.apache.aries.jmx.codec.PropertyData;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.jmx.service.cm.ConfigurationAdminMBean;
import org.osgi.service.cm.Configuration;
/**
* Implementation of <code>ConfigurationAdminMBean</code>
*
* @version $Rev$ $Date$
*/
public class ConfigurationAdmin implements ConfigurationAdminMBean {
private org.osgi.service.cm.ConfigurationAdmin configurationAdmin;
/**
* Constructs a ConfigurationAdmin implementation
* @param configurationAdmin instance of org.osgi.service.cm.ConfigurationAdmin service
*/
public ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin configurationAdmin) {
this.configurationAdmin = configurationAdmin;
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#createFactoryConfiguration(java.lang.String)
*/
public String createFactoryConfiguration(String factoryPid) throws IOException {
return createFactoryConfigurationForLocation(factoryPid, null);
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#createFactoryConfigurationForLocation(java.lang.String, java.lang.String)
*/
public String createFactoryConfigurationForLocation(String factoryPid, String location) throws IOException {
if (factoryPid == null || factoryPid.length() < 1) {
throw new IOException("Argument factoryPid cannot be null or empty");
}
Configuration config = configurationAdmin.createFactoryConfiguration(factoryPid);
config.setBundleLocation(location);
return config.getPid();
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#delete(java.lang.String)
*/
public void delete(String pid) throws IOException {
deleteForLocation(pid, null);
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#deleteForLocation(java.lang.String, java.lang.String)
*/
public void deleteForLocation(String pid, String location) throws IOException {
if (pid == null || pid.length() < 1) {
throw new IOException("Argument pid cannot be null or empty");
}
Configuration config = configurationAdmin.getConfiguration(pid, location);
config.delete();
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#deleteConfigurations(java.lang.String)
*/
public void deleteConfigurations(String filter) throws IOException {
if (filter == null || filter.length() < 1) {
throw new IOException("Argument filter cannot be null or empty");
}
Configuration[] configuations = null;
try {
configuations = configurationAdmin.listConfigurations(filter);
} catch (InvalidSyntaxException e) {
throw new IOException("Invalid filter [" + filter + "] : " + e);
}
if (configuations != null) {
for (Configuration config : configuations) {
config.delete();
}
}
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getBundleLocation(java.lang.String)
*/
public String getBundleLocation(String pid) throws IOException {
if (pid == null || pid.length() < 1) {
throw new IOException("Argument pid cannot be null or empty");
}
Configuration config = configurationAdmin.getConfiguration(pid, null);
String bundleLocation = (config.getBundleLocation() == null) ? "Configuration is not yet bound to a bundle location" : config.getBundleLocation();
return bundleLocation;
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getConfigurations(java.lang.String)
*/
public String[][] getConfigurations(String filter) throws IOException {
if (filter == null || filter.length() < 1) {
throw new IOException("Argument filter cannot be null or empty");
}
List<String[]> result = new ArrayList<String[]>();
Configuration[] configurations = null;
try {
configurations = configurationAdmin.listConfigurations(filter);
} catch (InvalidSyntaxException e) {
throw new IOException("Invalid filter [" + filter + "] : " + e);
}
if (configurations != null) {
for (Configuration config : configurations) {
result.add(new String[] { config.getPid(), config.getBundleLocation() });
}
}
return result.toArray(new String[result.size()][]);
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getFactoryPid(java.lang.String)
*/
public String getFactoryPid(String pid) throws IOException {
return getFactoryPidForLocation(pid, null);
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getFactoryPidForLocation(java.lang.String, java.lang.String)
*/
public String getFactoryPidForLocation(String pid, String location) throws IOException {
if (pid == null || pid.length() < 1) {
throw new IOException("Argument pid cannot be null or empty");
}
Configuration config = configurationAdmin.getConfiguration(pid, location);
return config.getFactoryPid();
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getProperties(java.lang.String)
*/
public TabularData getProperties(String pid) throws IOException {
return getPropertiesForLocation(pid, null);
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#getPropertiesForLocation(java.lang.String, java.lang.String)
*/
public TabularData getPropertiesForLocation(String pid, String location) throws IOException {
if (pid == null || pid.length() < 1) {
throw new IOException("Argument pid cannot be null or empty");
}
TabularData propertiesTable = null;
Configuration config = configurationAdmin.getConfiguration(pid, location);
Dictionary<String, Object> properties = config.getProperties();
if (properties != null) {
propertiesTable = new TabularDataSupport(PROPERTIES_TYPE);
Enumeration<String> keys = properties.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
propertiesTable.put(PropertyData.newInstance(key, properties.get(key)).toCompositeData());
}
}
return propertiesTable;
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#setBundleLocation(java.lang.String, java.lang.String)
*/
public void setBundleLocation(String pid, String location) throws IOException {
if (pid == null || pid.length() < 1) {
throw new IOException("Argument factoryPid cannot be null or empty");
}
Configuration config = configurationAdmin.getConfiguration(pid, null);
config.setBundleLocation(location);
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#update(java.lang.String, javax.management.openmbean.TabularData)
*/
public void update(String pid, TabularData configurationTable) throws IOException {
updateForLocation(pid, null, configurationTable);
}
/**
* @see org.osgi.jmx.service.cm.ConfigurationAdminMBean#updateForLocation(java.lang.String, java.lang.String, javax.management.openmbean.TabularData)
*/
@SuppressWarnings("unchecked")
public void updateForLocation(String pid, String location, TabularData configurationTable) throws IOException {
if (pid == null || pid.length() < 1) {
throw new IOException("Argument pid cannot be null or empty");
}
if (configurationTable == null) {
throw new IOException("Argument configurationTable cannot be null");
}
if (!PROPERTIES_TYPE.equals(configurationTable.getTabularType())) {
throw new IOException("Invalid TabularType [" + configurationTable.getTabularType() + "]");
}
Dictionary<String, Object> configurationProperties = new Hashtable<String, Object>();
Collection<CompositeData> compositeData = (Collection<CompositeData>) configurationTable.values();
for (CompositeData row: compositeData) {
PropertyData<? extends Class<?>> propertyData = PropertyData.from(row);
configurationProperties.put(propertyData.getKey(), propertyData.getValue());
}
Configuration config = configurationAdmin.getConfiguration(pid, location);
config.update(configurationProperties);
}
}
| 8,139 |
0 | Create_ds/aries/async/promise-api/src/test/java/org/apache/aries/async/promise | Create_ds/aries/async/promise-api/src/test/java/org/apache/aries/async/promise/test/CallbackTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.promise.test;
import org.osgi.util.promise.Deferred;
import org.osgi.util.promise.Promise;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CallbackTest {
@Test
public void testCallbacks() throws Exception {
Deferred<String> def = new Deferred<String>();
final Promise<String> promise = def.getPromise();
Callback cb1 = new Callback(promise, "Hello");
assertEquals("onResolve returns promise", promise, promise.onResolve(cb1));
Callback cb2 = new Callback(promise, "Hello");
promise.onResolve(cb2);
def.resolve("Hello");
assertTrue("callback1 executed", cb1.latch.await(1, TimeUnit.SECONDS));
assertEquals("callback1 succeeded", null, cb1.error);
assertTrue("callback2 executed", cb2.latch.await(1, TimeUnit.SECONDS));
assertEquals("callback2 succeeded", null, cb2.error);
// register callback after promise is resolved
Callback cb3 = new Callback(promise, "Hello");
promise.onResolve(cb3);
assertTrue("callback3 executed", cb3.latch.await(1, TimeUnit.SECONDS));
assertEquals("callback3 succeeded", null, cb3.error);
}
class Callback implements Runnable {
final CountDownLatch latch = new CountDownLatch(1);
Throwable error = null;
private final Promise promise;
private final Object value;
Callback(Promise promise, Object value) {
this.promise = promise;
this.value = value;
}
@Override
public void run() {
try {
assertTrue("Promise resolved", promise.isDone());
assertEquals("Value matches", value, promise.getValue());
}
catch (Throwable t) {
error = t;
}
finally {
latch.countDown();
}
}
}
}
| 8,140 |
0 | Create_ds/aries/async/promise-api/src/test/java/org/apache/aries/async/promise | Create_ds/aries/async/promise-api/src/test/java/org/apache/aries/async/promise/test/DeferredTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.promise.test;
import org.osgi.util.promise.Deferred;
import org.osgi.util.promise.Promise;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import static org.junit.Assert.*;
public class DeferredTest {
@Test
public void testResolve() throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> promise = def.getPromise();
assertFalse("Initial Promise not resolved", promise.isDone());
def.resolve("Hello");
assertTrue("Promise resolved", promise.isDone());
assertEquals("Value matches", "Hello", promise.getValue());
assertNull("Failure is null", promise.getFailure());
try {
def.resolve("Again");
fail("Already resolved didn't throw IllegalStateException");
} catch (IllegalStateException e) {
// suppress empty catch block warning
}
}
@Test
public void testResolveWithSuccess() throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> promise = def.getPromise();
Deferred<String> with = new Deferred<String>();
Promise<Void> resolvedWith = def.resolveWith(with.getPromise());
// If the specified Promise is successfully resolved,
// the associated Promise is resolved with the value of the specified Promise.
with.resolve("resolveWith");
assertTrue("Promise resolved", promise.isDone());
assertEquals("Value matches", "resolveWith", promise.getValue());
// The returned Promise will be successfully resolved, with the value null,
// if the associated Promise was resolved by the specified Promise.
assertNull("resolveWith null", resolvedWith.getValue());
}
@Test
public void testResolveWithAlreadyResolved() throws Exception {
Deferred<String> def = new Deferred<String>();
Deferred<String> with = new Deferred<String>();
Promise<Void> resolvedWith = def.resolveWith(with.getPromise());
// The returned Promise will be resolved with a failure of IllegalStateException
// if the associated Promise was already resolved when the specified Promise was resolved.
def.resolve("Already resolved");
with.resolve("resolveWith");
@SuppressWarnings({"not thrown", "all"})
Throwable failure = resolvedWith.getFailure();
assertTrue("resolveWith IllegalStateException", failure instanceof IllegalStateException);
}
@Test
public void testResolveWithAlreadyFailed() throws Exception {
Deferred<String> def = new Deferred<String>();
Deferred<String> with = new Deferred<String>();
Promise<Void> resolvedWith = def.resolveWith(with.getPromise());
// The returned Promise will be resolved with a failure of IllegalStateException
// if the associated Promise was already resolved when the specified Promise was resolved.
def.resolve("Already resolved");
with.fail(new Throwable("failed"));
@SuppressWarnings({"not thrown", "all"})
Throwable failure = resolvedWith.getFailure();
assertTrue("resolveWith IllegalStateException", failure instanceof IllegalStateException);
}
@Test
public void testResolveWithFailure() throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> promise = def.getPromise();
Deferred<String> def2 = new Deferred<String>();
Promise<String> promise2 = def2.getPromise();
Promise<Void> with = def.resolveWith(promise2);
// If the specified Promise is resolved with a failure,
// the associated Promise is resolved with the failure of the specified Promise.
Exception failure = new Exception("resolveWithFailure");
def2.fail(failure);
assertTrue("Promise resolved", promise.isDone());
assertEquals("Failure matches", failure, promise.getFailure());
// The returned Promise will be successfully resolved, with the value null,
// if the associated Promise was resolved by the specified Promise.
assertNull("resolveWith null", with.getValue());
}
@Test
public void testFail() throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> promise = def.getPromise();
Exception failure = new Exception("Oops");
def.fail(failure);
assertTrue("Promise resolved", promise.isDone());
assertEquals("Failure matches", failure, promise.getFailure());
try {
promise.getValue();
fail("getValue didn't throw InvocationTargetException");
} catch (InvocationTargetException e) {
assertEquals("Failure matches", failure, e.getCause());
}
try {
def.fail(failure);
fail("Already failed didn't throw IllegalStateException");
} catch (IllegalStateException e) {
assertNotNull(e);
}
}
}
| 8,141 |
0 | Create_ds/aries/async/promise-api/src/test/java/org/apache/aries/async/promise | Create_ds/aries/async/promise-api/src/test/java/org/apache/aries/async/promise/test/PromisesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.promise.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.osgi.util.promise.Deferred;
import org.osgi.util.promise.FailedPromisesException;
import org.osgi.util.promise.Promise;
import org.osgi.util.promise.Promises;
public class PromisesTest {
@Test
public void testResolved() throws Exception {
final Promise<String> promise = Promises.resolved("Resolved");
assertTrue("Promise resolved", promise.isDone());
assertEquals("Value matches", "Resolved", promise.getValue());
}
@Test
public void testFailed() throws Exception {
Exception failed = new Exception("Failed");
final Promise<String> promise = Promises.failed(failed);
assertTrue("Promise resolved", promise.isDone());
assertEquals("Value matches", failed, promise.getFailure());
}
@Test
public void testLatch() throws Exception {
testLatch(false, "hello", "world");
testLatch(true, "hello", "world");
testLatch(false, "goodbye", "!cruel", "world");
testLatch(true, "goodbye", "!cruel", "world");
testLatch(false, "goodbye", "!cruel", "!world");
testLatch(false);
testLatch(1, 2);
testLatch(1, -2, 3);
testLatch(1, -2, 3, -4);
testLatch(new Integer[0]);
}
// T = String
private void testLatch(boolean preResolve, String... rv) throws Exception {
@SuppressWarnings("unchecked")
Deferred<String>[] dv = new Deferred[rv.length];
@SuppressWarnings("unchecked")
Promise<String>[] pv = new Promise[rv.length];
for (int i = 0; i < rv.length; i++) {
dv[i] = new Deferred<String>();
pv[i] = dv[i].getPromise();
}
Promise<List<String>> latch = null;
if (!preResolve) {
Promise<List<String>> latch2 = Promises.all(pv);
latch = latch2;
if (rv.length == 0) {
assertTrue("latch resolved", latch.isDone());
return;
}
assertFalse("latch not resolved", latch.isDone());
}
int nFail = 0;
for (int i = 0; i < rv.length; i++) {
String res = rv[i];
if (res.startsWith("!")) {
dv[i].fail(new Exception(res));
nFail++;
} else {
dv[i].resolve(res);
}
}
if (preResolve) {
Promise<List<String>> latch2 = Promises.all(pv);
latch = latch2;
}
assertTrue("latch resolved", latch.isDone());
if (nFail > 0) {
@SuppressWarnings({"not thrown", "all"})
Throwable failure = latch.getFailure();
assertTrue("failure instanceof FailedPromisesException", failure instanceof FailedPromisesException);
Collection<Promise<?>> failedPromises = ((FailedPromisesException) failure).getFailedPromises();
assertEquals("failedPromises size matches", nFail, failedPromises.size());
for (int i = 0; i < rv.length; i++) {
Promise<String> promise = pv[i];
if (rv[i].startsWith("!")) {
assertTrue("failedPromises contains", failedPromises.contains(promise));
} else {
assertFalse("failedPromises doesn't contain", failedPromises.contains(promise));
}
}
} else {
List<String> list = latch.getValue();
assertEquals("list size matches", rv.length, list.size());
for (int i = 0; i < rv.length; i++) {
assertEquals("list[i] matches", rv[i], list.get(i));
}
// check list is modifiable
list.add(0, "new item");
assertEquals("list modifiable", "new item", list.get(0));
}
}
// T = Number
// S = Integer
private void testLatch(Integer... rv) throws Exception {
@SuppressWarnings("unchecked")
Deferred<Integer>[] dv = new Deferred[rv.length];
List<Promise<Integer>> promises = new ArrayList<Promise<Integer>>();
for (int i = 0; i < rv.length; i++) {
dv[i] = new Deferred<Integer>();
promises.add(dv[i].getPromise());
}
Promise<List<Number>> latch = Promises.all(promises);
if (rv.length == 0) {
assertTrue("latch resolved", latch.isDone());
return;
}
assertFalse("latch not resolved", latch.isDone());
int nFail = 0;
for (int i = 0; i < rv.length; i++) {
Integer res = rv[i];
if (res < 0) {
dv[i].fail(new Exception("fail" + res));
nFail++;
} else {
dv[i].resolve(res);
}
}
assertTrue("latch resolved", latch.isDone());
if (nFail > 0) {
@SuppressWarnings({"not thrown", "all"})
Throwable failure = latch.getFailure();
assertTrue("failure instanceof FailedPromisesException", failure instanceof FailedPromisesException);
Collection<Promise<?>> failedPromises = ((FailedPromisesException) failure).getFailedPromises();
assertEquals("failedPromises size matches", nFail, failedPromises.size());
for (int i = 0; i < rv.length; i++) {
Promise<Integer> promise = promises.get(i);
if (rv[i] < 0) {
assertTrue("failedPromises contains", failedPromises.contains(promise));
} else {
assertFalse("failedPromises doesn't contain", failedPromises.contains(promise));
}
}
} else {
List<Number> list = latch.getValue();
assertEquals("list size matches", rv.length, list.size());
for (int i = 0; i < rv.length; i++) {
assertEquals("list[i] matches", rv[i], list.get(i));
}
// check list is modifiable
list.add(0, 3.14);
assertEquals("list modifiable", 3.14, list.get(0));
}
}
}
| 8,142 |
0 | Create_ds/aries/async/promise-api/src/test/java/org/apache/aries/async/promise | Create_ds/aries/async/promise-api/src/test/java/org/apache/aries/async/promise/test/FunctionTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.promise.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.NoSuchElementException;
import org.junit.Test;
import org.osgi.util.function.Function;
import org.osgi.util.function.Predicate;
import org.osgi.util.promise.Deferred;
import org.osgi.util.promise.Promise;
import org.osgi.util.promise.Promises;
public class FunctionTest {
@Test
public void testFilter() throws Exception {
testFilter("hello");
testFilter("!reject");
testFilter("fail");
testFilter(null);
testFilter("already");
testFilter("already!");
}
@Test
public void testMap() throws Exception {
testMap("hello");
testMap("hello!");
testMap("fail");
testMap("fail!");
}
@Test
public void testFlatMap() throws Exception {
testFlatMap("hello");
testFlatMap("hello!");
testFlatMap("fail");
}
@Test
public void testRecover() throws Exception {
testRecover("hello");
testRecover("fail");
testRecover("null");
testRecover(null);
}
@Test
public void testRecoverWith() throws Exception {
testRecoverWith("hello");
testRecoverWith("fail");
testRecoverWith("null");
testRecoverWith(null);
}
@Test
public void testFallback() throws Exception {
testFallback("hello", "world");
testFallback("fail", "world");
testFallback("hello", "fail");
testFallback("fail", "fail");
}
@Test
public void testFilter2() throws Exception {
String bigValue = new String("value");
Promise<String> p1 = Promises.resolved(bigValue);
Promise<String> p2 = p1.filter(new Predicate<String>() {
public boolean test(String t) {
return t.length() > 0;
}
});
assertTrue("Filter2 resolved", p2.isDone());
assertEquals("Value2 matches", bigValue, p2.getValue());
Promise<String> p3 = p1.filter(new Predicate<String>() {
public boolean test(String t) {
return t.length() == 0;
}
});
assertTrue("Filter3 resolved", p3.isDone());
assertTrue("Value3 fail matches", p3.getFailure() instanceof NoSuchElementException);
}
public static class Nasty extends RuntimeException {
public Nasty(String msg) {
super(msg);
}
}
private void testFilter(String r) throws Exception {
Deferred<String> def = new Deferred<String>();
Throwable fail = new Throwable("fail");
boolean already = (r != null && r.startsWith("already"));
if (already) {
if (r.contains("!")) {
def.fail(fail);
} else {
def.resolve(r);
}
}
Promise<String> filter = def.getPromise().filter(new Predicate<String>() {
@Override
public boolean test(String s) {
if (s == null) {
throw new Nasty(null);
}
return !s.startsWith("!");
}
});
if (!already) {
if ("fail".equals(r)) {
def.fail(fail);
} else {
def.resolve(r);
}
}
assertTrue("Filter resolved", filter.isDone());
@SuppressWarnings({"not thrown", "all"})
Throwable failure = filter.getFailure();
if ("fail".equals(r)) {
assertEquals("Failure matches", fail, filter.getFailure());
} else if (already && r.contains("!")) {
assertEquals("Failure matches", fail, filter.getFailure());
} else if (r == null) {
assertTrue("Failure instance Nasty", failure instanceof Nasty);
} else if (r.startsWith("!")) {
assertTrue("Failure instanceof NoSuchElementException", failure instanceof NoSuchElementException);
} else {
assertEquals("Value matches", r, filter.getValue());
}
}
private void testMap(String r) throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> result = def.getPromise().map(new Function<String, String>() {
@Override
public String apply(String s) {
if (s.contains("!"))
throw new Nasty(s);
return s + s.length();
}
});
Throwable fail = new Throwable("fail");
if (r.startsWith("fail")) {
def.fail(fail);
} else {
def.resolve(r);
}
assertTrue("Map resolved", result.isDone());
@SuppressWarnings({"not thrown", "all"})
Throwable failure = result.getFailure();
if (r.startsWith("fail")) {
assertEquals("Failure matches", fail, failure);
} else if (r.contains("!")) {
assertTrue("Failure instance Nasty", failure instanceof Nasty);
} else {
assertEquals("Value matches", r + r.length(), result.getValue());
}
}
private void testFlatMap(String r) throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> flatMap = def.getPromise().flatMap(new Function<String, Promise<? extends String>>() {
@Override
public Promise<String> apply(String s) {
if (s.contains("!"))
throw new Nasty(s);
return Promises.resolved(s + s.length());
}
});
Throwable fail = new Throwable("fail");
if ("fail".equals(r)) {
def.fail(fail);
} else {
def.resolve(r);
}
assertTrue("FlatMap resolved", flatMap.isDone());
@SuppressWarnings({"not thrown", "all"})
Throwable failure = flatMap.getFailure();
if ("fail".equals(r)) {
assertEquals("Failure matches", fail, failure);
} else if (r.contains("!")) {
assertTrue("Failure instance Nasty", failure instanceof Nasty);
} else {
// "the returned Promise will be resolved with the Promise from the specified Function,
// as applied to the value of this Promise"
assertEquals("Value matches", r + r.length(), flatMap.getValue());
}
}
private void testRecover(String r) throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> recover = def.getPromise().recover(new Function<Promise<?>, String>() {
@Override
public String apply(Promise<?> promise) {
try {
@SuppressWarnings({"not thrown", "all"})
String msg = promise.getFailure().getMessage();
if (msg == null) {
throw new Nasty(null);
}
if (msg.equals("null")) {
return null;
}
return "recover:" + msg;
} catch (InterruptedException e) {
return null;
}
}
});
Throwable fail = new Throwable(r);
if (null == r || "fail".equals(r) || "null".equals(r)) {
def.fail(fail);
} else {
def.resolve(r);
}
assertTrue("Recover resolved", recover.isDone());
if ("fail".equals(r)) {
// "recover Promise will be resolved with the recovery value"
assertEquals("Recovery value matches", "recover:" + r, recover.getValue());
} else if ("null".equals(r)) {
// "recover Promise will be failed with the failure of this Promise"
assertEquals("Recovery failed matches", fail, recover.getFailure());
} else if (r == null) {
@SuppressWarnings({"not thrown", "all"})
Throwable failure = recover.getFailure();
assertTrue("Failure instance Nasty", failure instanceof Nasty);
} else {
// "the returned Promise will be resolved with the value of this Promise"
assertEquals("Value matches", def.getPromise().getValue(), recover.getValue());
}
}
private void testRecoverWith(String r) throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<? extends String> recover = def.getPromise().recoverWith(
new Function<Promise<?>, Promise<? extends String>>() {
@Override
public Promise<String> apply(Promise<?> promise) {
try {
@SuppressWarnings({"not thrown", "all"})
String msg = promise.getFailure().getMessage();
if (msg == null) {
throw new Nasty(null);
}
if (msg.equals("null")) {
return null;
}
return Promises.resolved("recover:" + msg);
} catch (InterruptedException e) {
return null;
}
}
});
Throwable fail = new Throwable(r);
if (null == r || "fail".equals(r) || "null".equals(r)) {
def.fail(fail);
} else {
def.resolve(r);
}
assertTrue("RecoverWith resolved", recover.isDone());
if ("fail".equals(r)) {
// "recover Promise will be resolved with the recovery value"
assertEquals("Recovery value matches", "recover:" + r, recover.getValue());
} else if ("null".equals(r)) {
// "recover Promise will be failed with the failure of this Promise"
assertEquals("Recovery failed matches", fail, recover.getFailure());
} else if (r == null) {
@SuppressWarnings({"not thrown", "all"})
Throwable failure = recover.getFailure();
assertTrue("Failure instance Nasty", failure instanceof Nasty);
} else {
// "the returned Promise will be resolved with the value of this Promise"
assertEquals("Value matches", def.getPromise().getValue(), recover.getValue());
}
}
void testFallback(String r, String f) throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> promise = def.getPromise();
Deferred<String> fallback = new Deferred<String>();
Promise<String> result = promise.fallbackTo(fallback.getPromise());
Throwable fail = new Throwable(r);
Throwable fail2 = new Throwable(f + f);
if ("fail".equals(r)) {
if ("fail".equals(f)) {
fallback.fail(fail2);
} else {
fallback.resolve(f);
}
def.fail(fail);
} else {
def.resolve(r);
}
assertTrue("result resolved", result.isDone());
if ("fail".equals(r)) {
if ("fail".equals(f)) {
assertEquals("Failure matches", fail, result.getFailure());
} else {
assertEquals("Fallback matches", f, result.getValue());
}
} else {
assertEquals("Value matches", r, result.getValue());
}
}
}
| 8,143 |
0 | Create_ds/aries/async/promise-api/src/test/java/org/apache/aries/async/promise | Create_ds/aries/async/promise-api/src/test/java/org/apache/aries/async/promise/test/ChainTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.promise.test;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Test;
import org.osgi.util.function.Callback;
import org.osgi.util.promise.Deferred;
import org.osgi.util.promise.Failure;
import org.osgi.util.promise.Promise;
import org.osgi.util.promise.Promises;
import org.osgi.util.promise.Success;
import org.osgi.util.promise.TimeoutException;
public class ChainTest {
@Test
public void testThenSuccess() throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> chain = def.getPromise().then(new Success<String, String>() {
@Override
public Promise<String> call(Promise<String> resolved) throws Exception {
return Promises.resolved("success!");
}
});
assertFalse("chain not resolved", chain.isDone());
def.resolve("ok");
assertTrue("chain resolved", chain.isDone());
assertEquals("chain value matches", "success!", chain.getValue());
}
@Test
public void testThenSuccessDeferred() throws Exception {
Deferred<String> def = new Deferred<String>();
final Deferred<String> def2 = new Deferred<String>();
Promise<String> chain = def.getPromise().then(new Success<String, String>() {
@Override
public Promise<String> call(Promise<String> resolved) throws Exception {
return def2.getPromise();
}
});
assertFalse("chain not resolved", chain.isDone());
def.resolve("ok");
assertFalse("chain still not resolved", chain.isDone());
def2.resolve("success!");
assertTrue("chain resolved", chain.isDone());
assertEquals("chain value matches", "success!", chain.getValue());
}
@Test
public void testThenSuccessFailed() throws Exception {
Deferred<String> def = new Deferred<String>();
final Promise<String> promise = def.getPromise();
final Throwable thenFail = new Throwable("failed!");
Promise<String> chain = promise.then(new Success<String, String>() {
@Override
public Promise<String> call(Promise<String> resolved) throws Exception {
return Promises.failed(thenFail);
}
});
assertFalse("chain not resolved", chain.isDone());
def.resolve("ok");
assertTrue("chain resolved", chain.isDone());
assertEquals("chain failure matches", thenFail, chain.getFailure());
}
@Test
public void testThenSuccessException() throws Exception {
Deferred<String> def = new Deferred<String>();
final Promise<String> promise = def.getPromise();
final Exception thenException = new Exception("then exception!");
Promise<String> chain = promise.then(new Success<String, String>() {
@Override
public Promise<String> call(Promise<String> resolved) throws Exception {
throw thenException;
}
});
assertFalse("chain not resolved", chain.isDone());
def.resolve("ok");
assertTrue("chain resolved", chain.isDone());
assertEquals("chain failure matches", thenException, chain.getFailure());
}
@Test
public void testThenFail() throws Exception {
Deferred<String> def = new Deferred<String>();
final Promise<String> promise = def.getPromise();
Promise<String> chain = promise.then(null, new Failure() {
@Override
public void fail(Promise<?> resolved) throws Exception {
}
});
assertFalse("chain not resolved", chain.isDone());
Throwable failure = new Throwable("fail!");
def.fail(failure);
assertTrue("chain resolved", chain.isDone());
assertEquals("chain failure matches", failure, chain.getFailure());
}
@Test
public void testThenFailNoCallback() throws Exception {
Deferred<String> def = new Deferred<String>();
final Promise<String> promise = def.getPromise();
Promise<String> chain = promise.then((Success)null);
assertFalse("chain not resolved", chain.isDone());
Throwable failure = new Throwable("fail!");
def.fail(failure);
assertTrue("chain resolved", chain.isDone());
assertEquals("chain failure matches", failure, chain.getFailure());
}
@Test
public void testThenFailException() throws Exception {
Deferred<String> def = new Deferred<String>();
final Promise<String> promise = def.getPromise();
final Exception thenException = new Exception("eek!");
Promise<String> chain = promise.then(null, new Failure() {
@Override
public void fail(Promise<?> resolved) throws Exception {
throw thenException;
}
});
assertFalse("chain not resolved", chain.isDone());
def.fail(new Throwable("failed"));
assertTrue("chain resolved", chain.isDone());
assertEquals("chain failure matches", thenException, chain.getFailure());
}
@Test
public void testThenNull() throws Exception {
Deferred<String> def = new Deferred<String>();
final Promise<String> promise = def.getPromise();
Promise<String> chain = promise.then((Success)null);
assertFalse("chain not resolved", chain.isDone());
def.resolve("ok");
assertTrue("chain resolved", chain.isDone());
assertNull("chain value null", chain.getValue());
}
@Test
public void testThenNullResolved() throws Exception {
Deferred<String> def = new Deferred<String>();
def.resolve("ok");
Promise<String> chain = def.getPromise().then((Success)null);
assertTrue("chain resolved", chain.isDone());
assertNull("chain value null", chain.getValue());
}
@Test
public void testThenAlreadyResolved() throws Exception {
Deferred<String> def = new Deferred<String>();
final Promise<String> promise = def.getPromise();
def.resolve("ok");
Promise<String> chain = promise.then(new Success<String, String>() {
@Override
public Promise<String> call(Promise<String> resolved) throws Exception {
return Promises.resolved("success!");
}
});
assertTrue("chain resolved", chain.isDone());
assertEquals("chain value matches", "success!", chain.getValue());
}
@Test
public void testExampleChain() throws Exception {
Success<String, String> doubler = new Success<String, String>() {
public Promise<String> call(Promise<String> p) throws Exception {
return Promises.resolved(p.getValue() + p.getValue());
}
};
Deferred<String> def = new Deferred<String>();
final Promise<String> foo = def.getPromise().then(doubler).then(doubler);
def.resolve("hello!");
assertEquals("doubler matches", "hello!hello!hello!hello!", foo.getValue());
}
@Test
public void testThen2() throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> chain1 = def.getPromise().then(new Success<String, String>() {
@Override
public Promise<String> call(Promise<String> resolved) throws Exception {
return Promises.resolved("success1");
}
});
assertFalse("chain not resolved", chain1.isDone());
Promise<String> chain2 = def.getPromise().then(new Success<String, String>() {
@Override
public Promise<String> call(Promise<String> resolved) throws Exception {
return Promises.resolved("success2");
}
});
assertFalse("chain not resolved", chain2.isDone());
def.resolve("ok");
assertTrue("chain1 resolved", chain1.isDone());
assertEquals("chain1 value matches", "success1", chain1.getValue());
assertTrue("chain2 resolved", chain2.isDone());
assertEquals("chain2 value matches", "success2", chain2.getValue());
}
@Test
public void testThenResolved() throws Exception {
Deferred<String> def = new Deferred<String>();
def.resolve("already resolved");
Promise<String> chain = def.getPromise().then(new Success<String, String>() {
@Override
public Promise<String> call(Promise<String> resolved) throws Exception {
return Promises.resolved("success!");
}
});
assertTrue("chain resolved", chain.isDone());
assertEquals("chain value matches", "success!", chain.getValue());
}
@Test
public void testThenResolved2() throws Exception {
Deferred<String> def = new Deferred<String>();
def.resolve("already resolved");
Promise<String> chain = def.getPromise().then(new Success<String, String>() {
@Override
public Promise<String> call(Promise<String> resolved) throws Exception {
return Promises.resolved("success1");
}
}).then(new Success<String, String>() {
@Override
public Promise<String> call(Promise<String> resolved) throws Exception {
return Promises.resolved("success2");
}
});
assertTrue("chain resolved", chain.isDone());
assertEquals("chain value matches", "success2", chain.getValue());
}
@Test
public void testThenCallbackSuccess() throws Exception {
Deferred<String> def = new Deferred<String>();
final AtomicBoolean run = new AtomicBoolean(false);
Promise<String> chain = def.getPromise().then(new Callback() {
@Override
public void run() throws Exception {
run.set(true);
}
});
assertFalse("chain should not be resolved", chain.isDone());
assertFalse("callback should not have been run", run.get());
def.resolve("ok");
assertTrue("chain resolved", chain.isDone());
assertEquals("chain value matches", "ok", chain.getValue());
assertTrue("callback should have been run", run.get());
}
@Test
public void testThenCallbackFail() throws Exception {
Deferred<String> def = new Deferred<String>();
final AtomicBoolean run = new AtomicBoolean(false);
Promise<String> chain = def.getPromise().then(new Callback() {
@Override
public void run() throws Exception {
run.set(true);
}
});
Exception failure = new Exception("bang!");
assertFalse("chain should not be resolved", chain.isDone());
assertFalse("callback should not have been run", run.get());
def.fail(failure);
assertTrue("chain resolved", chain.isDone());
assertSame("chain value matches", failure, chain.getFailure());
assertTrue("callback should have been run", run.get());
}
@Test
public void testThenCallbackThrowsExceptionSuccess() throws Exception {
Deferred<String> def = new Deferred<String>();
final Exception failure = new Exception("bang!");
Promise<String> chain = def.getPromise().then(new Callback() {
@Override
public void run() throws Exception {
throw failure;
}
});
assertFalse("chain should not be resolved", chain.isDone());
def.resolve("ok");
assertTrue("chain resolved", chain.isDone());
assertSame("chain value matches", failure, chain.getFailure());
}
@Test
public void testThenCallbackThrowsExceptionFail() throws Exception {
Deferred<String> def = new Deferred<String>();
final Exception failure = new Exception("bang!");
Promise<String> chain = def.getPromise().then(new Callback() {
@Override
public void run() throws Exception {
throw failure;
}
});
assertFalse("chain should not be resolved", chain.isDone());
def.fail(new IllegalStateException());
assertTrue("chain resolved", chain.isDone());
assertSame("chain value matches", failure, chain.getFailure());
}
@Test
public void testTimeout() throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> promise = def.getPromise();
long start = System.nanoTime();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicLong finish = new AtomicLong();
Promise<String> chain = promise.timeout(500)
.onResolve(new Runnable() {
@Override
public void run() {
finish.set(System.nanoTime());
latch.countDown();
}
});
assertFalse("promise should not be resolved", promise.isDone());
assertFalse("chain should not be resolved", chain.isDone());
assertTrue("Did not time out!", latch.await(1, SECONDS));
assertTrue("Finished too fast", NANOSECONDS.toMillis(finish.get() - start) > 450);
assertFalse("promise should not be resolved", promise.isDone());
assertTrue("chain should now be resolved", chain.isDone());
assertTrue("Should fail with a timeout exception", chain.getFailure() instanceof TimeoutException);
}
@Test
public void testTimeoutSuccess() throws Exception {
Deferred<String> def = new Deferred<String>();
Promise<String> promise = def.getPromise();
final CountDownLatch latch = new CountDownLatch(1);
Promise<String> chain = promise.timeout(500)
.onResolve(new Runnable() {
@Override
public void run() {
latch.countDown();
}
});
assertFalse("promise should not be resolved", promise.isDone());
assertFalse("chain should not be resolved", chain.isDone());
def.resolve("ok");
assertTrue("Did not eagerly complete!", latch.await(100, MILLISECONDS));
assertTrue("promise should not be resolved", promise.isDone());
assertTrue("chain should now be resolved", chain.isDone());
assertEquals(promise.getValue(), chain.getValue());
}
@Test
public void testTimeoutFailure() throws Exception{
Deferred<String> def = new Deferred<String>();
Promise<String> promise = def.getPromise();
final CountDownLatch latch = new CountDownLatch(1);
Promise<String> chain = promise.timeout(500)
.onResolve(new Runnable() {
@Override
public void run() {
latch.countDown();
}
});
assertFalse("promise should not be resolved", promise.isDone());
assertFalse("chain should not be resolved", chain.isDone());
Exception failure = new Exception("bang!");
def.fail(failure);
assertTrue("Did not eagerly complete!", latch.await(100, MILLISECONDS));
assertTrue("promise should not be resolved", promise.isDone());
assertTrue("chain should now be resolved", chain.isDone());
assertSame(promise.getFailure(), chain.getFailure());
}
}
| 8,144 |
0 | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util/function/Predicate.java | /*
* Copyright (c) OSGi Alliance 2015. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.util.function;
/**
* A predicate that accepts a single argument and produces a boolean result.
* <p>
* This is a functional interface and can be used as the assignment target for a lambda expression or method reference.
*
* @param <T> The type of the predicate input.
*/
@org.osgi.annotation.versioning.ConsumerType
public interface Predicate<T> {
/**
* Evaluates this predicate on the specified argument.
*
* @param t The input to this predicate.
* @return true if the specified argument is accepted by this predicate; false otherwise.
* @throws an Exception
*/
boolean test(T t) throws Exception;
}
| 8,145 |
0 | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util/function/Callback.java | /*
* Copyright (c) OSGi Alliance (2016). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.util.function;
import org.osgi.annotation.versioning.ConsumerType;
/**
* A callback that performs an operation and may throw an exception.
* <p>
* This is a functional interface and can be used as the assignment target for a
* lambda expression or method reference.
*
* @ThreadSafe
* @since 1.1
* @author $Id: 17ff376bc9c8c171caad89eb9d0bc496f46961ee $
*/
@ConsumerType
@FunctionalInterface
public interface Callback {
/**
* Execute the callback.
*
* @throws Exception An exception thrown by the method.
*/
void run() throws Exception;
}
| 8,146 |
0 | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util/function/Function.java | /*
* Copyright (c) OSGi Alliance 2015. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.util.function;
/**
* A function that accepts a single argument and produces a result.
* <p>
* This is a functional interface and can be used as the assignment target for a lambda expression or method reference.
*
* @param <T> The type of the function input.
* @param <R> The type of the function output.
*/
@org.osgi.annotation.versioning.ConsumerType
public interface Function<T, R> {
/**
* Applies this function to the specified argument.
* @param t The input to this function.
* @return The output of this function.
* @throws An Exception
*/
R apply(T t) throws Exception;
}
| 8,147 |
0 | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util/promise/Failure.java | /*
* Copyright (c) OSGi Alliance 2015. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.util.promise;
/**
* Failure callback for a Promise.
* <p>
* A Failure callback is registered with a Promise using the Promise.then(Success, Failure) method and is called if the Promise is resolved with a failure.
* <p>
* This is a functional interface and can be used as the assignment target for a lambda expression or method reference.
*/
@org.osgi.annotation.versioning.ConsumerType
public interface Failure {
/**
* Failure callback for a Promise.
* <p>
* This method is called if the Promise with which it is registered resolves with a failure.
* <p>
* In the remainder of this description we will refer to the Promise returned by Promise.then(Success, Failure) when this Failure callback was registered as the chained Promise.
* <p>
* If this method completes normally, the chained Promise will be failed with the same exception which failed the resolved Promise. If this method throws an exception, the chained Promise will be failed with the thrown exception.
*
* @param resolved The failed resolved Promise.
* @throws Exception The chained Promise will be failed with the thrown exception.
*/
void fail(Promise<?> resolved) throws Exception;
}
| 8,148 |
0 | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util/promise/Promise.java | /*
* Copyright (c) OSGi Alliance 2015. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.util.promise;
import java.lang.reflect.InvocationTargetException;
import org.osgi.util.function.Callback;
import org.osgi.util.function.Function;
import org.osgi.util.function.Predicate;
/**
* A Promise of a value.
* <p/>
* A Promise represents a future value. It handles the interactions to for asynchronous processing. A Deferred object
* can be used to create a Promise and later resolve the Promise. A Promise is used by the caller of an asynchronous
* function to get the result or handle the error. The caller can either get a callback when the Promise is resolved
* with a value or an error, or the Promise can be used in chaining. In chaining, callbacks are provided that receive
* the resolved Promise, and a new Promise is generated that resolves based upon the result of a callback.
* <p/>
* Both callbacks and chaining can be repeated any number of times, even after the Promise has been resolved.
* <p/>
* Example callback usage:
* <pre>
* final Promise<String> foo= foo();
* foo.onResolve(new Runnable() {
* public void run() {
* System.out.println(foo.getValue());
* }
* });
* </pre>
* <p/>
* Example chaining usage;
* <pre>
* Success<String,String> doubler = new Success<String,String>() {
* public Promise<String> call(Promise<String> p) throws Exception {
* return Promises.resolved(p.getValue()+p.getValue());
* }
* };
* final Promise<String> foo = foo().then(doubler).then(doubler);
* foo.onResolve(new Runnable() {
* public void run() {
* System.out.println(foo.getValue());
* }
* });
* </pre>
*
* @param <T> The value type associated with this Promise.
*/
@org.osgi.annotation.versioning.ProviderType
public interface Promise<T> {
/**
* Returns whether this Promise has been resolved.
* <p/>
* This Promise may be successfully resolved or resolved with a failure.
*
* @return true if this Promise was resolved either successfully or with a failure; false if this Promise is
* unresolved.
*/
boolean isDone();
/**
* Returns the value of this Promise.
* <p/>
* If this Promise is not resolved, this method must block and wait for this Promise to be resolved before
* completing.
* <p/>
* If this Promise was successfully resolved, this method returns with the value of this Promise. If this Promise
* was resolved with a failure, this method must throw an InvocationTargetException with the failure exception as
* the cause.
*
* @return The value of this resolved Promise.
* @throws InvocationTargetException If this Promise was resolved with a failure. The cause of the
* InvocationTargetException is the failure exception.
* @throws InterruptedException If the current thread was interrupted while waiting.
*/
T getValue() throws InvocationTargetException, InterruptedException;
/**
* Returns the failure of this Promise.
* <p/>
* If this Promise is not resolved, this method must block and wait for this Promise to be resolved before
* completing.
* <p/>
* If this Promise was resolved with a failure, this method returns with the failure of this Promise. If this
* Promise was successfully resolved, this method must return null.
*
* @return The failure of this resolved Promise or null if this Promise was successfully resolved.
* @throws InterruptedException If the current thread was interrupted while waiting.
*/
Throwable getFailure() throws InterruptedException;
/**
* Register a callback to be called when this Promise is resolved.
* <p/>
* The specified callback is called when this Promise is resolved either successfully or with a failure.
* <p/>
* This method may be called at any time including before and after this Promise has been resolved.
* <p/>
* Resolving this Promise happens-before any registered callback is called. That is, in a registered callback,
* isDone() must return true and getValue() and getFailure() must not block.
* <p/>
* A callback may be called on a different thread than the thread which registered the callback. So the callback
* must be thread safe but can rely upon that the registration of the callback happens-before the registered
* callback is called.
*
* @param callback A callback to be called when this Promise is resolved. Must not be null.
* @return This Promise.
*/
Promise<T> onResolve(Runnable callback);
/**
* Chain a new Promise to this Promise with Success and Failure callbacks.
* <p/>
* The specified Success callback is called when this Promise is successfully resolved and the specified Failure
* callback is called when this Promise is resolved with a failure.
* <p/>
* This method returns a new Promise which is chained to this Promise. The returned Promise must be resolved when
* this Promise is resolved after the specified Success or Failure callback is executed. The result of the executed
* callback must be used to resolve the returned Promise. Multiple calls to this method can be used to create a
* chain of promises which are resolved in sequence.
* <p/>
* If this Promise is successfully resolved, the Success callback is executed and the result Promise, if any, or
* thrown exception is used to resolve the returned Promise from this method. If this Promise is resolved with a
* failure, the Failure callback is executed and the returned Promise from this method is failed.
* <p/>
* This method may be called at any time including before and after this Promise has been resolved.
* <p/>
* Resolving this Promise happens-before any registered callback is called. That is, in a registered callback,
* isDone() must return true and getValue() and getFailure() must not block.
* <p/>
* A callback may be called on a different thread than the thread which registered the callback. So the callback
* must be thread safe but can rely upon that the registration of the callback happens-before the registered
* callback is called.
*
* @param <R> The value type associated with the returned Promise.
* @param success A Success callback to be called when this Promise is successfully resolved. May be null if no
* Success callback is required. In thi
* @param failure A Failure callback to be called when this Promise is resolved with a failure. May be null if no
* Failure callback is required.
* @return A new Promise which is chained to this Promise. The returned Promise must be resolved when this Promise
* is resolved after the specified Success or Failure callback, if any, is executed
*/
<R> Promise<R> then(Success<? super T, ? extends R> success, Failure failure);
/**
* Chain a new Promise to this Promise with a Success callback.
* <p/>
* This method performs the same function as calling then(Success, Failure) with the specified Success callback and
* null for the Failure callback
*
* @param success A Success callback to be called when this Promise is successfully resolved. May be null if no
* Success callback is required. In this case, the returned Promise must be resolved with the value
* null when this Promise is successfully resolved.
* @param <R> The value type associated with the returned Promise.
* @return A new Promise which is chained to this Promise. The returned Promise must be resolved when this Promise
* is resolved after the specified Success, if any, is executed.
* @see #then(Success, Failure)
*/
<R> Promise<R> then(Success<? super T, ? extends R> success);
/**
* Chain a new Promise to this Promise with a callback.
* <p>
* The specified {@link Callback} is called when this Promise is resolved
* either successfully or with a failure.
* <p>
* This method returns a new Promise which is chained to this Promise. The
* returned Promise must be resolved when this Promise is resolved after the
* specified callback is executed. If the callback throws an exception, the
* returned Promise is failed with that exception. Otherwise the returned
* Promise is resolved with this Promise.
* <p>
* This method may be called at any time including before and after this
* Promise has been resolved.
* <p>
* Resolving this Promise <i>happens-before</i> any registered callback is
* called. That is, in a registered callback, {@link #isDone()} must return
* {@code true} and {@link #getValue()} and {@link #getFailure()} must not
* block.
* <p>
* A callback may be called on a different thread than the thread which
* registered the callback. So the callback must be thread safe but can rely
* upon that the registration of the callback <i>happens-before</i> the
* registered callback is called.
*
* @param callback A callback to be called when this Promise is resolved.
* Must not be {@code null}.
* @return A new Promise which is chained to this Promise. The returned
* Promise must be resolved when this Promise is resolved after the
* specified callback is executed.
* @since 1.1
*/
Promise<T> then(Callback callback);
/**
* Filter the value of this Promise.
* <p/>
* If this Promise is successfully resolved, the returned Promise will either be resolved with the value of this
* Promise if the specified Predicate accepts that value or failed with a NoSuchElementException if the specified
* Predicate does not accept that value. If the specified Predicate throws an exception, the returned Promise will
* be failed with the exception.
* <p/>
* If this Promise is resolved with a failure, the returned Promise will be failed with that failure.
* <p/>
* This method may be called at any time including before and after this Promise has been resolved.
*
* @param predicate The Predicate to evaluate the value of this Promise. Must not be null.
* @return A Promise that filters the value of this Promise.
*/
Promise<T> filter(Predicate<? super T> predicate);
/**
* Map the value of this Promise.
* <p/>
* If this Promise is successfully resolved, the returned Promise will be resolved with the value of specified
* Function as applied to the value of this Promise. If the specified Function throws an exception, the returned
* Promise will be failed with the exception.
* <p/>
* If this Promise is resolved with a failure, the returned Promise will be failed with that failure.
* <p/>
* This method may be called at any time including before and after this Promise has been resolved.
*
* @param mapper The Function that will map the value of this Promise to the value that will be used to resolve the
* returned Promise. Must not be null.
* @param <R> The value type associated with the returned Promise.
* @return A Promise that returns the value of this Promise as mapped by the specified Function.
*/
<R> Promise<R> map(Function<? super T, ? extends R> mapper);
/**
* FlatMap the value of this Promise.
* <p/>
* If this Promise is successfully resolved, the returned Promise will be resolved with the Promise from the
* specified Function as applied to the value of this Promise. If the specified Function throws an exception, the
* returned Promise will be failed with the exception.
* <p/>
* If this Promise is resolved with a failure, the returned Promise will be failed with that failure.
* <p/>
* This method may be called at any time including before and after this Promise has been resolved.
*
* @param mapper The Function that will flatMap the value of this Promise to a Promise that will be used to resolve
* the returned Promise. Must not be null.
* @param <R> The value type associated with the returned Promise.
* @return A Promise that returns the value of this Promise as mapped by the specified Function.
*/
<R> Promise<R> flatMap(Function<? super T, Promise<? extends R>> mapper);
/**
* Recover from a failure of this Promise with a recovery value.
* <p/>
* If this Promise is successfully resolved, the returned Promise will be resolved with the value of this Promise.
* <p/>
* If this Promise is resolved with a failure, the specified Function is applied to this Promise to produce a
* recovery value.
* <p/>
* If the recovery value is not null, the returned Promise will be resolved with the recovery value.
* <p/>
* If the recovery value is null, the returned Promise will be failed with the failure of this Promise.
* <p/>
* If the specified Function throws an exception, the returned Promise will be failed with that exception.
* <p/>
* To recover from a failure of this Promise with a recovery value of null, the recoverWith(Function) method must be
* used. The specified Function for recoverWith(Function) can return Promises.resolved(null) to supply the desired
* null value.
* <p/>
* This method may be called at any time including before and after this Promise has been resolved.
*
* @param recovery If this Promise resolves with a failure, the specified Function is called to produce a recovery
* value to be used to resolve the returned Promise. Must not be null.
* @return A Promise that resolves with the value of this Promise or recovers from the failure of this Promise.
*/
Promise<T> recover(Function<Promise<?>, ? extends T> recovery);
/**
* Recover from a failure of this Promise with a recovery Promise.
* <p/>
* If this Promise is successfully resolved, the returned Promise will be resolved with the value of this Promise.
* <p/>
* If this Promise is resolved with a failure, the specified Function is applied to this Promise to produce a
* recovery Promise.
* <p/>
* If the recovery Promise is not null, the returned Promise will be resolved with the recovery Promise.
* <p/>
* If the recovery Promise is null, the returned Promise will be failed with the failure of this Promise.
* <p/>
* If the specified Function throws an exception, the returned Promise will be failed with that exception.
* <p/>
* This method may be called at any time including before and after this Promise has been resolved.
*
* @param recovery If this Promise resolves with a failure, the specified Function is called to produce a recovery
* Promise to be used to resolve the returned Promise. Must not be null.
* @return A Promise that resolves with the value of this Promise or recovers from the failure of this Promise.
*/
Promise<T> recoverWith(Function<Promise<?>, Promise<? extends T>> recovery);
/**
* Fall back to the value of the specified Promise if this Promise fails.
* <p/>
* If this Promise is successfully resolved, the returned Promise will be resolved with the value of this Promise.
* <p/>
* If this Promise is resolved with a failure, the successful result of the specified Promise is used to resolve the
* returned Promise. If the specified Promise is resolved with a failure, the returned Promise will be failed with
* the failure of this Promise rather than the failure of the specified Promise.
* <p/>
* This method may be called at any time including before and after this Promise has been resolved.
*
* @param fallback The Promise whose value will be used to resolve the returned Promise if this Promise resolves
* with a failure. Must not be null.
* @return A Promise that returns the value of this Promise or falls back to the value of the specified Promise.
*/
Promise<T> fallbackTo(Promise<? extends T> fallback);
/**
* Time out the resolution of this Promise.
* <p>
* If this Promise is successfully resolved before the timeout, the returned
* Promise is resolved with the value of this Promise. If this Promise is
* resolved with a failure before the timeout, the returned Promise is
* resolved with the failure of this Promise. If the timeout is reached
* before this Promise is resolved, the returned Promise is failed with a
* {@link TimeoutException}.
*
* @param milliseconds The time to wait in milliseconds. Zero and negative
* time is treated as an immediate timeout.
* @return A Promise that is resolved when either this Promise is resolved
* or the specified timeout is reached.
* @since 1.1
*/
Promise<T> timeout(long milliseconds);
/**
* Delay after the resolution of this Promise.
* <p>
* Once this Promise is resolved, resolve the returned Promise with this
* Promise after the specified delay.
*
* @param milliseconds The time to delay in milliseconds. Zero and negative
* time is treated as no delay.
* @return A Promise that is resolved with this Promise after this Promise
* is resolved and the specified delay has elapsed.
* @since 1.1
*/
Promise<T> delay(long milliseconds);
}
| 8,149 |
0 | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util/promise/Promises.java | /*
* Copyright (c) OSGi Alliance 2015. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.util.promise;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Static helper methods for Promises.
*/
public class Promises {
/**
* Create a new Promise that has been resolved with the specified value.
*
* @param value The value of the resolved Promise.
* @param <T> The value type associated with the returned Promise.
* @return A new Promise that has been resolved with the specified value.
*/
public static <T> Promise<T> resolved(T value) {
Deferred<T> def = new Deferred<T>();
def.resolve(value);
return def.getPromise();
}
/**
* Create a new Promise that has been resolved with the specified failure.
*
* @param failure The failure of the resolved Promise. Must not be null.
* @param <T> The value type associated with the returned Promise.
* @return A new Promise that has been resolved with the specified failure.
*/
public static <T> Promise<T> failed(Throwable failure) {
if (failure == null)
throw new NullPointerException();
Deferred<T> def = new Deferred<T>();
def.fail(failure);
return def.getPromise();
}
/**
* Create a new Promise that is a latch on the resolution of the specified Promises.
* <p/>
* The new Promise acts as a gate and must be resolved after all of the specified Promises are resolved.
*
* @param promises The Promises which must be resolved before the returned Promise must be resolved. Must not be
* null.
* @param <T> The value type of the List value associated with the returned Promise.
* @param <S> A subtype of the value type of the List value associated with the returned Promise.
* @return A Promise that is resolved only when all the specified Promises are resolved. The returned Promise will
* be successfully resolved, with a List of the values in the order of the specified Promises, if all the specified
* Promises are successfully resolved. The List in the returned Promise is the property of the caller and is
* modifiable. The returned Promise will be resolved with a failure of FailedPromisesException if any of the
* specified Promises are resolved with a failure. The failure FailedPromisesException must contain all of the
* specified Promises which resolved with a failure.
*/
public static <T, S> Promise<List<T>> all(final Collection<Promise<S>> promises) {
if (promises == null)
throw new NullPointerException();
final Deferred<List<T>> result = new Deferred<List<T>>();
final Collection<Promise<?>> failedPromises = new ArrayList<Promise<?>>();
final List<T> resolvedValues = new ArrayList<T>();
if (promises.size() == 0) {
result.resolve(resolvedValues);
}
for (final Promise<S> promise : promises) {
promise.then(new Success<S, T>() {
@Override
public Promise<T> call(Promise<S> resolved) throws Exception {
// "S is subtype of the value type of the List"
@SuppressWarnings("unchecked")
T value = (T) resolved.getValue();
resolvedValues.add(value);
if (resolvedValues.size() == promises.size()) {
result.resolve(resolvedValues);
} else if (failedPromises.size() + resolvedValues.size() == promises.size()) {
result.fail(new FailedPromisesException(failedPromises));
}
return null;
}
}, new Failure() {
@Override
public void fail(Promise<?> resolved) throws Exception {
failedPromises.add(resolved);
if (failedPromises.size() + resolvedValues.size() == promises.size()) {
result.fail(new FailedPromisesException(failedPromises));
}
}
});
}
return result.getPromise();
}
/**
* Create a new Promise that is a latch on the resolution of the specified Promises.
* <p/>
* The new Promise acts as a gate and must be resolved after all of the specified Promises are resolved.
*
* @param promises The Promises which must be resolved before the returned Promise must be resolved. Must not be
* null.
* @param <T> The value type associated with the specified Promises.
* @return A Promise that is resolved only when all the specified Promises are resolved. The returned Promise will
* be successfully resolved, with a List of the values in the order of the specified Promises, if all the specified
* Promises are successfully resolved. The List in the returned Promise is the property of the caller and is
* modifiable. The returned Promise will be resolved with a failure of FailedPromisesException if any of the
* specified Promises are resolved with a failure. The failure FailedPromisesException must contain all of the
* specified Promises which resolved with a failure.
*/
public static <T> Promise<List<T>> all(final Promise<? extends T>... promises) {
if (promises == null)
throw new NullPointerException();
List<Promise<T>> list = new ArrayList<Promise<T>>();
for (Promise<? extends T> promise : promises) {
@SuppressWarnings("unchecked")
Promise<T> pt = (Promise<T>) promise;
list.add(pt);
}
return all(list);
}
}
| 8,150 |
0 | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util/promise/TimeoutException.java | /*
* Copyright (c) OSGi Alliance (2016). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.util.promise;
/**
* Timeout exception for a Promise.
*
* @since 1.1
* @author $Id: 09186f5527a0552b14f95fab5e5468f47b536d43 $
*/
public class TimeoutException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Create a new {@code TimeoutException}.
*/
public TimeoutException() {
super();
}
}
| 8,151 |
0 | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util/promise/Success.java | /*
* Copyright (c) OSGi Alliance 2015. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.util.promise;
/**
* Success callback for a Promise.
* <p>
* A Success callback is registered with a Promise using the Promise.then(Success) method and is called if the Promise is resolved successfully.
* <p>
* This is a functional interface and can be used as the assignment target for a lambda expression or method reference.
* <p>
* @param <T> The value type of the resolved Promise passed as input to this callback.
* @param <R> The value type of the returned Promise from this callback.
*/
@org.osgi.annotation.versioning.ConsumerType
public interface Success<T,R> {
/**
* Success callback for a Promise.
* <p>
* This method is called if the Promise with which it is registered resolves successfully.
* <p>
* In the remainder of this description we will refer to the Promise returned by this method as the returned Promise and the Promise returned by Promise.then(Success) when this Success callback was registered as the chained Promise.
* <p>
* If the returned Promise is null then the chained Promise will resolve immediately with a successful value of null. If the returned Promise is not null then the chained Promise will be resolved when the returned Promise is resolved.
*
* @param resolved The successfully resolved Promise.
* @return The Promise to use to resolve the chained Promise, or null if the chained Promise is to be resolved immediately with the value null.
* @throws Exception The chained Promise will be failed with the thrown exception.
*/
Promise<R> call(Promise<T> resolved) throws Exception;
}
| 8,152 |
0 | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util/promise/FailedPromisesException.java | /*
* Copyright (c) OSGi Alliance 2015. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.util.promise;
import java.util.Collection;
import java.util.Collections;
/**
* Promise failure exception for a collection of failed Promises.
*/
public class FailedPromisesException extends RuntimeException {
private final Collection<Promise<?>> failed;
/**
* Create a new FailedPromisesException with the specified Promises.
*
* @param failed A collection of Promises that have been resolved with a failure. Must not be null.
*/
public FailedPromisesException(Collection<Promise<?>> failed) {
this(failed, null);
}
/**
* Create a new FailedPromisesException with the specified Promises.
*
* @param failed A collection of Promises that have been resolved with a failure. Must not be null.
* @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). (A <tt>null</tt>
* value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
public FailedPromisesException(Collection<Promise<?>> failed, Throwable cause) {
super(cause);
assert failed != null;
this.failed = failed;
}
/**
* Returns the collection of Promises that have been resolved with a failure.
*
* @return The collection of Promises that have been resolved with a failure. The returned collection is
* unmodifiable.
*/
public Collection<Promise<?>> getFailedPromises() {
return Collections.unmodifiableCollection(failed);
}
}
| 8,153 |
0 | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util | Create_ds/aries/async/promise-api/src/main/java/org/osgi/util/promise/Deferred.java | /*
* Copyright (c) OSGi Alliance 2015. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.util.promise;
import org.apache.aries.async.promise.PromiseImpl;
/**
* A Deferred Promise resolution.
* <p/>
* Instances of this class can be used to create a Promise that can be resolved in the future. The associated Promise
* can be successfully resolved with resolve(Object) or resolved with a failure with fail(Throwable).
* <p/>
* It can also be resolved with the resolution of another promise using resolveWith(Promise).
* <p/>
* The associated Promise can be provided to anyone, but the Deferred object should be made available only to the party
* that will responsible for resolving the Promise.
*
* @param <T> The value type associated with the created Promise.
*/
public class Deferred<T> {
private final PromiseImpl<T> promise;
/**
* Create a new Deferred with an associated Promise.
*/
public Deferred() {
promise = new PromiseImpl<T>();
}
/**
* Returns the Promise associated with this Deferred.
*
* @return The Promise associated with this Deferred.
*/
public Promise<T> getPromise() {
return promise;
}
/**
* Successfully resolve the Promise associated with this Deferred.
* <p/>
* After the associated Promise is resolved with the specified value, all registered callbacks are called and any
* chained Promises are resolved.
* <p/>
* Resolving the associated Promise happens-before any registered callback is called. That is, in a registered
* callback, Promise.isDone() must return true and Promise.getValue() and Promise.getFailure() must not block.
*
* @param value The value of the resolved Promise.
* @throws IllegalStateException If the associated Promise was already resolved.
*/
public void resolve(T value) {
promise.resolve(value);
}
/**
* Fail the Promise associated with this Deferred.
* <p/>
* After the associated Promise is resolved with the specified failure, all registered callbacks are called and any
* chained Promises are resolved.
* <p/>
* Resolving the associated Promise happens-before any registered callback is called. That is, in a registered
* callback, Promise.isDone() must return true and Promise.getValue() and Promise.getFailure() must not block.
*
* @param failure The failure of the resolved Promise. Must not be null.
* @throws IllegalStateException If the associated Promise was already resolved.
*/
public void fail(Throwable failure) {
promise.fail(failure);
}
/**
* Resolve the Promise associated with this Deferred with the specified Promise.
* <p/>
* If the specified Promise is successfully resolved, the associated Promise is resolved with the value of the
* specified Promise. If the specified Promise is resolved with a failure, the associated Promise is resolved with
* the failure of the specified Promise.
* <p/>
* After the associated Promise is resolved with the specified Promise, all registered callbacks are called and any
* chained Promises are resolved.
* <p/>
* Resolving the associated Promise happens-before any registered callback is called. That is, in a registered
* callback, Promise.isDone() must return true and Promise.getValue() and Promise.getFailure() must not block
*
* @param with A Promise whose value or failure will be used to resolve the associated Promise. Must not be null.
* @return A Promise that is resolved only when the associated Promise is resolved by the specified Promise. The
* returned Promise will be successfully resolved, with the value null, if the associated Promise was resolved by
* the specified Promise. The returned Promise will be resolved with a failure of IllegalStateException if the
* associated Promise was already resolved when the specified Promise was resolved.
*/
public Promise<Void> resolveWith(Promise<? extends T> with) {
return promise.resolveWith(with);
}
}
| 8,154 |
0 | Create_ds/aries/async/promise-api/src/main/java/org/apache/aries/async | Create_ds/aries/async/promise-api/src/main/java/org/apache/aries/async/promise/PromiseImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.promise;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.osgi.util.function.Callback;
import org.osgi.util.function.Function;
import org.osgi.util.function.Predicate;
import org.osgi.util.promise.Failure;
import org.osgi.util.promise.Promise;
import org.osgi.util.promise.Success;
import org.osgi.util.promise.TimeoutException;
public class PromiseImpl<T> implements Promise<T> {
private final Executor exec;
private final ScheduledExecutorService ses;
private final List<Runnable> tasks = new ArrayList<Runnable>();
private final CountDownLatch resolved = new CountDownLatch(1);
private List<PromiseImpl> chain;
private Success onSuccess;
private Failure onFailure;
private Throwable failure;
private T value;
public PromiseImpl() {
this(Executors.newSingleThreadExecutor());
}
public PromiseImpl(Executor executor) {
this(executor, Executors.newSingleThreadScheduledExecutor());
}
public PromiseImpl(Executor executor, ScheduledExecutorService ses) {
// Executor for onResolve() callbacks
// We could use an Executor that runs tasks in current thread
exec = executor;
this.ses = ses;
}
public void fail(Throwable failure) {
if (failure == null)
throw new NullPointerException();
complete(null, failure);
}
public void resolve(T value) {
complete(value, null);
}
public Promise<Void> resolveWith(final Promise<? extends T> with) {
if (with == null)
throw new NullPointerException();
final PromiseImpl<Void> result = new PromiseImpl<Void>(exec, ses);
with.then(new Success<T, T>() {
@Override
public Promise<T> call(Promise<T> resolved) throws Exception {
if (isDone()) {
result.fail(new IllegalStateException("associated Promise already resolved"));
}
PromiseImpl.this.resolve(resolved.getValue());
result.resolve(null);
return null;
}
}, new Failure() {
@Override
public void fail(Promise<?> resolved) throws Exception {
if (isDone()) {
result.fail(new IllegalStateException("associated Promise already resolved"));
}
PromiseImpl.this.fail(resolved.getFailure());
result.resolve(null);
}
});
return result;
}
private synchronized void complete(T value, Throwable failure) {
if (isDone()) {
throw new IllegalStateException("Promise is already resolved");
}
// mark this Promise as complete before invoking callbacks
if (failure != null) {
this.failure = failure;
} else {
this.value = value;
}
resolved.countDown();
if (chain != null) {
runChain();
}
// run onResolve() callbacks
for (Runnable task : tasks) {
try{
exec.execute(task);
} catch (RejectedExecutionException ree) {
task.run();
}
}
}
// run chained success/failure callbacks
@SuppressWarnings("unchecked")
private void runChain() {
while (!chain.isEmpty()) {
PromiseImpl next = chain.remove(0);
if (failure != null) {
try {
if (next.onFailure != null) {
// "This method is called if the Promise with which it is registered resolves with a failure."
next.onFailure.fail(this);
}
// "If this method completes normally, the chained Promise will be failed
// with the same exception which failed the resolved Promise."
next.fail(failure);
} catch (Exception e) {
// "If this method throws an exception, the chained Promise will be failed with the thrown exception."
next.fail(e);
}
} else {
try {
// "This method is called if the Promise with which it is registered resolves successfully."
Promise<T> p = null;
if (next.onSuccess != null) {
p = next.onSuccess.call(this);
}
if (p == null) {
// "If the returned Promise is null then the chained Promise will resolve immediately with a successful value of null."
next.resolve(null);
} else {
// "If the returned Promise is not null then the chained Promise will be resolved when the returned Promise is resolved"
next.resolveWith(p);
}
} catch (InvocationTargetException e) {
next.fail(e.getCause());
} catch (Exception e) {
next.fail(e);
}
}
}
}
// Promise API methods
@Override
public boolean isDone() {
return resolved.getCount() == 0;
}
@Override
public T getValue() throws InvocationTargetException, InterruptedException {
resolved.await();
if (failure != null) {
throw new InvocationTargetException(failure);
}
return value;
}
@Override
public Throwable getFailure() throws InterruptedException {
resolved.await();
return failure;
}
@Override
public synchronized Promise<T> onResolve(Runnable callback) {
if (callback == null)
throw new NullPointerException();
if (isDone()) {
try {
exec.execute(callback);
} catch (RejectedExecutionException ree) {
callback.run();
}
} else {
tasks.add(callback);
}
return this;
}
@Override
public <R> Promise<R> then(Success<? super T, ? extends R> success, Failure failure) {
PromiseImpl<R> result = new PromiseImpl<R>(exec, ses);
result.onSuccess = success;
result.onFailure = failure;
synchronized (this) {
if (chain == null) {
chain = new ArrayList<PromiseImpl>();
}
chain.add(result);
if (isDone()) {
runChain();
}
}
return result;
}
@Override
public <R> Promise<R> then(Success<? super T, ? extends R> success) {
return then(success, null);
}
@Override
public Promise<T> then(final Callback callback) {
if (callback == null)
throw new NullPointerException();
return then(new Success<T,T>() {
@Override
public Promise<T> call(Promise<T> resolved) throws Exception {
callback.run();
return resolved;
}
}, new Failure(){
@Override
public void fail(Promise<?> resolved) throws Exception {
callback.run();
}
});
}
@Override
public Promise<T> filter(final Predicate<? super T> predicate) {
if (predicate == null)
throw new NullPointerException();
final PromiseImpl<T> result = new PromiseImpl<T>(exec, ses);
then(new Success<T, T>() {
@Override
public Promise<T> call(Promise<T> resolved) throws Exception {
try {
if (predicate.test(resolved.getValue())) {
result.resolve(resolved.getValue());
} else {
result.fail(new NoSuchElementException("predicate does not accept value"));
}
} catch (Throwable t) {
result.fail(t);
}
return null;
}
}, new Failure() {
@Override
public void fail(Promise<?> resolved) throws Exception {
result.fail(resolved.getFailure());
}
});
return result;
}
@Override
public <R> Promise<R> map(final Function<? super T, ? extends R> mapper) {
if (mapper == null)
throw new NullPointerException();
final PromiseImpl<R> result = new PromiseImpl<R>(exec, ses);
then(new Success<T, T>() {
@Override
public Promise<T> call(Promise<T> resolved) throws Exception {
try {
R val = mapper.apply(resolved.getValue());
result.resolve(val);
} catch (Throwable t) {
result.fail(t);
}
return null;
}
}, new Failure() {
@Override
public void fail(Promise<?> resolved) throws Exception {
result.fail(resolved.getFailure());
}
});
return result;
}
@Override
public <R> Promise<R> flatMap(final Function<? super T, Promise<? extends R>> mapper) {
if (mapper == null)
throw new NullPointerException();
final PromiseImpl<R> result = new PromiseImpl<R>(exec, ses);
then(new Success<T, T>() {
@Override
public Promise<T> call(Promise<T> resolved) throws Exception {
try {
Promise<? extends R> p = mapper.apply(resolved.getValue());
result.resolveWith(p);
} catch (Throwable t) {
result.fail(t);
}
return null;
}
}, new Failure() {
@Override
public void fail(Promise<?> resolved) throws Exception {
result.fail(resolved.getFailure());
}
});
return result;
}
@Override
public Promise<T> recover(final Function<Promise<?>, ? extends T> recovery) {
if (recovery == null)
throw new NullPointerException();
final PromiseImpl<T> result = new PromiseImpl<T>(exec, ses);
then(new Success<T, T>() {
@Override
public Promise<T> call(Promise<T> resolved) throws Exception {
result.resolve(resolved.getValue());
return null;
}
}, new Failure() {
@Override
public void fail(Promise<?> resolved) throws Exception {
try {
T recover = recovery.apply(resolved);
if (recover != null) {
result.resolve(recover);
} else {
result.fail(resolved.getFailure());
}
} catch (Throwable t) {
result.fail(t);
}
}
});
return result;
}
@Override
public Promise<T> recoverWith(final Function<Promise<?>, Promise<? extends T>> recovery) {
if (recovery == null)
throw new NullPointerException();
final PromiseImpl<T> result = new PromiseImpl<T>(exec, ses);
then(new Success<T, T>() {
@Override
public Promise<T> call(Promise<T> resolved) throws Exception {
result.resolve(resolved.getValue());
return null;
}
}, new Failure() {
@Override
public void fail(Promise<?> resolved) throws Exception {
try {
Promise<? extends T> recover = recovery.apply(resolved);
if (recover != null) {
result.resolveWith(recover);
} else {
result.fail(resolved.getFailure());
}
} catch (Throwable t) {
result.fail(t);
}
}
});
return result;
}
@Override
public Promise<T> fallbackTo(final Promise<? extends T> fallback) {
if (fallback == null)
throw new NullPointerException();
final PromiseImpl<T> result = new PromiseImpl<T>(exec, ses);
then(new Success<T, T>() {
@Override
public Promise<T> call(Promise<T> resolved) throws Exception {
result.resolve(resolved.getValue());
return null;
}
}, new Failure() {
@Override
public void fail(Promise<?> resolved) throws Exception {
@SuppressWarnings({"not thrown", "all"})
Throwable fail = fallback.getFailure();
if (fail != null) {
result.fail(resolved.getFailure());
} else {
result.resolve(fallback.getValue());
}
}
});
return result;
}
@Override
public Promise<T> timeout(long milliseconds) {
final PromiseImpl<T> p = new PromiseImpl<T>();
p.resolveWith(this);
ses.schedule(new Runnable(){
@Override
public void run() {
if(!p.isDone()) {
try {
p.fail(new TimeoutException());
} catch (Exception e) {
// Already resolved
}
}
}
}, milliseconds, MILLISECONDS);
return p;
}
@Override
public Promise<T> delay(final long milliseconds) {
final PromiseImpl<T> p = new PromiseImpl<T>();
then(new Success<T,T>() {
@Override
public Promise<T> call(final Promise<T> resolved) throws Exception {
ses.schedule(new Runnable(){
@Override
public void run() {
try {
p.resolve(resolved.getValue());
} catch (IllegalStateException ise) {
// Someone else resolved our promise?
} catch (Exception e) {
p.fail(e);
}
}
}, milliseconds, MILLISECONDS);
return null;
}
}, new Failure(){
@Override
public void fail(final Promise<?> resolved) throws Exception {
ses.schedule(new Runnable(){
@Override
public void run() {
try {
p.fail(resolved.getFailure());
} catch (Exception e) {
p.fail(e);
}
}
}, milliseconds, MILLISECONDS);
}
});
return p;
}
}
| 8,155 |
0 | Create_ds/aries/async/async-api/src/main/java/org/osgi/service | Create_ds/aries/async/async-api/src/main/java/org/osgi/service/async/Async.java | /*
* Copyright (c) OSGi Alliance 2015. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.service.async;
import org.osgi.annotation.versioning.ProviderType;
import org.osgi.framework.ServiceReference;
import org.osgi.util.promise.Promise;
/**
* The Async Service, as defined in OSGi RFC 204
* https://github.com/osgi/design/tree/master/rfcs/rfc0206
*/
@ProviderType
public interface Async {
/**
* Create a mediated object for asynchronous calls
*
* @param target The object to mediate
* @param iface The type that the mediated object should implement or extend
* @return A mediated object
* @throws IllegalArgumentException if mediation fails
*/
<T> T mediate(T target, Class<T> iface);
/**
* Create a mediated object for asynchronous calls
*
* @param target The service reference to mediate
* @param iface The type that the mediated object should implement or extend
* @return A mediated service
* @throws IllegalArgumentException if mediation fails
*/
<T> T mediate(ServiceReference<? extends T> target, Class<T> iface);
/**
* Asynchronously run the last method call registered by a mediated object,
* returning the result as a Promise.
*
* @param r the return value of the mediated call
* @return a Promise
*/
<R> Promise<R> call(R r);
/**
* Asynchronously run the last method call registered by a mediated object,
* returning the result as a Promise.
*
* @return a Promise
*/
Promise<?> call();
/**
* Asynchronously run the last method call registered by a mediated object,
* ignoring the return value.
*
* @return a Promise indicating whether the task started successfully
*/
Promise<Void> execute();
}
| 8,156 |
0 | Create_ds/aries/async/async-api/src/main/java/org/osgi/service/async | Create_ds/aries/async/async-api/src/main/java/org/osgi/service/async/delegate/AsyncDelegate.java | /*
* Copyright (c) OSGi Alliance 2015. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.service.async.delegate;
import java.lang.reflect.Method;
import org.osgi.annotation.versioning.ConsumerType;
import org.osgi.util.promise.Promise;
/**
* The AsyncDelegate, as defined in OSGi RFC 204
* https://github.com/osgi/design/tree/master/rfcs/rfc0206
*/
@ConsumerType
public interface AsyncDelegate {
/**
* Asynchronously call a method
*
* @param m the method
* @param args the arguments
*
* @return A promise, or <code>null</code> if the method is not supported
*
* @throws Exception
*/
Promise<?> async(Method m, Object[] args) throws Exception;
/**
* Asynchronously call a method
*
* @param m the method
* @param args the arguments
*
* @return <code>true<code> if accepted, or <code>false</code> otherwise.
* @throws Exception
*/
boolean execute(Method m, Object[] args) throws Exception;
}
| 8,157 |
0 | Create_ds/aries/async/async-impl/src/test/java/org/apache/aries/async | Create_ds/aries/async/async-impl/src/test/java/org/apache/aries/async/impl/AsyncServiceTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.impl;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.osgi.service.log.LogService;
import org.osgi.util.function.Predicate;
import org.osgi.util.promise.Promise;
import org.osgi.util.promise.Success;
import org.osgi.util.tracker.ServiceTracker;
@RunWith(MockitoJUnitRunner.class)
public class AsyncServiceTest {
public static class DelayedEcho {
public String echo(String s, int delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
throw new RuntimeException("Thread interrupted", e);
}
if (s == null) throw new NullPointerException("Nothing to echo!");
return s;
}
}
private ExecutorService es;
private ScheduledExecutorService ses;
@Mock
ServiceTracker<LogService, LogService> serviceTracker;
@Before
public void start() {
es = Executors.newFixedThreadPool(3);
ses = Executors.newSingleThreadScheduledExecutor();
}
@After
public void stop() {
es.shutdownNow();
try {
es.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
ses.shutdownNow();
try {
ses.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void test() throws InterruptedException {
DelayedEcho raw = new DelayedEcho();
AsyncService service = new AsyncService(null, es, ses,
serviceTracker);
DelayedEcho mediated = service.mediate(raw, DelayedEcho.class);
Promise<String> promise = service.call(mediated.echo("Hello World", 1000));
final CountDownLatch latch = new CountDownLatch(1);
promise.filter(new Predicate<String>() {
@Override
public boolean test(String t) {
return "Hello World".equals(t);
}
}).then(new Success<String, Void>() {
@Override
public Promise<Void> call(Promise<String> resolved)
throws Exception {
latch.countDown();
return null;
}
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void testMultipleMediationsCacheClassLoader() throws Exception {
DelayedEcho raw = new DelayedEcho();
AsyncService service = new AsyncService(null, es, ses,
serviceTracker);
DelayedEcho mediated = service.mediate(raw, DelayedEcho.class);
assertSame(mediated.getClass(), service.mediate(raw, DelayedEcho.class).getClass());
}
@Test
public void testMultipleMediationsCacheClassLoaderInterface() throws Exception {
CharSequence raw = "test";
AsyncService service = new AsyncService(null, es, ses,
serviceTracker);
CharSequence mediated = service.mediate(raw, CharSequence.class);
assertSame(mediated.getClass(), service.mediate(raw, CharSequence.class).getClass());
}
}
| 8,158 |
0 | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async/impl/AsyncServiceFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.impl;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.async.Async;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
public class AsyncServiceFactory implements ServiceFactory<Async> {
private final ExecutorService executor;
private final ScheduledExecutorService ses;
private final ServiceTracker<LogService, LogService> logServiceTracker;
public AsyncServiceFactory(ExecutorService executor, ScheduledExecutorService ses,
ServiceTracker<LogService, LogService> logServiceTracker) {
this.logServiceTracker = logServiceTracker;
this.executor = executor;
this.ses = ses;
}
public Async getService(Bundle bundle,
ServiceRegistration<Async> registration) {
return new AsyncService(bundle, executor, ses, logServiceTracker);
}
public void ungetService(Bundle bundle,
ServiceRegistration<Async> registration, Async service) {
((AsyncService) service).clear();
}
}
| 8,159 |
0 | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async/impl/FireAndForgetWork.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.impl;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.apache.aries.async.promise.PromiseImpl;
public class FireAndForgetWork implements Runnable {
private final MethodCall methodCall;
private final PromiseImpl<Void> cleanup;
private final PromiseImpl<Void> started;
private final AccessControlContext acc;
public FireAndForgetWork(MethodCall methodCall, PromiseImpl<Void> cleanup, PromiseImpl<Void> started) {
this.methodCall = methodCall;
this.cleanup = cleanup;
this.started = started;
this.acc = AccessController.getContext();
}
public void run() {
try {
final Object service = methodCall.getService();
// This is necessary for non public methods. The original mediator call must
// have been allowed to happen, so this should always be safe.
methodCall.method.setAccessible(true);
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
started.resolve(null);
try {
methodCall.method.invoke(service, methodCall.arguments);
cleanup.resolve(null);
} catch (InvocationTargetException ite) {
cleanup.fail(ite.getTargetException());
} catch (Exception e) {
cleanup.fail(e);
}
return null;
}
}, acc);
} catch (Exception e) {
started.fail(e);
cleanup.fail(e);
} finally {
methodCall.releaseService();
}
}
}
| 8,160 |
0 | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async/impl/Work.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.impl;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import org.apache.aries.async.promise.PromiseImpl;
public class Work<T> implements Runnable {
private final MethodCall methodCall;
private final PromiseImpl<T> promiseImpl;
private final AccessControlContext acc;
public Work(MethodCall methodCall, PromiseImpl<T> promiseImpl) {
this.methodCall = methodCall;
this.promiseImpl = promiseImpl;
this.acc = AccessController.getContext();
}
public void run() {
try {
final Object service = methodCall.getService();
// This is necessary for non public methods. The original mediator call must
// have been allowed to happen, so this should always be safe.
methodCall.method.setAccessible(true);
@SuppressWarnings("unchecked")
T returnValue = AccessController.doPrivileged(new PrivilegedExceptionAction<T>() {
public T run() throws Exception {
return (T) methodCall.method.invoke(service, methodCall.arguments);
}
}, acc);
promiseImpl.resolve(returnValue);
} catch (PrivilegedActionException pae) {
Throwable targetException = pae.getCause();
if(targetException instanceof InvocationTargetException) {
targetException = ((InvocationTargetException) targetException).getTargetException();
}
promiseImpl.fail(targetException);
} catch (Exception e) {
promiseImpl.fail(e);
} finally {
methodCall.releaseService();
}
}
}
| 8,161 |
0 | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async/impl/TrackingInvocationHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.impl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
class TrackingInvocationHandler implements InvocationHandler, net.sf.cglib.proxy.InvocationHandler {
private static final Map<Class<?>, Object> RETURN_VALUES;
static {
Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();
map.put(boolean.class, Boolean.FALSE);
map.put(byte.class, Byte.valueOf((byte)0));
map.put(short.class, Short.valueOf((short)0));
map.put(char.class, Character.valueOf((char)0));
map.put(int.class, Integer.valueOf(0));
map.put(float.class, Float.valueOf(0));
map.put(long.class, Long.valueOf(0));
map.put(double.class, Double.valueOf(0));
RETURN_VALUES = Collections.unmodifiableMap(map);
}
/**
*
*/
private final AsyncService asyncService;
private final ServiceTracker<LogService, LogService> logServiceTracker;
private final Bundle clientBundle;
private final ServiceReference<?> ref;
private final Object delegate;
public TrackingInvocationHandler(AsyncService asyncService,
Bundle clientBundle, ServiceTracker<LogService, LogService> logServiceTracker,
ServiceReference<?> ref) {
this.asyncService = asyncService;
this.logServiceTracker = logServiceTracker;
this.clientBundle = clientBundle;
this.ref = ref;
this.delegate = null;
}
public TrackingInvocationHandler(AsyncService asyncService,
Bundle clientBundle,ServiceTracker<LogService, LogService> logServiceTracker,
Object service) {
this.asyncService = asyncService;
this.logServiceTracker = logServiceTracker;
this.clientBundle = clientBundle;
this.delegate = service;
this.ref = null;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
asyncService.registerInvocation(new MethodCall(clientBundle, logServiceTracker,
ref, delegate, method, args));
Class<?> returnType = method.getReturnType();
return RETURN_VALUES.get(returnType);
}
}
| 8,162 |
0 | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async/impl/Activator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.impl;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Hashtable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.service.async.Async;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
public class Activator implements BundleActivator {
private final ExecutorService executor = Executors.newFixedThreadPool(10, new ThreadFactory() {
private final AtomicInteger count = new AtomicInteger();
public Thread newThread(final Runnable r) {
Thread t = new Thread(new Runnable(){
public void run() {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
r.run();
return null;
}
});
}
}, "Asynchronous Execution Service Thread " + count.incrementAndGet());
return t;
}
});
private final ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
private final AtomicInteger count = new AtomicInteger();
public Thread newThread(final Runnable r) {
Thread t = new Thread(new Runnable(){
public void run() {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
r.run();
return null;
}
});
}
}, "Asynchronous Execution Service Timing Thread " + count.incrementAndGet());
return t;
}
});
private volatile ServiceTracker<LogService, LogService> logServiceTracker;
public void start(BundleContext context) throws Exception {
logServiceTracker = new ServiceTracker<LogService, LogService>(context, LogService.class, null);
logServiceTracker.open();
context.registerService(Async.class.getName(), new AsyncServiceFactory(executor, ses, logServiceTracker), new Hashtable<String, Object>());
}
public void stop(BundleContext context) throws Exception {
ses.shutdownNow();
executor.shutdownNow();
logServiceTracker.close();
}
}
| 8,163 |
0 | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async/impl/AsyncService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.impl;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.service.async.Async;
import org.osgi.service.log.LogService;
import org.osgi.util.promise.Promise;
import org.osgi.util.tracker.ServiceTracker;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.Factory;
public class AsyncService implements Async {
private static final class CGLibAwareClassLoader extends ClassLoader {
private final ClassLoader serviceTypeLoader;
private CGLibAwareClassLoader(Bundle registeringBundle) {
this.serviceTypeLoader = registeringBundle.adapt(BundleWiring.class).getClassLoader();
}
private CGLibAwareClassLoader(ClassLoader loader) {
this.serviceTypeLoader = loader;
}
@Override
protected Class<?> findClass(String var0)
throws ClassNotFoundException {
if(var0.startsWith("net.sf.cglib")) {
return AsyncService.class.getClassLoader().loadClass(var0);
} else {
return serviceTypeLoader.loadClass(var0);
}
}
}
/**
* It is important to use both weak keys *and* values in this map. The
* key must be weakly held because it is typically a type from another
* bundle, and would represent a classloader leak if held after that
* bundle was uninstalled. The value must be weak because it either
* extends or implements the type that is the key, and so holds a strong
* reference to the key, which again would cause a leak.
*
* This cache may drop the value type if no mediators are held, however in
* this situation we can simply create a new value without risking exploding
* the heap.
*/
private final WeakHashMap<Class<?>, WeakReference<Class<?>>> proxyLoaderCache
= new WeakHashMap<Class<?>, WeakReference<Class<?>>>();
private final Bundle clientBundle;
private final ConcurrentMap<Thread, MethodCall> invocations = new ConcurrentHashMap<Thread, MethodCall>();
private final ExecutorService executor;
private final ScheduledExecutorService ses;
private final ServiceTracker<LogService, LogService> logServiceTracker;
public AsyncService(Bundle clientBundle, ExecutorService executor, ScheduledExecutorService ses, ServiceTracker<LogService, LogService> logServiceTracker) {
super();
this.clientBundle = clientBundle;
this.executor = executor;
this.ses = ses;
this.logServiceTracker = logServiceTracker;
}
void clear() {
proxyLoaderCache.clear();
}
public <T> T mediate(final T service, final Class<T> iface) {
return AccessController.doPrivileged(new PrivilegedAction<T>() {
public T run() {
return privMediate(service, iface);
}
});
}
@SuppressWarnings("unchecked")
private <T> T privMediate(T service, Class<T> iface) {
TrackingInvocationHandler handler = new TrackingInvocationHandler(this,
clientBundle, logServiceTracker, service);
synchronized(proxyLoaderCache) {
T toReturn = cachedMediate(iface, handler);
if(toReturn != null) {
return toReturn;
} else if(iface.isInterface()) {
toReturn = (T) Proxy.newProxyInstance(
new ClassLoader(service.getClass().getClassLoader()){},
new Class[] {iface}, handler);
} else {
toReturn = (T) proxyClass(iface, handler,
new CGLibAwareClassLoader(service.getClass().getClassLoader()));
}
proxyLoaderCache.put(iface, new WeakReference<Class<?>>(toReturn.getClass()));
return toReturn;
}
}
@SuppressWarnings("unchecked")
private <T> T cachedMediate(Class<T> iface, TrackingInvocationHandler handler) {
WeakReference<Class<?>> weakReference = proxyLoaderCache.get(iface);
Class<?> cached = weakReference == null ? null : weakReference.get();
if(cached != null) {
if(iface.isInterface()) {
try {
return (T) cached.getConstructor(InvocationHandler.class)
.newInstance(handler);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to mediate interface: " + iface, e);
}
} else {
try {
T t = (T) cached.getConstructor().newInstance();
((Factory)t).setCallbacks(new Callback[] {handler});
return t;
} catch (Exception e) {
throw new IllegalArgumentException("Unable to mediate class: " + iface, e);
}
}
}
return null;
}
public <T> T mediate(final ServiceReference<? extends T> ref, final Class<T> iface) {
return AccessController.doPrivileged(new PrivilegedAction<T>() {
public T run() {
return privMediate(ref, iface);
}
});
}
@SuppressWarnings("unchecked")
private <T> T privMediate(ServiceReference<? extends T> ref, Class<T> iface) {
TrackingInvocationHandler handler = new TrackingInvocationHandler(this,
clientBundle, logServiceTracker, ref);
synchronized(proxyLoaderCache) {
T toReturn = cachedMediate(iface, handler);
if(toReturn != null) {
return toReturn;
} else if(iface.isInterface()) {
toReturn = (T) Proxy.newProxyInstance(
new ClassLoader(iface.getClassLoader()){},
new Class[] {iface}, handler);
} else {
toReturn = (T) proxyClass(iface, handler,
new CGLibAwareClassLoader(iface.getClassLoader()));
}
proxyLoaderCache.put(iface, new WeakReference<Class<?>>(toReturn.getClass()));
return toReturn;
}
}
private Object proxyClass(Class<?> mostSpecificClass,
TrackingInvocationHandler handler, ClassLoader classLoader) {
acceptClassType(mostSpecificClass);
Enhancer enhancer = new Enhancer();
enhancer.setClassLoader(classLoader);
enhancer.setSuperclass(mostSpecificClass);
enhancer.setCallback(handler);
return enhancer.create();
}
private void acceptClassType(Class<?> type) {
if(Modifier.isFinal(type.getModifiers())) {
throw new IllegalArgumentException("The type " + type.getName() + " is final");
}
try {
type.getConstructor();
} catch (NoSuchMethodException nsme) {
throw new IllegalArgumentException("The type " + type.getName() + " has no zero-argument constructor", nsme);
}
Class<?> toCheck = type;
while(toCheck != Object.class) {
for(Method m : toCheck.getDeclaredMethods()) {
if(Modifier.isFinal(m.getModifiers())) {
throw new IllegalArgumentException("The type hierarchy for " + type.getName() +
" has a final method " + m.getName() + " defined on " + toCheck.getName());
}
}
toCheck = toCheck.getSuperclass();
}
}
public <T> Promise<T> call(T call) throws IllegalStateException {
MethodCall currentInvocation = consumeCurrentInvocation();
if(currentInvocation == null) throw new IllegalStateException("Incorrect API usage - this thread has no pending method calls");
return currentInvocation.invokeAsynchronously(clientBundle, executor, ses);
}
public Promise<?> call() throws IllegalStateException {
return call(null);
}
public Promise<Void> execute() throws IllegalStateException {
MethodCall currentInvocation = consumeCurrentInvocation();
if(currentInvocation == null) throw new IllegalStateException("Incorrect API usage - this thread has no pending method calls");
return currentInvocation.fireAndForget(clientBundle, executor, ses);
}
void registerInvocation(MethodCall invocation) {
if(invocations.putIfAbsent(Thread.currentThread(), invocation) != null) {
invocations.remove(Thread.currentThread());
throw new IllegalStateException("Incorrect API usage - this thread already has a pending method call");
}
}
MethodCall consumeCurrentInvocation() {
return invocations.remove(Thread.currentThread());
}
}
| 8,164 |
0 | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async | Create_ds/aries/async/async-impl/src/main/java/org/apache/aries/async/impl/MethodCall.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.async.impl;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.aries.async.promise.PromiseImpl;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.async.delegate.AsyncDelegate;
import org.osgi.service.log.LogService;
import org.osgi.util.promise.Failure;
import org.osgi.util.promise.Promise;
import org.osgi.util.tracker.ServiceTracker;
public class MethodCall {
private final Bundle clientBundle;
private final ServiceTracker<LogService, LogService> logServiceTracker;
private final ServiceReference<?> reference;
private final Object service;
final Method method;
final Object[] arguments;
public MethodCall(Bundle clientBundle, ServiceTracker<LogService, LogService> logServiceTracker,
ServiceReference<?> reference, Object service, Method method, Object[] arguments) {
this.clientBundle = clientBundle;
this.logServiceTracker = logServiceTracker;
this.reference = reference;
this.service = service;
this.method = method;
this.arguments = arguments;
}
Object getService() {
if(reference != null) {
BundleContext bc = clientBundle.getBundleContext();
if(bc != null) {
try {
Object svc = bc.getService(reference);
if(svc == null) {
throw new ServiceException("Unable to retrieve the mediated service because it has been unregistered", 7);
} else {
return svc;
}
} catch (Exception e) {
throw new ServiceException("Unable to retrieve the mediated service", 7, e);
}
} else {
throw new ServiceException("Unable to retrieve the mediated service because the client bundle has been stopped", 7);
}
} else {
return service;
}
}
void releaseService() {
if(reference != null) {
BundleContext bc = clientBundle.getBundleContext();
if(bc != null) {
bc.ungetService(reference);
}
}
}
public <V> Promise<V> invokeAsynchronously(Bundle clientBundle, ExecutorService executor, ScheduledExecutorService ses) {
PromiseImpl<V> promiseImpl = new PromiseImpl<V>(executor, ses);
Object svc;
try {
svc = getService();
} catch (Exception e) {
promiseImpl.fail(e);
return promiseImpl;
}
if(svc instanceof AsyncDelegate) {
try {
@SuppressWarnings("unchecked")
Promise<V> p = (Promise<V>) ((AsyncDelegate) svc).async(method, arguments);
if(p != null) {
try {
promiseImpl.resolveWith(p);
return promiseImpl;
} finally {
releaseService();
}
}
} catch (Exception e) {
try {
promiseImpl.fail(e);
return promiseImpl;
} finally {
releaseService();
}
}
}
//If we get here then svc is either not an async delegate, or it rejected the call
try {
executor.execute(new Work<V>(this, promiseImpl));
} catch (RejectedExecutionException ree) {
promiseImpl.fail(new ServiceException("The Async service is unable to accept new requests", 7, ree));
}
//Release the service we got at the start of this method
promiseImpl.onResolve(new Runnable() {
public void run() {
releaseService();
}
});
return promiseImpl;
}
public Promise<Void> fireAndForget(Bundle clientBundle, ExecutorService executor, ScheduledExecutorService ses) {
PromiseImpl<Void> started = new PromiseImpl<Void>(executor, ses);
Object svc;
try {
svc = getService();
} catch (Exception e) {
logError("Unable to obtain the service object", e);
started.fail(e);
return started;
}
if(svc instanceof AsyncDelegate) {
try {
if(((AsyncDelegate) svc).execute(method, arguments)) {
releaseService();
started.resolve(null);
return started;
}
} catch (Exception e) {
releaseService();
logError("The AsyncDelegate rejected the fire-and-forget invocation with an exception", e);
started.fail(e);
return started;
}
}
//If we get here then svc is either not an async delegate, or it rejected the call
PromiseImpl<Void> cleanup = new PromiseImpl<Void>();
try {
executor.execute(new FireAndForgetWork(this, cleanup, started));
cleanup.onResolve(new Runnable() {
public void run() {
releaseService();
}
}).then(null, new Failure(){
public void fail(Promise<?> resolved) throws Exception {
logError("The fire-and-forget invocation failed", resolved.getFailure());
}
});
} catch (RejectedExecutionException ree) {
logError("The Async Service threadpool rejected the fire-and-forget invocation", ree);
started.fail(new ServiceException("Unable to enqueue the fire-and forget task", 7, ree));
}
return started;
}
void logError(String message, Throwable e) {
for(LogService log : logServiceTracker.getServices(new LogService[0])) {
if(reference == null) {
log.log(LogService.LOG_ERROR, message, e);
} else {
log.log(reference, LogService.LOG_ERROR, message, e);
}
}
}
}
| 8,165 |
0 | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba/EbaMojoTest.java | package org.apache.aries.plugin.eba;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Iterator;
import org.apache.maven.plugin.testing.AbstractMojoTestCase;
import org.codehaus.plexus.archiver.zip.ZipEntry;
import org.codehaus.plexus.archiver.zip.ZipFile;
import org.codehaus.plexus.util.FileUtils;
/**
* @author <a href="mailto:aramirez@apache.org">Allan Ramirez</a>
*/
public class EbaMojoTest
extends AbstractMojoTestCase
{
public void testEbaTestEnvironment()
throws Exception
{
File testPom = new File( getBasedir(),
"target/test-classes/unit/basic-eba-test/plugin-config.xml" );
EbaMojo mojo = ( EbaMojo ) lookupMojo( "eba", testPom );
assertNotNull( mojo );
}
public void testBasicEba()
throws Exception
{
File testPom = new File( getBasedir(),
"target/test-classes/unit/basic-eba-test/plugin-config.xml" );
EbaMojo mojo = ( EbaMojo ) lookupMojo( "eba", testPom );
assertNotNull( mojo );
String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" );
String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" );
String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" );
Boolean includeJar = ( Boolean ) getVariableValueFromObject( mojo, "includeJar" );
assertTrue( includeJar.booleanValue() );
//include the project jar to the eba
File projectJar = new File( getBasedir(), "src/test/resources/unit/basic-eba-test/target/test-eba.jar" );
FileUtils.copyFileToDirectory( projectJar, new File( outputDir ) );
mojo.execute();
//check the generated eba file
File ebaFile = new File( outputDir, finalName + ".eba" );
assertTrue( ebaFile.exists() );
//expected files/directories inside the eba file
List expectedFiles = new ArrayList();
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.properties" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.xml" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/" );
expectedFiles.add( "META-INF/maven/" );
// expectedFiles.add( "META-INF/MANIFEST.MF" );
expectedFiles.add( "META-INF/" );
expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" );
expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" );
expectedFiles.add( "test-eba.jar" );
ZipFile eba = new ZipFile( ebaFile );
Enumeration entries = eba.getEntries();
assertTrue( entries.hasMoreElements() );
assertTrue( entries.hasMoreElements() );
int missing = getSizeOfExpectedFiles(entries, expectedFiles);
assertEquals("Missing files: " + expectedFiles, 0, missing);
}
public void testBasicEbaWithDescriptor()
throws Exception
{
File testPom = new File( getBasedir(),
"target/test-classes/unit/basic-eba-with-descriptor/plugin-config.xml" );
EbaMojo mojo = ( EbaMojo ) lookupMojo( "eba", testPom );
assertNotNull( mojo );
String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" );
String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" );
String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" );
mojo.execute();
//check the generated eba file
File ebaFile = new File( outputDir, finalName + ".eba" );
assertTrue( ebaFile.exists() );
//expected files/directories inside the eba file
List expectedFiles = new ArrayList();
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.properties" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.xml" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/" );
expectedFiles.add( "META-INF/maven/" );
// expectedFiles.add( "META-INF/MANIFEST.MF" );
expectedFiles.add( "META-INF/APPLICATION.MF" );
expectedFiles.add( "META-INF/" );
expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" );
expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" );
ZipFile eba = new ZipFile( ebaFile );
Enumeration entries = eba.getEntries();
assertTrue( entries.hasMoreElements() );
assertTrue( entries.hasMoreElements() );
int missing = getSizeOfExpectedFiles(entries, expectedFiles);
assertEquals("Missing files: " + expectedFiles, 0, missing);
}
public void testBasicEbaWithManifest()
throws Exception
{
File testPom = new File( getBasedir(),
"target/test-classes/unit/basic-eba-with-manifest/plugin-config.xml" );
EbaMojo mojo = ( EbaMojo ) lookupMojo( "eba", testPom );
assertNotNull( mojo );
String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" );
String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" );
String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" );
mojo.execute();
//check the generated eba file
File ebaFile = new File( outputDir, finalName + ".eba" );
assertTrue( ebaFile.exists() );
//expected files/directories inside the eba file
List expectedFiles = new ArrayList();
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.properties" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.xml" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/" );
expectedFiles.add( "META-INF/maven/" );
expectedFiles.add( "META-INF/MANIFEST.MF" );
expectedFiles.add( "META-INF/APPLICATION.MF" );
expectedFiles.add( "META-INF/" );
expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" );
expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" );
ZipFile eba = new ZipFile( ebaFile );
Enumeration entries = eba.getEntries();
assertTrue( entries.hasMoreElements() );
int missing = getSizeOfExpectedFiles(entries, expectedFiles);
assertEquals("Missing files: " + expectedFiles, 0, missing);
}
public void testApplicationManifestGeneration()
throws Exception
{
File testPom = new File( getBasedir(),
"target/test-classes/unit/basic-eba-without-manifest/plugin-config.xml" );
EbaMojo mojo = ( EbaMojo ) lookupMojo( "eba", testPom );
assertNotNull( mojo );
String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" );
String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" );
String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" );
mojo.execute();
//check the generated eba file
File ebaFile = new File( outputDir, finalName + ".eba" );
assertTrue( ebaFile.exists() );
//expected files/directories inside the eba file
List expectedFiles = new ArrayList();
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.properties" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.xml" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/" );
expectedFiles.add( "META-INF/maven/" );
expectedFiles.add( "META-INF/APPLICATION.MF" );
expectedFiles.add( "META-INF/" );
expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" );
expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" );
ZipFile eba = new ZipFile( ebaFile );
Enumeration entries = eba.getEntries();
assertTrue( entries.hasMoreElements() );
int missing = getSizeOfExpectedFiles(entries, expectedFiles);
assertEquals("Missing files: " + expectedFiles, 0, missing);
//Test Application-ImportService Application-ExportService and Use-Bundle inclusion
ZipEntry entry = eba.getEntry("META-INF/APPLICATION.MF");
BufferedReader br = new BufferedReader(new InputStreamReader(eba.getInputStream(entry)));
String appServiceExport = new String("Application-ExportService: test.ExportService");
String appServiceImport = new String("Application-ImportService: test.ImportService");
String useBundle = new String("Use-Bundle: org.apache.aries.test.Bundle;version=1.0.0-SNAPSHOT");
Boolean foundAppExport=false;
Boolean foundAppImport=false;
Boolean foundUseBundle=false;
String line;
while ((line = br.readLine()) != null) {
if (line.contains(new String("Application-ExportService"))) {
assertEquals(appServiceExport, line);
foundAppExport = true;
}
if (line.contains(new String("Application-ImportService"))) {
assertEquals(appServiceImport, line);
foundAppImport = true;
}
if (line.contains(new String("Use-Bundle"))) {
assertEquals(useBundle, line);
foundUseBundle = true;
}
}
assertTrue("Found Application-ExportService:", foundAppExport);
assertTrue("Found Application-ImportService:", foundAppImport);
assertTrue("Found Use-Bundle:", foundUseBundle);
}
public void testArchiveContentConfigurationNoBundles()
throws Exception
{
File testPom = new File( getBasedir(),
"target/test-classes/unit/basic-eba-no-bundles/plugin-config.xml" );
EbaMojo mojo = ( EbaMojo ) lookupMojo( "eba", testPom );
assertNotNull( mojo );
String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" );
String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" );
String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" );
mojo.execute();
//check the generated eba file
File ebaFile = new File( outputDir, finalName + ".eba" );
assertTrue( ebaFile.exists() );
//expected files/directories inside the eba file
List expectedFiles = new ArrayList();
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.properties" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.xml" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/" );
expectedFiles.add( "META-INF/maven/" );
expectedFiles.add( "META-INF/APPLICATION.MF" );
expectedFiles.add( "META-INF/" );
ZipFile eba = new ZipFile( ebaFile );
Enumeration entries = eba.getEntries();
assertTrue( entries.hasMoreElements() );
int missing = getSizeOfExpectedFiles(entries, expectedFiles);
assertEquals("Missing files: " + expectedFiles, 0, missing);
}
public void testArchiveContentConfigurationApplicationContentBundles()
throws Exception
{
File testPom = new File( getBasedir(),
"target/test-classes/unit/basic-eba-content-bundles-only/plugin-config.xml" );
EbaMojo mojo = ( EbaMojo ) lookupMojo( "eba", testPom );
assertNotNull( mojo );
String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" );
String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" );
String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" );
mojo.execute();
//check the generated eba file
File ebaFile = new File( outputDir, finalName + ".eba" );
assertTrue( ebaFile.exists() );
//expected files/directories inside the eba file
List expectedFiles = new ArrayList();
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.properties" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.xml" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/" );
expectedFiles.add( "META-INF/maven/" );
expectedFiles.add( "META-INF/APPLICATION.MF" );
expectedFiles.add( "META-INF/" );
expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" );
expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" );
ZipFile eba = new ZipFile( ebaFile );
Enumeration entries = eba.getEntries();
assertTrue( entries.hasMoreElements() );
int missing = getSizeOfExpectedFiles(entries, expectedFiles);
assertEquals("Missing files: " + expectedFiles, 0, missing);
}
public void testArchiveContentConfigurationAllBundles()
throws Exception
{
File testPom = new File( getBasedir(),
"target/test-classes/unit/basic-eba-all-bundles/plugin-config.xml" );
EbaMojo mojo = ( EbaMojo ) lookupMojo( "eba", testPom );
assertNotNull( mojo );
String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" );
String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" );
String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" );
mojo.execute();
//check the generated eba file
File ebaFile = new File( outputDir, finalName + ".eba" );
assertTrue( ebaFile.exists() );
//expected files/directories inside the eba file
List expectedFiles = new ArrayList();
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.properties" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/pom.xml" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-eba-test/" );
expectedFiles.add( "META-INF/maven/org.apache.maven.test/" );
expectedFiles.add( "META-INF/maven/" );
expectedFiles.add( "META-INF/APPLICATION.MF" );
expectedFiles.add( "META-INF/" );
expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" );
expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" );
expectedFiles.add( "maven-artifact03-1.0-SNAPSHOT.jar" );
ZipFile eba = new ZipFile( ebaFile );
Enumeration entries = eba.getEntries();
assertTrue( entries.hasMoreElements() );
int missing = getSizeOfExpectedFiles(entries, expectedFiles);
assertEquals("Missing files: " + expectedFiles, 0, missing);
}
private int getSizeOfExpectedFiles( Enumeration entries, List expectedFiles )
{
while( entries.hasMoreElements() )
{
ZipEntry entry = ( ZipEntry ) entries.nextElement();
if( expectedFiles.contains( entry.getName() ) )
{
expectedFiles.remove( entry.getName() );
assertFalse( expectedFiles.contains( entry.getName() ) );
}
else
{
fail( entry.getName() + " is not included in the expected files" );
}
}
return expectedFiles.size();
}
}
| 8,166 |
0 | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba/stubs/EbaMavenProjectStub6.java | package org.apache.aries.plugin.eba.stubs;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.io.File;
public class EbaMavenProjectStub6
extends EbaMavenProjectStub
{
public File getFile()
{
return new File( getBasedir(), "src/test/resources/unit/basic-eba-content-bundles-only/plugin-config.xml" );
}
}
| 8,167 |
0 | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba/stubs/EbaMavenProjectStub7.java | package org.apache.aries.plugin.eba.stubs;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.io.File;
public class EbaMavenProjectStub7
extends EbaMavenProjectStub
{
public File getFile()
{
return new File( getBasedir(), "src/test/resources/unit/basic-eba-all-bundles/plugin-config.xml" );
}
}
| 8,168 |
0 | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba/stubs/EbaArtifactStub.java | package org.apache.aries.plugin.eba.stubs;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.io.File;
import org.apache.maven.plugin.testing.stubs.ArtifactStub;
/**
* @author <a href="mailto:aramirez@apache.org">Allan Ramirez</a>
*/
public class EbaArtifactStub
extends ArtifactStub
{
private String groupId;
private String artifactId;
private String version;
private String scope;
private boolean optional;
private File file;
public String getArtifactId()
{
return artifactId;
}
public void setArtifactId( String artifactId )
{
this.artifactId = artifactId;
}
public File getFile()
{
return file;
}
public void setFile( File file )
{
this.file = file;
}
public String getGroupId()
{
return groupId;
}
public void setGroupId( String groupId )
{
this.groupId = groupId;
}
public boolean isOptional()
{
return optional;
}
public void setOptional( boolean optional )
{
this.optional = optional;
}
public String getScope()
{
return scope;
}
public void setScope( String scope )
{
this.scope = scope;
}
public String getVersion()
{
return version;
}
public void setVersion( String version )
{
this.version = version;
}
public String getId()
{
return getGroupId() + ":" + getArtifactId() + ":" + getVersion();
}
public String getBaseVersion()
{
return getVersion();
}
}
| 8,169 |
0 | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba/stubs/EbaMavenProjectStub.java | package org.apache.aries.plugin.eba.stubs;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Model;
import org.apache.maven.model.Organization;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.PlexusTestCase;
/**
* @author <a href="mailto:aramirez@apache.org">Allan Ramirez</a>
*/
public class EbaMavenProjectStub
extends MavenProject
{
private List attachedArtifacts;
public EbaMavenProjectStub()
{
super( new Model() );
super.setGroupId( getGroupId() );
super.setArtifactId( getArtifactId() );
super.setVersion( getVersion() );
super.setDescription( "Test description" );
Organization org = new Organization();
org.setName( "organization" );
org.setUrl( "http://www.some.org" );
super.setOrganization( org );
super.setFile( getFile() );
super.setPluginArtifacts( Collections.EMPTY_SET );
super.setReportArtifacts( Collections.EMPTY_SET );
super.setExtensionArtifacts( Collections.EMPTY_SET );
super.setArtifact( getArtifact() );
super.setRemoteArtifactRepositories( Collections.EMPTY_LIST );
super.setPluginArtifactRepositories( Collections.EMPTY_LIST );
super.setCollectedProjects( Collections.EMPTY_LIST );
super.setActiveProfiles( Collections.EMPTY_LIST );
super.addCompileSourceRoot( getBasedir() + "/src/test/resources/unit/basic-eba-test/src/main/java" );
super.addTestCompileSourceRoot( getBasedir() + "/src/test/resources/unit/basic-eba-test/src/test/java" );
super.setExecutionRoot( false );
}
public String getGroupId()
{
return "org.apache.maven.test";
}
public String getArtifactId()
{
return "maven-eba-test";
}
public String getVersion()
{
return "1.0-SNAPSHOT";
}
public File getFile()
{
return new File( getBasedir(), "src/test/resources/unit/basic-eba-test/plugin-config.xml" );
}
public File getBasedir()
{
return new File( PlexusTestCase.getBasedir() );
}
public Artifact getArtifact()
{
Artifact artifact = new EbaArtifactStub();
artifact.setGroupId( getGroupId() );
artifact.setArtifactId( getArtifactId() );
artifact.setVersion( getVersion() );
return artifact;
}
public Set getArtifacts()
{
Set artifacts = getDependencyArtifacts();
// this one's a transitive dependency
artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact03", "1.0-SNAPSHOT", false ) );
return artifacts;
}
@Override
public Set getDependencyArtifacts() {
Set artifacts = new HashSet();
artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact01", "1.0-SNAPSHOT", false ) );
artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact02", "1.0-SNAPSHOT", false ) );
return artifacts;
}
public List getAttachedArtifacts()
{
if ( attachedArtifacts == null )
{
attachedArtifacts = new ArrayList();
}
return attachedArtifacts;
}
protected Artifact createArtifact( String groupId, String artifactId, String version, boolean optional )
{
Artifact artifact = new EbaArtifactStub();
artifact.setGroupId( groupId );
artifact.setArtifactId( artifactId );
artifact.setVersion( version );
artifact.setOptional( optional );
artifact.setFile( new File ( getBasedir() + "/src/test/remote-repo/" + artifact.getGroupId().replace( '.', '/' ) +
"/" + artifact.getArtifactId() + "/" + artifact.getVersion() +
"/" + artifact.getArtifactId() + "-" + artifact.getVersion() + ".jar" ) ) ;
return artifact;
}
}
| 8,170 |
0 | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba/stubs/EbaMavenProjectStub2.java | package org.apache.aries.plugin.eba.stubs;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.io.File;
public class EbaMavenProjectStub2
extends EbaMavenProjectStub
{
public File getFile()
{
return new File( getBasedir(), "src/test/resources/unit/basic-eba-with-descriptor/plugin-config.xml" );
}
}
| 8,171 |
0 | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba/stubs/EbaMavenProjectStub3.java | package org.apache.aries.plugin.eba.stubs;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.io.File;
public class EbaMavenProjectStub3
extends EbaMavenProjectStub
{
public File getFile()
{
return new File( getBasedir(), "src/test/resources/unit/basic-eba-with-manifest/plugin-config.xml" );
}
}
| 8,172 |
0 | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba/stubs/EbaMavenProjectStub4.java | package org.apache.aries.plugin.eba.stubs;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.io.File;
public class EbaMavenProjectStub4
extends EbaMavenProjectStub
{
public File getFile()
{
return new File( getBasedir(), "src/test/resources/unit/basic-eba-without-manifest/plugin-config.xml" );
}
}
| 8,173 |
0 | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba | Create_ds/aries/eba-maven-plugin/src/test/java/org/apache/aries/plugin/eba/stubs/EbaMavenProjectStub5.java | package org.apache.aries.plugin.eba.stubs;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.io.File;
public class EbaMavenProjectStub5
extends EbaMavenProjectStub
{
public File getFile()
{
return new File( getBasedir(), "src/test/resources/unit/basic-eba-no-bundles/plugin-config.xml" );
}
}
| 8,174 |
0 | Create_ds/aries/eba-maven-plugin/src/main/java/org/apache/aries/plugin | Create_ds/aries/eba-maven-plugin/src/main/java/org/apache/aries/plugin/eba/EbaMojo.java | package org.apache.aries.plugin.eba;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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 org.apache.maven.archiver.PomPropertiesUtil;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.zip.ZipArchiver;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter;
import org.apache.maven.shared.osgi.Maven2OsgiConverter;
import aQute.lib.osgi.Analyzer;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* Builds Aries Enterprise Bundle Archive (eba) files.
*
* @version $Id: $
* @goal eba
* @phase package
* @requiresDependencyResolution test
*/
public class EbaMojo
extends AbstractMojo
{
public static final String APPLICATION_MF_URI = "META-INF/APPLICATION.MF";
private static final String[] DEFAULT_INCLUDES = {"**/**"};
/**
* Application manifest headers
*/
private static final String MANIFEST_VERSION = "Manifest-Version";
private static final String APPLICATION_MANIFESTVERSION = "Application-ManifestVersion";
private static final String APPLICATION_SYMBOLICNAME = "Application-SymbolicName";
private static final String APPLICATION_VERSION = "Application-Version";
private static final String APPLICATION_NAME = "Application-Name";
private static final String APPLICATION_DESCRIPTION = "Application-Description";
private static final String APPLICATION_CONTENT = "Application-Content";
private static final String APPLICATION_EXPORTSERVICE = "Application-ExportService";
private static final String APPLICATION_IMPORTSERVICE = "Application-ImportService";
private static final String APPLICATION_USEBUNDLE = "Use-Bundle";
/**
* Coverter for maven pom values to OSGi manifest values (pulled in from the maven-bundle-plugin)
*/
private Maven2OsgiConverter maven2OsgiConverter = new DefaultMaven2OsgiConverter();
/**
* Single directory for extra files to include in the eba.
*
* @parameter expression="${basedir}/src/main/eba"
* @required
*/
private File ebaSourceDirectory;
/**
* The location of the APPLICATION.MF file to be used within the eba file.
*
* @parameter expression="${basedir}/src/main/eba/META-INF/APPLICATION.MF"
*/
private File applicationManifestFile;
/**
* Specify if the generated jar file of this project should be
* included in the eba file ; default is true.
*
* @parameter
*/
private Boolean includeJar = Boolean.TRUE;
/**
* The location of the manifest file to be used within the eba file.
*
* @parameter expression="${basedir}/src/main/eba/META-INF/MANIFEST.MF"
*/
private File manifestFile;
/**
* Directory that resources are copied to during the build.
*
* @parameter expression="${project.build.directory}/${project.build.finalName}"
* @required
*/
private String workDirectory;
/**
* Directory that remote-resources puts legal files.
*
* @parameter expression="${project.build.directory}/maven-shared-archive-resources"
* @required
*/
private String sharedResources;
/**
* The directory for the generated eba.
*
* @parameter expression="${project.build.directory}"
* @required
*/
private String outputDirectory;
/**
* The name of the eba file to generate.
*
* @parameter alias="ebaName" expression="${project.build.finalName}"
* @required
*/
private String finalName;
/**
* The maven project.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* The Jar archiver.
*
* @component role="org.codehaus.plexus.archiver.Archiver" roleHint="zip"
* @required
*/
private ZipArchiver zipArchiver;
/**
* Whether to generate a manifest based on maven configuration.
*
* @parameter expression="${generateManifest}" default-value="false"
*/
private boolean generateManifest;
/**
* Configuration for the plugin.
*
* @parameter
*/
private Map instructions = new LinkedHashMap();;
/**
* Adding pom.xml and pom.properties to the archive.
*
* @parameter expression="${addMavenDescriptor}" default-value="true"
*/
private boolean addMavenDescriptor;
/**
* Include or not empty directories
*
* @parameter expression="${includeEmptyDirs}" default-value="true"
*/
private boolean includeEmptyDirs;
/**
* Whether creating the archive should be forced.
*
* @parameter expression="${forceCreation}" default-value="false"
*/
private boolean forceCreation;
/**
* Whether to follow transitive dependencies or use explicit dependencies.
*
* @parameter expression="${useTransitiveDependencies}" default-value="false"
*/
private boolean useTransitiveDependencies;
/**
* Define which bundles to include in the archive.
* none - no bundles are included
* applicationContent - direct dependencies go into the content
* all - direct and transitive dependencies go into the content
*
* @parameter expression="${archiveContent}" default-value="applicationContent"
*/
private String archiveContent;
private File buildDir;
public void execute()
throws MojoExecutionException
{
getLog().debug( " ======= EbaMojo settings =======" );
getLog().debug( "ebaSourceDirectory[" + ebaSourceDirectory + "]" );
getLog().debug( "manifestFile[" + manifestFile + "]" );
getLog().debug( "applicationManifestFile[" + applicationManifestFile + "]" );
getLog().debug( "workDirectory[" + workDirectory + "]" );
getLog().debug( "outputDirectory[" + outputDirectory + "]" );
getLog().debug( "finalName[" + finalName + "]" );
getLog().debug( "generateManifest[" + generateManifest + "]" );
if (archiveContent == null) {
archiveContent = new String("applicationContent");
}
getLog().debug( "archiveContent[" + archiveContent + "]" );
getLog().info( "archiveContent[" + archiveContent + "]" );
zipArchiver.setIncludeEmptyDirs( includeEmptyDirs );
zipArchiver.setCompress( true );
zipArchiver.setForced( forceCreation );
// Check if jar file is there and if requested, copy it
try
{
if (includeJar.booleanValue()) {
File generatedJarFile = new File( outputDirectory, finalName + ".jar" );
if (generatedJarFile.exists()) {
getLog().info( "Including generated jar file["+generatedJarFile.getName()+"]");
zipArchiver.addFile(generatedJarFile, finalName + ".jar");
}
}
}
catch ( ArchiverException e )
{
throw new MojoExecutionException( "Error adding generated Jar file", e );
}
// Copy dependencies
try
{
Set<Artifact> artifacts = null;
if (useTransitiveDependencies || "all".equals(archiveContent)) {
// if use transitive is set (i.e. true) then we need to make sure archiveContent does not contradict (i.e. is set
// to the same compatible value or is the default).
if ("none".equals(archiveContent)) {
throw new MojoExecutionException("<useTransitiveDependencies/> and <archiveContent/> incompatibly configured. <useTransitiveDependencies/> is deprecated in favor of <archiveContent/>." );
}
else {
artifacts = project.getArtifacts();
}
} else {
// check that archiveContent is compatible
if ("applicationContent".equals(archiveContent)) {
artifacts = project.getDependencyArtifacts();
}
else {
// the only remaining options should be applicationContent="none"
getLog().info("archiveContent=none: application arvhive will not contain any bundles.");
}
}
if (artifacts != null) {
for (Artifact artifact : artifacts) {
ScopeArtifactFilter filter = new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME);
if (!artifact.isOptional() && filter.include(artifact)) {
getLog().info("Copying artifact[" + artifact.getGroupId() + ", " + artifact.getId() + ", " +
artifact.getScope() + "]");
zipArchiver.addFile(artifact.getFile(), artifact.getArtifactId() + "-" + artifact.getVersion() + "." + (artifact.getType() == null ? "jar" : artifact.getType()));
}
}
}
}
catch ( ArchiverException e )
{
throw new MojoExecutionException( "Error copying EBA dependencies", e );
}
// Copy source files
try
{
File ebaSourceDir = ebaSourceDirectory;
if ( ebaSourceDir.exists() )
{
getLog().info( "Copy eba resources to " + getBuildDir().getAbsolutePath() );
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir( ebaSourceDir.getAbsolutePath() );
scanner.setIncludes( DEFAULT_INCLUDES );
scanner.addDefaultExcludes();
scanner.scan();
String[] dirs = scanner.getIncludedDirectories();
for ( int j = 0; j < dirs.length; j++ )
{
new File( getBuildDir(), dirs[j] ).mkdirs();
}
String[] files = scanner.getIncludedFiles();
for ( int j = 0; j < files.length; j++ )
{
File targetFile = new File( getBuildDir(), files[j] );
targetFile.getParentFile().mkdirs();
File file = new File( ebaSourceDir, files[j] );
FileUtils.copyFileToDirectory( file, targetFile.getParentFile() );
}
}
}
catch ( Exception e )
{
throw new MojoExecutionException( "Error copying EBA resources", e );
}
// Include custom manifest if necessary
try
{
if (!generateManifest) {
includeCustomApplicationManifestFile();
}
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error copying APPLICATION.MF file", e );
}
// Generate application manifest if requested
if (generateManifest) {
String fileName = new String(getBuildDir() + "/"
+ APPLICATION_MF_URI);
File appMfFile = new File(fileName);
try {
// Delete any old manifest
if (appMfFile.exists()) {
FileUtils.fileDelete(fileName);
}
appMfFile.getParentFile().mkdirs();
if (appMfFile.createNewFile()) {
writeApplicationManifest(fileName);
}
} catch (java.io.IOException e) {
throw new MojoExecutionException(
"Error generating APPLICATION.MF file: " + fileName, e);
}
}
// Check if connector deployment descriptor is there
File ddFile = new File( getBuildDir(), APPLICATION_MF_URI);
if ( !ddFile.exists() )
{
getLog().warn(
"Application manifest: " + ddFile.getAbsolutePath() + " does not exist." );
}
try
{
if (addMavenDescriptor) {
if (project.getArtifact().isSnapshot()) {
project.setVersion(project.getArtifact().getVersion());
}
String groupId = project.getGroupId();
String artifactId = project.getArtifactId();
zipArchiver.addFile(project.getFile(), "META-INF/maven/" + groupId + "/" + artifactId + "/pom.xml");
PomPropertiesUtil pomPropertiesUtil = new PomPropertiesUtil();
File dir = new File(project.getBuild().getDirectory(), "maven-zip-plugin");
File pomPropertiesFile = new File(dir, "pom.properties");
pomPropertiesUtil.createPomProperties(project, zipArchiver, pomPropertiesFile, forceCreation);
}
File ebaFile = new File( outputDirectory, finalName + ".eba" );
zipArchiver.setDestFile(ebaFile);
File buildDir = getBuildDir();
if (buildDir.isDirectory()) {
zipArchiver.addDirectory(buildDir);
}
//include legal files if any
File sharedResourcesDir = new File(sharedResources);
if (sharedResourcesDir.isDirectory()) {
zipArchiver.addDirectory(sharedResourcesDir);
}
zipArchiver.createArchive();
project.getArtifact().setFile( ebaFile );
}
catch ( Exception e )
{
throw new MojoExecutionException( "Error assembling eba", e );
}
}
private void writeApplicationManifest(String fileName)
throws MojoExecutionException {
try {
// TODO: add support for dependency version ranges. Need to pick
// them up from the pom and convert them to OSGi version ranges.
FileUtils.fileAppend(fileName, MANIFEST_VERSION + ": " + "1" + "\n");
FileUtils.fileAppend(fileName, APPLICATION_MANIFESTVERSION + ": " + "1" + "\n");
FileUtils.fileAppend(fileName, APPLICATION_SYMBOLICNAME + ": "
+ getApplicationSymbolicName(project.getArtifact()) + "\n");
FileUtils.fileAppend(fileName, APPLICATION_VERSION + ": "
+ getApplicationVersion() + "\n");
FileUtils.fileAppend(fileName, APPLICATION_NAME + ": " + project.getName() + "\n");
FileUtils.fileAppend(fileName, APPLICATION_DESCRIPTION + ": "
+ project.getDescription() + "\n");
// Write the APPLICATION-CONTENT
// TODO: check that the dependencies are bundles (currently, the converter
// will throw an exception)
Set<Artifact> artifacts;
if (useTransitiveDependencies) {
artifacts = project.getArtifacts();
} else {
artifacts = project.getDependencyArtifacts();
}
artifacts = selectArtifacts(artifacts);
Iterator<Artifact> iter = artifacts.iterator();
FileUtils.fileAppend(fileName, APPLICATION_CONTENT + ": ");
if (iter.hasNext()) {
Artifact artifact = iter.next();
FileUtils.fileAppend(fileName, maven2OsgiConverter
.getBundleSymbolicName(artifact)
+ ";version=\""
+ Analyzer.cleanupVersion(artifact.getVersion())
// + maven2OsgiConverter.getVersion(artifact.getVersion())
+ "\"");
}
while (iter.hasNext()) {
Artifact artifact = iter.next();
FileUtils.fileAppend(fileName, ",\n "
+ maven2OsgiConverter.getBundleSymbolicName(artifact)
+ ";version=\""
+ Analyzer.cleanupVersion(artifact.getVersion())
// + maven2OsgiConverter.getVersion(artifact.getVersion())
+ "\"");
}
FileUtils.fileAppend(fileName, "\n");
// Add any service imports or exports
if (instructions.containsKey(APPLICATION_EXPORTSERVICE)) {
FileUtils.fileAppend(fileName, APPLICATION_EXPORTSERVICE + ": "
+ instructions.get(APPLICATION_EXPORTSERVICE) + "\n");
}
if (instructions.containsKey(APPLICATION_IMPORTSERVICE)) {
FileUtils.fileAppend(fileName, APPLICATION_IMPORTSERVICE + ": "
+ instructions.get(APPLICATION_IMPORTSERVICE) + "\n");
}
if (instructions.containsKey(APPLICATION_USEBUNDLE)) {
FileUtils.fileAppend(fileName, APPLICATION_USEBUNDLE + ": "
+ instructions.get(APPLICATION_USEBUNDLE) + "\n");
}
// Add any use bundle entry
} catch (Exception e) {
throw new MojoExecutionException(
"Error writing dependencies into APPLICATION.MF", e);
}
}
// The maven2OsgiConverter assumes the artifact is a jar so we need our own
// This uses the same fallback scheme as the converter
private String getApplicationSymbolicName(Artifact artifact) {
if (instructions.containsKey(APPLICATION_SYMBOLICNAME)) {
return instructions.get(APPLICATION_SYMBOLICNAME).toString();
}
return artifact.getGroupId() + "." + artifact.getArtifactId();
}
private String getApplicationVersion() {
if (instructions.containsKey(APPLICATION_VERSION)) {
return instructions.get(APPLICATION_VERSION).toString();
}
return aQute.lib.osgi.Analyzer.cleanupVersion(project.getVersion());
}
protected File getBuildDir()
{
if ( buildDir == null )
{
buildDir = new File( workDirectory );
}
return buildDir;
}
private void includeCustomApplicationManifestFile()
throws IOException
{
if (applicationManifestFile == null) {
throw new NullPointerException("Application manifest file location not set. Use <generateManifest>true</generateManifest> if you want it to be generated.");
}
File appMfFile = applicationManifestFile;
if (appMfFile.exists()) {
getLog().info( "Using APPLICATION.MF "+ applicationManifestFile);
File metaInfDir = new File(getBuildDir(), "META-INF");
FileUtils.copyFileToDirectory( appMfFile, metaInfDir);
}
}
/**
* Return artifacts in 'compile' or 'runtime' scope only.
*/
private Set<Artifact> selectArtifacts(Set<Artifact> artifacts)
{
Set<Artifact> selected = new LinkedHashSet<Artifact>();
for (Artifact artifact : artifacts) {
String scope = artifact.getScope();
if (scope == null
|| Artifact.SCOPE_COMPILE.equals(scope)
|| Artifact.SCOPE_RUNTIME.equals(scope)) {
selected.add(artifact);
}
}
return selected;
}
}
| 8,175 |
0 | Create_ds/aries/samples/twitter/twitter-itests/src/test/java/org/apache/aries/sample/twitter | Create_ds/aries/samples/twitter/twitter-itests/src/test/java/org/apache/aries/sample/twitter/itest/TwitterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.sample.twitter.itest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
import static org.ops4j.pax.exam.CoreOptions.maven;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import static org.ops4j.pax.exam.CoreOptions.vmOption;
import static org.ops4j.pax.exam.CoreOptions.when;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.inject.Inject;
import org.apache.aries.application.DeploymentContent;
import org.apache.aries.application.DeploymentMetadata;
import org.apache.aries.application.management.AriesApplication;
import org.apache.aries.application.management.AriesApplicationContext;
import org.apache.aries.application.management.AriesApplicationManager;
import org.apache.aries.application.utils.AppConstants;
import org.apache.aries.itest.AbstractIntegrationTest;
import org.apache.felix.bundlerepository.Repository;
import org.apache.felix.bundlerepository.RepositoryAdmin;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.options.MavenArtifactUrlReference;
@RunWith(PaxExam.class)
public class TwitterTest extends AbstractIntegrationTest
{
public static final String CORE_BUNDLE_BY_VALUE = "core.bundle.by.value";
public static final String CORE_BUNDLE_BY_REFERENCE = "core.bundle.by.reference";
public static final String TRANSITIVE_BUNDLE_BY_VALUE = "transitive.bundle.by.value";
public static final String TRANSITIVE_BUNDLE_BY_REFERENCE = "transitive.bundle.by.reference";
public static final String USE_BUNDLE_BY_REFERENCE = "use.bundle.by.reference";
public static final String REPO_BUNDLE = "aries.bundle1";
public static final String HELLO_WORLD_CLIENT_BUNDLE="hello.world.client.bundle";
public static final String HELLO_WORLD_SERVICE_BUNDLE1="hello.world.service.bundle1";
public static final String HELLO_WORLD_SERVICE_BUNDLE2="hello.world.service.bundle2";
@Inject
RepositoryAdmin repositoryAdmin;
@Inject
AriesApplicationManager manager;
/**
* Test for ARIES-461
* Application that bring in dependency bundles from a bundle repository doesn't deploy
*
* @throws Exception
*/
@Test
public void testTwitter() throws Exception
{
// provision against the local runtime
System.setProperty(AppConstants.PROVISON_EXCLUDE_LOCAL_REPO_SYSPROP, "false");
deleteRepos();
MavenArtifactUrlReference twitterEbaUrl = maven("org.apache.aries.samples.twitter", "org.apache.aries.samples.twitter.eba").versionAsInProject().type("eba");
MavenArtifactUrlReference twitterCommonLangJar = maven("commons-lang", "commons-lang").versionAsInProject();
MavenArtifactUrlReference twitterJar = maven("org.apache.aries.samples.twitter", "org.apache.aries.samples.twitter.twitter4j").versionAsInProject();
// add the repository xml to the repository admin
String repositoryXML = getRepoContent("/obr/twitter/TwitterRepository.xml");
// replace the jar file url with the real url related to the environment
String repo = repositoryXML
.replaceAll("commons.lang.location", twitterCommonLangJar.getURL())
.replaceAll("twitter4j.location", twitterJar.getURL());
URL url = getRepoUrl(repo);
repositoryAdmin.addRepository(url);
AriesApplication app = manager.createApplication(new URL(twitterEbaUrl.getURL()));
app = manager.resolve(app);
DeploymentMetadata depMeta = app.getDeploymentMetadata();
List<DeploymentContent> provision = depMeta.getApplicationProvisionBundles();
Collection<DeploymentContent> useBundles = depMeta.getDeployedUseBundle();
Collection<DeploymentContent> appContent = depMeta.getApplicationDeploymentContents();
// We cannot be sure whether there are two or three provision bundles pulled in by Felix OBR as there is an outstanding defect
// https://issues.apache.org/jira/browse/FELIX-2672
// The workaround is to check we get the two bundles we are looking for, instead of insisting on just having two bundles.
List<String> provisionBundleSymbolicNames = new ArrayList<String>();
for (DeploymentContent dep : provision) {
provisionBundleSymbolicNames.add(dep.getContentName());
}
String provision_bundle1 = "org.apache.commons.lang";
String provision_bundle2 = "twitter4j";
assertTrue("Bundle " + provision_bundle1 + " not found.", provisionBundleSymbolicNames.contains(provision_bundle1));
assertTrue("Bundle " + provision_bundle2 + " not found.", provisionBundleSymbolicNames.contains(provision_bundle2));
assertEquals(useBundles.toString(), 0, useBundles.size());
assertEquals(appContent.toString(), 1, appContent.size());
AriesApplicationContext ctx = manager.install(app);
ctx.start();
}
private URL getRepoUrl(String repo) throws IOException,
MalformedURLException {
File repoFile = File.createTempFile("twitterRepo", "xml");
FileWriter writer = new FileWriter(repoFile);
writer.write(repo);
writer.close();
return repoFile.toURI().toURL();
}
private void deleteRepos() {
Repository[] repos = repositoryAdmin.listRepositories();
for (Repository repo : repos) {
repositoryAdmin.removeRepository(repo.getURI());
}
}
private String getRepoContent(String path) throws IOException {
StringBuilder repositoryXML = new StringBuilder();
InputStream resourceAsStream = this.getClass().getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(resourceAsStream));
String line;
while ((line = reader.readLine()) != null) {
repositoryXML.append(line);
repositoryXML.append("\r\n");
}
return repositoryXML.toString();
}
protected Option baseOptions() {
String localRepo = System.getProperty("maven.repo.local");
if (localRepo == null) {
localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository");
}
return composite(
junitBundles(),
mavenBundle("org.ops4j.pax.logging", "pax-logging-api", "1.7.2"),
mavenBundle("org.ops4j.pax.logging", "pax-logging-service", "1.7.2"),
mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(),
// this is how you set the default log level when using pax
// logging (logProfile)
systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
when(localRepo != null).useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo))
);
}
@Configuration
public Option[] configuration() {
return CoreOptions.options(
baseOptions(),
mavenBundle("org.osgi", "org.osgi.compendium").versionAsInProject(),
mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(),
mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(),
mavenBundle("org.apache.aries.application", "org.apache.aries.application.management").versionAsInProject(),
mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(),
mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime").versionAsInProject(),
mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.obr").versionAsInProject(),
mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").versionAsInProject(),
mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(),
mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(),
mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime.itest.interfaces").versionAsInProject(),
mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(),
mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint").versionAsInProject(),
mavenBundle("org.ow2.asm", "asm-all").versionAsInProject(),
mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy").versionAsInProject(),
mavenBundle("org.apache.aries.samples.twitter", "org.apache.aries.samples.twitter.twitter4j").versionAsInProject()
// For debugging
//vmOption ("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5010"),
);
}
}
| 8,176 |
0 | Create_ds/aries/samples/twitter/twitter-bundle/src/main/java/org/apache/aries/sample | Create_ds/aries/samples/twitter/twitter-bundle/src/main/java/org/apache/aries/sample/twitter/TwitterQuery.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.sample.twitter;
import java.util.List;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import org.apache.commons.lang.StringEscapeUtils;
public class TwitterQuery implements BundleActivator {
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
Twitter twitter = new Twitter();
Query query = new Query("from:theasf");
try {
QueryResult result = twitter.search(query);
List<Tweet> tweets = result.getTweets();
System.out.println("hits:" + tweets.size());
for (Tweet tweet : tweets) {
System.out.println(tweet.getFromUser() + ":" + StringEscapeUtils.unescapeXml(tweet.getText()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
}
}
| 8,177 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api/TradeServicesManager.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.api;
import java.util.ArrayList;
import java.util.List;
import org.apache.aries.samples.ariestrader.api.persistence.MarketSummaryDataBean;
/**
* TradeServicesManager interface provides an interface to be
* used for managing the implementations of TradeServices that
* are available.
*
*/
public interface TradeServicesManager {
/**
* Get CurrentModes that are registered
*/
public ArrayList<Integer> getCurrentModes();
/**
* Get the currently selected TradeServices
*/
public TradeServices getTradeServices();
/**
* Compute and return a snapshot of the current market
* conditions. This includes the TSIA - and index of the
* of the top 100 Trade stock quotes. The openTSIA(the index
* at the open), The volume of shares traded, Top Stocks gain
* and loss.
*
* This is a special version of this function which will cache
* the results provided by the currently selected
* TradeServices.
*
* @return A snapshot of the current market summary
*/
public MarketSummaryDataBean getMarketSummary() throws Exception;
}
| 8,178 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api/TradeDBManager.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.api;
import org.apache.aries.samples.ariestrader.api.persistence.RunStatsDataBean;
/**
* TradeDBManager interface centralizes and simplifies the DB
* configuration methods that are shared by some TradeServices
* implementations.
*
*/
public interface TradeDBManager {
/**
* Return a String containing the DBProductName configured for
* the current DataSource
*
* used by TradeBuildDB
*
* @return A String of the currently configured DataSource
*
*/
public String checkDBProductName() throws Exception;
/**
* Recreate DataBase Tables for AriesTrader
*
* used by TradeBuildDB
*
* @return boolean of success/failure in recreate of DB tables
*
*/
public boolean recreateDBTables(Object[] sqlBuffer, java.io.PrintWriter out) throws Exception;
/**
* Reset the statistics for the Test AriesTrader Scenario
*
* used by TradeConfigServlet
*
* @return the RunStatsDataBean
*
*/
public RunStatsDataBean resetTrade(boolean deleteAll) throws Exception;
}
| 8,179 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api/TradeServiceUtilities.java | /**
* Licensed to4the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file to
* You under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.api;
import org.apache.aries.samples.ariestrader.util.Log;
import org.apache.aries.samples.ariestrader.util.ServiceUtilities;
/**
* TradeServiceUtilities provides servlet specific client side
* utility functions.
*/
public class TradeServiceUtilities {
/**
* Lookup and return the TradeServices osgi service
*
* @return TradeServices
*
*/
public static final TradeServices getTradeServices() {
if (Log.doTrace())
Log.trace("TradeServiceUtilities:getTradeServices()");
return getTradeServices(null);
}
/**
* Lookup and return the TradeServices osgi service with filter
*
* @return TradeServices
*
*/
public static final TradeServices getTradeServices(String filter) {
if (Log.doTrace())
Log.trace("TradeServiceUtilities:getTradeServices()" , filter);
return (TradeServices) ServiceUtilities.getOSGIService(TradeServices.class.getName(), filter);
}
/**
* Lookup and return the TradeServicesManager osgi service
*
* @return TradeServicesManager
*
*/
public static final TradeServicesManager getTradeServicesManager() {
if (Log.doTrace())
Log.trace("TradeServiceUtilities:getTradeServicesManager()");
return (TradeServicesManager) ServiceUtilities.getOSGIService(TradeServicesManager.class.getName());
}
/**
* Lookup and return the TradeDBManager osgi service
*
* @return TradeDBManager
*
*/
public static final TradeDBManager getTradeDBManager() {
if (Log.doTrace())
Log.trace("TradeServiceUtilities:getTradeDBManager()");
return (TradeDBManager) ServiceUtilities.getOSGIService(TradeDBManager.class.getName());
}
} | 8,180 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api/TradeServices.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.api;
import java.math.BigDecimal;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Collection;
import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.AccountProfileDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.HoldingDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.MarketSummaryDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.OrderDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.QuoteDataBean;
import org.apache.aries.samples.ariestrader.util.TradeConfig;
/**
* TradeServices interface specifies the business methods provided by the Trade online broker application.
* These business methods represent the features and operations that can be performed by customers of
* the brokerage such as login, logout, get a stock quote, buy or sell a stock, etc.
* This interface is implemented by {@link Trade} providing an EJB implementation of these
* business methods and also by {@link TradeDirect} providing a JDBC implementation.
*
* @see Trade
* @see TradeDirect
*
*/
public interface TradeServices extends Remote {
/**
* Compute and return a snapshot of the current market conditions
* This includes the TSIA - an index of the price of the top 100 Trade stock quotes
* The openTSIA ( the index at the open)
* The volume of shares traded,
* Top Stocks gain and loss
*
* @return A snapshot of the current market summary
*/
public MarketSummaryDataBean getMarketSummary() throws Exception, RemoteException;
/**
* Purchase a stock and create a new holding for the given user.
* Given a stock symbol and quantity to purchase, retrieve the current quote price,
* debit the user's account balance, and add holdings to user's portfolio.
* buy/sell are asynchronous, using J2EE messaging,
* A new order is created and submitted for processing to the TradeBroker
*
* @param userID the customer requesting the stock purchase
* @param symbol the symbol of the stock being purchased
* @param quantity the quantity of shares to purchase
* @return OrderDataBean providing the status of the newly created buy order
*/
public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception, RemoteException;
/**
* Sell a stock holding and removed the holding for the given user.
* Given a Holding, retrieve current quote, credit user's account,
* and reduce holdings in user's portfolio.
*
* @param userID the customer requesting the sell
* @param holdingID the users holding to be sold
* @return OrderDataBean providing the status of the newly created sell order
*/
public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) throws Exception, RemoteException;
/**
* Queue the Order identified by orderID to be processed
*
* Orders are submitted through JMS to a Trading Broker
* and completed asynchronously. This method queues the order for processing
*
* The boolean twoPhase specifies to the server implementation whether or not the
* method is to participate in a global transaction
*
* @param orderID the Order being queued for processing
* @return OrderDataBean providing the status of the completed order
*/
public void queueOrder(Integer orderID, boolean twoPhase) throws Exception, RemoteException;
/**
* Complete the Order identefied by orderID
* Orders are submitted through JMS to a Trading agent
* and completed asynchronously. This method completes the order
* For a buy, the stock is purchased creating a holding and the users account is debited
* For a sell, the stock holding is removed and the users account is credited with the proceeds
*
* The boolean twoPhase specifies to the server implementation whether or not the
* method is to participate in a global transaction
*
* @param orderID the Order to complete
* @return OrderDataBean providing the status of the completed order
*/
public OrderDataBean completeOrder(Integer orderID, boolean twoPhase) throws Exception, RemoteException;
/**
* Cancel the Order identefied by orderID
*
* The boolean twoPhase specifies to the server implementation whether or not the
* method is to participate in a global transaction
*
* @param orderID the Order to complete
* @return OrderDataBean providing the status of the completed order
*/
public void cancelOrder(Integer orderID, boolean twoPhase) throws Exception, RemoteException;
/**
* Signify an order has been completed for the given userID
*
* @param userID the user for which an order has completed
* @param orderID the order which has completed
*
*/
public void orderCompleted(String userID, Integer orderID) throws Exception, RemoteException;
/**
* Get the collection of all orders for a given account
*
* @param userID the customer account to retrieve orders for
* @return Collection OrderDataBeans providing detailed order information
*/
public Collection getOrders(String userID) throws Exception, RemoteException;
/**
* Get the collection of completed orders for a given account that need to be alerted to the user
*
* @param userID the customer account to retrieve orders for
* @return Collection OrderDataBeans providing detailed order information
*/
public Collection getClosedOrders(String userID) throws Exception, RemoteException;
/**
* Given a market symbol, price, and details, create and return a new {@link QuoteDataBean}
*
* @param symbol the symbol of the stock
* @param price the current stock price
* @param details a short description of the stock or company
* @return a new QuoteDataBean or null if Quote could not be created
*/
public QuoteDataBean createQuote(String symbol, String companyName, BigDecimal price) throws Exception, RemoteException;
/**
* Return a {@link QuoteDataBean} describing a current quote for the given stock symbol
*
* @param symbol the stock symbol to retrieve the current Quote
* @return the QuoteDataBean
*/
public QuoteDataBean getQuote(String symbol) throws Exception, RemoteException;
/**
* Return a {@link java.util.Collection} of {@link QuoteDataBean}
* describing all current quotes
* @return A collection of QuoteDataBean
*/
public Collection getAllQuotes() throws Exception, RemoteException;
/**
* Update the stock quote price and volume for the specified stock symbol
*
* @param symbol for stock quote to update
* @param price the updated quote price
* @return the QuoteDataBean describing the stock
*/
public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal newPrice, double sharesTraded) throws Exception, RemoteException;
/**
* Return the portfolio of stock holdings for the specified customer
* as a collection of HoldingDataBeans
*
* @param userID the customer requesting the portfolio
* @return Collection of the users portfolio of stock holdings
*/
public Collection getHoldings(String userID) throws Exception, RemoteException;
/**
* Return a specific user stock holding identified by the holdingID
*
* @param holdingID the holdingID to return
* @return a HoldingDataBean describing the holding
*/
public HoldingDataBean getHolding(Integer holdingID) throws Exception, RemoteException;
/**
* Return an AccountDataBean object for userID describing the account
*
* @param userID the account userID to lookup
* @return User account data in AccountDataBean
*/
public AccountDataBean getAccountData(String userID)
throws Exception, RemoteException;
/**
* Return an AccountProfileDataBean for userID providing the users profile
*
* @param userID the account userID to lookup
* @param User account profile data in AccountProfileDataBean
*/
public AccountProfileDataBean getAccountProfileData(String userID) throws Exception, RemoteException;
/**
* Update userID's account profile information using the provided AccountProfileDataBean object
*
* @param userID the account userID to lookup
* @param password the updated password
* @param fullName the updated fullName
* @param address the updated address
* @param address the updated email
* @param the updated creditcard
*/
public AccountProfileDataBean updateAccountProfile(String userID, String password, String fullName, String address, String email, String creditcard) throws Exception, RemoteException;
/**
* Attempt to authenticate and login a user with the given password
*
* @param userID the customer to login
* @param password the password entered by the customer for authentication
* @return User account data in AccountDataBean
*/
public AccountDataBean login(String userID, String password) throws Exception, RemoteException;
/**
* Logout the given user
*
* @param userID the customer to logout
* @return the login status
*/
public void logout(String userID) throws Exception, RemoteException;
/**
* Register a new Trade customer.
* Create a new user profile, user registry entry, account with initial balance,
* and empty portfolio.
*
* @param userID the new customer to register
* @param password the customers password
* @param fullname the customers fullname
* @param address the customers street address
* @param email the customers email address
* @param creditcard the customers creditcard number
* @param initialBalance the amount to charge to the customers credit to open the account and set the initial balance
* @return the userID if successful, null otherwise
*/
public AccountDataBean register(String userID,
String password,
String fullname,
String address,
String email,
String creditcard,
BigDecimal openBalance) throws Exception, RemoteException;
/**
* Get mode - returns the persistence mode
* (TradeConfig.JDBC, JPA, etc...)
*
* @return TradeConfig.ModeType
*/
public TradeConfig.ModeType getMode();
}
| 8,181 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api/persistence/QuoteDataBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.api.persistence;
import java.math.BigDecimal;
public interface QuoteDataBean {
public String toString();
public String toHTML();
public String getSymbol();
public void setSymbol(String symbol);
public String getCompanyName();
public void setCompanyName(String companyName);
public BigDecimal getPrice();
public void setPrice(BigDecimal price);
public BigDecimal getOpen();
public void setOpen(BigDecimal open);
public BigDecimal getLow();
public void setLow(BigDecimal low);
public BigDecimal getHigh();
public void setHigh(BigDecimal high);
public double getChange();
public void setChange(double change);
public double getVolume();
public void setVolume(double volume);
}
| 8,182 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api/persistence/AccountProfileDataBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.api.persistence;
public interface AccountProfileDataBean {
public String toString();
public String toHTML();
public String getUserID();
public void setUserID(String userID);
public String getPassword();
public void setPassword(String password);
public String getFullName();
public void setFullName(String fullName);
public String getAddress();
public void setAddress(String address);
public String getEmail();
public void setEmail(String email);
public String getCreditCard();
public void setCreditCard(String creditCard);
public AccountDataBean getAccount();
public void setAccount(AccountDataBean account);
}
| 8,183 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api/persistence/RunStatsDataBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.api.persistence;
import java.io.Serializable;
public class RunStatsDataBean implements Serializable
{
//Constructors
public RunStatsDataBean(){ }
// count of trade users in the database (users w/ userID like 'uid:%')
private int tradeUserCount;
// count of trade stocks in the database (stocks w/ symbol like 's:%')
private int tradeStockCount;
// count of new registered users in this run (users w/ userID like 'ru:%') -- random user
private int newUserCount;
// sum of logins by trade users
private int sumLoginCount;
// sum of logouts by trade users
private int sumLogoutCount;
// count of holdings of trade users
private int holdingCount;
// count of orders of trade users
private int orderCount;
// count of buy orders of trade users
private int buyOrderCount;
// count of sell orders of trade users
private int sellOrderCount;
// count of canceled orders of trade users
private int cancelledOrderCount;
// count of open orders of trade users
private int openOrderCount;
// count of orders deleted during this trade Reset
private int deletedOrderCount;
public String toString()
{
return "\n\tRunStatsData for reset at " + new java.util.Date()
+ "\n\t\t tradeUserCount: " + getTradeUserCount()
+ "\n\t\t newUserCount: " + getNewUserCount()
+ "\n\t\t sumLoginCount: " + getSumLoginCount()
+ "\n\t\t sumLogoutCount: " + getSumLogoutCount()
+ "\n\t\t holdingCount: " + getHoldingCount()
+ "\n\t\t orderCount: " + getOrderCount()
+ "\n\t\t buyOrderCount: " + getBuyOrderCount()
+ "\n\t\t sellOrderCount: " + getSellOrderCount()
+ "\n\t\t cancelledOrderCount: " + getCancelledOrderCount()
+ "\n\t\t openOrderCount: " + getOpenOrderCount()
+ "\n\t\t deletedOrderCount: " + getDeletedOrderCount()
;
}
/**
* Gets the tradeUserCount
* @return Returns a int
*/
public int getTradeUserCount() {
return tradeUserCount;
}
/**
* Sets the tradeUserCount
* @param tradeUserCount The tradeUserCount to set
*/
public void setTradeUserCount(int tradeUserCount) {
this.tradeUserCount = tradeUserCount;
}
/**
* Gets the newUserCount
* @return Returns a int
*/
public int getNewUserCount() {
return newUserCount;
}
/**
* Sets the newUserCount
* @param newUserCount The newUserCount to set
*/
public void setNewUserCount(int newUserCount) {
this.newUserCount = newUserCount;
}
/**
* Gets the sumLoginCount
* @return Returns a int
*/
public int getSumLoginCount() {
return sumLoginCount;
}
/**
* Sets the sumLoginCount
* @param sumLoginCount The sumLoginCount to set
*/
public void setSumLoginCount(int sumLoginCount) {
this.sumLoginCount = sumLoginCount;
}
/**
* Gets the sumLogoutCount
* @return Returns a int
*/
public int getSumLogoutCount() {
return sumLogoutCount;
}
/**
* Sets the sumLogoutCount
* @param sumLogoutCount The sumLogoutCount to set
*/
public void setSumLogoutCount(int sumLogoutCount) {
this.sumLogoutCount = sumLogoutCount;
}
/**
* Gets the holdingCount
* @return Returns a int
*/
public int getHoldingCount() {
return holdingCount;
}
/**
* Sets the holdingCount
* @param holdingCount The holdingCount to set
*/
public void setHoldingCount(int holdingCount) {
this.holdingCount = holdingCount;
}
/**
* Gets the buyOrderCount
* @return Returns a int
*/
public int getBuyOrderCount() {
return buyOrderCount;
}
/**
* Sets the buyOrderCount
* @param buyOrderCount The buyOrderCount to set
*/
public void setBuyOrderCount(int buyOrderCount) {
this.buyOrderCount = buyOrderCount;
}
/**
* Gets the sellOrderCount
* @return Returns a int
*/
public int getSellOrderCount() {
return sellOrderCount;
}
/**
* Sets the sellOrderCount
* @param sellOrderCount The sellOrderCount to set
*/
public void setSellOrderCount(int sellOrderCount) {
this.sellOrderCount = sellOrderCount;
}
/**
* Gets the cancelledOrderCount
* @return Returns a int
*/
public int getCancelledOrderCount() {
return cancelledOrderCount;
}
/**
* Sets the cancelledOrderCount
* @param cancelledOrderCount The cancelledOrderCount to set
*/
public void setCancelledOrderCount(int cancelledOrderCount) {
this.cancelledOrderCount = cancelledOrderCount;
}
/**
* Gets the openOrderCount
* @return Returns a int
*/
public int getOpenOrderCount() {
return openOrderCount;
}
/**
* Sets the openOrderCount
* @param openOrderCount The openOrderCount to set
*/
public void setOpenOrderCount(int openOrderCount) {
this.openOrderCount = openOrderCount;
}
/**
* Gets the deletedOrderCount
* @return Returns a int
*/
public int getDeletedOrderCount() {
return deletedOrderCount;
}
/**
* Sets the deletedOrderCount
* @param deletedOrderCount The deletedOrderCount to set
*/
public void setDeletedOrderCount(int deletedOrderCount) {
this.deletedOrderCount = deletedOrderCount;
}
/**
* Gets the orderCount
* @return Returns a int
*/
public int getOrderCount() {
return orderCount;
}
/**
* Sets the orderCount
* @param orderCount The orderCount to set
*/
public void setOrderCount(int orderCount) {
this.orderCount = orderCount;
}
/**
* Gets the tradeStockCount
* @return Returns a int
*/
public int getTradeStockCount() {
return tradeStockCount;
}
/**
* Sets the tradeStockCount
* @param tradeStockCount The tradeStockCount to set
*/
public void setTradeStockCount(int tradeStockCount) {
this.tradeStockCount = tradeStockCount;
}
}
| 8,184 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api/persistence/OrderDataBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.api.persistence;
import java.math.BigDecimal;
import java.util.Date;
public interface OrderDataBean {
public String toString();
public String toHTML();
public Integer getOrderID();
public void setOrderID(Integer orderID);
public String getOrderType();
public void setOrderType(String orderType);
public String getOrderStatus();
public void setOrderStatus(String orderStatus);
public Date getOpenDate();
public void setOpenDate(Date openDate);
public Date getCompletionDate();
public void setCompletionDate(Date completionDate);
public double getQuantity();
public void setQuantity(double quantity);
public BigDecimal getPrice();
public void setPrice(BigDecimal price);
public BigDecimal getOrderFee();
public void setOrderFee(BigDecimal orderFee);
public String getSymbol();
public void setSymbol(String symbol);
public AccountDataBean getAccount();
public void setAccount(AccountDataBean account);
public QuoteDataBean getQuote();
public void setQuote(QuoteDataBean quote);
public HoldingDataBean getHolding();
public void setHolding(HoldingDataBean holding);
public boolean isBuy();
public boolean isSell();
public boolean isOpen();
public boolean isCompleted();
public boolean isCancelled();
public void cancel();
}
| 8,185 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api/persistence/MarketSummaryDataBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.api.persistence;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import org.apache.aries.samples.ariestrader.util.FinancialUtils;
import org.apache.aries.samples.ariestrader.util.Log;
import org.apache.aries.samples.ariestrader.util.TradeConfig;
public class MarketSummaryDataBean implements Serializable
{
private BigDecimal TSIA; /* Trade Stock Index Average */
private BigDecimal openTSIA; /* Trade Stock Index Average at the open */
private double volume; /* volume of shares traded */
private Collection topGainers; /* Collection of top gaining stocks */
private Collection topLosers; /* Collection of top losing stocks */
//FUTURE private Collection topVolume; /* Collection of top stocks by volume */
private Date summaryDate; /* Date this summary was taken */
//cache the gainPercent once computed for this bean
private BigDecimal gainPercent=null;
public MarketSummaryDataBean(){ }
public MarketSummaryDataBean(BigDecimal TSIA,
BigDecimal openTSIA,
double volume,
Collection topGainers,
Collection topLosers//, Collection topVolume
)
{
setTSIA(TSIA);
setOpenTSIA(openTSIA);
setVolume(volume);
setTopGainers(topGainers);
setTopLosers(topLosers);
setSummaryDate(new java.sql.Date(System.currentTimeMillis()));
gainPercent = FinancialUtils.computeGainPercent(getTSIA(), getOpenTSIA());
}
public String toString()
{
StringBuilder ret = new StringBuilder();
ret.append("\n\tMarket Summary at: ").append(getSummaryDate())
.append("\n\t\t TSIA:").append(getTSIA())
.append("\n\t\t openTSIA:").append(getOpenTSIA())
.append("\n\t\t gain:").append(getGainPercent())
.append("\n\t\t volume:").append(getVolume());
if ( (getTopGainers()==null) || (getTopLosers()==null) )
return ret.toString();
ret.append("\n\t\t Current Top Gainers:");
Iterator it = getTopGainers().iterator();
while ( it.hasNext() )
{
QuoteDataBean quoteData = (QuoteDataBean) it.next();
ret.append("\n\t\t\t").append(quoteData.toString());
}
ret.append("\n\t\t Current Top Losers:");
it = getTopLosers().iterator();
while ( it.hasNext() )
{
QuoteDataBean quoteData = (QuoteDataBean) it.next();
ret.append("\n\t\t\t").append(quoteData.toString());
}
return ret.toString();
}
public String toHTML()
{
String ret = "<BR>Market Summary at: " + getSummaryDate()
+ "<LI> TSIA:" + getTSIA() + "</LI>"
+ "<LI> openTSIA:" + getOpenTSIA() + "</LI>"
+ "<LI> volume:" + getVolume() + "</LI>"
;
if ( (getTopGainers()==null) || (getTopLosers()==null) )
return ret;
ret += "<BR> Current Top Gainers:";
Iterator it = getTopGainers().iterator();
while ( it.hasNext() )
{
QuoteDataBean quoteData = (QuoteDataBean) it.next();
ret += ( "<LI>" + quoteData.toString() + "</LI>" );
}
ret += "<BR> Current Top Losers:";
it = getTopLosers().iterator();
while ( it.hasNext() )
{
QuoteDataBean quoteData = (QuoteDataBean) it.next();
ret += ( "<LI>" + quoteData.toString() + "</LI>" );
}
return ret;
}
public void print()
{
Log.log( this.toString() );
}
public BigDecimal getGainPercent()
{
if ( gainPercent == null )
gainPercent = FinancialUtils.computeGainPercent(getTSIA(), getOpenTSIA());
return gainPercent;
}
/**
* Gets the tSIA
* @return Returns a BigDecimal
*/
public BigDecimal getTSIA() {
return TSIA;
}
/**
* Sets the tSIA
* @param tSIA The tSIA to set
*/
public void setTSIA(BigDecimal tSIA) {
TSIA = tSIA;
}
/**
* Gets the openTSIA
* @return Returns a BigDecimal
*/
public BigDecimal getOpenTSIA() {
return openTSIA;
}
/**
* Sets the openTSIA
* @param openTSIA The openTSIA to set
*/
public void setOpenTSIA(BigDecimal openTSIA) {
this.openTSIA = openTSIA;
}
/**
* Gets the volume
* @return Returns a BigDecimal
*/
public double getVolume() {
return volume;
}
/**
* Sets the volume
* @param volume The volume to set
*/
public void setVolume(double volume) {
this.volume = volume;
}
/**
* Gets the topGainers
* @return Returns a Collection
*/
public Collection getTopGainers() {
return topGainers;
}
/**
* Sets the topGainers
* @param topGainers The topGainers to set
*/
public void setTopGainers(Collection topGainers) {
this.topGainers = topGainers;
}
/**
* Gets the topLosers
* @return Returns a Collection
*/
public Collection getTopLosers() {
return topLosers;
}
/**
* Sets the topLosers
* @param topLosers The topLosers to set
*/
public void setTopLosers(Collection topLosers) {
this.topLosers = topLosers;
}
/**
* Gets the summaryDate
* @return Returns a Date
*/
public Date getSummaryDate() {
return summaryDate;
}
/**
* Sets the summaryDate
* @param summaryDate The summaryDate to set
*/
public void setSummaryDate(Date summaryDate) {
this.summaryDate = summaryDate;
}
}
| 8,186 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api/persistence/AccountDataBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.api.persistence;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
public interface AccountDataBean {
public String toString();
public String toHTML();
public Integer getAccountID();
public void setAccountID(Integer accountID);
public int getLoginCount();
public void setLoginCount(int loginCount);
public int getLogoutCount();
public void setLogoutCount(int logoutCount);
public Date getLastLogin();
public void setLastLogin(Date lastLogin);
public Date getCreationDate();
public void setCreationDate(Date creationDate);
public BigDecimal getBalance();
public void setBalance(BigDecimal balance);
public BigDecimal getOpenBalance();
public void setOpenBalance(BigDecimal openBalance);
public String getProfileID();
public void setProfileID(String profileID);
public Collection<OrderDataBean> getOrders();
public Collection<HoldingDataBean> getHoldings();
public AccountProfileDataBean getProfile();
public void setProfile(AccountProfileDataBean profile);
public void login(String password);
public void logout();
} | 8,187 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api | Create_ds/aries/samples/ariestrader/modules/ariestrader-api/src/main/java/org/apache/aries/samples/ariestrader/api/persistence/HoldingDataBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.api.persistence;
import java.math.BigDecimal;
import java.util.Date;
public interface HoldingDataBean {
public String toString();
public String toHTML();
public Integer getHoldingID();
public void setHoldingID(Integer holdingID);
public double getQuantity();
public void setQuantity(double quantity);
public BigDecimal getPurchasePrice();
public void setPurchasePrice(BigDecimal purchasePrice);
public Date getPurchaseDate();
public void setPurchaseDate(Date purchaseDate);
public String getQuoteID();
public void setQuoteID(String quoteID);
public AccountDataBean getAccount();
public void setAccount(AccountDataBean account);
public QuoteDataBean getQuote();
public void setQuote(QuoteDataBean quote);
}
| 8,188 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-beans/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-beans/src/main/java/org/apache/aries/samples/ariestrader/beans/AccountDataBeanImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.beans;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import org.apache.aries.samples.ariestrader.util.Log;
import org.apache.aries.samples.ariestrader.util.TradeConfig;
import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.AccountProfileDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.HoldingDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.OrderDataBean;
public class AccountDataBeanImpl implements AccountDataBean, Serializable {
private Integer accountID; /* accountID */
private int loginCount; /* loginCount */
private int logoutCount; /* logoutCount */
private Date lastLogin; /* lastLogin Date */
private Date creationDate; /* creationDate */
private BigDecimal balance; /* balance */
private BigDecimal openBalance; /* open balance */
private Collection<OrderDataBean> orders;
private Collection<HoldingDataBean> holdings;
private AccountProfileDataBean profile;
/* Accessor methods for relationship fields are only included for the AccountProfile profileID */
private String profileID;
public AccountDataBeanImpl() {
}
public AccountDataBeanImpl(Integer accountID,
int loginCount,
int logoutCount,
Date lastLogin,
Date creationDate,
BigDecimal balance,
BigDecimal openBalance,
String profileID) {
setAccountID(accountID);
setLoginCount(loginCount);
setLogoutCount(logoutCount);
setLastLogin(lastLogin);
setCreationDate(creationDate);
setBalance(balance);
setOpenBalance(openBalance);
setProfileID(profileID);
}
public AccountDataBeanImpl(int loginCount,
int logoutCount,
Date lastLogin,
Date creationDate,
BigDecimal balance,
BigDecimal openBalance,
String profileID) {
setLoginCount(loginCount);
setLogoutCount(logoutCount);
setLastLogin(lastLogin);
setCreationDate(creationDate);
setBalance(balance);
setOpenBalance(openBalance);
setProfileID(profileID);
}
public static AccountDataBean getRandomInstance() {
return new AccountDataBeanImpl(new Integer(TradeConfig.rndInt(100000)), //accountID
TradeConfig.rndInt(10000), //loginCount
TradeConfig.rndInt(10000), //logoutCount
new java.util.Date(), //lastLogin
new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)), //creationDate
TradeConfig.rndBigDecimal(1000000.0f), //balance
TradeConfig.rndBigDecimal(1000000.0f), //openBalance
TradeConfig.rndUserID() //profileID
);
}
public String toString() {
return "\n\tAccount Data for account: " + getAccountID()
+ "\n\t\t loginCount:" + getLoginCount()
+ "\n\t\t logoutCount:" + getLogoutCount()
+ "\n\t\t lastLogin:" + getLastLogin()
+ "\n\t\t creationDate:" + getCreationDate()
+ "\n\t\t balance:" + getBalance()
+ "\n\t\t openBalance:" + getOpenBalance()
+ "\n\t\t profileID:" + getProfileID()
;
}
public String toHTML() {
return "<BR>Account Data for account: <B>" + getAccountID() + "</B>"
+ "<LI> loginCount:" + getLoginCount() + "</LI>"
+ "<LI> logoutCount:" + getLogoutCount() + "</LI>"
+ "<LI> lastLogin:" + getLastLogin() + "</LI>"
+ "<LI> creationDate:" + getCreationDate() + "</LI>"
+ "<LI> balance:" + getBalance() + "</LI>"
+ "<LI> openBalance:" + getOpenBalance() + "</LI>"
+ "<LI> profileID:" + getProfileID() + "</LI>"
;
}
public void print() {
Log.log(this.toString());
}
public Integer getAccountID() {
return accountID;
}
public void setAccountID(Integer accountID) {
this.accountID = accountID;
}
public int getLoginCount() {
return loginCount;
}
public void setLoginCount(int loginCount) {
this.loginCount = loginCount;
}
public int getLogoutCount() {
return logoutCount;
}
public void setLogoutCount(int logoutCount) {
this.logoutCount = logoutCount;
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public BigDecimal getOpenBalance() {
return openBalance;
}
public void setOpenBalance(BigDecimal openBalance) {
this.openBalance = openBalance;
}
public String getProfileID() {
return profileID;
}
public void setProfileID(String profileID) {
this.profileID = profileID;
}
public Collection<OrderDataBean> getOrders() {
return orders;
}
public void setOrders(Collection<OrderDataBean> orders) {
this.orders = orders;
}
public Collection<HoldingDataBean> getHoldings() {
return holdings;
}
public void setHoldings(Collection<HoldingDataBean> holdings) {
this.holdings = holdings;
}
public AccountProfileDataBean getProfile() {
return profile;
}
public void setProfile(AccountProfileDataBean profile) {
this.profile = profile;
}
public void login(String password) {
AccountProfileDataBean profile = getProfile();
if ((profile == null) || (profile.getPassword().equals(password) == false)) {
String error = "AccountBean:Login failure for account: " + getAccountID() +
((profile == null) ? "null AccountProfile" :
"\n\tIncorrect password-->" + profile.getUserID() + ":" + profile.getPassword());
throw new RuntimeException(error);
}
setLastLogin(new Timestamp(System.currentTimeMillis()));
setLoginCount(getLoginCount() + 1);
}
public void logout() {
setLogoutCount(getLogoutCount() + 1);
}
@Override
public int hashCode() {
int hash = 0;
hash += (this.accountID != null ? this.accountID.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof AccountDataBeanImpl)) {
return false;
}
AccountDataBeanImpl other = (AccountDataBeanImpl)object;
if (this.accountID != other.accountID && (this.accountID == null || !this.accountID.equals(other.accountID))) return false;
return true;
}
} | 8,189 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-beans/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-beans/src/main/java/org/apache/aries/samples/ariestrader/beans/AccountProfileDataBeanImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.beans;
import org.apache.aries.samples.ariestrader.util.Log;
import org.apache.aries.samples.ariestrader.util.TradeConfig;
import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.AccountProfileDataBean;
public class AccountProfileDataBeanImpl implements AccountProfileDataBean, java.io.Serializable {
private String userID; /* userID */
private String passwd; /* password */
private String fullName; /* fullName */
private String address; /* address */
private String email; /* email */
private String creditCard; /* creditCard */
private AccountDataBean account;
public AccountProfileDataBeanImpl() {
}
public AccountProfileDataBeanImpl(String userID,
String password,
String fullName,
String address,
String email,
String creditCard) {
setUserID(userID);
setPassword(password);
setFullName(fullName);
setAddress(address);
setEmail(email);
setCreditCard(creditCard);
}
public static AccountProfileDataBean getRandomInstance() {
return new AccountProfileDataBeanImpl(
TradeConfig.rndUserID(), // userID
TradeConfig.rndUserID(), // passwd
TradeConfig.rndFullName(), // fullname
TradeConfig.rndAddress(), // address
TradeConfig.rndEmail(TradeConfig.rndUserID()), //email
TradeConfig.rndCreditCard() // creditCard
);
}
public String toString() {
return "\n\tAccount Profile Data for userID:" + getUserID()
+ "\n\t\t passwd:" + getPassword()
+ "\n\t\t fullName:" + getFullName()
+ "\n\t\t address:" + getAddress()
+ "\n\t\t email:" + getEmail()
+ "\n\t\t creditCard:" + getCreditCard()
;
}
public String toHTML() {
return "<BR>Account Profile Data for userID: <B>" + getUserID() + "</B>"
+ "<LI> passwd:" + getPassword() + "</LI>"
+ "<LI> fullName:" + getFullName() + "</LI>"
+ "<LI> address:" + getAddress() + "</LI>"
+ "<LI> email:" + getEmail() + "</LI>"
+ "<LI> creditCard:" + getCreditCard() + "</LI>"
;
}
public void print() {
Log.log(this.toString());
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getPassword() {
return passwd;
}
public void setPassword(String password) {
this.passwd = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCreditCard() {
return creditCard;
}
public void setCreditCard(String creditCard) {
this.creditCard = creditCard;
}
public AccountDataBean getAccount() {
return account;
}
public void setAccount(AccountDataBean account) {
this.account = account;
}
@Override
public int hashCode() {
int hash = 0;
hash += (this.userID != null ? this.userID.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof AccountProfileDataBeanImpl)) {
return false;
}
AccountProfileDataBeanImpl other = (AccountProfileDataBeanImpl)object;
if (this.userID != other.userID && (this.userID == null || !this.userID.equals(other.userID))) return false;
return true;
}
}
| 8,190 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-beans/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-beans/src/main/java/org/apache/aries/samples/ariestrader/beans/HoldingDataBeanImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.beans;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import org.apache.aries.samples.ariestrader.util.Log;
import org.apache.aries.samples.ariestrader.util.TradeConfig;
import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.HoldingDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.QuoteDataBean;
public class HoldingDataBeanImpl implements HoldingDataBean, Serializable {
/* persistent/relationship fields */
private Integer holdingID; /* holdingID */
private double quantity; /* quantity */
private BigDecimal purchasePrice; /* purchasePrice */
private Date purchaseDate; /* purchaseDate */
private String quoteID; /* Holding(*) ---> Quote(1) */
private AccountDataBean account;
private QuoteDataBean quote;
public HoldingDataBeanImpl() {
}
public HoldingDataBeanImpl(Integer holdingID,
double quantity,
BigDecimal purchasePrice,
Date purchaseDate,
String quoteID) {
setHoldingID(holdingID);
setQuantity(quantity);
setPurchasePrice(purchasePrice);
setPurchaseDate(purchaseDate);
setQuoteID(quoteID);
}
public HoldingDataBeanImpl(double quantity,
BigDecimal purchasePrice,
Date purchaseDate,
AccountDataBean account,
QuoteDataBean quote) {
setQuantity(quantity);
setPurchasePrice(purchasePrice);
setPurchaseDate(purchaseDate);
setAccount(account);
setQuote(quote);
}
public static HoldingDataBean getRandomInstance() {
return new HoldingDataBeanImpl(
new Integer(TradeConfig.rndInt(100000)), //holdingID
TradeConfig.rndQuantity(), //quantity
TradeConfig.rndBigDecimal(1000.0f), //purchasePrice
new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)), //purchaseDate
TradeConfig.rndSymbol() // symbol
);
}
public String toString() {
return "\n\tHolding Data for holding: " + getHoldingID()
+ "\n\t\t quantity:" + getQuantity()
+ "\n\t\t purchasePrice:" + getPurchasePrice()
+ "\n\t\t purchaseDate:" + getPurchaseDate()
+ "\n\t\t quoteID:" + getQuoteID()
;
}
public String toHTML() {
return "<BR>Holding Data for holding: " + getHoldingID() + "</B>"
+ "<LI> quantity:" + getQuantity() + "</LI>"
+ "<LI> purchasePrice:" + getPurchasePrice() + "</LI>"
+ "<LI> purchaseDate:" + getPurchaseDate() + "</LI>"
+ "<LI> quoteID:" + getQuoteID() + "</LI>"
;
}
public void print() {
Log.log(this.toString());
}
public Integer getHoldingID() {
return holdingID;
}
public void setHoldingID(Integer holdingID) {
this.holdingID = holdingID;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public BigDecimal getPurchasePrice() {
return purchasePrice;
}
public void setPurchasePrice(BigDecimal purchasePrice) {
this.purchasePrice = purchasePrice;
}
public Date getPurchaseDate() {
return purchaseDate;
}
public void setPurchaseDate(Date purchaseDate) {
this.purchaseDate = purchaseDate;
}
public String getQuoteID() {
if (quote != null) {
return quote.getSymbol();
}
return quoteID;
}
public void setQuoteID(String quoteID) {
this.quoteID = quoteID;
}
public AccountDataBean getAccount() {
return account;
}
public void setAccount(AccountDataBean account) {
this.account = account;
}
public QuoteDataBean getQuote() {
return quote;
}
public void setQuote(QuoteDataBean quote) {
this.quote = quote;
}
@Override
public int hashCode() {
int hash = 0;
hash += (this.holdingID != null ? this.holdingID.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof HoldingDataBeanImpl)) {
return false;
}
HoldingDataBeanImpl other = (HoldingDataBeanImpl) object;
if (this.holdingID != other.holdingID && (this.holdingID == null || !this.holdingID.equals(other.holdingID))) return false;
return true;
}
}
| 8,191 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-beans/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-beans/src/main/java/org/apache/aries/samples/ariestrader/beans/QuoteDataBeanImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.beans;
import java.io.Serializable;
import java.math.BigDecimal;
import org.apache.aries.samples.ariestrader.util.Log;
import org.apache.aries.samples.ariestrader.util.TradeConfig;
import org.apache.aries.samples.ariestrader.api.persistence.QuoteDataBean;
public class QuoteDataBeanImpl implements QuoteDataBean, Serializable {
private String symbol; /* symbol */
private String companyName; /* companyName */
private double volume; /* volume */
private BigDecimal price; /* price */
private BigDecimal open1; /* open1 price */
private BigDecimal low; /* low price */
private BigDecimal high; /* high price */
private double change1; /* price change */
public QuoteDataBeanImpl() {
}
public QuoteDataBeanImpl(String symbol, String companyName, double volume,
BigDecimal price, BigDecimal open, BigDecimal low,
BigDecimal high, double change) {
setSymbol(symbol);
setCompanyName(companyName);
setVolume(volume);
setPrice(price);
setOpen(open);
setLow(low);
setHigh(high);
setChange(change);
}
public static QuoteDataBean getRandomInstance() {
return new QuoteDataBeanImpl(
TradeConfig.rndSymbol(), //symbol
TradeConfig.rndSymbol() + " Incorporated", //Company Name
TradeConfig.rndFloat(100000), //volume
TradeConfig.rndBigDecimal(1000.0f), //price
TradeConfig.rndBigDecimal(1000.0f), //open1
TradeConfig.rndBigDecimal(1000.0f), //low
TradeConfig.rndBigDecimal(1000.0f), //high
TradeConfig.rndFloat(100000) //volume
);
}
//Create a "zero" value QuoteDataBeanImpl for the given symbol
public QuoteDataBeanImpl(String symbol) {
setSymbol(symbol);
}
public String toString() {
return "\n\tQuote Data for: " + getSymbol()
+ "\n\t\t companyName: " + getCompanyName()
+ "\n\t\t volume: " + getVolume()
+ "\n\t\t price: " + getPrice()
+ "\n\t\t open1: " + getOpen()
+ "\n\t\t low: " + getLow()
+ "\n\t\t high: " + getHigh()
+ "\n\t\t change1: " + getChange()
;
}
public String toHTML() {
return "<BR>Quote Data for: " + getSymbol()
+ "<LI> companyName: " + getCompanyName() + "</LI>"
+ "<LI> volume: " + getVolume() + "</LI>"
+ "<LI> price: " + getPrice() + "</LI>"
+ "<LI> open1: " + getOpen() + "</LI>"
+ "<LI> low: " + getLow() + "</LI>"
+ "<LI> high: " + getHigh() + "</LI>"
+ "<LI> change1: " + getChange() + "</LI>"
;
}
public void print() {
Log.log(this.toString());
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public BigDecimal getOpen() {
return open1;
}
public void setOpen(BigDecimal open) {
this.open1 = open;
}
public BigDecimal getLow() {
return low;
}
public void setLow(BigDecimal low) {
this.low = low;
}
public BigDecimal getHigh() {
return high;
}
public void setHigh(BigDecimal high) {
this.high = high;
}
public double getChange() {
return change1;
}
public void setChange(double change) {
this.change1 = change;
}
public double getVolume() {
return volume;
}
public void setVolume(double volume) {
this.volume = volume;
}
@Override
public int hashCode() {
int hash = 0;
hash += (this.symbol != null ? this.symbol.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof QuoteDataBeanImpl)) {
return false;
}
QuoteDataBeanImpl other = (QuoteDataBeanImpl)object;
if (this.symbol != other.symbol && (this.symbol == null || !this.symbol.equals(other.symbol))) return false;
return true;
}
}
| 8,192 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-beans/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-beans/src/main/java/org/apache/aries/samples/ariestrader/beans/OrderDataBeanImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.beans;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import org.apache.aries.samples.ariestrader.util.Log;
import org.apache.aries.samples.ariestrader.util.TradeConfig;
import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.HoldingDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.OrderDataBean;
import org.apache.aries.samples.ariestrader.api.persistence.QuoteDataBean;
public class OrderDataBeanImpl implements OrderDataBean, Serializable {
private Integer orderID; /* orderID */
private String orderType; /* orderType (buy, sell, etc.) */
private String orderStatus; /* orderStatus (open, processing, completed, closed, cancelled) */
private Date openDate; /* openDate (when the order was entered) */
private Date completionDate; /* completionDate */
private double quantity; /* quantity */
private BigDecimal price; /* price */
private BigDecimal orderFee; /* price */
private AccountDataBean account;
private QuoteDataBean quote;
private HoldingDataBean holding;
private String symbol;
public OrderDataBeanImpl() {
}
public OrderDataBeanImpl(Integer orderID,
String orderType,
String orderStatus,
Date openDate,
Date completionDate,
double quantity,
BigDecimal price,
BigDecimal orderFee,
String symbol
) {
setOrderID(orderID);
setOrderType(orderType);
setOrderStatus(orderStatus);
setOpenDate(openDate);
setCompletionDate(completionDate);
setQuantity(quantity);
setPrice(price);
setOrderFee(orderFee);
setSymbol(symbol);
}
public OrderDataBeanImpl(String orderType,
String orderStatus,
Date openDate,
Date completionDate,
double quantity,
BigDecimal price,
BigDecimal orderFee,
AccountDataBean account,
QuoteDataBean quote, HoldingDataBean holding) {
setOrderType(orderType);
setOrderStatus(orderStatus);
setOpenDate(openDate);
setCompletionDate(completionDate);
setQuantity(quantity);
setPrice(price);
setOrderFee(orderFee);
setAccount(account);
setQuote(quote);
setHolding(holding);
}
public static OrderDataBean getRandomInstance() {
return new OrderDataBeanImpl(
new Integer(TradeConfig.rndInt(100000)),
TradeConfig.rndBoolean() ? "buy" : "sell",
"open",
new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)),
new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)),
TradeConfig.rndQuantity(),
TradeConfig.rndBigDecimal(1000.0f),
TradeConfig.rndBigDecimal(1000.0f),
TradeConfig.rndSymbol()
);
}
public String toString()
{
return "Order " + getOrderID()
+ "\n\t orderType: " + getOrderType()
+ "\n\t orderStatus: " + getOrderStatus()
+ "\n\t openDate: " + getOpenDate()
+ "\n\t completionDate: " + getCompletionDate()
+ "\n\t quantity: " + getQuantity()
+ "\n\t price: " + getPrice()
+ "\n\t orderFee: " + getOrderFee()
+ "\n\t symbol: " + getSymbol()
;
}
public String toHTML()
{
return "<BR>Order <B>" + getOrderID() + "</B>"
+ "<LI> orderType: " + getOrderType() + "</LI>"
+ "<LI> orderStatus: " + getOrderStatus() + "</LI>"
+ "<LI> openDate: " + getOpenDate() + "</LI>"
+ "<LI> completionDate: " + getCompletionDate() + "</LI>"
+ "<LI> quantity: " + getQuantity() + "</LI>"
+ "<LI> price: " + getPrice() + "</LI>"
+ "<LI> orderFee: " + getOrderFee() + "</LI>"
+ "<LI> symbol: " + getSymbol() + "</LI>"
;
}
public void print()
{
Log.log( this.toString() );
}
public Integer getOrderID() {
return orderID;
}
public void setOrderID(Integer orderID) {
this.orderID = orderID;
}
public String getOrderType() {
return orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
public Date getOpenDate() {
return openDate;
}
public void setOpenDate(Date openDate) {
this.openDate = openDate;
}
public Date getCompletionDate() {
return completionDate;
}
public void setCompletionDate(Date completionDate) {
this.completionDate = completionDate;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public BigDecimal getOrderFee() {
return orderFee;
}
public void setOrderFee(BigDecimal orderFee) {
this.orderFee = orderFee;
}
public String getSymbol() {
if (quote != null) {
return quote.getSymbol();
}
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public AccountDataBean getAccount() {
return account;
}
public void setAccount(AccountDataBean account) {
this.account = account;
}
public QuoteDataBean getQuote() {
return quote;
}
public void setQuote(QuoteDataBean quote) {
this.quote = quote;
}
public HoldingDataBean getHolding() {
return holding;
}
public void setHolding(HoldingDataBean holding) {
this.holding = holding;
}
public boolean isBuy()
{
String orderType = getOrderType();
if ( orderType.compareToIgnoreCase("buy") == 0 )
return true;
return false;
}
public boolean isSell()
{
String orderType = getOrderType();
if ( orderType.compareToIgnoreCase("sell") == 0 )
return true;
return false;
}
public boolean isOpen()
{
String orderStatus = getOrderStatus();
if ( (orderStatus.compareToIgnoreCase("open") == 0) ||
(orderStatus.compareToIgnoreCase("processing") == 0) )
return true;
return false;
}
public boolean isCompleted()
{
String orderStatus = getOrderStatus();
if ( (orderStatus.compareToIgnoreCase("completed") == 0) ||
(orderStatus.compareToIgnoreCase("alertcompleted") == 0) ||
(orderStatus.compareToIgnoreCase("cancelled") == 0) )
return true;
return false;
}
public boolean isCancelled()
{
String orderStatus = getOrderStatus();
if (orderStatus.compareToIgnoreCase("cancelled") == 0)
return true;
return false;
}
public void cancel()
{
setOrderStatus("cancelled");
}
@Override
public int hashCode() {
int hash = 0;
hash += (this.orderID != null ? this.orderID.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof OrderDataBeanImpl)) {
return false;
}
OrderDataBeanImpl other = (OrderDataBeanImpl)object;
if (this.orderID != other.orderID && (this.orderID == null || !this.orderID.equals(other.orderID))) return false;
return true;
}
}
| 8,193 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-core/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-core/src/main/java/org/apache/aries/samples/ariestrader/core/TradeDBManagerImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.core;
import javax.sql.DataSource;
import org.apache.aries.samples.ariestrader.api.persistence.RunStatsDataBean;
import org.apache.aries.samples.ariestrader.util.Log;
import org.apache.aries.samples.ariestrader.util.MDBStats;
import org.apache.aries.samples.ariestrader.util.ServiceUtilities;
import org.apache.aries.samples.ariestrader.util.TradeConfig;
import org.apache.aries.samples.ariestrader.api.TradeDBManager;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* TradeDBManagerImpl centralizes and simplifies the DB
* configuration methods that are shared by some TradeServices
* implementations.
*
* @see
* org.apache.aries.samples.ariestrader.api.TradeDBManager
*/
public class TradeDBManagerImpl implements TradeDBManager {
private DataSource dataSource = null;
private static boolean initialized = false;
private static int connCount = 0;
private static Integer lock = new Integer(0);
/**
* Zero arg constructor for TradeDBManagerImpl
*/
public TradeDBManagerImpl() {
}
/**
* set data source
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* Return a String containing the DBProductName configured for
* the current DataSource
*
* used by TradeBuildDB
*
* @return A String of the currently configured DataSource
*
*/
public String checkDBProductName() throws Exception {
Connection conn = null;
String dbProductName = null;
try {
if (Log.doTrace())
Log.traceEnter("TradeDBManagerImpl:checkDBProductName");
conn = getConn();
DatabaseMetaData dbmd = conn.getMetaData();
dbProductName = dbmd.getDatabaseProductName();
}
catch (SQLException e) {
Log.error(e, "TradeDBManagerImpl:checkDBProductName() -- Error checking the AriesTrader Database Product Name");
}
finally {
releaseConn(conn);
}
return dbProductName;
}
/**
* Recreate DataBase Tables for AriesTrader
*
* used by TradeBuildDB
*
* @return boolean of success/failure in recreate of DB tables
*
*/
public boolean recreateDBTables(Object[] sqlBuffer, java.io.PrintWriter out) throws Exception {
// Clear MDB Statistics
MDBStats.getInstance().reset();
Connection conn = null;
boolean success = false;
try {
if (Log.doTrace())
Log.traceEnter("TradeDBManagerImpl:recreateDBTables");
conn = getConn();
Statement stmt = conn.createStatement();
int bufferLength = sqlBuffer.length;
for (int i = 0; i < bufferLength; i++) {
try {
stmt.executeUpdate((String) sqlBuffer[i]);
}
catch (SQLException ex) {
// Ignore DROP statements as tables won't always exist.
if (((String) sqlBuffer[i]).indexOf("DROP TABLE") < 0) {
Log.error("TradeDBManagerImpl:recreateDBTables SQL Exception thrown on executing the foll sql command: "
+ sqlBuffer[i], ex);
out.println("<BR>SQL Exception thrown on executing the foll sql command: <I>" + sqlBuffer[i]
+ "</I> . Check log for details.</BR>");
}
}
}
stmt.close();
commit(conn);
success = true;
}
catch (Exception e) {
Log.error(e, "TradeDBManagerImpl:recreateDBTables() -- Error dropping and recreating the database tables");
}
finally {
releaseConn(conn);
}
return success;
}
/**
* Reset the statistics for the Test AriesTrader Scenario
*
* used by TradeConfigServlet
*
* @return the RunStatsDataBean
*
*/
public RunStatsDataBean resetTrade(boolean deleteAll) throws Exception {
// Clear MDB Statistics
MDBStats.getInstance().reset();
// Reset Trade
RunStatsDataBean runStatsData = new RunStatsDataBean();
Connection conn = null;
try {
if (Log.doTrace())
Log.traceEnter("TradeDBManagerImpl:resetTrade deleteAll rows=" + deleteAll);
conn = getConn();
PreparedStatement stmt = null;
ResultSet rs = null;
if (deleteAll) {
try {
stmt = getStatement(conn, "delete from quoteejb");
stmt.executeUpdate();
stmt.close();
stmt = getStatement(conn, "delete from accountejb");
stmt.executeUpdate();
stmt.close();
stmt = getStatement(conn, "delete from accountprofileejb");
stmt.executeUpdate();
stmt.close();
stmt = getStatement(conn, "delete from holdingejb");
stmt.executeUpdate();
stmt.close();
stmt = getStatement(conn, "delete from orderejb");
stmt.executeUpdate();
stmt.close();
// FUTURE: - DuplicateKeyException - For now, don't start at
// zero as KeySequenceDirect and KeySequenceBean will still
// give out
// the cached Block and then notice this change. Better
// solution is
// to signal both classes to drop their cached blocks
// stmt = getStatement(conn, "delete from keygenejb");
// stmt.executeUpdate();
// stmt.close();
commit(conn);
}
catch (Exception e) {
Log.error(e, "TradeDBManagerImpl:resetTrade(deleteAll) -- Error deleting Trade users and stock from the Trade database");
}
return runStatsData;
}
stmt = getStatement(conn, "delete from holdingejb where holdingejb.account_accountid is null");
stmt.executeUpdate();
stmt.close();
// Count and Delete newly registered users (users w/ id that start
// "ru:%":
stmt = getStatement(conn, "delete from accountprofileejb where userid like 'ru:%'");
stmt.executeUpdate();
stmt.close();
stmt = getStatement(conn,
"delete from orderejb where account_accountid in (select accountid from accountejb a where a.profile_userid like 'ru:%')");
stmt.executeUpdate();
stmt.close();
stmt = getStatement(conn,
"delete from holdingejb where account_accountid in (select accountid from accountejb a where a.profile_userid like 'ru:%')");
stmt.executeUpdate();
stmt.close();
stmt = getStatement(conn, "delete from accountejb where profile_userid like 'ru:%'");
int newUserCount = stmt.executeUpdate();
runStatsData.setNewUserCount(newUserCount);
stmt.close();
// Count of trade users
stmt = getStatement(conn,
"select count(accountid) as \"tradeUserCount\" from accountejb a where a.profile_userid like 'uid:%'");
rs = stmt.executeQuery();
rs.next();
int tradeUserCount = rs.getInt("tradeUserCount");
runStatsData.setTradeUserCount(tradeUserCount);
stmt.close();
rs.close();
// Count of trade stocks
stmt = getStatement(conn,
"select count(symbol) as \"tradeStockCount\" from quoteejb a where a.symbol like 's:%'");
rs = stmt.executeQuery();
rs.next();
int tradeStockCount = rs.getInt("tradeStockCount");
runStatsData.setTradeStockCount(tradeStockCount);
stmt.close();
// Count of trade users login, logout
stmt = getStatement(conn,
"select sum(loginCount) as \"sumLoginCount\", sum(logoutCount) as \"sumLogoutCount\" from accountejb a where a.profile_userID like 'uid:%'");
rs = stmt.executeQuery();
rs.next();
int sumLoginCount = rs.getInt("sumLoginCount");
int sumLogoutCount = rs.getInt("sumLogoutCount");
runStatsData.setSumLoginCount(sumLoginCount);
runStatsData.setSumLogoutCount(sumLogoutCount);
stmt.close();
rs.close();
// Update logoutcount and loginCount back to zero
stmt =
getStatement(conn, "update accountejb set logoutCount=0,loginCount=0 where profile_userID like 'uid:%'");
stmt.executeUpdate();
stmt.close();
// count holdings for trade users
stmt = getStatement(conn,
"select count(holdingid) as \"holdingCount\" from holdingejb h where h.account_accountid in "
+ "(select accountid from accountejb a where a.profile_userid like 'uid:%')");
rs = stmt.executeQuery();
rs.next();
int holdingCount = rs.getInt("holdingCount");
runStatsData.setHoldingCount(holdingCount);
stmt.close();
rs.close();
// count orders for trade users
stmt = getStatement(conn,
"select count(orderid) as \"orderCount\" from orderejb o where o.account_accountid in "
+ "(select accountid from accountejb a where a.profile_userid like 'uid:%')");
rs = stmt.executeQuery();
rs.next();
int orderCount = rs.getInt("orderCount");
runStatsData.setOrderCount(orderCount);
stmt.close();
rs.close();
// count orders by type for trade users
stmt = getStatement(conn,
"select count(orderid) \"buyOrderCount\"from orderejb o where (o.account_accountid in "
+ "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND "
+ " (o.orderType='buy')");
rs = stmt.executeQuery();
rs.next();
int buyOrderCount = rs.getInt("buyOrderCount");
runStatsData.setBuyOrderCount(buyOrderCount);
stmt.close();
rs.close();
// count orders by type for trade users
stmt = getStatement(conn,
"select count(orderid) \"sellOrderCount\"from orderejb o where (o.account_accountid in "
+ "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND "
+ " (o.orderType='sell')");
rs = stmt.executeQuery();
rs.next();
int sellOrderCount = rs.getInt("sellOrderCount");
runStatsData.setSellOrderCount(sellOrderCount);
stmt.close();
rs.close();
// Delete cancelled orders
stmt = getStatement(conn, "delete from orderejb where orderStatus='cancelled'");
int cancelledOrderCount = stmt.executeUpdate();
runStatsData.setCancelledOrderCount(cancelledOrderCount);
stmt.close();
rs.close();
// count open orders by type for trade users
stmt = getStatement(conn,
"select count(orderid) \"openOrderCount\"from orderejb o where (o.account_accountid in "
+ "(select accountid from accountejb a where a.profile_userid like 'uid:%')) AND "
+ " (o.orderStatus='open')");
rs = stmt.executeQuery();
rs.next();
int openOrderCount = rs.getInt("openOrderCount");
runStatsData.setOpenOrderCount(openOrderCount);
stmt.close();
rs.close();
// Delete orders for holding which have been purchased and sold
stmt = getStatement(conn, "delete from orderejb where holding_holdingid is null");
int deletedOrderCount = stmt.executeUpdate();
runStatsData.setDeletedOrderCount(deletedOrderCount);
stmt.close();
rs.close();
commit(conn);
System.out.println("TradeDBManagerImpl:reset Run stats data\n\n" + runStatsData);
}
catch (Exception e) {
Log.error(e, "Failed to reset Trade");
rollBack(conn, e);
throw e;
}
finally {
releaseConn(conn);
}
return runStatsData;
}
private void releaseConn(Connection conn) throws Exception {
try {
if (conn != null) {
conn.close();
if (Log.doTrace()) {
synchronized (lock) {
connCount--;
}
Log.trace("TradeDBManagerImpl:releaseConn -- connection closed, connCount=" + connCount);
}
}
}
catch (Exception e) {
Log.error("TradeDBManagerImpl:releaseConnection -- failed to close connection", e);
}
}
/*
* Lookup the TradeData DataSource
*/
private void lookupDataSource() throws Exception {
if (dataSource == null) {
dataSource = (DataSource) ServiceUtilities.getOSGIService(DataSource.class.getName(),TradeConfig.OSGI_DS_NAME_FILTER);
}
}
/*
* Allocate a new connection to the datasource
*/
private Connection getConn() throws Exception {
Connection conn = null;
lookupDataSource();
conn = dataSource.getConnection();
conn.setAutoCommit(false);
if (Log.doTrace()) {
synchronized (lock) {
connCount++;
}
Log.trace("TradeDBManagerImpl:getConn -- new connection allocated, IsolationLevel="
+ conn.getTransactionIsolation() + " connectionCount = " + connCount);
}
return conn;
}
/*
* Commit the provided connection
*/
private void commit(Connection conn) throws Exception {
if (conn != null)
conn.commit();
}
/*
* Rollback the statement for the given connection
*/
private void rollBack(Connection conn, Exception e) throws Exception {
Log.log("TradeDBManagerImpl:rollBack -- rolling back conn due to previously caught exception");
if (conn != null)
conn.rollback();
else
throw e; // Throw the exception
}
/*
* Allocate a new prepared statement for this connection
*/
private PreparedStatement getStatement(Connection conn, String sql) throws Exception {
return conn.prepareStatement(sql);
}
public void init() {
if (initialized)
return;
if (Log.doTrace())
Log.trace("TradeDBManagerImpl:init -- *** initializing");
if (Log.doTrace())
Log.trace("TradeDBManagerImpl:init -- +++ initialized");
initialized = true;
}
public void destroy() {
try {
Log.trace("TradeDBManagerImpl:destroy");
if (!initialized)
return;
}
catch (Exception e) {
Log.error("TradeDBManagerImpl:destroy", e);
}
}
}
| 8,194 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-core/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-core/src/main/java/org/apache/aries/samples/ariestrader/core/TradeServicesManagerImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.core;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.aries.samples.ariestrader.api.persistence.MarketSummaryDataBean;
import org.apache.aries.samples.ariestrader.util.Log;
import org.apache.aries.samples.ariestrader.util.TradeConfig;
import org.apache.aries.samples.ariestrader.api.TradeServicesManager;
import org.apache.aries.samples.ariestrader.api.TradeServices;
/**
* TradeServicesManagerImpl coordinates access to the currently
* selected TradeServices implementation and manages the list of
* currently available TradeServices implementations.
*
* @see
* org.apache.geronimo.samples.daytrader.api.TradeServicesManager
*
*/
public class TradeServicesManagerImpl implements TradeServicesManager {
private static TradeServices[] tradeServicesList = new TradeServices[TradeConfig.runTimeModeNames.length] ;
// This lock is used to serialize market summary operations.
private static final Integer marketSummaryLock = new Integer(0);
private static long nextMarketSummary = System.currentTimeMillis();
private static MarketSummaryDataBean cachedMSDB = null;
/**
* TradeServicesManagerImpl null constructor
*/
public TradeServicesManagerImpl() {
if (Log.doTrace())
Log.trace("TradeServicesManagerImpl()");
}
/**
* init
*/
public void init() {
if (Log.doTrace())
Log.trace("TradeServicesManagerImpl:init()");
}
/**
* Get CurrentModes that are registered
*/
public ArrayList<Integer> getCurrentModes() {
if (Log.doTrace())
Log.trace("TradeServicesManagerImpl:getCurrentModes()");
ArrayList<Integer> modes = new ArrayList<Integer>();
for (int i=0; i<tradeServicesList.length; i++) {
TradeServices tradeServicesRef = tradeServicesList[i];
if (tradeServicesRef != null) {
modes.add(i);
}
}
return modes;
}
/**
* Get TradeServices reference
*/
public TradeServices getTradeServices() {
if (Log.doTrace())
Log.trace("TradeServicesManagerImpl:getTradeServices()");
return tradeServicesList[TradeConfig.getRunTimeMode().ordinal()];
}
/**
* Bind a new TradeServices implementation
*/
public void bindService(TradeServices tradeServices, Map props) {
if (Log.doTrace())
Log.trace("TradeServicesManagerImpl:bindService()", tradeServices, props);
if (tradeServices != null) {
String mode = (String) props.get("mode");
tradeServicesList[Enum.valueOf(TradeConfig.ModeType.class, mode).ordinal()] = tradeServices;
}
}
/**
* Unbind a TradeServices implementation
*/
public void unbindService(TradeServices tradeServices, Map props) {
if (Log.doTrace())
Log.trace("TradeServicesManagerImpl:unbindService()", tradeServices, props);
if (tradeServices != null) {
String mode = (String) props.get("mode");
tradeServicesList[Enum.valueOf(TradeConfig.ModeType.class, mode).ordinal()] = null;
}
}
/**
* Market Summary is inherently a heavy database operation. For servers that have a caching
* story this is a great place to cache data that is good for a period of time. In order to
* provide a flexible framework for this we allow the market summary operation to be
* invoked on every transaction, time delayed or never. This is configurable in the
* configuration panel.
*
* @return An instance of the market summary
*/
public MarketSummaryDataBean getMarketSummary() throws Exception {
if (Log.doActionTrace()) {
Log.trace("TradeAction:getMarketSummary()");
}
if (Log.doTrace())
Log.trace("TradeServicesManagerImpl:getMarketSummary()");
if (TradeConfig.getMarketSummaryInterval() == 0) return getMarketSummaryInternal();
if (TradeConfig.getMarketSummaryInterval() < 0) return cachedMSDB;
/**
* This is a little funky. If its time to fetch a new Market summary then we'll synchronize
* access to make sure only one requester does it. Others will merely return the old copy until
* the new MarketSummary has been executed.
*/
long currentTime = System.currentTimeMillis();
if (currentTime > nextMarketSummary) {
long oldNextMarketSummary = nextMarketSummary;
boolean fetch = false;
synchronized (marketSummaryLock) {
/**
* Is it still ahead or did we miss lose the race? If we lost then let's get out
* of here as the work has already been done.
*/
if (oldNextMarketSummary == nextMarketSummary) {
fetch = true;
nextMarketSummary += TradeConfig.getMarketSummaryInterval()*1000;
/**
* If the server has been idle for a while then its possible that nextMarketSummary
* could be way off. Rather than try and play catch up we'll simply get in sync with the
* current time + the interval.
*/
if (nextMarketSummary < currentTime) {
nextMarketSummary = currentTime + TradeConfig.getMarketSummaryInterval()*1000;
}
}
}
/**
* If we're the lucky one then let's update the MarketSummary
*/
if (fetch) {
cachedMSDB = getMarketSummaryInternal();
}
}
return cachedMSDB;
}
/**
* Compute and return a snapshot of the current market conditions This
* includes the TSIA - an index of the price of the top 100 Trade stock
* quotes The openTSIA ( the index at the open) The volume of shares traded,
* Top Stocks gain and loss
*
* @return A snapshot of the current market summary
*/
private MarketSummaryDataBean getMarketSummaryInternal() throws Exception {
if (Log.doActionTrace()) {
Log.trace("TradeAction:getMarketSummaryInternal()");
}
MarketSummaryDataBean marketSummaryData = null;
marketSummaryData = tradeServicesList[TradeConfig.getRunTimeMode().ordinal()].getMarketSummary();
return marketSummaryData;
}
}
| 8,195 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader/util/MDBStats.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.util;
/**
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
* To enable and disable the creation of type comments go to
* Window>Preferences>Java>Code Generation.
*/
public class MDBStats extends java.util.HashMap {
//Singleton class
private static MDBStats mdbStats = null;
private MDBStats()
{
}
public static synchronized MDBStats getInstance()
{
if (mdbStats == null)
mdbStats = new MDBStats();
return mdbStats;
}
public TimerStat addTiming(String type, long sendTime, long recvTime)
{
TimerStat stats = null;
synchronized (type)
{
stats = (TimerStat) get(type);
if (stats == null) stats = new TimerStat();
long time = recvTime - sendTime;
if ( time > stats.getMax() ) stats.setMax(time);
if ( time < stats.getMin() ) stats.setMin(time);
stats.setCount(stats.getCount()+1);
stats.setTotalTime(stats.getTotalTime() + time);
put(type, stats);
}
return stats;
}
public synchronized void reset()
{
clear();
}
}
| 8,196 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader/util/FinancialUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.util;
import java.math.BigDecimal;
public class FinancialUtils {
//TODO -- FinancialUtils should have parts reimplemented as JSPTaglibs
public final static int ROUND = BigDecimal.ROUND_HALF_UP;
public final static int SCALE = 2;
public final static BigDecimal ZERO = (new BigDecimal(0.00)).setScale(SCALE);
public final static BigDecimal ONE = (new BigDecimal(1.00)).setScale(SCALE);
public final static BigDecimal HUNDRED = (new BigDecimal(100.00)).setScale(SCALE);
public static BigDecimal computeGain(BigDecimal currentBalance,
BigDecimal openBalance)
{
return currentBalance.subtract(openBalance).setScale(SCALE);
}
public static BigDecimal computeGainPercent(BigDecimal currentBalance,
BigDecimal openBalance)
{
if (openBalance.doubleValue() == 0.0) return ZERO;
BigDecimal gainPercent =
currentBalance.divide(openBalance, ROUND).subtract(ONE).multiply(HUNDRED);
return gainPercent;
}
public static String printGainHTML(BigDecimal gain) {
String htmlString, arrow;
if (gain.doubleValue() < 0.0) {
htmlString = "<FONT color=\"#ff0000\">";
arrow = "arrowdown.gif";
}
else {
htmlString = "<FONT color=\"#009900\">";
arrow = "arrowup.gif";
}
htmlString += gain.setScale(SCALE, ROUND) + "</FONT><IMG src=\"images/" + arrow + "\" width=\"10\" height=\"10\" border=\"0\"></IMG>";
return htmlString;
}
public static String printChangeHTML(double change) {
String htmlString, arrow;
if (change < 0.0) {
htmlString = "<FONT color=\"#ff0000\">";
arrow = "arrowdown.gif";
}
else {
htmlString = "<FONT color=\"#009900\">";
arrow = "arrowup.gif";
}
htmlString += change + "</FONT><IMG src=\"images/" + arrow + "\" width=\"10\" height=\"10\" border=\"0\"></IMG>";
return htmlString;
}
public static String printGainPercentHTML(BigDecimal gain) {
String htmlString, arrow;
if (gain.doubleValue() < 0.0) {
htmlString = "(<B><FONT color=\"#ff0000\">";
arrow = "arrowdown.gif";
}
else {
htmlString = "(<B><FONT color=\"#009900\">+";
arrow = "arrowup.gif";
}
htmlString += gain.setScale(SCALE, ROUND);
htmlString += "%</FONT></B>)<IMG src=\"images/" + arrow + "\" width=\"10\" height=\"10\" border=\"0\"></IMG>";
return htmlString;
}
public static String printQuoteLink(String symbol)
{
return "<A href=\"app?action=quotes&symbols="+ symbol+"\">" + symbol + "</A>";
}
} | 8,197 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader/util/TimerStat.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.util;
/**
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
* To enable and disable the creation of type comments go to
* Window>Preferences>Java>Code Generation.
*/
public class TimerStat {
private double min=1000000000.0, max=0.0, totalTime=0.0;
private int count;
/**
* Returns the count.
* @return int
*/
public int getCount() {
return count;
}
/**
* Returns the max.
* @return double
*/
public double getMax() {
return max;
}
/**
* Returns the min.
* @return double
*/
public double getMin() {
return min;
}
/**
* Sets the count.
* @param count The count to set
*/
public void setCount(int count) {
this.count = count;
}
/**
* Sets the max.
* @param max The max to set
*/
public void setMax(double max) {
this.max = max;
}
/**
* Sets the min.
* @param min The min to set
*/
public void setMin(double min) {
this.min = min;
}
/**
* Returns the totalTime.
* @return double
*/
public double getTotalTime() {
return totalTime;
}
/**
* Sets the totalTime.
* @param totalTime The totalTime to set
*/
public void setTotalTime(double totalTime) {
this.totalTime = totalTime;
}
/**
* Returns the max in Secs
* @return double
*/
public double getMaxSecs() {
return max/1000.0;
}
/**
* Returns the min in Secs
* @return double
*/
public double getMinSecs() {
return min/1000.0;
}
/**
* Returns the average time in Secs
* @return double
*/
public double getAvgSecs() {
double avg = (double)getTotalTime() / (double)getCount();
return avg / 1000.0;
}
}
| 8,198 |
0 | Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader | Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader/util/ServiceUtilities.java | /**
* Licensed to4the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file to
* You under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.samples.ariestrader.util;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
* ServiceUtilities provides servlet specific client side
* utility functions.
*/
public class ServiceUtilities {
/**
* Lookup and return an osgi service
*
* @return Object
* @exception javax.io.IOException
* If an exception occurs during the service
* lookup
*
*/
public static final Object getOSGIService(String serviceName) {
if (Log.doTrace())
Log.trace("ServiceUtilities:getOSGIService()", serviceName);
return getOSGIService(serviceName, null);
}
/**
* Lookup and return an osgi service
*
* @return Object
*
*/
public static final Object getOSGIService(String serviceName, String filter) {
if (Log.doTrace())
Log.trace("ServiceUtilities:getOSGIService()", serviceName, filter);
String name = TradeConfig.OSGI_SERVICE_PREFIX + serviceName;
if (filter != null) {
name = name + "/" + filter;
}
try {
InitialContext ic = new InitialContext();
return ic.lookup(name);
} catch (NamingException e) {
Log.error("ServiceUtilities:getOSGIService() -- NamingException on OSGI service lookup", name, e);
e.printStackTrace();
return null;
}
}
} | 8,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.