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/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/content/ConfigurationHandler.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.subsystem.core.content;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PushbackReader;
import java.io.Writer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/* This class was taken from the Felix Codebase to read Felix ConfigAdmin .config files. */
/**
* The <code>ConfigurationHandler</code> class implements configuration reading
* form a <code>java.io.InputStream</code> and writing to a
* <code>java.io.OutputStream</code> on behalf of the
* {@link FilePersistenceManager} class.
*
* <pre>
* cfg = prop "=" value .
* prop = symbolic-name . // 1.4.2 of OSGi Core Specification
* symbolic-name = token { "." token } .
* token = { [ 0..9 ] | [ a..z ] | [ A..Z ] | '_' | '-' } .
* value = [ type ] ( "[" values "]" | "(" values ")" | simple ) .
* values = simple { "," simple } .
* simple = """ stringsimple """ .
* type = // 1-char type code .
* stringsimple = // quoted string representation of the value .
* </pre>
*/
public class ConfigurationHandler
{
protected static final String ENCODING = "UTF-8";
protected static final int TOKEN_NAME = 'N';
protected static final int TOKEN_EQ = '=';
protected static final int TOKEN_ARR_OPEN = '[';
protected static final int TOKEN_ARR_CLOS = ']';
protected static final int TOKEN_VEC_OPEN = '(';
protected static final int TOKEN_VEC_CLOS = ')';
protected static final int TOKEN_COMMA = ',';
protected static final int TOKEN_VAL_OPEN = '"'; // '{';
protected static final int TOKEN_VAL_CLOS = '"'; // '}';
// simple types (string & primitive wrappers)
protected static final int TOKEN_SIMPLE_STRING = 'T';
protected static final int TOKEN_SIMPLE_INTEGER = 'I';
protected static final int TOKEN_SIMPLE_LONG = 'L';
protected static final int TOKEN_SIMPLE_FLOAT = 'F';
protected static final int TOKEN_SIMPLE_DOUBLE = 'D';
protected static final int TOKEN_SIMPLE_BYTE = 'X';
protected static final int TOKEN_SIMPLE_SHORT = 'S';
protected static final int TOKEN_SIMPLE_CHARACTER = 'C';
protected static final int TOKEN_SIMPLE_BOOLEAN = 'B';
// primitives
protected static final int TOKEN_PRIMITIVE_INT = 'i';
protected static final int TOKEN_PRIMITIVE_LONG = 'l';
protected static final int TOKEN_PRIMITIVE_FLOAT = 'f';
protected static final int TOKEN_PRIMITIVE_DOUBLE = 'd';
protected static final int TOKEN_PRIMITIVE_BYTE = 'x';
protected static final int TOKEN_PRIMITIVE_SHORT = 's';
protected static final int TOKEN_PRIMITIVE_CHAR = 'c';
protected static final int TOKEN_PRIMITIVE_BOOLEAN = 'b';
protected static final String CRLF = "\r\n";
protected static final Map code2Type;
protected static final Map type2Code;
// set of valid characters for "symblic-name"
private static final BitSet NAME_CHARS;
private static final BitSet TOKEN_CHARS;
static
{
type2Code = new HashMap();
// simple (exclusive String whose type code is not written)
type2Code.put( Integer.class, new Integer( TOKEN_SIMPLE_INTEGER ) );
type2Code.put( Long.class, new Integer( TOKEN_SIMPLE_LONG ) );
type2Code.put( Float.class, new Integer( TOKEN_SIMPLE_FLOAT ) );
type2Code.put( Double.class, new Integer( TOKEN_SIMPLE_DOUBLE ) );
type2Code.put( Byte.class, new Integer( TOKEN_SIMPLE_BYTE ) );
type2Code.put( Short.class, new Integer( TOKEN_SIMPLE_SHORT ) );
type2Code.put( Character.class, new Integer( TOKEN_SIMPLE_CHARACTER ) );
type2Code.put( Boolean.class, new Integer( TOKEN_SIMPLE_BOOLEAN ) );
// primitives
type2Code.put( Integer.TYPE, new Integer( TOKEN_PRIMITIVE_INT ) );
type2Code.put( Long.TYPE, new Integer( TOKEN_PRIMITIVE_LONG ) );
type2Code.put( Float.TYPE, new Integer( TOKEN_PRIMITIVE_FLOAT ) );
type2Code.put( Double.TYPE, new Integer( TOKEN_PRIMITIVE_DOUBLE ) );
type2Code.put( Byte.TYPE, new Integer( TOKEN_PRIMITIVE_BYTE ) );
type2Code.put( Short.TYPE, new Integer( TOKEN_PRIMITIVE_SHORT ) );
type2Code.put( Character.TYPE, new Integer( TOKEN_PRIMITIVE_CHAR ) );
type2Code.put( Boolean.TYPE, new Integer( TOKEN_PRIMITIVE_BOOLEAN ) );
// reverse map to map type codes to classes, string class mapping
// to be added manually, as the string type code is not written and
// hence not included in the type2Code map
code2Type = new HashMap();
for ( Iterator ti = type2Code.entrySet().iterator(); ti.hasNext(); )
{
Map.Entry entry = ( Map.Entry ) ti.next();
code2Type.put( entry.getValue(), entry.getKey() );
}
code2Type.put( new Integer( TOKEN_SIMPLE_STRING ), String.class );
NAME_CHARS = new BitSet();
for ( int i = '0'; i <= '9'; i++ )
NAME_CHARS.set( i );
for ( int i = 'a'; i <= 'z'; i++ )
NAME_CHARS.set( i );
for ( int i = 'A'; i <= 'Z'; i++ )
NAME_CHARS.set( i );
NAME_CHARS.set( '_' );
NAME_CHARS.set( '-' );
NAME_CHARS.set( '.' );
NAME_CHARS.set( '\\' );
TOKEN_CHARS = new BitSet();
TOKEN_CHARS.set( TOKEN_EQ );
TOKEN_CHARS.set( TOKEN_ARR_OPEN );
TOKEN_CHARS.set( TOKEN_ARR_CLOS );
TOKEN_CHARS.set( TOKEN_VEC_OPEN );
TOKEN_CHARS.set( TOKEN_VEC_CLOS );
TOKEN_CHARS.set( TOKEN_COMMA );
TOKEN_CHARS.set( TOKEN_VAL_OPEN );
TOKEN_CHARS.set( TOKEN_VAL_CLOS );
TOKEN_CHARS.set( TOKEN_SIMPLE_STRING );
TOKEN_CHARS.set( TOKEN_SIMPLE_INTEGER );
TOKEN_CHARS.set( TOKEN_SIMPLE_LONG );
TOKEN_CHARS.set( TOKEN_SIMPLE_FLOAT );
TOKEN_CHARS.set( TOKEN_SIMPLE_DOUBLE );
TOKEN_CHARS.set( TOKEN_SIMPLE_BYTE );
TOKEN_CHARS.set( TOKEN_SIMPLE_SHORT );
TOKEN_CHARS.set( TOKEN_SIMPLE_CHARACTER );
TOKEN_CHARS.set( TOKEN_SIMPLE_BOOLEAN );
// primitives
TOKEN_CHARS.set( TOKEN_PRIMITIVE_INT );
TOKEN_CHARS.set( TOKEN_PRIMITIVE_LONG );
TOKEN_CHARS.set( TOKEN_PRIMITIVE_FLOAT );
TOKEN_CHARS.set( TOKEN_PRIMITIVE_DOUBLE );
TOKEN_CHARS.set( TOKEN_PRIMITIVE_BYTE );
TOKEN_CHARS.set( TOKEN_PRIMITIVE_SHORT );
TOKEN_CHARS.set( TOKEN_PRIMITIVE_CHAR );
TOKEN_CHARS.set( TOKEN_PRIMITIVE_BOOLEAN );
}
/**
* Writes the configuration data from the <code>Dictionary</code> to the
* given <code>OutputStream</code>.
* <p>
* This method writes at the current location in the stream and does not
* close the outputstream.
*
* @param out
* The <code>OutputStream</code> to write the configurtion data
* to.
* @param properties
* The <code>Dictionary</code> to write.
* @throws IOException
* If an error occurrs writing to the output stream.
*/
public static void write( OutputStream out, Dictionary properties ) throws IOException
{
BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( out, ENCODING ) );
for ( Enumeration ce = properties.keys(); ce.hasMoreElements(); )
{
String key = ( String ) ce.nextElement();
// cfg = prop "=" value "." .
writeQuoted( bw, key );
bw.write( TOKEN_EQ );
writeValue( bw, properties.get( key ) );
bw.write( CRLF );
}
bw.flush();
}
/**
* Reads configuration data from the given <code>InputStream</code> and
* returns a new <code>Dictionary</code> object containing the data.
* <p>
* This method reads from the current location in the stream upto the end of
* the stream but does not close the stream at the end.
*
* @param ins
* The <code>InputStream</code> from which to read the
* configuration data.
* @return A <code>Dictionary</code> object containing the configuration
* data. This object may be empty if the stream contains no
* configuration data.
* @throws IOException
* If an error occurrs reading from the stream. This exception
* is also thrown if a syntax error is encountered.
*/
public static Dictionary read( InputStream ins ) throws IOException
{
return new ConfigurationHandler().readInternal( ins );
}
// private constructor, this class is not to be instantiated from the
// outside
private ConfigurationHandler()
{
}
// ---------- Configuration Input Implementation ---------------------------
private int token;
private String tokenValue;
private int line;
private int pos;
private Dictionary readInternal( InputStream ins ) throws IOException
{
BufferedReader br = new BufferedReader( new InputStreamReader( ins, ENCODING ) );
PushbackReader pr = new PushbackReader( br, 1 );
token = 0;
tokenValue = null;
line = 0;
pos = 0;
Hashtable configuration = new Hashtable();
token = 0;
while ( nextToken( pr ) == TOKEN_NAME )
{
String key = tokenValue;
// expect equal sign
if ( nextToken( pr ) != TOKEN_EQ )
{
throw readFailure( token, TOKEN_EQ );
}
// expect the token value
Object value = readValue( pr );
if ( value != null )
{
configuration.put( key, value );
}
}
return configuration;
}
/**
* value = type ( "[" values "]" | "(" values ")" | simple ) . values =
* value { "," value } . simple = "{" stringsimple "}" . type = // 1-char
* type code . stringsimple = // quoted string representation of the value .
*
* @param pr
* @return
* @throws IOException
*/
private Object readValue( PushbackReader pr ) throws IOException
{
// read (optional) type code
int type = read( pr );
// read value kind code if type code is not a value kinde code
int code;
if ( code2Type.containsKey( new Integer( type ) ) )
{
code = read( pr );
}
else
{
code = type;
type = TOKEN_SIMPLE_STRING;
}
switch ( code )
{
case TOKEN_ARR_OPEN:
return readArray( type, pr );
case TOKEN_VEC_OPEN:
return readCollection( type, pr );
case TOKEN_VAL_OPEN:
Object value = readSimple( type, pr );
ensureNext( pr, TOKEN_VAL_CLOS );
return value;
default:
return null;
}
}
private Object readArray( int typeCode, PushbackReader pr ) throws IOException
{
List list = new ArrayList();
for ( ;; )
{
int c = read(pr);
if ( c == TOKEN_VAL_OPEN )
{
Object value = readSimple( typeCode, pr );
if ( value == null )
{
// abort due to error
return null;
}
ensureNext( pr, TOKEN_VAL_CLOS );
list.add( value );
c = read( pr );
}
if ( c == TOKEN_ARR_CLOS )
{
Class type = ( Class ) code2Type.get( new Integer( typeCode ) );
Object array = Array.newInstance( type, list.size() );
for ( int i = 0; i < list.size(); i++ )
{
Array.set( array, i, list.get( i ) );
}
return array;
}
else if ( c < 0 )
{
return null;
}
else if ( c != TOKEN_COMMA )
{
return null;
}
}
}
private Collection readCollection( int typeCode, PushbackReader pr ) throws IOException
{
Collection collection = new ArrayList();
for ( ;; )
{
int c = read( pr );
if ( c == TOKEN_VAL_OPEN )
{
Object value = readSimple( typeCode, pr );
if ( value == null )
{
// abort due to error
return null;
}
ensureNext( pr, TOKEN_VAL_CLOS );
collection.add( value );
c = read( pr );
}
if ( c == TOKEN_VEC_CLOS )
{
return collection;
}
else if ( c < 0 )
{
return null;
}
else if ( c != TOKEN_COMMA )
{
return null;
}
}
}
private Object readSimple( int code, PushbackReader pr ) throws IOException
{
switch ( code )
{
case -1:
return null;
case TOKEN_SIMPLE_STRING:
return readQuoted( pr );
// Simple/Primitive, only use wrapper classes
case TOKEN_SIMPLE_INTEGER:
case TOKEN_PRIMITIVE_INT:
return Integer.valueOf( readQuoted( pr ) );
case TOKEN_SIMPLE_LONG:
case TOKEN_PRIMITIVE_LONG:
return Long.valueOf( readQuoted( pr ) );
case TOKEN_SIMPLE_FLOAT:
case TOKEN_PRIMITIVE_FLOAT:
int fBits = Integer.parseInt( readQuoted( pr ) );
return new Float( Float.intBitsToFloat( fBits ) );
case TOKEN_SIMPLE_DOUBLE:
case TOKEN_PRIMITIVE_DOUBLE:
long dBits = Long.parseLong( readQuoted( pr ) );
return new Double( Double.longBitsToDouble( dBits ) );
case TOKEN_SIMPLE_BYTE:
case TOKEN_PRIMITIVE_BYTE:
return Byte.valueOf( readQuoted( pr ) );
case TOKEN_SIMPLE_SHORT:
case TOKEN_PRIMITIVE_SHORT:
return Short.valueOf( readQuoted( pr ) );
case TOKEN_SIMPLE_CHARACTER:
case TOKEN_PRIMITIVE_CHAR:
String cString = readQuoted( pr );
if ( cString != null && cString.length() > 0 )
{
return new Character( cString.charAt( 0 ) );
}
return null;
case TOKEN_SIMPLE_BOOLEAN:
case TOKEN_PRIMITIVE_BOOLEAN:
return Boolean.valueOf( readQuoted( pr ) );
// unknown type code
default:
return null;
}
}
private void ensureNext( PushbackReader pr, int expected ) throws IOException
{
int next = read( pr );
if ( next != expected )
{
readFailure( next, expected );
}
}
private boolean checkNext( PushbackReader pr, int expected ) throws IOException
{
int next = read( pr );
if ( next < 0 )
{
return false;
}
if ( next == expected )
{
return true;
}
return false;
}
private String readQuoted( PushbackReader pr ) throws IOException
{
StringBuffer buf = new StringBuffer();
for ( ;; )
{
int c = read( pr );
switch ( c )
{
// escaped character
case '\\':
c = read( pr );
switch ( c )
{
// well known escapes
case 'b':
buf.append( '\b' );
break;
case 't':
buf.append( '\t' );
break;
case 'n':
buf.append( '\n' );
break;
case 'f':
buf.append( '\f' );
break;
case 'r':
buf.append( '\r' );
break;
case 'u':// need 4 characters !
char[] cbuf = new char[4];
if ( read( pr, cbuf ) == 4 )
{
c = Integer.parseInt( new String( cbuf ), 16 );
buf.append( ( char ) c );
}
break;
// just an escaped character, unescape
default:
buf.append( ( char ) c );
}
break;
// eof
case -1: // fall through
// separator token
case TOKEN_EQ:
case TOKEN_VAL_CLOS:
pr.unread( c );
return buf.toString();
// no escaping
default:
buf.append( ( char ) c );
}
}
}
private int nextToken( PushbackReader pr ) throws IOException
{
int c = ignorableWhiteSpace( pr );
// immediately return EOF
if ( c < 0 )
{
return ( token = c );
}
// check whether there is a name
if ( NAME_CHARS.get( c ) || !TOKEN_CHARS.get( c ) )
{
// read the property name
pr.unread( c );
tokenValue = readQuoted( pr );
return ( token = TOKEN_NAME );
}
// check another token
if ( TOKEN_CHARS.get( c ) )
{
return ( token = c );
}
// unexpected character -> so what ??
return ( token = -1 );
}
private int ignorableWhiteSpace( PushbackReader pr ) throws IOException
{
int c = read( pr );
while ( c >= 0 && Character.isWhitespace( ( char ) c ) )
{
c = read( pr );
}
return c;
}
private int read( PushbackReader pr ) throws IOException
{
int c = pr.read();
if ( c == '\r' )
{
int c1 = pr.read();
if ( c1 != '\n' )
{
pr.unread( c1 );
}
c = '\n';
}
if ( c == '\n' )
{
line++;
pos = 0;
}
else
{
pos++;
}
return c;
}
private int read( PushbackReader pr, char[] buf ) throws IOException
{
for ( int i = 0; i < buf.length; i++ )
{
int c = read( pr );
if ( c >= 0 )
{
buf[i] = ( char ) c;
}
else
{
return i;
}
}
return buf.length;
}
private IOException readFailure( int current, int expected )
{
return new IOException( "Unexpected token " + current + "; expected: " + expected + " (line=" + line + ", pos="
+ pos + ")" );
}
// ---------- Configuration Output Implementation --------------------------
private static void writeValue( Writer out, Object value ) throws IOException
{
Class clazz = value.getClass();
if ( clazz.isArray() )
{
writeArray( out, value );
}
else if ( value instanceof Collection )
{
writeCollection( out, ( Collection ) value );
}
else
{
writeType( out, clazz );
writeSimple( out, value );
}
}
private static void writeArray( Writer out, Object arrayValue ) throws IOException
{
int size = Array.getLength( arrayValue );
writeType( out, arrayValue.getClass().getComponentType() );
out.write( TOKEN_ARR_OPEN );
for ( int i = 0; i < size; i++ )
{
if ( i > 0 )
out.write( TOKEN_COMMA );
writeSimple( out, Array.get( arrayValue, i ) );
}
out.write( TOKEN_ARR_CLOS );
}
private static void writeCollection( Writer out, Collection collection ) throws IOException
{
if ( collection.isEmpty() )
{
out.write( TOKEN_VEC_OPEN );
out.write( TOKEN_VEC_CLOS );
}
else
{
Iterator ci = collection.iterator();
Object firstElement = ci.next();
writeType( out, firstElement.getClass() );
out.write( TOKEN_VEC_OPEN );
writeSimple( out, firstElement );
while ( ci.hasNext() )
{
out.write( TOKEN_COMMA );
writeSimple( out, ci.next() );
}
out.write( TOKEN_VEC_CLOS );
}
}
private static void writeType( Writer out, Class valueType ) throws IOException
{
Integer code = ( Integer ) type2Code.get( valueType );
if ( code != null )
{
out.write( ( char ) code.intValue() );
}
}
private static void writeSimple( Writer out, Object value ) throws IOException
{
if ( value instanceof Double )
{
double dVal = ( ( Double ) value ).doubleValue();
value = new Long( Double.doubleToRawLongBits( dVal ) );
}
else if ( value instanceof Float )
{
float fVal = ( ( Float ) value ).floatValue();
value = new Integer( Float.floatToRawIntBits( fVal ) );
}
out.write( TOKEN_VAL_OPEN );
writeQuoted( out, String.valueOf( value ) );
out.write( TOKEN_VAL_CLOS );
}
private static void writeQuoted( Writer out, String simple ) throws IOException
{
if ( simple == null || simple.length() == 0 )
{
return;
}
char c = 0;
int len = simple.length();
for ( int i = 0; i < len; i++ )
{
c = simple.charAt( i );
switch ( c )
{
case '\\':
case TOKEN_VAL_CLOS:
case ' ':
case TOKEN_EQ:
out.write( '\\' );
out.write( c );
break;
// well known escapes
case '\b':
out.write( "\\b" );
break;
case '\t':
out.write( "\\t" );
break;
case '\n':
out.write( "\\n" );
break;
case '\f':
out.write( "\\f" );
break;
case '\r':
out.write( "\\r" );
break;
// other escaping
default:
if ( c < ' ' )
{
String t = "000" + Integer.toHexString( c );
out.write( "\\u" + t.substring( t.length() - 4 ) );
}
else
{
out.write( c );
}
}
}
}
}
| 8,700 |
0 | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core | Create_ds/aries/subsystem/subsystem-core/src/main/java/org/apache/aries/subsystem/core/content/ConfigAdminContentHandler.java | /*
* 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.apache.aries.subsystem.core.content;
import java.io.IOException;
import java.io.InputStream;
import java.util.Dictionary;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.aries.subsystem.ContentHandler;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.util.tracker.ServiceTracker;
public class ConfigAdminContentHandler implements ContentHandler {
public static final String FELIXCM_CONTENT_TYPE = "felix.cm.config";
public static final String PROPERTIES_CONTENT_TYPE = "osgi.config.properties";
public static final String[] CONTENT_TYPES = {PROPERTIES_CONTENT_TYPE, FELIXCM_CONTENT_TYPE};
private final ServiceTracker<ConfigurationAdmin,ConfigurationAdmin> cmTracker;
private final BundleContext ctx;
private Map<String, Dictionary<String, Object>> configurations = new ConcurrentHashMap<String, Dictionary<String, Object>>();
public ConfigAdminContentHandler(BundleContext ctx) {
this.ctx = ctx;
cmTracker = new ServiceTracker<ConfigurationAdmin, ConfigurationAdmin>(
ctx, ConfigurationAdmin.class, null);
cmTracker.open();
}
public void shutDown() {
cmTracker.close();
}
@Override @SuppressWarnings({ "unchecked", "rawtypes" })
public void install(InputStream is, String symbolicName, String contentType, Subsystem subsystem, Coordination coordination) {
Dictionary configuration = null;
try {
if (PROPERTIES_CONTENT_TYPE.equals(contentType)) {
Properties p = new Properties();
p.load(is);
configuration = p;
} else if (FELIXCM_CONTENT_TYPE.equals(contentType)) {
configuration = ConfigurationHandler.read(is);
}
} catch (IOException e) {
coordination.fail(new Exception("Problem loading configuration " +
symbolicName + " for subsystem " + subsystem.getSymbolicName(), e));
return;
} finally {
try { is.close(); } catch (IOException ioe) {}
}
if (configuration != null) {
configurations.put(symbolicName, configuration);
}
}
@Override
public void start(String symbolicName, String contentType, Subsystem subsystem, Coordination coordination) {
Dictionary<String, Object> configuration = configurations.get(symbolicName);
if (configuration == null) {
coordination.fail(new Exception("Cannot start configuration " + symbolicName + " for subsystem " + subsystem.getSymbolicName() +
" it was not previously loaded"));
return;
}
try {
ConfigurationAdmin cm = cmTracker.getService();
if (cm == null) {
coordination.fail(new Exception("No Configuration Admin Service found. Cannot apply configuration " +
symbolicName + " to subsystem " + subsystem.getSymbolicName()));
return;
}
Configuration[] matchingConfs = cm.listConfigurations(
ctx.createFilter("(service.pid=" + symbolicName + ")").toString());
if(matchingConfs == null || matchingConfs.length == 0) {
// No configuration exists: create a new one.
Configuration conf = cm.getConfiguration(symbolicName, "?");
conf.update(configuration);
}
// Update has happened, we can forget the configuration data now
configurations.remove(symbolicName);
} catch(InvalidSyntaxException e) {
// Unlikely to happen.
coordination.fail(new Exception("Failed to list existing configurations for " + symbolicName + " in subsystem " +
subsystem.getSymbolicName(), e));
} catch (IOException e) {
coordination.fail(new Exception("Problem applying configuration " + symbolicName + " in subsystem " +
subsystem.getSymbolicName(), e));
}
}
@Override
public void stop(String symbolicName, String contentType, Subsystem subsystem) {
// We don't remove the configuration on stop, as this is generally not desired.
// Specifically, other changes may have been made to the configuration that we
// don't want to wipe out.
}
@Override
public void uninstall(String symbolicName, String contentType, Subsystem subsystem) {
// Nothing to uninstall
}
}
| 8,701 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/classes | Create_ds/aries/subsystem/subsystem-itests/src/test/classes/a/A.java | package a;
public class A {
}
| 8,702 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/classes | Create_ds/aries/subsystem/subsystem-itests/src/test/classes/b/B.java | package b;
public class B {
}
| 8,703 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/classes/b | Create_ds/aries/subsystem/subsystem-itests/src/test/classes/b/a/A.java | package b.a;
public class A {
}
| 8,704 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/UnmanagedBundleTest.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.subsystem.itests;
import java.io.FileInputStream;
import java.io.IOException;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.Subsystem;
/*
* Contains a series of tests for unmanaged bundles. An unmanaged bundle is a
* bundle that was installed outside of the Subsystems API.
*/
public class UnmanagedBundleTest extends SubsystemTest {
/*
* Bundle-SymbolicName: bundle.a.jar
*/
private static final String BUNDLE_A = "bundle.a.jar";
@Override
public void createApplications() throws Exception {
createBundleA();
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A));
}
/*
* Test that an unmanaged bundle is detected as a constituent in the root
* subsystem when the subsystems core bundle is active.
*/
@Test
public void testInstallWhileImplBundleActive() throws Exception {
Bundle a = bundleContext.installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A));
try {
assertConstituent(getRootSubsystemInState(Subsystem.State.ACTIVE, 5000L), BUNDLE_A);
}
finally {
uninstallSilently(a);
}
}
/*
* Test that an unmanaged bundle is detected as a constituent in the root
* subsystem when the subsystems core bundle is stopped. This ensures that
* persistence isn't interfering with detection.
*/
@Test
public void testInstallWhileImplBundleStopped() throws Exception {
Bundle core = getSubsystemCoreBundle();
core.stop();
try {
Bundle a = bundleContext.installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A));
try {
core.start();
assertConstituent(getRootSubsystem(), BUNDLE_A);
}
finally {
uninstallSilently(a);
}
}
finally {
core.start();
}
}
/*
* Test that an unmanaged bundle is detected as a constituent in the root
* subsystem when the subsystems core bundle is uninstalled.
*/
@Test
public void testInstallWhileImplBundleUninstalled() throws Exception {
Bundle core = getSubsystemCoreBundle();
core.uninstall();
try {
Bundle a = bundleContext.installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A));
try {
core = bundleContext.installBundle(normalizeBundleLocation(core));
core.start();
assertConstituent(getRootSubsystem(), BUNDLE_A);
}
finally {
uninstallSilently(a);
}
}
finally {
if (core.getState() == Bundle.UNINSTALLED) {
core = bundleContext.installBundle(normalizeBundleLocation(core));
core.start();
}
}
}
/*
* Test that bundles installed when the bundle event hook is unavailable
* (i.e. when the subsystems core bundle is stopped) are handled properly
* by the hook when uninstalled.
*
* See https://issues.apache.org/jira/browse/ARIES-967.
*/
@Test
public void testBundleEventHook() throws Exception {
Bundle core = getSubsystemCoreBundle();
// Stop the subsystems core bundle so the bundle event hook is not registered.
core.stop();
try {
// Install an unmanaged bundle that will not be seen by the bundle event hook.
Bundle a = bundleContext.installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A));
try {
// Restart the subsystems core bundle.
core.start();
// Bundle A should be detected as a constituent of the root subsystem.
assertConstituent(getRootSubsystem(), BUNDLE_A);
// Uninstall bundle A so that it is seen by the bundle event hook.
a.uninstall();
// Bundle A should no longer be a constituent of the root subsystem.
assertNotConstituent(getRootSubsystem(), BUNDLE_A);
}
finally {
uninstallSilently(a);
}
}
finally {
try {
core.start();
}
catch (Exception e) {}
}
}
}
| 8,705 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/NoBSNTest.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.subsystem.itests;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.apache.aries.subsystem.itests.util.TestCapability;
import org.apache.aries.subsystem.itests.util.TestRepository;
import org.apache.aries.subsystem.itests.util.TestRepositoryContent;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.resource.Resource;
import org.osgi.service.repository.Repository;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class NoBSNTest extends SubsystemTest {
@Override
public void createApplications() throws Exception {
createApplication("nobsn", "tb1.jar");
}
/*
* Subsystem application1 has content bundle tb1.jar.
* Bundle tb1.jar has an import package dependency on org.apache.aries.subsystem.itests.tb3.
*/
@Test
public void testApplication1() throws Exception {
Subsystem nobsn = installSubsystemFromFile("nobsn.esa");
try {
assertSymbolicName("org.apache.aries.subsystem.nobsn", nobsn);
assertVersion("0.0.0", nobsn);
assertType(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, nobsn);
assertChildren(0, nobsn);
assertConstituents(1, nobsn);
startSubsystem(nobsn);
}
finally {
stopSubsystemSilently(nobsn);
uninstallSubsystemSilently(nobsn);
}
}
}
| 8,706 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/BasicTest.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.subsystem.itests;
import org.junit.Test;
import org.osgi.framework.Version;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class BasicTest extends SubsystemTest {
@Override
public void createApplications() throws Exception {
createApplication("emptyFeature", new String[]{});
createApplication("emptySubsystem", new String[]{});
}
@Test
public void testEmptyFeature() throws Exception {
Subsystem emptyFeature = installSubsystemFromFile("emptyFeature.esa");
AssertionError error = null;
try {
assertSymbolicName("org.apache.aries.subsystem.itests.feature.empty", emptyFeature);
assertVersion("1.1.2", emptyFeature);
assertType(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE, emptyFeature);
assertConstituents(0, emptyFeature);
assertChildren(0, emptyFeature);
startSubsystem(emptyFeature);
stopSubsystem(emptyFeature);
}
catch (AssertionError e) {
error = e;
throw e;
}
finally {
try {
uninstallSubsystemSilently(emptyFeature);
}
catch (AssertionError e) {
if (error == null)
throw e;
e.printStackTrace();
}
}
}
/*
* This tests a subsystem containing only a subsystem manifest which, in
* turn, contains only a Subsystem-SymbolicName header.
*/
@Test
public void testEmptySubsystem() throws Exception {
Subsystem emptySubsystem = installSubsystemFromFile("emptySubsystem.esa");
AssertionError error = null;
try {
assertSymbolicName("org.apache.aries.subsystem.itests.subsystem.empty", emptySubsystem);
// The version should be the default version.
assertVersion(Version.emptyVersion, emptySubsystem);
// The type should be the default type.
assertType(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, emptySubsystem);
// Since the default type is application, which is a scoped subsystem, there will
// be one constituent representing the region context bundle.
assertConstituents(1, emptySubsystem);
assertChildren(0, emptySubsystem);
startSubsystem(emptySubsystem);
stopSubsystem(emptySubsystem);
}
catch (AssertionError e) {
error = e;
throw e;
}
finally {
try {
uninstallSubsystemSilently(emptySubsystem);
}
catch (AssertionError e) {
if (error == null)
throw e;
e.printStackTrace();
}
}
}
}
| 8,707 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/DynamicImportTest.java | package org.apache.aries.subsystem.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.aries.itest.RichBundleContext;
import org.apache.aries.subsystem.itests.hello.api.Hello;
import org.apache.aries.unittest.fixture.ArchiveFixture;
import org.apache.aries.unittest.fixture.ArchiveFixture.JarFixture;
import org.apache.aries.unittest.fixture.ArchiveFixture.ManifestFixture;
import org.junit.Test;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.hooks.weaving.WeavingHook;
import org.osgi.framework.hooks.weaving.WovenClass;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
/*
* Simple iTest for dynamic imports. In the first instance we'll use a
* DynamicImport-Package header because it's the simplest to set up.
* _Hopefully_ if this works, then packages added by WeavingProxy services
* will also work. If not, we'll need extra tests :-/
*/
@ExamReactorStrategy(PerMethod.class)
public class DynamicImportTest extends SubsystemTest
{
@Override
protected void createApplications() throws Exception {
createApplication("dynamicImport", "dynamicImport.jar");
createEmptyClass();
createBundleA();
createApplicationA();
}
/*
* Install an .esa containing a bundle with a BundleActivator, and a
* DynamicImport-Package on org.apache.aries.subsystem.itests.hello.api.
* This app should fail to start because we've not yet intervened to permit
* this dynamic package wiring requirement from being met.
*/
@Test
public void verifyThatDynamicImportNeedsHandling() throws Exception
{
Subsystem subsystem = installSubsystemFromFile ("dynamicImport.esa");
try {
startSubsystem(subsystem);
Bundle[] bundles = subsystem.getBundleContext().getBundles();
for (Bundle b : bundles) {
System.out.println (b.getSymbolicName() + " -> " + b.getState());
}
fail ("dynamicImport.esa started when we didn't expect it to");
} catch (SubsystemException sx) {
Throwable cause = sx.getCause();
assertTrue("BundleException expected", cause instanceof BundleException);
}
}
class TokenWeaver implements WeavingHook {
@Override
public void weave(WovenClass arg0) {
if ("org.apache.aries.subsystem.itests.dynamicImport".equals(arg0.getBundleWiring().getBundle().getSymbolicName())) {
arg0.getDynamicImports().add("org.apache.aries.subsystem.itests.hello.api");
}
}
}
@SuppressWarnings("rawtypes")
@Test
public void testFirstPassWeavingApproach() throws Exception
{
ServiceRegistration<?> sr = bundleContext.registerService(WeavingHook.class, new TokenWeaver(), null);
try {
Subsystem subsystem = installSubsystemFromFile ("dynamicImport.esa");
startSubsystem(subsystem);
BundleContext bc = subsystem.getBundleContext();
Hello h = new RichBundleContext(bc).getService(Hello.class);
String message = h.saySomething();
assertEquals ("Wrong message back", "Hello, this is something", message); // DynamicImportHelloImpl.java
stopSubsystem(subsystem);
uninstallSubsystem(subsystem);
} finally {
sr.unregister();
}
}
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
*/
private static final String BUNDLE_A = "bundle.a.jar";
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private static void createBundleA() throws IOException {
JarFixture bundle = ArchiveFixture.newJar();
bundle.binary("Empty.class", new FileInputStream("Empty.class"));
ManifestFixture manifest = bundle.manifest();
manifest.attribute(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_A);
write(BUNDLE_A, bundle);
}
/*
* Dynamic package imports added by a weaver to a woven class should be
* added to the region's sharing policy even if the subsystem has no
* Import-Package header.
*/
@SuppressWarnings("rawtypes")
@Test
public void testDynamicPackageImportsAddedToSharingPolicyWhenNoImportPackageHeader() throws Exception {
final AtomicBoolean weavingHookCalled = new AtomicBoolean(false);
ServiceRegistration reg = bundleContext.registerService(
WeavingHook.class,
new WeavingHook() {
@Override
public void weave(WovenClass wovenClass) {
if (BUNDLE_A.equals(wovenClass.getBundleWiring().getBundle().getSymbolicName())) {
wovenClass.getDynamicImports().add("org.osgi.framework");
weavingHookCalled.set(true);
}
}
},
null);
try {
Subsystem s = installSubsystemFromFile(APPLICATION_A);
try {
assertNull("Import-Package header should not exist", s.getSubsystemHeaders(null).get(Constants.IMPORT_PACKAGE));
Bundle a = getConstituentAsBundle(s, BUNDLE_A, null, null);
// Force the class load so the weaving hook gets called.
a.loadClass("Empty");
assertTrue("Weaving hook not called", weavingHookCalled.get());
try {
// Try to load a class from the dynamically imported package.
a.loadClass("org.osgi.framework.Bundle");
}
catch (Exception e) {
fail("Woven dynamic package import not added to the region's sharing policy");
}
}
finally {
try {
s.uninstall();
}
catch (Exception e) {}
}
}
finally {
try {
reg.unregister();
}
catch (Exception e) {}
}
}
protected static final byte[] EMPTY_CLASS = new byte[] {
(byte)0xca, (byte)0xfe, (byte)0xba, (byte)0xbe,
(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x32,
(byte)0x00, (byte)0x12, (byte)0x07, (byte)0x00,
(byte)0x02, (byte)0x01, (byte)0x00, (byte)0x05,
(byte)0x45, (byte)0x6d, (byte)0x70, (byte)0x74,
(byte)0x79, (byte)0x07, (byte)0x00, (byte)0x04,
(byte)0x01, (byte)0x00, (byte)0x10, (byte)0x6a,
(byte)0x61, (byte)0x76, (byte)0x61, (byte)0x2f,
(byte)0x6c, (byte)0x61, (byte)0x6e, (byte)0x67,
(byte)0x2f, (byte)0x4f, (byte)0x62, (byte)0x6a,
(byte)0x65, (byte)0x63, (byte)0x74, (byte)0x07,
(byte)0x00, (byte)0x06, (byte)0x01, (byte)0x00,
(byte)0x14, (byte)0x6a, (byte)0x61, (byte)0x76,
(byte)0x61, (byte)0x2f, (byte)0x69, (byte)0x6f,
(byte)0x2f, (byte)0x53, (byte)0x65, (byte)0x72,
(byte)0x69, (byte)0x61, (byte)0x6c, (byte)0x69,
(byte)0x7a, (byte)0x61, (byte)0x62, (byte)0x6c,
(byte)0x65, (byte)0x01, (byte)0x00, (byte)0x06,
(byte)0x3c, (byte)0x69, (byte)0x6e, (byte)0x69,
(byte)0x74, (byte)0x3e, (byte)0x01, (byte)0x00,
(byte)0x03, (byte)0x28, (byte)0x29, (byte)0x56,
(byte)0x01, (byte)0x00, (byte)0x04, (byte)0x43,
(byte)0x6f, (byte)0x64, (byte)0x65, (byte)0x0a,
(byte)0x00, (byte)0x03, (byte)0x00, (byte)0x0b,
(byte)0x0c, (byte)0x00, (byte)0x07, (byte)0x00,
(byte)0x08, (byte)0x01, (byte)0x00, (byte)0x0f,
(byte)0x4c, (byte)0x69, (byte)0x6e, (byte)0x65,
(byte)0x4e, (byte)0x75, (byte)0x6d, (byte)0x62,
(byte)0x65, (byte)0x72, (byte)0x54, (byte)0x61,
(byte)0x62, (byte)0x6c, (byte)0x65, (byte)0x01,
(byte)0x00, (byte)0x12, (byte)0x4c, (byte)0x6f,
(byte)0x63, (byte)0x61, (byte)0x6c, (byte)0x56,
(byte)0x61, (byte)0x72, (byte)0x69, (byte)0x61,
(byte)0x62, (byte)0x6c, (byte)0x65, (byte)0x54,
(byte)0x61, (byte)0x62, (byte)0x6c, (byte)0x65,
(byte)0x01, (byte)0x00, (byte)0x04, (byte)0x74,
(byte)0x68, (byte)0x69, (byte)0x73, (byte)0x01,
(byte)0x00, (byte)0x07, (byte)0x4c, (byte)0x45,
(byte)0x6d, (byte)0x70, (byte)0x74, (byte)0x79,
(byte)0x3b, (byte)0x01, (byte)0x00, (byte)0x0a,
(byte)0x53, (byte)0x6f, (byte)0x75, (byte)0x72,
(byte)0x63, (byte)0x65, (byte)0x46, (byte)0x69,
(byte)0x6c, (byte)0x65, (byte)0x01, (byte)0x00,
(byte)0x0a, (byte)0x45, (byte)0x6d, (byte)0x70,
(byte)0x74, (byte)0x79, (byte)0x2e, (byte)0x6a,
(byte)0x61, (byte)0x76, (byte)0x61, (byte)0x00,
(byte)0x21, (byte)0x00, (byte)0x01, (byte)0x00,
(byte)0x03, (byte)0x00, (byte)0x01, (byte)0x00,
(byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00,
(byte)0x01, (byte)0x00, (byte)0x01, (byte)0x00,
(byte)0x07, (byte)0x00, (byte)0x08, (byte)0x00,
(byte)0x01, (byte)0x00, (byte)0x09, (byte)0x00,
(byte)0x00, (byte)0x00, (byte)0x2f, (byte)0x00,
(byte)0x01, (byte)0x00, (byte)0x01, (byte)0x00,
(byte)0x00, (byte)0x00, (byte)0x05, (byte)0x2a,
(byte)0xb7, (byte)0x00, (byte)0x0a, (byte)0xb1,
(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x02,
(byte)0x00, (byte)0x0c, (byte)0x00, (byte)0x00,
(byte)0x00, (byte)0x06, (byte)0x00, (byte)0x01,
(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x04,
(byte)0x00, (byte)0x0d, (byte)0x00, (byte)0x00,
(byte)0x00, (byte)0x0c, (byte)0x00, (byte)0x01,
(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x05,
(byte)0x00, (byte)0x0e, (byte)0x00, (byte)0x0f,
(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01,
(byte)0x00, (byte)0x10, (byte)0x00, (byte)0x00,
(byte)0x00, (byte)0x02, (byte)0x00, (byte)0x11
};
protected static void createEmptyClass() throws IOException {
FileOutputStream fos = new FileOutputStream("Empty.class");
fos.write(EMPTY_CLASS);
fos.close();
}
}
| 8,708 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/OptionalDependenciesTest.java | /*
* 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.apache.aries.subsystem.itests;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class OptionalDependenciesTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Import-Package: x;resolution:=optional
* Require-Bundle: x;resolution:=optional
* Require-Capability: x;resolution:=optional
*/
private static final String BUNDLE_A = "bundle.a.jar";
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), importPackage("x;resolution:=optional"),
requireBundle("x;resolution:=optional"),
new Header(Constants.REQUIRE_CAPABILITY, "x;resolution:=optional"));
}
@Override
public void createApplications() throws Exception {
createBundleA();
createApplicationA();
}
@Test
public void testOptionalImportPackage() throws Exception {
try {
Subsystem subsystem = installSubsystemFromFile(APPLICATION_A);
try {
try {
startSubsystem(subsystem);
}
catch (Exception e) {
e.printStackTrace();
fail("Missing optional requirements must not cause subsystem start failure");
}
}
finally {
stopAndUninstallSubsystemSilently(subsystem);
}
}
catch (Exception e) {
e.printStackTrace();
fail("Missing optional requirements must not cause subsystem installation failure");
}
}
}
| 8,709 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/NoRequirementFilterTest.java | /*
* 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.apache.aries.subsystem.itests;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* Generic requirements are not required to specify the filter directive, in
* which case it would match any capability from the same namespace.
*
* Generic capabilities are not required to use the namespace as an attribute.
*/
public class NoRequirementFilterTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Require-Capability: y
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Provide-Capability: y
*/
private static final String BUNDLE_B = "bundle.b.jar";
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), new Header(Constants.REQUIRE_CAPABILITY, "y"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), new Header(Constants.PROVIDE_CAPABILITY, "y"));
}
@Override
protected void createApplications() throws Exception {
createBundleA();
createBundleB();
createApplicationA();
}
public void setUp() throws Exception {
super.setUp();
registerRepositoryService(BUNDLE_A);
}
@Test
public void testNoFilterDirectiveWithNoNamespaceAttribute() throws Exception {
Bundle bundleB = installBundleFromFile(BUNDLE_B);
try {
Subsystem subsystem = installSubsystemFromFile(APPLICATION_A);
try {
startSubsystem(subsystem);
stopSubsystem(subsystem);
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
finally {
uninstallSilently(bundleB);
}
}
}
| 8,710 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/AutostartTest.java | /*
* 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.apache.aries.subsystem.itests;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class AutostartTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: application.b.esa
* Subsystem-Content: bundle.a.jar,application.a.esa;type=osgi.subsystem.application
*/
private static final String APPLICATION_B = "application.b.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Export-Package: x
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Import-Package: x
*/
private static final String BUNDLE_B = "bundle.b.jar";
/*
* Subsystem-SymbolicName: composite.a.esa
* Subsystem-Type: osgi.subsystem.composite
* Subsystem-Content: bundle.a.jar;version="[0,0]"
* Export-Package: x
*/
private static final String COMPOSITE_A = "composite.a.esa";
/*
* Subsystem-SymbolicName: composite.b.esa
* Subsystem-Type: osgi.subsystem.composite
* Subsystem-Content: bundle.a.jar;version="[0,0]"
* Import-Package: x
* Preferred-Provider: composite.a.esa
*/
private static final String COMPOSITE_B = "composite.b.esa";
/*
* Subsystem-SymbolicName: feature.a.esa
* Subsystem-Type: osgi.subsystem.feature
* Subsystem-Content: bundle.a.jar
*/
private static final String FEATURE_A = "feature.a.esa";
/*
* Subsystem-SymbolicName: feature.b.esa
* Subsystem-Type: osgi.subsystem.feature
* Subsystem-Content: bundle.a.jar,feature.a.esa;type=osgi.subsystem.feature
*/
private static final String FEATURE_B = "feature.b.esa";
/*
* Subsystem-SymbolicName: feature.c.esa
* Subsystem-Type: osgi.subsystem.feature
* Subsystem-Content: bundle.a.jar,feature.a.esa;type=osgi.subsystem.feature
*/
private static final String FEATURE_C = "feature.c.esa";
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B, BUNDLE_A, APPLICATION_A);
}
private void createApplicationBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A + ',' + APPLICATION_A + ';' + IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE + '=' + SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION);
createManifest(APPLICATION_B + ".mf", attributes);
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), exportPackage("x"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), importPackage("x"));
}
private void createCompositeA() throws IOException {
createCompositeAManifest();
createSubsystem(COMPOSITE_A, BUNDLE_A);
}
private void createCompositeAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A + ';' + IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE + "=\"[0,0]\"");
attributes.put(Constants.EXPORT_PACKAGE, "x");
createManifest(COMPOSITE_A + ".mf", attributes);
}
private static void createCompositeB() throws IOException {
createCompositeBManifest();
createSubsystem(COMPOSITE_B, BUNDLE_B);
}
private static void createCompositeBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_B);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_B + ';' + IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE + "=\"[0,0]\"");
attributes.put(Constants.IMPORT_PACKAGE, "x");
attributes.put(SubsystemConstants.PREFERRED_PROVIDER, COMPOSITE_A);
createManifest(COMPOSITE_B + ".mf", attributes);
}
private static void createFeatureA() throws IOException {
createFeatureAManifest();
createSubsystem(FEATURE_A, BUNDLE_A);
}
private static void createFeatureAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(FEATURE_A + ".mf", attributes);
}
private static void createFeatureB() throws IOException {
createFeatureBManifest();
createSubsystem(FEATURE_B, BUNDLE_A);
}
private static void createFeatureBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_B);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(FEATURE_B + ".mf", attributes);
}
private static void createFeatureC() throws IOException {
createFeatureCManifest();
createSubsystem(FEATURE_C, BUNDLE_A, FEATURE_A);
}
private static void createFeatureCManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_C);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A + ',' + FEATURE_A + ';' + IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE + '=' + SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
createManifest(FEATURE_C + ".mf", attributes);
}
@Override
public void createApplications() throws Exception {
createBundleA();
createBundleB();
createApplicationA();
createApplicationB();
createCompositeA();
createCompositeB();
createFeatureA();
createFeatureB();
createFeatureC();
}
@Test
public void testAutostartScoped() throws Exception {
Subsystem subsystem = null;
try {
subsystem = installSubsystemFromFile(APPLICATION_A);
restartSubsystemsImplBundle();
subsystem = findSubsystemService(subsystem.getSubsystemId());
assertState(Subsystem.State.INSTALLED, subsystem);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, subsystem);
startSubsystem(subsystem);
restartSubsystemsImplBundle();
subsystem = findSubsystemService(subsystem.getSubsystemId());
assertState(Subsystem.State.ACTIVE, subsystem);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, subsystem);
stopSubsystem(subsystem);
restartSubsystemsImplBundle();
subsystem = findSubsystemService(subsystem.getSubsystemId());
assertState(Subsystem.State.RESOLVED, subsystem);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, subsystem);
}
finally {
stopAndUninstallSubsystemSilently(subsystem);
}
}
@Test
public void testAutostartUnscoped() throws Exception {
Subsystem subsystem = null;
try {
subsystem = installSubsystemFromFile(FEATURE_A);
restartSubsystemsImplBundle();
subsystem = findSubsystemService(subsystem.getSubsystemId());
assertState(Subsystem.State.INSTALLED, subsystem);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, subsystem);
startSubsystem(subsystem);
restartSubsystemsImplBundle();
subsystem = findSubsystemService(subsystem.getSubsystemId());
assertState(Subsystem.State.ACTIVE, subsystem);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, subsystem);
stopSubsystem(subsystem);
restartSubsystemsImplBundle();
subsystem = findSubsystemService(subsystem.getSubsystemId());
assertState(Subsystem.State.RESOLVED, subsystem);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, subsystem);
}
finally {
stopAndUninstallSubsystemSilently(subsystem);
}
}
@Test
public void testAutostartChildScoped() throws Exception {
Subsystem compositeA = null;
try {
compositeA = installSubsystemFromFile(COMPOSITE_A);
Subsystem applicationA = installSubsystemFromFile(compositeA, APPLICATION_A);
restartSubsystemsImplBundle();
compositeA = findSubsystemService(compositeA.getSubsystemId());
applicationA = findSubsystemService(applicationA.getSubsystemId());
assertState(Subsystem.State.INSTALLED, compositeA);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, compositeA);
assertState(Subsystem.State.INSTALLED, applicationA);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, applicationA);
startSubsystem(compositeA);
restartSubsystemsImplBundle();
compositeA = findSubsystemService(compositeA.getSubsystemId());
applicationA = findSubsystemService(applicationA.getSubsystemId());;
assertState(Subsystem.State.ACTIVE, compositeA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, compositeA);
assertState(Subsystem.State.RESOLVED, applicationA);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, applicationA);
startSubsystemFromResolved(applicationA);
restartSubsystemsImplBundle();
compositeA = findSubsystemService(compositeA.getSubsystemId());
applicationA = findSubsystemService(applicationA.getSubsystemId());;
assertState(Subsystem.State.ACTIVE, compositeA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, compositeA);
assertState(Subsystem.State.ACTIVE, applicationA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, applicationA);
stopSubsystem(applicationA);
restartSubsystemsImplBundle();
compositeA = findSubsystemService(compositeA.getSubsystemId());
applicationA = findSubsystemService(applicationA.getSubsystemId());;
assertState(Subsystem.State.ACTIVE, compositeA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, compositeA);
assertState(Subsystem.State.RESOLVED, applicationA);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, applicationA);
startSubsystemFromResolved(applicationA);
stopSubsystem(compositeA);
restartSubsystemsImplBundle();
compositeA = findSubsystemService(compositeA.getSubsystemId());
applicationA = findSubsystemService(applicationA.getSubsystemId());;
assertState(Subsystem.State.RESOLVED, compositeA);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, compositeA);
assertState(Subsystem.State.RESOLVED, applicationA);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, compositeA);
}
finally {
stopAndUninstallSubsystemSilently(compositeA);
}
}
@Test
public void testAutostartChildUnscoped() throws Exception {
Subsystem featureA = null;
try {
featureA = installSubsystemFromFile(FEATURE_A);
Subsystem featureB = installSubsystemFromFile(featureA, FEATURE_B);
restartSubsystemsImplBundle();
featureA = findSubsystemService(featureA.getSubsystemId());
featureB = findSubsystemService(featureB.getSubsystemId());
assertState(Subsystem.State.INSTALLED, featureA);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, featureA);
assertState(Subsystem.State.INSTALLED, featureB);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, featureB);
startSubsystem(featureA);
restartSubsystemsImplBundle();
featureA = findSubsystemService(featureA.getSubsystemId());
featureB = findSubsystemService(featureB.getSubsystemId());;
assertState(Subsystem.State.ACTIVE, featureA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureA);
assertState(Subsystem.State.RESOLVED, featureB);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureB);
startSubsystemFromResolved(featureB);
restartSubsystemsImplBundle();
featureA = findSubsystemService(featureA.getSubsystemId());
featureB = findSubsystemService(featureB.getSubsystemId());;
assertState(Subsystem.State.ACTIVE, featureA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureA);
assertState(Subsystem.State.ACTIVE, featureB);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureB);
stopSubsystem(featureB);
restartSubsystemsImplBundle();
featureA = findSubsystemService(featureA.getSubsystemId());
featureB = findSubsystemService(featureB.getSubsystemId());;
assertState(Subsystem.State.ACTIVE, featureA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureA);
assertState(Subsystem.State.RESOLVED, featureB);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureB);
startSubsystemFromResolved(featureB);
stopSubsystem(featureA);
restartSubsystemsImplBundle();
featureA = findSubsystemService(featureA.getSubsystemId());
featureB = findSubsystemService(featureB.getSubsystemId());;
assertState(Subsystem.State.RESOLVED, featureA);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, featureA);
assertState(Subsystem.State.RESOLVED, featureB);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, featureA);
}
finally {
stopAndUninstallSubsystemSilently(featureA);
}
}
@Test
public void testAutostartChildAsContentScoped() throws Exception {
Subsystem applicationB = null;
try {
applicationB = installSubsystemFromFile(APPLICATION_B);
Subsystem applicationA = applicationB.getChildren().iterator().next();
restartSubsystemsImplBundle();
applicationB = findSubsystemService(applicationB.getSubsystemId());
applicationA = findSubsystemService(applicationA.getSubsystemId());
assertState(Subsystem.State.INSTALLED, applicationB);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, applicationB);
assertState(Subsystem.State.INSTALLED, applicationA);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, applicationA);
startSubsystem(applicationB);
restartSubsystemsImplBundle();
applicationB = findSubsystemService(applicationB.getSubsystemId());
applicationA = findSubsystemService(applicationA.getSubsystemId());;
assertState(Subsystem.State.ACTIVE, applicationB);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, applicationB);
assertState(Subsystem.State.ACTIVE, applicationA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, applicationA);
stopSubsystem(applicationA);
restartSubsystemsImplBundle();
applicationB = findSubsystemService(applicationB.getSubsystemId());
applicationA = findSubsystemService(applicationA.getSubsystemId());;
assertState(Subsystem.State.ACTIVE, applicationB);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, applicationB);
assertState(Subsystem.State.ACTIVE, applicationA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, applicationA);
stopSubsystem(applicationB);
restartSubsystemsImplBundle();
applicationB = findSubsystemService(applicationB.getSubsystemId());
applicationA = findSubsystemService(applicationA.getSubsystemId());;
assertState(Subsystem.State.RESOLVED, applicationB);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, applicationB);
assertState(Subsystem.State.RESOLVED, applicationA);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, applicationA);
}
finally {
stopAndUninstallSubsystemSilently(applicationB);
}
}
@Test
public void testAutostartChildAsContentUnscoped() throws Exception {
Subsystem featureC = null;
try {
featureC = installSubsystemFromFile(FEATURE_C);
Subsystem featureA = featureC.getChildren().iterator().next();
restartSubsystemsImplBundle();
featureC = findSubsystemService(featureC.getSubsystemId());
featureA = findSubsystemService(featureA.getSubsystemId());
assertState(Subsystem.State.INSTALLED, featureC);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, featureC);
assertState(Subsystem.State.INSTALLED, featureA);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, featureA);
startSubsystem(featureC);
restartSubsystemsImplBundle();
featureC = findSubsystemService(featureC.getSubsystemId());
featureA = findSubsystemService(featureA.getSubsystemId());;
assertState(Subsystem.State.ACTIVE, featureC);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureC);
assertState(Subsystem.State.ACTIVE, featureA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureA);
stopSubsystem(featureA);
restartSubsystemsImplBundle();
featureC = findSubsystemService(featureC.getSubsystemId());
featureA = findSubsystemService(featureA.getSubsystemId());;
assertState(Subsystem.State.ACTIVE, featureC);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureC);
assertState(Subsystem.State.ACTIVE, featureA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureA);
stopSubsystem(featureC);
restartSubsystemsImplBundle();
featureC = findSubsystemService(featureC.getSubsystemId());
featureA = findSubsystemService(featureA.getSubsystemId());;
assertState(Subsystem.State.RESOLVED, featureC);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, featureC);
assertState(Subsystem.State.RESOLVED, featureA);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, featureA);
}
finally {
stopAndUninstallSubsystemSilently(featureC);
}
}
@Test
public void testAutostartDependency() throws Exception {
Subsystem compositeA = installSubsystemFromFile(COMPOSITE_A);
try {
Subsystem compositeB = installSubsystemFromFile(COMPOSITE_B);
try {
restartSubsystemsImplBundle();
compositeB = findSubsystemService(compositeB.getSubsystemId());
compositeA = findSubsystemService(compositeA.getSubsystemId());
assertState(Subsystem.State.INSTALLED, compositeB);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_B, compositeB);
assertState(Subsystem.State.INSTALLED, compositeA);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_A, compositeA);
startSubsystem(compositeA);
restartSubsystemsImplBundle();
compositeB = findSubsystemService(compositeB.getSubsystemId());
compositeA = findSubsystemService(compositeA.getSubsystemId());
assertState(Subsystem.State.INSTALLED, compositeB);
assertBundleState(Bundle.INSTALLED | Bundle.RESOLVED, BUNDLE_B, compositeB);
assertState(Subsystem.State.ACTIVE, compositeA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, compositeA);
stopSubsystem(compositeA);
startSubsystem(compositeB);
restartSubsystemsImplBundle();
compositeB = findSubsystemService(compositeB.getSubsystemId());
compositeA = findSubsystemService(compositeA.getSubsystemId());
assertState(Subsystem.State.ACTIVE, compositeB);
assertBundleState(Bundle.ACTIVE, BUNDLE_B, compositeB);
assertState(Subsystem.State.ACTIVE, compositeA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, compositeA);
stopSubsystem(compositeB);
restartSubsystemsImplBundle();
compositeB = findSubsystemService(compositeB.getSubsystemId());
compositeA = findSubsystemService(compositeA.getSubsystemId());
assertState(Subsystem.State.RESOLVED, compositeB);
assertBundleState(Bundle.RESOLVED, BUNDLE_B, compositeB);
assertState(Subsystem.State.RESOLVED, compositeA);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, compositeA);
uninstallSubsystem(compositeB);
restartSubsystemsImplBundle();
compositeA = findSubsystemService(compositeA.getSubsystemId());
assertState(Subsystem.State.RESOLVED, compositeA);
assertBundleState(Bundle.RESOLVED, BUNDLE_A, compositeA);
startSubsystemFromResolved(compositeA);
restartSubsystemsImplBundle();
compositeA = findSubsystemService(compositeA.getSubsystemId());
assertState(Subsystem.State.ACTIVE, compositeA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, compositeA);
}
finally {
stopAndUninstallSubsystemSilently(compositeB);
}
}
finally {
stopAndUninstallSubsystemSilently(compositeA);
}
}
@Test
/* Start a composite with a dependency on an installed, but unresolved subsystem.
* The unresolved dependency should be auto-resolved and started (test fix to
* bug ARIES-1348).
*
* composite b imports package exported by a bundle in composite.a.
* - install composite a
* - install composite b
* - start composite b
*/
public void testStartCompositeWithUnresolvedDependency() throws Exception {
Subsystem compositeA = installSubsystemFromFile(COMPOSITE_A);
Subsystem compositeB = installSubsystemFromFile(COMPOSITE_B);
try {
startSubsystem(compositeB);
// A should be automatically resolved and started.
assertState(Subsystem.State.ACTIVE, compositeA);
}
finally {
stopSubsystemSilently(compositeB);
stopSubsystemSilently(compositeA);
uninstallSubsystemSilently(compositeB);
uninstallSubsystemSilently(compositeA);
}
}
}
| 8,711 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/SubsystemEventHandler.java | package org.apache.aries.subsystem.itests;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.Version;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemConstants;
public class SubsystemEventHandler implements ServiceListener {
static class ServiceEventInfo {
private final ServiceEvent event;
private final long id;
private final State state;
private final String symbolicName;
private final String type;
private final Version version;
public ServiceEventInfo(ServiceEvent event) {
id = (Long)event.getServiceReference().getProperty(SubsystemConstants.SUBSYSTEM_ID_PROPERTY);
state = (State)event.getServiceReference().getProperty(SubsystemConstants.SUBSYSTEM_STATE_PROPERTY);
symbolicName = (String)event.getServiceReference().getProperty(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME_PROPERTY);
type = (String)event.getServiceReference().getProperty(SubsystemConstants.SUBSYSTEM_TYPE_PROPERTY);
version = (Version)event.getServiceReference().getProperty(SubsystemConstants.SUBSYSTEM_VERSION_PROPERTY);
this.event = event;
}
public int getEventType() {
return event.getType();
}
public long getId() {
return id;
}
public State getState() {
return state;
}
public String getSymbolicName() {
return symbolicName;
}
public String getType() {
return type;
}
public Version getVersion() {
return version;
}
}
private final Map<Long, List<SubsystemEventHandler.ServiceEventInfo>> subsystemIdToEvents = new HashMap<Long, List<SubsystemEventHandler.ServiceEventInfo>>();
public void clear() {
synchronized (subsystemIdToEvents) {
subsystemIdToEvents.clear();
}
}
public SubsystemEventHandler.ServiceEventInfo poll(long subsystemId) throws InterruptedException {
return poll(subsystemId, 0);
}
public SubsystemEventHandler.ServiceEventInfo poll(long subsystemId, long timeout) throws InterruptedException {
List<SubsystemEventHandler.ServiceEventInfo> events;
synchronized (subsystemIdToEvents) {
events = subsystemIdToEvents.get(subsystemId);
if (events == null) {
events = new ArrayList<SubsystemEventHandler.ServiceEventInfo>();
subsystemIdToEvents.put(subsystemId, events);
}
}
synchronized (events) {
if (events.isEmpty()) {
events.wait(timeout);
if (events.isEmpty()) {
return null;
}
}
return events.remove(0);
}
}
public void serviceChanged(ServiceEvent event) {
Long subsystemId = (Long)event.getServiceReference().getProperty(SubsystemConstants.SUBSYSTEM_ID_PROPERTY);
synchronized (subsystemIdToEvents) {
List<SubsystemEventHandler.ServiceEventInfo> events = subsystemIdToEvents.get(subsystemId);
if (events == null) {
events = new ArrayList<SubsystemEventHandler.ServiceEventInfo>();
subsystemIdToEvents.put(subsystemId, events);
}
synchronized (events) {
events.add(new ServiceEventInfo(event));
events.notify();
}
}
}
public int size() {
synchronized (subsystemIdToEvents) {
return subsystemIdToEvents.size();
}
}
} | 8,712 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/BlueprintTest.java | package org.apache.aries.subsystem.itests;
import static org.junit.Assert.assertEquals;
import java.io.InputStream;
import org.apache.aries.itest.RichBundleContext;
import org.apache.aries.subsystem.itests.bundles.blueprint.BPHelloImpl;
import org.apache.aries.subsystem.itests.hello.api.Hello;
import org.junit.Test;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
/*
* iTest for blueprint with subsystems
*/
public class BlueprintTest extends SubsystemTest
{
private static final String BLUEPRINT_ESA = "target/blueprint.esa";
protected void init() throws Exception {
writeToFile(createBlueprintEsa(), BLUEPRINT_ESA);
}
@Test
public void checkBlueprint() throws Exception
{
Subsystem subsystem = installSubsystemFromFile(BLUEPRINT_ESA);
try {
startSubsystem(subsystem);
BundleContext bc = subsystem.getBundleContext();
Hello h = new RichBundleContext(bc).getService(Hello.class);
String message = h.saySomething();
assertEquals("Wrong message back", "messageFromBlueprint", message);
} finally {
stopSubsystem(subsystem);
uninstallSubsystem(subsystem);
}
}
private InputStream createBlueprintEsa() throws Exception {
return TinyBundles.bundle()
.add("OSGI-INF/SUBSYSTEM.MF", getResource("blueprint/OSGI-INF/SUBSYSTEM.MF"))
.add("blueprint.jar", createBlueprintTestBundle())
.build(TinyBundles.withBnd());
}
private InputStream createBlueprintTestBundle() {
return TinyBundles.bundle()
.add(BPHelloImpl.class)
.add("OSGI-INF/blueprint/blueprint.xml", getResource("blueprint/OSGI-INF/blueprint/blueprint.xml"))
.set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.subsystem.itests.blueprint")
.build(TinyBundles.withBnd());
}
}
| 8,713 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/CompositeServiceTest.java | /*
* 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.apache.aries.subsystem.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Dictionary;
import java.util.Hashtable;
import org.junit.Test;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.util.tracker.ServiceTracker;
public class CompositeServiceTest extends SubsystemTest {
@Override
protected void createApplications() throws Exception {
createApplication("composite2", "tb4.jar");
}
@Test
public void testCompositeServiceImportExportWildcards() throws Exception {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put("test", "testCompositeServiceImports");
ServiceRegistration<String> reg = bundleContext.registerService(String.class, "testCompositeServiceImports", props);
Filter filter = bundleContext.createFilter("(&(objectClass=java.lang.String)(test=tb4))");
ServiceTracker<String, String> st = new ServiceTracker<String, String>(bundleContext, filter, null);
st.open();
Subsystem subsystem = installSubsystemFromFile("composite2.esa");
try {
assertEquals(Subsystem.State.INSTALLED, subsystem.getState());
subsystem.start();
String svc = st.waitForService(5000);
assertNotNull("The service registered by the bundle inside the composite cannot be found", svc);
assertEquals(Subsystem.State.ACTIVE, subsystem.getState());
} finally {
subsystem.stop();
uninstallSubsystem(subsystem);
reg.unregister();
st.close();
}
}
}
| 8,714 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/BundleEventHookTest.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.subsystem.itests;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.subsystem.Subsystem;
public class BundleEventHookTest extends SubsystemTest {
/*
* Bundle-SymbolicName: bundle.a.jar
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
*/
private static final String BUNDLE_B = "bundle.b.jar";
@Override
public void createApplications() throws Exception {
createBundleA();
createBundleB();
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B));
}
/*
* See https://issues.apache.org/jira/browse/ARIES-982.
*
* When activating, the subsystems bundle must initialize the root subsystem
* along with any persisted subsystems. Part of the root subsystem
* initialization consists of adding all pre-existing bundles as
* constituents. In order to ensure that no bundles are missed, a bundle
* event hook is registered first. The bundle event hook cannot process
* events until the initialization is complete. Another part of
* initialization consists of registering the root subsystem service.
* Therefore, a potential deadlock exists if something reacts to the
* service registration by installing an unmanaged bundle.
*/
@Test
public void testNoDeadlockWhenSubsystemsInitializing() throws Exception {
final Bundle bundle = getSubsystemCoreBundle();
bundle.stop();
final AtomicBoolean completed = new AtomicBoolean(false);
final ExecutorService executor = Executors.newFixedThreadPool(2);
try {
bundleContext.addServiceListener(new ServiceListener() {
@Override
public void serviceChanged(ServiceEvent event) {
Future<?> future = executor.submit(new Runnable() {
public void run() {
try {
Bundle a = bundle.getBundleContext().installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A));
completed.set(true);
a.uninstall();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
try {
future.get();
completed.set(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
}, "(&(objectClass=org.osgi.service.subsystem.Subsystem)(subsystem.id=0))");
Future<?> future = executor.submit(new Runnable() {
public void run() {
try {
bundle.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
try {
future.get(3, TimeUnit.SECONDS);
assertTrue("Deadlock detected", completed.get());
}
catch (TimeoutException e) {
fail("Deadlock detected");
}
}
finally {
executor.shutdownNow();
}
}
/*
* Because bundle events are queued for later asynchronous processing while
* the root subsystem is initializing, it is possible to see an installed
* event for a bundle that has been uninstalled (i.e. the bundle revision
* will be null). These events should be ignored.
*/
@Test
public void testIgnoreUninstalledBundleInAsyncInstalledEvent() throws Exception {
final Bundle core = getSubsystemCoreBundle();
core.stop();
final AtomicReference<Bundle> a = new AtomicReference<Bundle>();
bundleContext.addServiceListener(
new ServiceListener() {
@SuppressWarnings("unchecked")
@Override
public void serviceChanged(ServiceEvent event) {
if ((event.getType() & (ServiceEvent.REGISTERED | ServiceEvent.MODIFIED)) == 0)
return;
if (a.get() != null)
// We've been here before and already done what needs doing.
return;
ServiceReference sr = (ServiceReference)event.getServiceReference();
bundleContext.getService(sr);
try {
// Queue up the installed event.
a.set(core.getBundleContext().installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A)));
// Ensure the bundle will be uninstalled before the event is processed.
a.get().uninstall();
}
catch (Exception e) {
e.printStackTrace();
}
}
},
"(&(objectClass=org.osgi.service.subsystem.Subsystem)(subsystem.id=0)(subsystem.state=RESOLVED))");
try {
// Before the fix, this would fail due to an NPE resulting from a
// null bundle revision.
core.start();
}
catch (BundleException e) {
e.printStackTrace();
fail("Subsystems failed to handle an asynchronous bundle installed event after the bundle was uninstalled");
}
assertBundleState(a.get(), Bundle.UNINSTALLED);
Subsystem root = getRootSubsystem();
assertState(Subsystem.State.ACTIVE, root);
assertNotConstituent(root, a.get().getSymbolicName());
}
/*
* Because bundle events are queued for later asynchronous processing while
* the root subsystem is initializing, it is possible to see an installed
* event whose origin bundle has been uninstalled (i.e. the origin bundle's
* revision will be null). These events should result in the installed
* bundle being associated with the root subsystem.
*/
@Test
public void testIgnoreUninstalledOriginBundleInAsyncInstalledEvent() throws Exception {
final Bundle core = getSubsystemCoreBundle();
core.stop();
final Bundle b = bundleContext.installBundle(BUNDLE_B, new FileInputStream(BUNDLE_B));
// Ensure bundle B has a context.
b.start();
final AtomicReference<Bundle> a = new AtomicReference<Bundle>();
bundleContext.addServiceListener(
new ServiceListener() {
@SuppressWarnings("unchecked")
@Override
public void serviceChanged(ServiceEvent event) {
if ((event.getType() & (ServiceEvent.REGISTERED | ServiceEvent.MODIFIED)) == 0)
return;
if (a.get() != null)
// We've been here before and already done what needs doing.
return;
ServiceReference sr = (ServiceReference)event.getServiceReference();
bundleContext.getService(sr);
try {
// Queue up the installed event for bundle A using B's context.
a.set(b.getBundleContext().installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A)));
// Ensure the origin bundle will be uninstalled before the event is processed.
b.uninstall();
}
catch (Exception e) {
e.printStackTrace();
}
}
},
"(&(objectClass=org.osgi.service.subsystem.Subsystem)(subsystem.id=0)(subsystem.state=RESOLVED))");
try {
// Before the fix, this would fail due to an NPE resulting from a
// null bundle revision.
core.start();
}
catch (BundleException e) {
e.printStackTrace();
fail("Subsystems failed to handle an asynchronous bundle installed event after the origin bundle was uninstalled");
}
assertBundleState(a.get(), Bundle.INSTALLED);
assertBundleState(b, Bundle.UNINSTALLED);
Subsystem root = getRootSubsystem();
assertState(Subsystem.State.ACTIVE, root);
assertConstituent(root, a.get().getSymbolicName());
}
}
| 8,715 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/ConfigAdminPropsFileContentHandlerTest.java | /*
* 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.apache.aries.subsystem.itests;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.osgi.framework.Filter;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.util.tracker.ServiceTracker;
import java.util.Dictionary;
import java.util.Hashtable;
public class ConfigAdminPropsFileContentHandlerTest extends SubsystemTest {
public ConfigAdminPropsFileContentHandlerTest() {
installConfigAdmin = true;
}
@Override
protected void createApplications() throws Exception {
createApplication("cmContent", "org.foo.Bar.cfg", "com.blah.Blah.cfg",
"cmContentBundleZ.jar");
}
@Test
public void testConfigurationContentHandler() throws Exception {
// This test works as follows: it first installs a subsystem (cmContent.esa)
// that contains two configuration files (org.foo.Bar.cfg and com.blah.Blah.cfg)
// These configuration files are marked as 'osgi.config' content type.
// The ConfigAdminContentHandler handles the installation of this content
// and registers them as configuration with the Config Admin Service.
// The .esa file also contains an ordinary bundle that registers two
// Config Admin ManagedServices. Each registerd under one of the PIDs.
// Once they receive the expected configuration they each register a String
// service to mark that they have.
// After starting the subsystem this test waits for these 'String' services
// to appear so that it knows that the whole process worked.
Subsystem subsystem = installSubsystemFromFile("cmContent.esa");
subsystem.start();
// Now check that both Managed Services (Config Admin services) have been configured
// If they are configured correctly they will register a marker String service to
// indicate this.
Filter f = bundleContext.createFilter(
"(&(objectClass=java.lang.String)(test.pid=org.foo.Bar))");
ServiceTracker<String, String> barTracker =
new ServiceTracker<String, String>(bundleContext, f, null);
try {
barTracker.open();
String blahSvc = barTracker.waitForService(2000);
assertEquals("Bar!", blahSvc);
} finally {
barTracker.close();
}
Filter f2 = bundleContext.createFilter(
"(&(objectClass=java.lang.String)(test.pid=com.blah.Blah))");
ServiceTracker<String, String> blahTracker =
new ServiceTracker<String, String>(bundleContext, f2, null);
try {
blahTracker.open();
String blahSvc = blahTracker.waitForService(2000);
assertEquals("Blah!", blahSvc);
} finally {
blahTracker.close();
}
stopAndUninstallSubsystemSilently(subsystem);
}
@Test
public void testAries1352() throws Exception {
// Same test than testConfigurationContentHandler, but an existing
// configuration exists before the subsystem is installed.
// The configuration should not be overwritten by the subsystem
// installation.
ConfigurationAdmin cm = bundleContext.getService(
bundleContext.getServiceReference(ConfigurationAdmin.class));
Configuration blahConf = cm.getConfiguration("com.blah.Blah", "?");
Dictionary<String, Object> blahProps = new Hashtable<String, Object>(1);
blahProps.put("configVal", "Hello");
blahConf.update(blahProps);
Subsystem subsystem = installSubsystemFromFile("cmContent.esa");
subsystem.start();
// No configuration exists for the service Bar: configuration
// values are loaded by the subsystem.
Filter f = bundleContext.createFilter(
"(&(objectClass=java.lang.String)(test.pid=org.foo.Bar))");
ServiceTracker<String, String> barTracker =
new ServiceTracker<String, String>(bundleContext, f, null);
try {
barTracker.open();
String blahSvc = barTracker.waitForService(2000);
assertEquals("Bar!", blahSvc);
} finally {
barTracker.close();
}
// A configuration exists for Blah: the subsystem installation should
// not overwrite it.
Filter f2 = bundleContext.createFilter(
"(&(objectClass=java.lang.String)(test.pid=com.blah.Blah))");
ServiceTracker<String, String> blahTracker =
new ServiceTracker<String, String>(bundleContext, f2, null);
try {
blahTracker.open();
String blahSvc = blahTracker.waitForService(2000);
assertEquals("Hello", blahSvc);
} finally {
blahTracker.close();
}
stopAndUninstallSubsystemSilently(subsystem);
blahConf.delete();
}
}
| 8,716 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/BundleStartLevelTest.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.subsystem.itests;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class BundleStartLevelTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.b.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Export-Package: x
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Import-Package: x
*/
private static final String BUNDLE_B = "bundle.b.jar";
/*
* Bundle-SymbolicName: bundle.c.jar
*/
private static final String BUNDLE_C = "bundle.c.jar";
@Override
public void createApplications() throws Exception {
createBundleA();
createBundleB();
createBundleC();
createApplicationA();
registerRepositoryService(BUNDLE_A, BUNDLE_B);
}
private void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A);
}
private void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_B);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), exportPackage("x"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), importPackage("x"));
}
private void createBundleC() throws IOException {
createBundle(name(BUNDLE_C));
}
/*
* Tests the start level of bundle constituents.
*
* A managed bundle is a bundle that was installed via the Subsystems API
* either as content or a dependency. This includes the region context
* bundle. The life cycle of managed bundles should follow the life cycle of
* the subsystem of which they are constituents. They therefore receive a
* start level of 1 to ensure they will be started and stopped at the same
* time as the subsystem.
*
* An unmanaged bundle is a bundle that was installed outside of the
* Subsystem API. For example, the root subsystem may contain bundles that
* were installed prior to the subsystems bundle. It's also possible to
* install bundles via subsystem.getBundleContext().install(...). Unmanaged
* bundles retain the start level setting assigned by the framework or
* third party.
*/
@Test
public void testBundleStartLevel() throws Exception {
// Set the default bundle start level to something other than 1.
getSystemBundleAsFrameworkStartLevel().setInitialBundleStartLevel(5);
Subsystem a = installSubsystemFromFile(APPLICATION_A);
try {
startSubsystem(a);
try {
// Test managed bundles.
assertStartLevel(context(a).getBundleByName(BUNDLE_B), 1);
assertStartLevel(getRegionContextBundle(a), 1);
assertStartLevel(context(getRootSubsystem()).getBundleByName(BUNDLE_A), 1);
// Test unmanaged bundle.
Bundle c = installBundleFromFile(BUNDLE_C, a);
try {
assertConstituent(a, BUNDLE_C);
assertStartLevel(c, 5);
}
finally {
uninstallSilently(c);
}
}
finally {
stopSubsystemSilently(a);
}
}
finally {
uninstallSubsystemSilently(a);
}
}
}
| 8,717 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/RootSubsystemTest.java | /*
* 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.apache.aries.subsystem.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.equinox.region.Region;
import org.eclipse.equinox.region.RegionDigraph;
import org.eclipse.equinox.region.RegionFilter;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.Version;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class RootSubsystemTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Import-Package: org.osgi.framework
*/
private static final String BUNDLE_A = "bundle.a.jar";
@Override
public void createApplications() throws Exception {
createBundleA();
createApplicationA();
}
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), importPackage("org.osgi.framework"));
}
// TODO Test root subsystem headers.
@Test
public void testDoNotStartExtraneousRootRegionBundles() throws Exception {
bundleContext.installBundle(new File(BUNDLE_A).toURI().toURL().toString());
getSubsystemCoreBundle().stop();
getSubsystemCoreBundle().start();
Bundle bundleA = context().getBundleByName(BUNDLE_A);
assertTrue("Extraneous root region bundle should not be started", (bundleA.getState() & (Bundle.INSTALLED | Bundle.RESOLVED)) != 0);
}
@Test
public void testId() {
assertEquals("Wrong root ID", getRootSubsystem().getSubsystemId(), 0);
}
@Test
public void testLocation() {
assertEquals("Wrong root location", getRootSubsystem().getLocation(), "subsystem://?Subsystem-SymbolicName=org.osgi.service.subsystem.root&Subsystem-Version=1.0.0");
}
@Test
public void testRegionContextBundle() throws BundleException {
assertRegionContextBundle(getRootSubsystem());
getSubsystemCoreBundle().stop();
getSubsystemCoreBundle().start();
assertRegionContextBundle(getRootSubsystem());
}
@Test
public void testServiceEvents() throws Exception {
Subsystem root = getRootSubsystem();
Bundle core = getSubsystemCoreBundle();
// TODO Temporary(?) workaround to allow time for any tardy service
// events to arrive so they can be cleared. So far, this sleep has only
// been necessary on the IBM 6.0 64-bit JDK.
Thread.sleep(1000);
subsystemEvents.clear();
core.stop();
assertServiceEventsStop(root);
core.uninstall();
core = bundleContext.installBundle(normalizeBundleLocation(core));
core.start();
// There should be install events since the persisted root subsystem was
// deleted when the subsystems implementation bundle was uninstalled.
assertServiceEventsInstall(root);
assertServiceEventsResolve(root);
assertServiceEventsStart(root);
core.stop();
assertServiceEventsStop(root);
core.start();
// There should be no install events or RESOLVING event since there
// should be a persisted root subsystem already in the RESOLVED state.
assertServiceEventResolved(root, ServiceEvent.REGISTERED);
assertServiceEventsStart(root);
}
@Test
public void testSymbolicName() {
assertEquals("Wrong root symbolic name", getRootSubsystem().getSymbolicName(), "org.osgi.service.subsystem.root");
}
@Test
public void testUninstallRootRegionBundleWithNoBundleEventHook() throws Exception {
// Install an extraneous bundle into the root region. The bundle will
// be recorded in the root subsystem's persistent memory.
Bundle bundleA = bundleContext.installBundle(new File(BUNDLE_A).toURI().toURL().toString());
try {
Bundle core = getSubsystemCoreBundle();
// Stop the subsystems bundle in order to unregister the bundle
// event hook.
core.stop();
// Uninstall the bundle so it won't be there on restart.
bundleA.uninstall();
try {
// Start the subsystems bundle and ensure the root subsystem
// recovers from the uninstalled bundle being in persistent
// memory.
core.start();
}
catch (BundleException e) {
fail("Could not start subsystems bundle after uninstalling a root region bundle with no bundle event hook registered");
}
}
finally {
if (Bundle.UNINSTALLED != bundleA.getState())
bundleA.uninstall();
}
}
@Test
public void testVersion() {
assertEquals("Wrong root version", getRootSubsystem().getVersion(), Version.parseVersion("1.0.0"));
}
/*
* The root subsystem should be associated with the region in which the
* subsystems implementation bundle is installed.
*/
@Test
public void testRegion() throws Exception {
RegionDigraph digraph = context().getService(RegionDigraph.class);
Bundle core = getSubsystemCoreBundle();
Region kernel = digraph.getRegion(core);
Subsystem root = getRootSubsystem();
Bundle rootRegionContext = root.getBundleContext().getBundle();
// Get the region containing the subsystem's region context bundle,
// which is the same thing as getting the region with which the
// subsystem is associated.
Region region = digraph.getRegion(root.getBundleContext().getBundle());
assertEquals("Wrong region", kernel, region);
// Uninstall the core bundle to remove the persisted root subsystem.
core.uninstall();
// Clean up the lingering region context bundle.
rootRegionContext.uninstall();
// Create a new region and install the core bundle into it.
Region user = digraph.createRegion("user");
// Allow everything from the kernel region into the user region so the
// core bundle will resolve.
user.connectRegion(
kernel,
digraph.createRegionFilterBuilder().allowAll(RegionFilter.VISIBLE_ALL_NAMESPACE).build());
// Allow everything from the user region into the kernel region so the
// root subsystem service can be found.
kernel.connectRegion(
user,
digraph.createRegionFilterBuilder().allowAll(RegionFilter.VISIBLE_ALL_NAMESPACE).build());
core = user.installBundle(normalizeBundleLocation(core.getLocation()));
user = digraph.getRegion(core);
core.start();
root = getRootSubsystem();
region = digraph.getRegion(root.getBundleContext().getBundle());
// The root subsystem should now be in the new region.
assertEquals("Wrong region", user, region);
// Extra test. Install application A into the root region (user) and
// make sure it resolves. Although the system bundle is in the kernel
// region and not a constituent of the root subsystem, the capability
// should still be found and used.
try {
Subsystem applicationA = installSubsystemFromFile(root, APPLICATION_A);
uninstallSubsystemSilently(applicationA);
}
catch (Exception e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
}
| 8,718 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/ProvisionPolicyTest.java | /*
* 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.apache.aries.subsystem.itests;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
public class ProvisionPolicyTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Type: osgi.subsystem.application;provision-policy:=acceptDependencies
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Import-Package: x
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Export-Package: x
*/
private static final String BUNDLE_B = "bundle.b.jar";
/*
* Subsystem-SymbolicName: composite.a.esa
* Subsystem-Type: osgi.subsystem.composite
* Import-Package: x
*/
private static final String COMPOSITE_A = "composite.a.esa";
/*
* Subsystem-SymbolicName: feature.a.esa
* Subsystem-Type: osgi.subsystem.feature;provision-policy:=acceptDependencies
*/
private static final String FEATURE_A = "feature.a.esa";
/*
* Subsystem-SymbolicName: feature.b.esa
* Subsystem-Type: osgi.subsystem.feature
* Subsystem-Content: bundle.a.jar
*/
private static final String FEATURE_B = "feature.b.esa";
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes
.put(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION
+ ';'
+ SubsystemConstants.PROVISION_POLICY_DIRECTIVE
+ ":="
+ SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), importPackage("x"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), exportPackage("x"));
}
private void createCompositeA() throws IOException {
createCompositeAManifest();
createSubsystem(COMPOSITE_A);
}
private void createCompositeAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(Constants.IMPORT_PACKAGE, "x");
createManifest(COMPOSITE_A + ".mf", attributes);
}
private void createFeatureA() throws IOException {
createFeatureAManifest();
createSubsystem(FEATURE_A);
}
private void createFeatureAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_A);
attributes
.put(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_FEATURE
+ ';'
+ SubsystemConstants.PROVISION_POLICY_DIRECTIVE
+ ":="
+ SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES);
createManifest(FEATURE_A + ".mf", attributes);
}
private static void createFeatureB() throws IOException {
createFeatureBManifest();
createSubsystem(FEATURE_B, BUNDLE_A);
}
private static void createFeatureBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_B);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(FEATURE_B + ".mf", attributes);
}
@Override
public void createApplications() throws Exception {
createBundleA();
createBundleB();
createApplicationA();
createCompositeA();
createFeatureA();
createFeatureB();
}
public void setUp() throws Exception {
super.setUp();
Subsystem root = getRootSubsystem();
assertProvisionPolicy(root, true);
registerRepositoryService(BUNDLE_B);
}
@Test
public void testFailInstallFeatureAcceptDependencies() throws Exception {
Subsystem subsystem = null;
try {
subsystem = installSubsystemFromFile(FEATURE_A);
fail("Feature with provision-policy:=acceptDependencies did not fail installation");
}
catch (SubsystemException e) {
// TODO Brittle...
assertTrue(e.getMessage().contains("Feature subsystems may not declare a provision-policy of acceptDependencies"));
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
@Test
public void testProvisionToNonRootAncestor() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem application = installSubsystemFromFile(root, APPLICATION_A);
try {
assertProvisionPolicy(application, true);
Subsystem composite = installSubsystemFromFile(application, COMPOSITE_A);
try {
assertProvisionPolicy(composite, false);
Subsystem feature = installSubsystemFromFile(composite, FEATURE_B);
try {
assertProvisionPolicy(feature, false);
assertConstituent(feature, BUNDLE_A);
assertNotConstituent(feature, BUNDLE_B);
assertNotConstituent(composite, BUNDLE_A);
assertNotConstituent(composite, BUNDLE_B);
assertConstituent(application, BUNDLE_A);
assertConstituent(application, BUNDLE_B);
assertNotConstituent(root, BUNDLE_A);
assertNotConstituent(root, BUNDLE_B);
}
finally {
uninstallSubsystemSilently(feature);
}
}
finally {
uninstallSubsystemSilently(composite);
}
}
finally {
uninstallSubsystemSilently(application);
}
}
@Test
public void testProvisionToRoot() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem composite = installSubsystemFromFile(root, COMPOSITE_A);
try {
assertProvisionPolicy(composite, false);
Subsystem feature = installSubsystemFromFile(composite, FEATURE_B);
try {
assertProvisionPolicy(feature, false);
assertConstituent(feature, BUNDLE_A);
assertNotConstituent(feature, BUNDLE_B);
assertNotConstituent(composite, BUNDLE_A);
assertNotConstituent(composite, BUNDLE_B);
assertNotConstituent(root, BUNDLE_A);
assertConstituent(root, BUNDLE_B);
}
finally {
uninstallSubsystemSilently(feature);
}
}
finally {
uninstallSubsystemSilently(composite);
}
}
@Test
public void testProvisionToSelf() throws Exception {
Subsystem root = getRootSubsystem();
assertProvisionPolicy(root, true);
registerRepositoryService(BUNDLE_B);
Subsystem subsystem = installSubsystemFromFile(root, APPLICATION_A);
try {
assertProvisionPolicy(subsystem, true);
assertConstituent(subsystem, BUNDLE_A);
assertConstituent(subsystem, BUNDLE_B);
assertNotConstituent(root, BUNDLE_A);
assertNotConstituent(root, BUNDLE_B);
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
}
| 8,719 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/ServiceDependencyTest.java | /*
* 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.apache.aries.subsystem.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.aries.subsystem.core.archive.SubsystemImportServiceHeader;
import org.apache.aries.subsystem.itests.util.GenericMetadataWrapper;
import org.apache.aries.util.manifest.ManifestHeaderProcessor;
import org.apache.aries.util.manifest.ManifestHeaderProcessor.GenericMetadata;
import org.junit.Assert;
import org.junit.Test;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.Version;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
public class ServiceDependencyTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: application.b.esa
* Subsystem-Content: bundle.b.jar
*/
private static final String APPLICATION_B = "application.b.esa";
/*
* Subsystem-SymbolicName: application.b.esa
* Subsystem-Content: bundle.a.jar, bundle.b.jar
*/
private static final String APPLICATION_C = "application.c.esa";
/*
* Subsystem-SymbolicName: application.d.esa
* Subsystem-Content: bundle.a.jar, composite.a.esa
*/
private static final String APPLICATION_D = "application.d.esa";
/*
* Subsystem-SymbolicName: composite.a.esa
* Subsystem-Content: bundle.b.jar
*/
private static final String COMPOSITE_A = "composite.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Bundle-Blueprint: OSGI-INF/blueprint/*.xml
*
* <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
* <reference interface="bundle.b" filter="(&(active=true)(mode=shared))"/>
* <service interface="bundle.a" ref="bundle.a"/>
* </blueprint>
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Bundle-Blueprint: OSGI-INF/blueprint/*.xml
*
* <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
* <reference interface="bundle.a" availability="optional"/>
* <service ref="bundle.b">
* <interfaces>
* <value>bundle.b</value>
* <value>bundle.b1</value>
* </interfaces>
* <service-properties>
* <entry key="active">
* <value type="java.lang.Boolean">true</value>
* </entry>
* <entry key="mode" value="shared"/>
* </service-properties>
* </service>
* </blueprint>
*/
private static final String BUNDLE_B = "bundle.b.jar";
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B, BUNDLE_B);
}
private static void createApplicationC() throws IOException {
createApplicationCManifest();
createSubsystem(APPLICATION_C, BUNDLE_A, BUNDLE_B);
}
private static void createApplicationD() throws IOException {
createApplicationDManifest();
createSubsystem(APPLICATION_D, BUNDLE_A, COMPOSITE_A);
}
private static void createApplicationAManifest() throws IOException {
createBasicApplicationManifest(APPLICATION_A);
}
private static void createApplicationBManifest() throws IOException {
createBasicApplicationManifest(APPLICATION_B);
}
private static void createApplicationCManifest() throws IOException {
createBasicApplicationManifest(APPLICATION_C);
}
private static void createApplicationDManifest() throws IOException {
createBasicApplicationManifest(APPLICATION_D);
}
private static void createBasicApplicationManifest(String symbolicName) throws IOException {
createBasicSubsystemManifest(symbolicName, null, null);
}
private static void createBasicSubsystemManifest(String symbolicName, Version version, String type) throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, symbolicName);
if (version != null)
attributes.put(SubsystemConstants.SUBSYSTEM_VERSION, version.toString());
if (type != null)
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, type);
createManifest(symbolicName + ".mf", attributes);
}
private static void createBundleA() throws IOException {
createBlueprintBundle(
BUNDLE_A,
new StringBuilder()
.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<blueprint ")
.append("xmlns=\"http://www.osgi.org/xmlns/blueprint/v1.0.0\">")
.append("<reference ")
.append("interface=\"bundle.b\" ")
.append("filter=\"(active=true)(mode=shared)\"")
.append("/>")
.append("<service ")
.append("interface=\"bundle.a\" ")
.append("ref=\"bundle.a\"")
.append("/>")
.append("</blueprint>")
.toString());
}
private static void createBundleB() throws IOException {
createBlueprintBundle(
BUNDLE_B,
new StringBuilder()
.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<blueprint ")
.append("xmlns=\"http://www.osgi.org/xmlns/blueprint/v1.0.0\">")
.append("<reference ")
.append("interface=\"bundle.a\" ")
.append("availability=\"optional\"")
.append("/>")
.append("<service ref=\"bundle.b\">")
.append("<interfaces>")
.append("<value>bundle.b</value>")
.append("<value>bundle.b1</value>")
.append("</interfaces>")
.append("<service-properties>")
.append("<entry key=\"active\">")
.append("<value type=\"java.lang.Boolean\">true</value>")
.append("</entry>")
.append("<entry key=\"mode\" value=\"shared\"/>")
.append("</service-properties>")
.append("</service>")
.append("</blueprint>")
.toString());
}
private static void createCompositeA() throws IOException {
createCompositeAManifest();
createSubsystem(COMPOSITE_A, BUNDLE_B);
}
private static void createCompositeAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(
SubsystemConstants.SUBSYSTEM_EXPORTSERVICE,
"bundle.b;filter:=\"(&(active=true)(mode=shared))\"");
createManifest(COMPOSITE_A + ".mf", attributes);
}
@Override
public void createApplications() throws Exception {
createBundleA();
createBundleB();
createApplicationA();
createApplicationB();
createApplicationC();
createCompositeA();
createApplicationD();
}
//@Test
public void testImportServiceDependencySatisfiedByChild() throws Exception {
try {
Subsystem subsystem = installSubsystemFromFile(APPLICATION_D);
try {
assertNull(
"Generated application Subsystem-ImportService header when dependency satisfied by child",
subsystem.getSubsystemHeaders(null).get(SubsystemConstants.SUBSYSTEM_IMPORTSERVICE));
assertSubsystemExportServiceHeader(
subsystem.getChildren().iterator().next(),
"bundle.b;filter:=\"(&(active=true)(mode=shared))\"");
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Installation must succeed if missing service dependency is satisfied");
}
}
@Test
public void testImportServiceDependencySatisfiedByContent() throws Exception {
try {
Subsystem subsystem = installSubsystemFromFile(APPLICATION_C);
try {
assertNull(
"Generated application Subsystem-ImportService header when dependency satisfied by content",
subsystem.getSubsystemHeaders(null).get(SubsystemConstants.SUBSYSTEM_IMPORTSERVICE));
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Installation must succeed if service dependency is satisfied");
}
}
@Test
public void testImportServiceDependencySatisfiedByParent() throws Exception {
try {
Subsystem parent = installSubsystemFromFile(APPLICATION_B);
try {
Subsystem child = installSubsystemFromFile(parent, APPLICATION_A);
try {
assertSubsystemImportServiceHeader(child, "bundle.b;filter:=\"(&(active=true)(mode=shared))\";resolution:=mandatory;cardinality:=single;effective:=active");
}
finally {
uninstallSubsystemSilently(child);
}
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Installation must succeed if service dependency is satisfied");
}
finally {
uninstallSubsystemSilently(parent);
}
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Installation must succeed if missing service dependency is optional");
}
}
@Test
public void testMissingImportServiceDependencyMandatory() throws Exception {
try {
Subsystem subsystem = installSubsystemFromFile(APPLICATION_A);
uninstallSubsystemSilently(subsystem);
fail("Installation must fail due to missing service dependency");
}
catch (SubsystemException e) {
// Okay.
}
}
@Test
public void testMissingImportServiceDependencyOptional() throws Exception {
try {
Subsystem subsystem = installSubsystemFromFile(APPLICATION_B);
try {
assertSubsystemImportServiceHeader(subsystem, "bundle.a;resolution:=optional;cardinality:=single;effective:=active");
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Installation must succeed if missing service dependency is optional");
}
}
private void assertSubsystemExportServiceHeader(Subsystem subsystem, String value) throws InvalidSyntaxException {
String header = assertHeaderExists(subsystem, SubsystemConstants.SUBSYSTEM_EXPORTSERVICE);
List<GenericMetadata> actual = ManifestHeaderProcessor.parseRequirementString(header);
List<GenericMetadata> expected = ManifestHeaderProcessor.parseRequirementString(value);
Assert.assertEquals("Wrong number of clauses", expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++)
assertEquals("Wrong clause", new GenericMetadataWrapper(expected.get(i)), new GenericMetadataWrapper(actual.get(i)));
}
private void assertSubsystemImportServiceHeader(Subsystem subsystem, String value) throws InvalidSyntaxException {
String header = assertHeaderExists(subsystem, SubsystemConstants.SUBSYSTEM_IMPORTSERVICE);
SubsystemImportServiceHeader actual = new SubsystemImportServiceHeader(header);
SubsystemImportServiceHeader expected = new SubsystemImportServiceHeader(value);
Collection<SubsystemImportServiceHeader.Clause> actualClauses = actual.getClauses();
Collection<SubsystemImportServiceHeader.Clause> expectedClauses = expected.getClauses();
Assert.assertEquals("Wrong number of clauses", expectedClauses.size(), actualClauses.size());
Iterator<SubsystemImportServiceHeader.Clause> actualItr = actualClauses.iterator();
Iterator<SubsystemImportServiceHeader.Clause> expectedItr = expectedClauses.iterator();
while (expectedItr.hasNext()) {
assertEquals("Wrong clause", expectedItr.next(), actualItr.next());
}
}
}
| 8,720 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/CustomContentHandlerTest.java | /*
* 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.apache.aries.subsystem.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Scanner;
import org.apache.aries.subsystem.ContentHandler;
import org.junit.Ignore;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Resource;
import org.osgi.service.coordinator.Coordination;
import org.osgi.service.subsystem.Subsystem;
public class CustomContentHandlerTest extends SubsystemTest {
@Override
protected void createApplications() throws Exception {
createApplication("customContent", "custom1.sausages", "customContentBundleA.jar");
createApplication("customContent1", "custom2.sausages", "customContentBundleB.jar");
createApplication("customContent2", "custom3.sausages", "customContentBundleC.jar");
createApplication("customContent3", "custom4.sausages", "customContentBundleD.jar");
}
@Test
public void testCustomContentHandler() throws Exception {
for (Bundle b : bundleContext.getBundles()) {
if ("org.apache.aries.subsystem.itests.customcontent.bundleA".equals(b.getSymbolicName())) {
fail("Precondition");
}
}
SausagesContentHandler handler = new SausagesContentHandler();
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(ContentHandler.CONTENT_TYPE_PROPERTY, "foo.sausages");
ServiceRegistration<ContentHandler> reg = bundleContext.registerService(ContentHandler.class, handler, props);
try {
assertEquals("Precondition", 0, handler.calls.size());
Subsystem subsystem = installSubsystemFromFile("customContent.esa");
try {
assertEquals(Arrays.asList("install:customContent1 sausages = 1"), handler.calls);
Collection<Resource> constituents = subsystem.getConstituents();
assertEquals("The custom content should not show up as a subsystem constituent",
1, constituents.size());
boolean foundBundle = false;
for (Bundle b : bundleContext.getBundles()) {
if ("org.apache.aries.subsystem.itests.customcontent.bundleA".equals(b.getSymbolicName())) {
foundBundle = true;
}
}
assertTrue(foundBundle);
boolean foundBundleInConstituents = false;
for (Resource c : constituents) {
for(Capability idCap : c.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE)) {
Object name = idCap.getAttributes().get(IdentityNamespace.IDENTITY_NAMESPACE);
if ("org.apache.aries.subsystem.itests.customcontent.bundleA".equals(name))
foundBundleInConstituents = true;
}
}
assertTrue(foundBundleInConstituents);
handler.calls.clear();
assertEquals(Subsystem.State.INSTALLED, subsystem.getState());
subsystem.start();
assertEquals(Arrays.asList("start:customContent1"), handler.calls);
handler.calls.clear();
assertEquals(Subsystem.State.ACTIVE, subsystem.getState());
subsystem.stop();
assertEquals(Arrays.asList("stop:customContent1"), handler.calls);
assertEquals(Subsystem.State.RESOLVED, subsystem.getState());
} finally {
handler.calls.clear();
subsystem.uninstall();
assertEquals(Arrays.asList("uninstall:customContent1"), handler.calls);
assertEquals(Subsystem.State.UNINSTALLED, subsystem.getState());
}
} finally {
reg.unregister();
}
}
@Test
public void testCustomContentInstallationException() throws Exception {
for (Bundle b : bundleContext.getBundles()) {
if ("org.apache.aries.subsystem.itests.customcontent.bundleB".equals(b.getSymbolicName())) {
fail("Precondition");
}
}
SausagesContentHandler handler = new SausagesContentHandler(true, "install");
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(ContentHandler.CONTENT_TYPE_PROPERTY, "foo.sausages");
ServiceRegistration<ContentHandler> reg = bundleContext.registerService(ContentHandler.class, handler, props);
assertEquals("Precondition", 0, handler.calls.size());
try {
installSubsystemFromFile("customContent1.esa");
} catch (Exception ex) {
// ignore
}
try {
for (Bundle b : bundleContext.getBundles()) {
if ("org.apache.aries.subsystem.itests.customcontent.bundleB".equals(b.getSymbolicName())) {
fail("Should not have installed the bundle");
}
}
} finally {
reg.unregister();
}
}
@Test @Ignore("This test exposes a problem that needs to be fixed, namely that the previous test leaves stuff behind and that "
+ "customContent1.esa cannot be installed again. Currently ignored until someone finds the time to fix it.")
public void testCustomContentInstallationSecondTime() throws Exception {
for (Bundle b : bundleContext.getBundles()) {
if ("org.apache.aries.subsystem.itests.customcontent.bundleB".equals(b.getSymbolicName())) {
fail("Precondition");
}
}
SausagesContentHandler handler = new SausagesContentHandler();
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(ContentHandler.CONTENT_TYPE_PROPERTY, "foo.sausages");
ServiceRegistration<ContentHandler> reg = bundleContext.registerService(ContentHandler.class, handler, props);
try {
Subsystem subsystem = installSubsystemFromFile("customContent1.esa");
subsystem.uninstall();
} finally {
reg.unregister();
}
}
@Test
public void testCustomContentInstallationCoordinationFails() throws Exception {
for (Bundle b : bundleContext.getBundles()) {
if ("org.apache.aries.subsystem.itests.customcontent.bundleC".equals(b.getSymbolicName())) {
fail("Precondition");
}
}
SausagesContentHandler handler = new SausagesContentHandler(false, "install");
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(ContentHandler.CONTENT_TYPE_PROPERTY, "foo.sausages");
ServiceRegistration<ContentHandler> reg = bundleContext.registerService(ContentHandler.class, handler, props);
assertEquals("Precondition", 0, handler.calls.size());
try {
installSubsystemFromFile("customContent2.esa");
} catch (Exception ex) {
// ignore
}
try {
for (Bundle b : bundleContext.getBundles()) {
if ("org.apache.aries.subsystem.itests.customcontent.bundleC".equals(b.getSymbolicName())) {
fail("Should not have installed the bundle");
}
}
} finally {
reg.unregister();
}
}
@Test @Ignore("This test currently doesn't pass, the bundle moves to the active state, while it shouldn't")
public void testCustomContentStartException() throws Exception {
for (Bundle b : bundleContext.getBundles()) {
if ("org.apache.aries.subsystem.itests.customcontent.bundleC".equals(b.getSymbolicName())) {
fail("Precondition");
}
}
SausagesContentHandler handler = new SausagesContentHandler(true, "start");
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(ContentHandler.CONTENT_TYPE_PROPERTY, "foo.sausages");
ServiceRegistration<ContentHandler> reg = bundleContext.registerService(ContentHandler.class, handler, props);
assertEquals("Precondition", 0, handler.calls.size());
Subsystem subsystem = installSubsystemFromFile("customContent2.esa");
try {
assertEquals(Arrays.asList("install:customContent3 sausages = 3"), handler.calls);
try {
Bundle theBundle = null;
for (Bundle b : bundleContext.getBundles()) {
if ("org.apache.aries.subsystem.itests.customcontent.bundleC".equals(b.getSymbolicName())) {
assertEquals(Bundle.INSTALLED, b.getState());
theBundle = b;
}
}
assertNotNull(theBundle);
try {
subsystem.start();
} catch (Exception ex) {
// good
}
assertEquals("There was an exception during start, so the bundle should not be started",
Bundle.INSTALLED, theBundle.getState());
} finally {
subsystem.uninstall();
}
} finally {
reg.unregister();
}
}
@Test @Ignore("This test currently doesn't pass, the bundle moves to the active state, while it shouldn't")
public void testCustomContentStartFailCoordination() throws Exception {
for (Bundle b : bundleContext.getBundles()) {
if ("org.apache.aries.subsystem.itests.customcontent.bundleD".equals(b.getSymbolicName())) {
fail("Precondition");
}
}
SausagesContentHandler handler = new SausagesContentHandler(false, "start");
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(ContentHandler.CONTENT_TYPE_PROPERTY, "foo.sausages");
ServiceRegistration<ContentHandler> reg = bundleContext.registerService(ContentHandler.class, handler, props);
assertEquals("Precondition", 0, handler.calls.size());
Subsystem subsystem = installSubsystemFromFile("customContent3.esa");
try {
assertEquals(Arrays.asList("install:customContent4 sausages = 4"), handler.calls);
try {
Bundle theBundle = null;
for (Bundle b : bundleContext.getBundles()) {
if ("org.apache.aries.subsystem.itests.customcontent.bundleD".equals(b.getSymbolicName())) {
assertEquals(Bundle.INSTALLED, b.getState());
theBundle = b;
}
}
assertNotNull(theBundle);
try {
subsystem.start();
} catch (Exception ex) {
// good
}
assertEquals("The coordination failued during start, so the bundle should not be started",
Bundle.INSTALLED, theBundle.getState());
} finally {
subsystem.uninstall();
}
} finally {
reg.unregister();
}
}
private static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
static class SausagesContentHandler implements ContentHandler {
List<String> calls = new ArrayList<String>();
private final boolean exception;
private final String state;
public SausagesContentHandler() {
this(false, null);
}
public SausagesContentHandler(boolean exception, String state) {
this.exception = exception;
this.state = state;
}
@Override
public void install(InputStream is, String symbolicName, String type, Subsystem subsystem,
Coordination coordination) {
if ("install".equals(state)) {
if (exception) {
throw new RuntimeException(state);
} else {
coordination.fail(new RuntimeException(state));
}
}
String content = convertStreamToString(is);
calls.add(("install:" + symbolicName + " " + content).trim());
}
@Override
public void start(String symbolicName, String type, Subsystem subsystem, Coordination coordination) {
if ("start".equals(state)) {
if (exception) {
throw new RuntimeException(state);
} else {
coordination.fail(new RuntimeException(state));
}
}
calls.add("start:" + symbolicName);
}
@Override
public void stop(String symbolicName, String type, Subsystem subsystem) {
calls.add("stop:" + symbolicName);
}
@Override
public void uninstall(String symbolicName, String type, Subsystem subsystem) {
calls.add("uninstall:" + symbolicName);
}
}
}
| 8,721 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/SubsystemTest.java | /*
* 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.apache.aries.subsystem.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.streamBundle;
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.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.aries.itest.AbstractIntegrationTest;
import org.apache.aries.itest.RichBundleContext;
import org.apache.aries.subsystem.AriesSubsystem;
import org.apache.aries.subsystem.core.archive.AriesProvisionDependenciesDirective;
import org.apache.aries.subsystem.core.archive.ProvisionPolicyDirective;
import org.apache.aries.subsystem.core.archive.SubsystemTypeHeader;
import org.apache.aries.subsystem.core.archive.TypeAttribute;
import org.apache.aries.subsystem.core.internal.BasicSubsystem;
import org.apache.aries.subsystem.core.internal.BundleResource;
import org.apache.aries.subsystem.core.internal.SubsystemIdentifier;
import org.apache.aries.subsystem.itests.util.TestRepository;
import org.apache.aries.subsystem.itests.util.Utils;
import org.apache.aries.unittest.fixture.ArchiveFixture;
import org.apache.aries.unittest.fixture.ArchiveFixture.JarFixture;
import org.apache.aries.unittest.fixture.ArchiveFixture.ManifestFixture;
import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture;
import org.apache.aries.util.filesystem.FileSystem;
import org.eclipse.equinox.region.Region;
import org.eclipse.equinox.region.RegionDigraph;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.ops4j.io.StreamUtils;
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.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.startlevel.BundleStartLevel;
import org.osgi.framework.startlevel.FrameworkStartLevel;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.FrameworkWiring;
import org.osgi.resource.Capability;
import org.osgi.resource.Resource;
import org.osgi.service.repository.Repository;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemConstants;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerClass.class)
public abstract class SubsystemTest extends AbstractIntegrationTest {
private static final String SUBSYSTEM_CORE_NAME = "org.apache.aries.subsystem.core";
protected static boolean createdApplications = false;
boolean installModeler = true;
boolean installConfigAdmin = false;
public SubsystemTest() {
}
public SubsystemTest(boolean installModeller) {
this.installModeler = installModeller;
}
public Option baseOptions() {
String localRepo = getLocalRepo();
return composite(
junitBundles(),
// 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() throws Exception {
new File("target").mkdirs();
init();
return new Option[] {
baseOptions(),
systemProperty("org.osgi.framework.bsnversion").value("multiple"),
systemProperty("org.osgi.framework.storage.clean").value("onFirstInit"),
// Bundles
mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(),
mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils").versionAsInProject(),
mavenBundle("org.apache.aries.application", "org.apache.aries.application.api").versionAsInProject(),
when(installModeler).useOptions(modelerBundles()),
when(installConfigAdmin).useOptions(
mavenBundle("org.apache.felix", "org.apache.felix.configadmin").versionAsInProject()),
mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.api").versionAsInProject(),
mavenBundle("org.apache.aries.subsystem", SUBSYSTEM_CORE_NAME).versionAsInProject(),
streamBundle(createCoreFragment()).noStart(),
mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.itest.interfaces").versionAsInProject(),
mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(),
//mavenBundle("org.apache.felix", "org.apache.felix.resolver").versionAsInProject(),
mavenBundle("org.eclipse.equinox", "org.eclipse.equinox.coordinator").version("1.1.0.v20120522-1841"),
mavenBundle("org.eclipse.equinox", "org.eclipse.equinox.event").versionAsInProject(),
mavenBundle("org.eclipse.equinox", "org.eclipse.equinox.region").version("1.1.0.v20120522-1841"),
mavenBundle("org.osgi", "org.osgi.enterprise").versionAsInProject(),
mavenBundle("org.easymock", "easymock").versionAsInProject(),
mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(),
mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(),
mavenBundle("org.ops4j.pax.tinybundles", "tinybundles").versionAsInProject(),
mavenBundle("biz.aQute.bnd", "bndlib").versionAsInProject(),
mavenBundle("org.apache.aries.subsystem", "org.apache.aries.subsystem.obr").versionAsInProject(),
mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(),
// org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=7777"),
};
}
protected void init() throws Exception {
}
protected long lastSubsystemId() throws Exception {
Method method = SubsystemIdentifier.class.getDeclaredMethod("getLastId");
method.setAccessible(true);
return (Long)method.invoke(null);
}
private Option modelerBundles() {
return CoreOptions.composite(
mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(),
mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint").versionAsInProject(),
mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy").versionAsInProject());
}
/**
* The itests need private packages from the core subsystems bundle.
* So this fragment exports them.
* @return stream containing the fragment
*/
private InputStream createCoreFragment() {
return TinyBundles.bundle()
.set("Bundle-SymbolicName", SUBSYSTEM_CORE_NAME + ".fragment")
.set("Export-Package", "org.apache.aries.subsystem.core.internal,org.apache.aries.subsystem.core.archive")
.set("Fragment-Host", SUBSYSTEM_CORE_NAME)
.build();
}
protected final SubsystemEventHandler subsystemEvents = new SubsystemEventHandler();
@SuppressWarnings("rawtypes")
protected Collection<ServiceRegistration> serviceRegistrations = new ArrayList<ServiceRegistration>();
protected final List<Region> deletableRegions = Collections.synchronizedList(new ArrayList<Region>());
protected final List<Subsystem> stoppableSubsystems = Collections.synchronizedList(new ArrayList<Subsystem>());
protected final List<Bundle> uninstallableBundles = Collections.synchronizedList(new ArrayList<Bundle>());
protected final List<Subsystem> uninstallableSubsystems = Collections.synchronizedList(new ArrayList<Subsystem>());
@Before
public void setUp() throws Exception {
serviceRegistrations.clear();
deletableRegions.clear();
stoppableSubsystems.clear();
uninstallableBundles.clear();
uninstallableSubsystems.clear();
if (!createdApplications) {
createApplications();
createdApplications = true;
}
bundleContext.getBundle(0).getBundleContext().addServiceListener(subsystemEvents, '(' + Constants.OBJECTCLASS + '=' + Subsystem.class.getName() + ')');
}
@SuppressWarnings("rawtypes")
@After
public void tearDown() throws Exception
{
for (Subsystem subsystem : stoppableSubsystems) {
stopSubsystemSilently(subsystem);
}
for (Subsystem subsystem : uninstallableSubsystems) {
uninstallSubsystemSilently(subsystem);
}
RegionDigraph digraph = context().getService(RegionDigraph.class);
for (Region region : deletableRegions) {
digraph.removeRegion(region);
}
for (Bundle bundle : uninstallableBundles) {
uninstallSilently(bundle);
}
bundleContext.removeServiceListener(subsystemEvents);
for (ServiceRegistration registration : serviceRegistrations)
Utils.unregisterQuietly(registration);
}
protected void createApplications() throws Exception {
}
protected RichBundleContext context(Subsystem subsystem) {
return new RichBundleContext(subsystem.getBundleContext());
}
protected void assertEmptySubsystem(Subsystem subsystem) {
assertSymbolicName("org.apache.aries.subsystem.itests.subsystem.empty", subsystem);
assertVersion("0", subsystem);
assertType(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, subsystem);
}
protected void assertBundleState(int state, String symbolicName, Subsystem subsystem) {
Bundle bundle = context(subsystem).getBundleByName(symbolicName);
assertNotNull("Bundle not found: " + symbolicName, bundle);
assertBundleState(bundle, state);
}
protected void assertBundleState(Bundle bundle, int state) {
assertTrue("Wrong state: " + bundle + " [expected " + state + " but was " + bundle.getState() + "]", (bundle.getState() & state) != 0);
}
protected Subsystem assertChild(Subsystem parent, String symbolicName) {
return assertChild(parent, symbolicName, null, null);
}
protected Subsystem assertChild(Subsystem parent, String symbolicName, Version version) {
return assertChild(parent, symbolicName, version, null);
}
protected Subsystem assertChild(Subsystem parent, String symbolicName, Version version, String type) {
Subsystem result = getChild(parent, symbolicName, version, type);
assertNotNull("Child does not exist: " + symbolicName, result);
return result;
}
protected void assertChild(Subsystem parent, Subsystem child) {
Collection<Subsystem> children = new ArrayList<Subsystem>(1);
children.add(child);
assertChildren(parent, children);
}
protected void assertChildren(int size, Subsystem subsystem) {
assertEquals("Wrong number of children", size, subsystem.getChildren().size());
}
protected void assertChildren(Subsystem parent, Collection<Subsystem> children) {
assertTrue("Parent did not contain all children", parent.getChildren().containsAll(children));
}
protected void assertClassLoadable(String clazz, Bundle bundle) {
try {
bundle.loadClass(clazz);
}
catch (Exception e) {
e.printStackTrace();
fail("Class " + clazz + " from bundle " + bundle + " should be loadable");
}
}
protected void assertConstituent(Subsystem subsystem, String symbolicName) {
assertConstituent(subsystem, symbolicName, Version.emptyVersion);
}
protected void assertConstituent(Subsystem subsystem, String symbolicName, Version version) {
assertConstituent(subsystem, symbolicName, version, IdentityNamespace.TYPE_BUNDLE);
}
protected void assertConstituent(Subsystem subsystem, String symbolicName, String type) {
assertConstituent(subsystem, symbolicName, Version.emptyVersion, type);
}
protected Resource assertConstituent(Subsystem subsystem, String symbolicName, Version version, String type) {
Resource constituent = getConstituent(subsystem, symbolicName, version, type);
assertNotNull("Constituent not found: " + symbolicName + ';' + version + ';' + type, constituent);
return constituent;
}
protected void assertConstituents(int size, Subsystem subsystem) {
assertEquals("Wrong number of constituents", size, subsystem.getConstituents().size());
}
protected void assertEvent(Subsystem subsystem, Subsystem.State state) throws InterruptedException {
assertEvent(subsystem, state, 0);
}
protected void assertEvent(Subsystem subsystem, Subsystem.State state, long timeout) throws InterruptedException {
assertEvent(subsystem, state, subsystemEvents.poll(subsystem.getSubsystemId(), timeout));
}
protected void assertEvent(Subsystem subsystem, Subsystem.State state, SubsystemEventHandler.ServiceEventInfo event) {
if (State.INSTALLING.equals(state))
assertEvent(subsystem, state, event, ServiceEvent.REGISTERED);
else
assertEvent(subsystem, state, event, ServiceEvent.MODIFIED);
}
protected void assertEvent(Subsystem subsystem, Subsystem.State state, SubsystemEventHandler.ServiceEventInfo event, int type) {
assertEvent(subsystem.getSubsystemId(), subsystem.getSymbolicName(),
subsystem.getVersion(), subsystem.getType(), state, event, type);
}
protected void assertEvent(
long id,
String symbolicName,
Version version,
String type,
Subsystem.State state,
SubsystemEventHandler.ServiceEventInfo event,
int eventType) {
// TODO Could accept a ServiceRegistration as an argument and verify it against the one in the event.
assertNotNull("No event", event);
assertEquals("Wrong ID", id, event.getId());
assertEquals("Wrong symbolic name", symbolicName, event.getSymbolicName());
assertEquals("Wrong version", version, event.getVersion());
assertEquals("Wrong type", type, event.getType());
assertEquals("Wrong state", state, event.getState());
assertEquals("Wrong event type", eventType, event.getEventType());
}
protected String assertHeaderExists(Subsystem subsystem, String name) {
String header = subsystem.getSubsystemHeaders(null).get(name);
assertNotNull("Missing header: " + name, header);
return header;
}
protected void assertId(Subsystem subsystem) {
assertId(subsystem.getSubsystemId());
}
protected void assertId(Long id) {
assertTrue("Subsystem ID was not a positive integer: " + id, id > 0);
}
protected void assertLastId(long id) throws Exception {
Subsystem root = getRootSubsystem();
Field lastId = SubsystemIdentifier.class.getDeclaredField("lastId");
lastId.setAccessible(true);
assertEquals("Wrong lastId", id, lastId.getLong(root));
}
protected void resetLastId() throws Exception {
Field lastId = SubsystemIdentifier.class.getDeclaredField("lastId");
lastId.setAccessible(true);
lastId.setInt(SubsystemIdentifier.class, 0);
}
protected void assertLocation(String expected, String actual) {
assertTrue("Wrong location: " + actual, actual.indexOf(expected) != -1);
}
protected void assertLocation(String expected, Subsystem subsystem) {
assertLocation(expected, subsystem.getLocation());
}
protected void assertNotChild(Subsystem parent, Subsystem child) {
assertFalse("Parent contained child", parent.getChildren().contains(child));
}
protected void assertNotConstituent(Subsystem subsystem, String symbolicName) {
assertNotConstituent(subsystem, symbolicName, Version.emptyVersion, IdentityNamespace.TYPE_BUNDLE);
}
protected void assertNotConstituent(Subsystem subsystem, String symbolicName, Version version, String type) {
Resource constituent = getConstituent(subsystem, symbolicName, version, type);
assertNull("Constituent found: " + symbolicName + ';' + version + ';' + type, constituent);
}
protected void assertParent(Subsystem expected, Subsystem subsystem) {
for (Subsystem parent : subsystem.getParents()) {
if (parent.equals(expected))
return;
}
fail("Parent did not exist: " + expected.getSymbolicName());
}
protected void assertProvisionPolicy(Subsystem subsystem, boolean acceptsDependencies) {
String headerStr = subsystem.getSubsystemHeaders(null).get(SubsystemConstants.SUBSYSTEM_TYPE);
assertNotNull("Missing subsystem type header", headerStr);
SubsystemTypeHeader header = new SubsystemTypeHeader(headerStr);
ProvisionPolicyDirective directive = header.getProvisionPolicyDirective();
if (acceptsDependencies)
assertTrue("Subsystem does not accept dependencies", directive.isAcceptDependencies());
else
assertTrue("Subsystem accepts dependencies", directive.isRejectDependencies());
}
protected void assertRefresh(Collection<Bundle> bundles) throws InterruptedException {
FrameworkWiring wiring = getSystemBundleAsFrameworkWiring();
final AtomicBoolean refreshed = new AtomicBoolean(false);
wiring.refreshBundles(bundles, new FrameworkListener[]{ new FrameworkListener() {
@Override
public void frameworkEvent(FrameworkEvent event) {
if (FrameworkEvent.PACKAGES_REFRESHED == event.getType()) {
synchronized (refreshed) {
refreshed.set(true);
refreshed.notify();
}
}
}
}});
synchronized (refreshed) {
refreshed.wait(5000);
}
assertTrue("Bundles not refreshed", refreshed.get());
}
protected void assertRefreshAndResolve(Collection<Bundle> bundles) throws InterruptedException {
assertRefresh(bundles);
assertResolve(bundles);
}
protected void assertRegionContextBundle(Subsystem s) {
Bundle b = getRegionContextBundle(s);
assertEquals("Not active", Bundle.ACTIVE, b.getState());
assertEquals("Wrong location", s.getLocation() + '/' + s.getSubsystemId(), b.getLocation());
assertEquals("Wrong symbolic name", "org.osgi.service.subsystem.region.context." + s.getSubsystemId(), b.getSymbolicName());
assertEquals("Wrong version", Version.parseVersion("1.0.0"), b.getVersion());
assertConstituent(s, "org.osgi.service.subsystem.region.context." + s.getSubsystemId(), Version.parseVersion("1.0.0"), IdentityNamespace.TYPE_BUNDLE);
}
protected void assertResolve(Collection<Bundle> bundles) {
FrameworkWiring wiring = getSystemBundleAsFrameworkWiring();
assertTrue("Bundles not resolved", wiring.resolveBundles(bundles));
}
protected void assertServiceEventsInstall(Subsystem subsystem) throws InterruptedException {
assertEvent(subsystem, Subsystem.State.INSTALLING, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertEvent(subsystem, Subsystem.State.INSTALLED, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
}
protected void assertServiceEventsResolve(Subsystem subsystem) throws InterruptedException {
assertEvent(subsystem, Subsystem.State.RESOLVING, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertServiceEventResolved(subsystem, ServiceEvent.MODIFIED);
}
protected void assertServiceEventsStart(Subsystem subsystem) throws InterruptedException {
assertEvent(subsystem, Subsystem.State.STARTING, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertEvent(subsystem, Subsystem.State.ACTIVE, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
}
protected void assertServiceEventsStop(Subsystem subsystem) throws InterruptedException {
assertEvent(subsystem, Subsystem.State.STOPPING, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertServiceEventResolved(subsystem, ServiceEvent.MODIFIED);
// Don't forget about the unregistering event, which will have the same state as before.
assertServiceEventResolved(subsystem, ServiceEvent.UNREGISTERING);
}
protected void assertServiceEventResolved(Subsystem subsystem, int type) throws InterruptedException {
assertEvent(subsystem, Subsystem.State.RESOLVED, subsystemEvents.poll(subsystem.getSubsystemId(), 5000), type);
}
protected void assertStartLevel(Bundle bundle, int expected) {
assertNotNull("Bundle is null", bundle);
assertEquals("Wrong start level", expected, bundle.adapt(BundleStartLevel.class).getStartLevel());
}
protected void assertState(State expected, State actual) {
assertState(EnumSet.of(expected), actual);
}
protected void assertState(EnumSet<State> expected, State actual) {
assertTrue("Wrong state: expected=" + expected + ", actual=" + actual, expected.contains(actual));
}
protected void assertState(State expected, Subsystem subsystem) {
assertState(expected, subsystem.getState());
}
protected void assertState(EnumSet<State> expected, Subsystem subsystem) {
assertState(expected, subsystem.getState());
}
protected Subsystem assertSubsystemLifeCycle(File file) throws Exception {
Subsystem rootSubsystem = context().getService(Subsystem.class);
assertNotNull("Root subsystem was null", rootSubsystem);
Subsystem subsystem = rootSubsystem.install(file.toURI().toURL().toExternalForm());
assertNotNull("The subsystem was null", subsystem);
assertState(EnumSet.of(State.INSTALLING, State.INSTALLED), subsystem.getState());
assertEvent(subsystem, Subsystem.State.INSTALLING, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertEvent(subsystem, Subsystem.State.INSTALLED, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertChild(rootSubsystem, subsystem);
subsystem.start();
assertState(EnumSet.of(State.RESOLVING, State.RESOLVED, State.STARTING, State.ACTIVE), subsystem.getState());
assertEvent(subsystem, Subsystem.State.RESOLVING, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertEvent(subsystem, Subsystem.State.RESOLVED, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertEvent(subsystem, Subsystem.State.STARTING, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertEvent(subsystem, Subsystem.State.ACTIVE, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
subsystem.stop();
assertState(EnumSet.of(State.STOPPING, State.RESOLVED), subsystem.getState());
assertEvent(subsystem, Subsystem.State.STOPPING, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertEvent(subsystem, Subsystem.State.RESOLVED, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
subsystem.uninstall();
assertState(EnumSet.of(State.UNINSTALLING, State.UNINSTALLED), subsystem.getState());
assertEvent(subsystem, Subsystem.State.UNINSTALLING, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertEvent(subsystem, Subsystem.State.UNINSTALLED, subsystemEvents.poll(subsystem.getSubsystemId(), 5000));
assertNotChild(rootSubsystem, subsystem);
return subsystem;
}
protected void assertSubsystemNotNull(Subsystem subsystem) {
assertNotNull("Subsystem was null", subsystem);
}
protected void assertSymbolicName(String expected, Subsystem subsystem) {
assertSymbolicName(expected, subsystem.getSymbolicName());
}
protected void assertSymbolicName(String expected, String actual) {
assertEquals("Wrong symbolic name", expected, actual);
}
protected void assertType(String expected, Subsystem subsystem) {
assertEquals("Wrong type", expected, subsystem.getType());
}
protected void assertVersion(String expected, Subsystem subsystem) {
assertVersion(Version.parseVersion(expected), subsystem);
}
protected void assertVersion(Version expected, Subsystem subsystem) {
assertVersion(expected, subsystem.getVersion());
}
protected void assertVersion(Version expected, Version actual) {
assertEquals("Wrong version", expected, actual);
}
protected Header version(String version) {
return new Header(Constants.BUNDLE_VERSION, version);
}
protected Header name(String name) {
return new Header(Constants.BUNDLE_SYMBOLICNAME, name);
}
protected Header exportPackage(String exportPackage) {
return new Header(Constants.EXPORT_PACKAGE, exportPackage);
}
protected Header importPackage(String importPackage) {
return new Header(Constants.IMPORT_PACKAGE, importPackage);
}
protected Header requireBundle(String bundleName) {
return new Header(Constants.REQUIRE_BUNDLE, bundleName);
}
protected Header requireCapability(String capability) {
return new Header(Constants.REQUIRE_CAPABILITY, capability);
}
protected Header provideCapability(String capability) {
return new Header(Constants.PROVIDE_CAPABILITY, capability);
}
protected static void createBundle(Header... headers) throws IOException {
createBundle(Collections.<String> emptyList(), headers);
}
protected static void createBundle(List<String> emptyFiles, Header... headers) throws IOException {
HashMap<String, String> headerMap = new HashMap<String, String>();
for (Header header : headers) {
headerMap.put(header.key, header.value);
}
createBundle(emptyFiles, headerMap);
}
protected static void createBundle(List<String> emptyFiles, Map<String, String> headers) throws IOException {
createBundle(headers.get(Constants.BUNDLE_SYMBOLICNAME), emptyFiles, headers);
}
protected static void createBundle(String fileName, List<String> emptyFiles, Map<String, String> headers) throws IOException
{
JarFixture bundle = ArchiveFixture.newJar();
ManifestFixture manifest = bundle.manifest();
for (Entry<String, String> header : headers.entrySet()) {
manifest.attribute(header.getKey(), header.getValue());
}
for (String path : emptyFiles) {
bundle.file(path).end();
}
write(fileName, bundle);
}
protected static void createBlueprintBundle(String symbolicName, String blueprintXml)
throws IOException {
write(symbolicName,
ArchiveFixture.newJar().manifest().symbolicName(symbolicName)
.end().file("OSGI-INF/blueprint/blueprint.xml", blueprintXml));
}
protected Resource createBundleRepositoryContent(String file) throws Exception {
return createBundleRepositoryContent(new File(file));
}
protected Resource createBundleRepositoryContent(File file) throws Exception {
return new BundleResource(FileSystem.getFSRoot(file));
}
protected static void createManifest(String name, Map<String, String> headers) throws IOException {
ManifestFixture manifest = ArchiveFixture.newJar().manifest();
for (Entry<String, String> header : headers.entrySet()) {
manifest.attribute(header.getKey(), header.getValue());
}
write(name, manifest);
}
protected static void createSubsystem(String name, String...contents) throws IOException {
File manifest = new File(name + ".mf");
ZipFixture fixture = ArchiveFixture.newZip();
if (manifest.exists())
// The following input stream is closed by ArchiveFixture.copy.
fixture.binary("OSGI-INF/SUBSYSTEM.MF", new FileInputStream(name + ".mf"));
if (contents != null) {
for (String content : contents) {
// The following input stream is closed by ArchiveFixture.copy.
fixture.binary(content, new FileInputStream(content));
}
}
write(name, fixture);
}
protected Subsystem findSubsystemService(long id) throws InvalidSyntaxException {
String filter = "(" + SubsystemConstants.SUBSYSTEM_ID_PROPERTY + "=" + id + ")";
return context().getService(Subsystem.class, filter, 5000);
}
protected Subsystem getChild(Subsystem parent, String symbolicName) {
return getChild(parent, symbolicName, null, null);
}
protected Subsystem getChild(Subsystem parent, String symbolicName, Version version) {
return getChild(parent, symbolicName, version, null);
}
protected Subsystem getChild(Subsystem parent, String symbolicName, Version version, String type) {
for (Subsystem child : parent.getChildren()) {
if (symbolicName.equals(child.getSymbolicName())) {
if (version == null)
version = Version.emptyVersion;
if (version.equals(child.getVersion())) {
if (type == null)
type = SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION;
if (type.equals(child.getType())) {
return child;
}
}
}
}
return null;
}
public static Object getIdentityAttribute(Resource resource, String name) {
List<Capability> capabilities = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE);
Capability capability = capabilities.get(0);
return capability.getAttributes().get(name);
}
public static String getSymbolicNameAttribute(Resource resource) {
return (String)getIdentityAttribute(resource, IdentityNamespace.IDENTITY_NAMESPACE);
}
public static Version getVersionAttribute(Resource resource) {
Version result = (Version)getIdentityAttribute(resource, IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE);
if (result == null)
result = Version.emptyVersion;
return result;
}
public static String getTypeAttribute(Resource resource) {
String result = (String)getIdentityAttribute(resource, IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE);
if (result == null)
result = TypeAttribute.DEFAULT_VALUE;
return result;
}
protected Resource getConstituent(Subsystem subsystem, String symbolicName, Version version, String type) {
for (Resource resource : subsystem.getConstituents()) {
if (symbolicName.equals(getSymbolicNameAttribute(resource))) {
if (version == null)
version = Version.emptyVersion;
if (version.equals(getVersionAttribute(resource))) {
if (type == null)
type = IdentityNamespace.TYPE_BUNDLE;
if (type.equals(getTypeAttribute(resource))) {
return resource;
}
}
}
}
return null;
}
protected AriesSubsystem getConstituentAsAriesSubsystem(Subsystem subsystem, String symbolicName, Version version, String type) {
Resource resource = getConstituent(subsystem, symbolicName, version, type);
return (AriesSubsystem)resource;
}
protected Bundle getConstituentAsBundle(Subsystem subsystem, String symbolicName, Version version, String type) {
return getConstituentAsBundleRevision(subsystem, symbolicName, version, type).getBundle();
}
protected BundleRevision getConstituentAsBundleRevision(Subsystem subsystem, String symbolicName, Version version, String type) {
Resource resource = getConstituent(subsystem, symbolicName, version, type);
return (BundleRevision)resource;
}
protected Subsystem getConstituentAsSubsystem(Subsystem subsystem, String symbolicName, Version version, String type) {
Resource resource = getConstituent(subsystem, symbolicName, version, type);
return (Subsystem)resource;
}
protected Region getRegion(Subsystem subsystem) {
RegionDigraph digraph = context().getService(RegionDigraph.class);
String name = getRegionName(subsystem);
Region region = digraph.getRegion(name);
assertNotNull("Region not found: " + name, region);
return region;
}
protected Bundle getRegionContextBundle(Subsystem subsystem) {
BundleContext bc = subsystem.getBundleContext();
assertNotNull("No region context bundle", bc);
return bc.getBundle();
}
protected String getRegionName(Subsystem subsystem) {
if (subsystem.getSubsystemId() == 0)
return "org.eclipse.equinox.region.kernel";
return subsystem.getSymbolicName() + ';' + subsystem.getVersion() + ';' + subsystem.getType() + ';' + subsystem.getSubsystemId();
}
protected AriesSubsystem getRootAriesSubsystem() {
return context().getService(AriesSubsystem.class);
}
protected Subsystem getRootSubsystem() {
return context().getService(Subsystem.class, "(subsystem.id=0)");
}
protected Subsystem getRootSubsystemInState(Subsystem.State state, long timeout) throws InterruptedException {
Subsystem root = getRootSubsystem();
long now = System.currentTimeMillis();
long then = now + timeout;
while (!root.getState().equals(state) && System.currentTimeMillis() < then)
Thread.sleep(100);
if (!root.getState().equals(state))
fail("Root subsystem never achieved state: " + state);
return root;
}
protected Bundle getSystemBundle() {
return bundleContext.getBundle(Constants.SYSTEM_BUNDLE_LOCATION);
}
protected FrameworkStartLevel getSystemBundleAsFrameworkStartLevel() {
return getSystemBundle().adapt(FrameworkStartLevel.class);
}
protected FrameworkWiring getSystemBundleAsFrameworkWiring() {
return getSystemBundle().adapt(FrameworkWiring.class);
}
protected Bundle getSubsystemCoreBundle() {
return context().getBundleByName(SUBSYSTEM_CORE_NAME);
}
protected Bundle installBundleFromFile(String fileName) throws FileNotFoundException, BundleException {
return installBundleFromFile(new File(fileName), getRootSubsystem());
}
protected Bundle installBundleFromFile(String fileName, Subsystem subsystem) throws FileNotFoundException, BundleException {
return installBundleFromFile(new File(fileName), subsystem);
}
private Bundle installBundleFromFile(File file, Subsystem subsystem) throws FileNotFoundException, BundleException {
Bundle bundle = installBundleFromFile(file, subsystem.getBundleContext());
assertBundleState(Bundle.INSTALLED|Bundle.RESOLVED, bundle.getSymbolicName(), subsystem);
return bundle;
}
private Bundle installBundleFromFile(File file, BundleContext bundleContext) throws FileNotFoundException, BundleException {
// The following input stream is closed by the bundle context.
return bundleContext.installBundle(file.toURI().toString(), new FileInputStream(file));
}
protected Subsystem installSubsystemFromFile(Subsystem parent, String fileName) throws Exception {
return installSubsystemFromFile(parent, new File(fileName));
}
protected Subsystem installSubsystemFromFile(String fileName, Boolean ... configChecks) throws Exception {
return installSubsystemFromFile(new File(fileName), configChecks);
}
protected Subsystem installSubsystemFromFile(Subsystem parent, File file) throws Exception {
return installSubsystem(parent, file.toURI().toURL().toExternalForm());
}
private Subsystem installSubsystemFromFile(File file, Boolean ... configChecks) throws Exception {
return installSubsystem(getRootSubsystem(), file.toURI().toURL().toExternalForm(), configChecks);
}
protected Subsystem installSubsystemFromFile(Subsystem parent, File file, String location) throws Exception {
return installSubsystem(parent, location, new URL(file.toURI().toURL().toExternalForm()).openStream());
}
protected Subsystem installSubsystem(String location) throws Exception {
return installSubsystem(getRootSubsystem(), location);
}
protected Subsystem installSubsystem(String location, InputStream content) throws Exception {
return installSubsystem(getRootSubsystem(), location, content);
}
protected Subsystem installSubsystem(Subsystem parent, String location, Boolean ... configChecks) throws Exception {
// The following input stream is closed by Subsystem.install.
return installSubsystem(parent, location, new URL(location).openStream(), configChecks);
}
protected Subsystem installSubsystem(Subsystem parent, String location, InputStream content, Boolean ... configChecks) throws Exception {
boolean ariesProvisionDepsAtInstall = true; //set default value
if (configChecks!=null && configChecks.length > 0) {
ariesProvisionDepsAtInstall = configChecks[0].booleanValue();
}
subsystemEvents.clear();
Subsystem subsystem = parent.install(location, content);
assertSubsystemNotNull(subsystem);
assertEvent(subsystem, State.INSTALLING, 5000);
if (ariesProvisionDepsAtInstall) {
assertEvent(subsystem, State.INSTALLED, 5000);
}
assertChild(parent, subsystem);
assertLocation(location, subsystem);
assertParent(parent, subsystem);
State finalState=State.INSTALLED;
if (!ariesProvisionDepsAtInstall) {
finalState=State.INSTALLING;
}
assertState(finalState, subsystem);
assertLocation(location, subsystem);
assertId(subsystem);
// TODO This does not take into account nested directories.
// assertDirectory(subsystem);
return subsystem;
}
protected void registerRepositoryService(Repository repository) {
serviceRegistrations.add(bundleContext.registerService(
Repository.class, repository, null));
}
protected void registerRepositoryService(Resource...resources) {
TestRepository.Builder builder = new TestRepository.Builder();
for (Resource resource : resources) {
builder.resource(resource);
}
registerRepositoryService(builder.build());
}
protected void registerRepositoryService(String...files) throws Exception {
Resource[] resources = new Resource[files.length];
int i = 0;
for (String file : files) {
resources[i++] = (Resource)createBundleRepositoryContent(file);
}
registerRepositoryService(resources);
}
protected void removeConnectionWithParent(Subsystem subsystem) throws BundleException {
Region tail = getRegion(subsystem);
RegionDigraph digraph = tail.getRegionDigraph();
RegionDigraph copy = digraph.copy();
Region tailCopy = copy.getRegion(tail.getName());
Set<Long> ids = tail.getBundleIds();
copy.removeRegion(tailCopy);
tailCopy= copy.createRegion(tailCopy.getName());
for (long id : ids) {
tailCopy.addBundle(id);
}
digraph.replace(copy);
}
protected void restartSubsystemsImplBundle() throws BundleException {
Bundle b = getSubsystemCoreBundle();
b.stop();
b.start();
}
protected void startBundle(Bundle bundle) throws BundleException {
startBundle(bundle, getRootSubsystem());
}
protected void startBundle(Bundle bundle, Subsystem subsystem) throws BundleException {
bundle.start();
assertBundleState(Bundle.ACTIVE, bundle.getSymbolicName(), subsystem);
}
protected void startSubsystem(Subsystem subsystem, Boolean ... configChecks) throws Exception {
startSubsystemFromInstalled(subsystem, configChecks);
}
protected void startSubsystemFromInstalled(Subsystem subsystem, Boolean ... configChecks) throws InterruptedException {
boolean ariesProvisionDependenciesAtInstall = true; //set default value
if (configChecks.length>0) {
ariesProvisionDependenciesAtInstall = configChecks[0].booleanValue();
}
if (ariesProvisionDependenciesAtInstall) {
assertState(State.INSTALLED, subsystem);
}
else {
assertState(State.INSTALLING, subsystem);
}
subsystemEvents.clear();
subsystem.start();
if (!ariesProvisionDependenciesAtInstall) {
assertEvent(subsystem, State.INSTALLED, 5000);
}
assertEvent(subsystem, State.RESOLVING, 5000);
assertEvent(subsystem, State.RESOLVED, 5000);
assertEvent(subsystem, State.STARTING, 5000);
assertEvent(subsystem, State.ACTIVE, 5000);
assertState(State.ACTIVE, subsystem);
}
protected void startSubsystemFromResolved(Subsystem subsystem) throws InterruptedException {
assertState(State.RESOLVED, subsystem);
subsystemEvents.clear();
subsystem.start();
assertEvent(subsystem, State.STARTING, 5000);
assertEvent(subsystem, State.ACTIVE, 5000);
assertState(State.ACTIVE, subsystem);
}
protected void stopAndUninstallSubsystemSilently(Subsystem subsystem) {
stopSubsystemSilently(subsystem);
uninstallSubsystemSilently(subsystem);
}
protected void stopSubsystem(Subsystem subsystem) throws Exception {
assertState(State.ACTIVE, subsystem);
subsystemEvents.clear();
subsystem.stop();
assertEvent(subsystem, State.STOPPING, 5000);
assertEvent(subsystem, State.RESOLVED, 5000);
assertState(State.RESOLVED, subsystem);
}
protected void stopSubsystemSilently(Subsystem subsystem) {
try {
stopSubsystem(subsystem);
}
catch (Throwable t) {
t.printStackTrace();
}
}
protected void uninstallSilently(Bundle bundle) {
if (bundle == null)
return;
try {
bundle.uninstall();
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void uninstallSubsystem(Subsystem subsystem) throws Exception {
uninstallSubsystem(subsystem, false);
}
protected void uninstallSubsystem(Subsystem subsystem, boolean quietly) throws Exception {
BasicSubsystem basicSubsystem = (BasicSubsystem)subsystem;
AriesProvisionDependenciesDirective directive = basicSubsystem.getAriesProvisionDependenciesDirective();
Bundle b = null;
Region region = null;
RegionDigraph digraph = context().getService(RegionDigraph.class);
if (!quietly) {
if (directive.isResolve()) {
assertState(EnumSet.of(State.INSTALLING, State.INSTALLED, State.RESOLVED), subsystem);
}
else {
assertState(EnumSet.of(State.INSTALLED, State.RESOLVED), subsystem);
}
subsystemEvents.clear();
if (subsystem.getType().equals(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION)
|| subsystem.getType().equals(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE)) {
b = getRegionContextBundle(subsystem);
region = digraph.getRegion(b);
}
}
State state = subsystem.getState();
subsystem.uninstall();
if (quietly) {
return;
}
Collection<Subsystem> parents = subsystem.getParents();
if (!EnumSet.of(State.INSTALL_FAILED, State.INSTALLED, State.INSTALLING).contains(state)) {
assertEvent(subsystem, State.INSTALLED, 5000);
}
assertEvent(subsystem, State.UNINSTALLING, 5000);
assertEvent(subsystem, State.UNINSTALLED, 5000);
assertState(State.UNINSTALLED, subsystem);
for (Subsystem parent : parents) {
assertNotChild(parent, subsystem);
}
if (subsystem.getType().equals(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION)
|| subsystem.getType().equals(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE)) {
assertEquals("Region context bundle not uninstalled", Bundle.UNINSTALLED, b.getState());
assertNull("Region not removed", digraph.getRegion(region.getName()));
}
}
protected void uninstallSubsystemSilently(Subsystem subsystem) {
if (subsystem == null)
return;
try {
uninstallSubsystem(subsystem, true);
}
catch (Throwable t) {
t.printStackTrace();
}
}
protected void writeToFile(InputStream is, String name) {
try {
FileOutputStream dest = new FileOutputStream(name);
StreamUtils.copyStream(is, dest, true);
} catch (IOException e) {
e.printStackTrace();
}
}
protected static void write(String file, ArchiveFixture.AbstractFixture fixture) throws IOException
{
write(new File(file), fixture);
}
private static void write(File file, ArchiveFixture.AbstractFixture fixture) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
try {
fixture.writeOut(fos);
}
finally {
fos.close();
}
}
static void createApplication(String name, String ... contents) throws Exception
{
ClassLoader cl = SubsystemTest.class.getClassLoader();
ZipFixture feature = ArchiveFixture
.newZip()
.binary("OSGI-INF/SUBSYSTEM.MF",
// The following input stream is closed by ArchiveFixture.copy.
cl.getResourceAsStream(name + "/OSGI-INF/SUBSYSTEM.MF"));
for (String content : contents) {
try {
feature.binary(content,
// The following input stream is closed by ArchiveFixture.copy.
cl.getResourceAsStream(name + '/' + content));
}
catch (Exception e) {
// The following input stream is closed by ArchiveFixture.copy.
feature.binary(content, new FileInputStream(new File(content)));
}
}
feature.end();
FileOutputStream fos = new FileOutputStream(name + ".esa");
try {
feature.writeOut(fos);
} finally {
Utils.closeQuietly(fos);
}
}
protected static String normalizeBundleLocation(Bundle bundle) {
return normalizeBundleLocation(bundle.getLocation());
}
protected static String normalizeBundleLocation(String location) {
if (location.startsWith("initial@"))
return location.substring(8);
return location;
}
protected InputStream getResource(String path) {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(path);
if (is == null) {
throw new IllegalArgumentException("No resource found at path " + path);
}
return is;
}
}
| 8,722 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/SharedResourceTest.java | /*
* 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.apache.aries.subsystem.itests;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class SharedResourceTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: application.b.esa
* Subsystem-Content: bundle.b.jar
*/
private static final String APPLICATION_B = "application.b.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Import-Package: x
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Import-Package: x
*/
private static final String BUNDLE_B = "bundle.b.jar";
/*
* Bundle-SymbolicName: bundle.c.jar
* Export-Package: x
*/
private static final String BUNDLE_C = "bundle.c.jar";
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private static void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B, BUNDLE_B);
}
private static void createApplicationBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_B);
createManifest(APPLICATION_B + ".mf", attributes);
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), importPackage("x"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), importPackage("x"));
}
private void createBundleC() throws IOException {
createBundle(name(BUNDLE_C), exportPackage("x"));
}
@Override
public void createApplications() throws Exception {
createBundleA();
createBundleB();
createBundleC();
createApplicationA();
createApplicationB();
}
public void setUp() throws Exception {
super.setUp();
registerRepositoryService(BUNDLE_C);
}
@Test
public void testSharedBundleNotUninstalledWhileStillReferenced() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
startSubsystem(applicationA);
Subsystem applicationB = installSubsystemFromFile(APPLICATION_B);
try {
startSubsystem(applicationB);
stopSubsystem(applicationA);
uninstallSubsystem(applicationA);
assertBundleState(Bundle.ACTIVE, BUNDLE_C, getRootSubsystem());
}
finally {
stopAndUninstallSubsystemSilently(applicationB);
}
}
finally {
stopAndUninstallSubsystemSilently(applicationA);
}
}
}
| 8,723 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/DependencyLifeCycleTest.java | /*
* 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.apache.aries.subsystem.itests;
import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class DependencyLifeCycleTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Import-Package: x
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Export-Package: x
*/
private static final String BUNDLE_B = "bundle.b.jar";
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), importPackage("x"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), exportPackage("x"));
}
@Override
public void createApplications() throws Exception {
createBundleA();
createBundleB();
createApplicationA();
}
public void setUp() throws Exception {
super.setUp();
registerRepositoryService(BUNDLE_A, BUNDLE_B);
}
@Test
public void testBundleDependencyInstall() throws Exception {
Subsystem subsystem = installSubsystemFromFile(APPLICATION_A);
try {
assertBundleState(Bundle.INSTALLED, BUNDLE_B, getRootSubsystem());
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
@Test
public void testBundleDependencyStart() throws Exception {
Subsystem subsystem = installSubsystemFromFile(APPLICATION_A);
try {
subsystem.start();
try {
assertBundleState(Bundle.ACTIVE, BUNDLE_B, getRootSubsystem());
}
finally {
stopSubsystemSilently(subsystem);
}
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
@Test
public void testBundleDependencyStop() throws Exception {
Subsystem subsystem = installSubsystemFromFile(APPLICATION_A);
try {
subsystem.start();
subsystem.stop();
assertBundleState(Bundle.RESOLVED, BUNDLE_B, getRootSubsystem());
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
@Test
public void testBundleDependencyUninstall() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystemFromFile(APPLICATION_A);
try {
assertConstituent(root, BUNDLE_B);
Bundle bundle = context(root).getBundleByName(BUNDLE_B);
subsystem.uninstall();
assertBundleState(bundle, Bundle.UNINSTALLED);
assertNotConstituent(root, BUNDLE_B);
}
finally {
if (!EnumSet.of(Subsystem.State.UNINSTALLING, Subsystem.State.UNINSTALLED).contains(subsystem.getState()))
uninstallSubsystemSilently(subsystem);
}
}
}
| 8,724 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/ApplicationTest.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.subsystem.itests;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.apache.aries.subsystem.itests.util.TestCapability;
import org.apache.aries.subsystem.itests.util.TestRepository;
import org.apache.aries.subsystem.itests.util.TestRepositoryContent;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.resource.Resource;
import org.osgi.service.repository.Repository;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class ApplicationTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: application.b.esa
* Subsystem-Content: bundle.c.jar
*/
private static final String APPLICATION_B = "application.b.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Require-Capability: foo; filter:="(foo=bar)"
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Provide-Capability: foo; foo=bar
*/
private static final String BUNDLE_B = "bundle.b.jar";
/*
* Bundle-SymbolicName: bundle.c.jar
* Require-Bundle: bundle.b.jar
*/
private static final String BUNDLE_C = "bundle.c.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createBundleB();
createBundleC();
createApplicationA();
createApplicationB();
createdTestFiles = true;
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), version("1.0.0"),
new Header(Constants.REQUIRE_CAPABILITY, "foo; filter:=\"(foo=bar)\""));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), version("1.0.0"),
new Header(Constants.PROVIDE_CAPABILITY, "foo; foo=bar"));
}
private void createBundleC() throws IOException {
createBundle(name(BUNDLE_C), version("1.0.0"), requireBundle(BUNDLE_B));
}
private void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B, BUNDLE_C);
}
private void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createApplicationBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_C);
createManifest(APPLICATION_B + ".mf", attributes);
}
@Override
public void createApplications() throws Exception {
createApplication("application1", "tb1.jar");
}
public void setUp() throws Exception {
super.setUp();
try {
serviceRegistrations.add(
bundleContext.registerService(
Repository.class,
createTestRepository(),
null));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/*
* Subsystem application1 has content bundle tb1.jar.
* Bundle tb1.jar has an import package dependency on org.apache.aries.subsystem.itests.tb3.
*/
@Test
public void testApplication1() throws Exception {
Subsystem application1 = installSubsystemFromFile("application1.esa");
try {
assertSymbolicName("org.apache.aries.subsystem.application1", application1);
assertVersion("0.0.0", application1);
assertType(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, application1);
assertChildren(0, application1);
assertConstituents(2, application1);
startSubsystem(application1);
assertBundleState(Bundle.RESOLVED|Bundle.ACTIVE, "org.apache.aries.subsystem.itests.tb1", application1);
assertBundleState(Bundle.RESOLVED|Bundle.ACTIVE, "org.apache.aries.subsystem.itests.tb3", getRootSubsystem());
}
finally {
stopSubsystemSilently(application1);
uninstallSubsystemSilently(application1);
}
}
@Test
public void testRequireBundle() throws Exception {
File file = new File(BUNDLE_B);
// The following input stream is closed by the bundle context.
Bundle b = getRootSubsystem().getBundleContext().installBundle(file.toURI().toString(), new FileInputStream(file));
try {
Subsystem application = installSubsystemFromFile(APPLICATION_B);
try {
startSubsystem(application);
}
finally {
stopSubsystemSilently(application);
uninstallSubsystemSilently(application);
}
}
finally {
uninstallSilently(b);
}
}
@Test
public void testRequireCapability() throws Exception {
File file = new File(BUNDLE_B);
// The following input stream is closed by the bundle context.
Bundle b = getRootSubsystem().getBundleContext().installBundle(file.toURI().toString(), new FileInputStream(file));
try {
Subsystem application = installSubsystemFromFile(APPLICATION_A);
try {
startSubsystem(application);
}
finally {
stopSubsystemSilently(application);
uninstallSubsystemSilently(application);
}
}
finally {
uninstallSilently(b);
}
}
private byte[] createTestBundle3Content() throws IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.subsystem.itests.tb3");
manifest.getMainAttributes().putValue(Constants.EXPORT_PACKAGE, "org.apache.aries.subsystem.itests.tb3");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jos = new JarOutputStream(baos, manifest);
jos.close();
return baos.toByteArray();
}
private Resource createTestBundle3Resource() throws IOException {
return new TestRepositoryContent.Builder()
.capability(
new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(IdentityNamespace.IDENTITY_NAMESPACE, "org.apache.aries.subsystem.itests.tb3")
.attribute(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE, Version.emptyVersion)
.attribute(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, IdentityNamespace.TYPE_BUNDLE))
.capability(
new TestCapability.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.attribute(PackageNamespace.PACKAGE_NAMESPACE, "org.apache.aries.subsystem.itests.tb3")
.attribute(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE, "0.0.0"))
.content(createTestBundle3Content())
.build();
}
private Repository createTestRepository() throws IOException {
return new TestRepository.Builder()
.resource(createTestBundle3Resource())
.build();
}
}
| 8,725 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/AriesSubsystemTest.java | package org.apache.aries.subsystem.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.AriesSubsystem;
import org.apache.aries.subsystem.core.internal.BasicRequirement;
import org.apache.aries.util.filesystem.FileSystem;
import org.apache.aries.util.filesystem.IDirectory;
import org.easymock.EasyMock;
import org.eclipse.equinox.region.Region;
import org.eclipse.equinox.region.RegionFilter;
import org.junit.Test;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.resource.Namespace;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
@ExamReactorStrategy(PerMethod.class)
public class AriesSubsystemTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: application.b.esa
* Subsystem-Content: bundle.b.jar
*/
private static final String APPLICATION_B = "application.b.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Import-Package: org.osgi.framework,org.osgi.resource
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Import-Package: org.osgi.resource
*/
private static final String BUNDLE_B = "bundle.b.jar";
/*
* Subsystem-SymbolicName: composite.a.esa
* Subsystem-Type: osgi.subsystem.composite
*/
private static final String COMPOSITE_A = "composite.a.esa";
private void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B, BUNDLE_B);
}
private void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createApplicationBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
createManifest(APPLICATION_B + ".mf", attributes);
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), importPackage("org.osgi.framework,org.osgi.resource"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), importPackage("org.osgi.resource"));
}
private void createCompositeA() throws IOException {
createCompositeAManifest();
createSubsystem(COMPOSITE_A, BUNDLE_B, APPLICATION_B);
}
private void createCompositeAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT,
BUNDLE_B + ';' + IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE + "=\"[0,0]\","
+ APPLICATION_B + ';' + IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE + "=\"[0,0]\";" + IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE + '=' + SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION);
attributes.put(Constants.IMPORT_PACKAGE, "org.osgi.resource");
createManifest(COMPOSITE_A + ".mf", attributes);
}
@Override
public void createApplications() throws Exception {
createBundleA();
createBundleB();
createApplicationA();
createApplicationB();
createCompositeA();
}
/*
* The region copy process when adding additional requirements should
* keep all edges, not just the ones running between parent and child. This
* is of particular concern with regard to the connections all subsystem
* regions have with the root region to allow the subsystem services
* through. However, it may also be of concern if the region digraph is
* modified outside of the subsystems API.
*/
@Test
public void testAddRequirementsKeepsEdgesOtherThanParentChild() throws Exception {
AriesSubsystem compositeA = (AriesSubsystem)installSubsystemFromFile(COMPOSITE_A);
try {
AriesSubsystem applicationB = (AriesSubsystem)getConstituentAsSubsystem(compositeA, APPLICATION_B, null, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION);
Region bRegion = getRegion(applicationB);
// One edge to parent for import package. One edge to root for subsystem
// service.
assertEquals("Wrong number of edges", 2, bRegion.getEdges().size());
Requirement requirement = new BasicRequirement.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.directive(
PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE,
"(osgi.wiring.package=org.osgi.framework)")
.resource(EasyMock.createMock(Resource.class))
.build();
applicationB.addRequirements(Collections.singleton(requirement));
bRegion = getRegion(applicationB);
// Still one edge to parent for import package. One edge to root for
// subsystem service.
assertEquals("Wrong number of edges", 2, bRegion.getEdges().size());
Region rootRegion = getRegion(getRootSubsystem());
// The root region won't be the tail region for any connection unless
// manually added.
assertEquals("Wrong number of edges", 0, rootRegion.getEdges().size());
// Manually add a connection from root to application B.
rootRegion.connectRegion(
bRegion,
rootRegion.getRegionDigraph().createRegionFilterBuilder().allow(
"com.foo",
"(bar=b)").build());
// The root region should now have an edge.
assertEquals("Wrong number of edges", 1, rootRegion.getEdges().size());
// Add another requirement to force a copy.
requirement = new BasicRequirement.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.directive(
PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE,
"(osgi.wiring.package=org.osgi.framework.wiring)")
.resource(EasyMock.createMock(Resource.class))
.build();
applicationB.addRequirements(Collections.singleton(requirement));
rootRegion = getRegion(getRootSubsystem());
// The root region should still have its edge.
assertEquals("Wrong number of edges", 1, rootRegion.getEdges().size());
bRegion = getRegion(applicationB);
// Still one edge to parent for import package. One edge to root for
// subsystem service.
assertEquals("Wrong number of edges", 2, bRegion.getEdges().size());
}
finally {
uninstallSubsystemSilently(compositeA);
}
}
/*
* Test the AriesSubsystem.addRequirements(Collection<Requirement>) method.
*
* There are several things to consider for this test.
*
* (1) Installing a child subsystem before the requirement has been added
* should fail.
* (2) Installing a child subsystem after the requirement has been added
* should succeed.
* (3) The newly created region should contain all of the bundles from the
* old one.
* (4) The connections between the subsystem with the added requirement and
* its parents should be reestablished.
* (5) The connections between the subsystem with the added requirement and
* its children should be reestablished.
*/
@Test
public void testAddRequirements() throws Exception {
AriesSubsystem compositeA = (AriesSubsystem)installSubsystemFromFile(COMPOSITE_A);
try {
startSubsystem(compositeA);
assertCompositeABefore(compositeA);
// Test that the installation of applicationA fails.
try {
installSubsystemFromFile(compositeA, APPLICATION_A);
fail("Subsystem should not have installed due to unresolved org.osgi.framework package requirement");
} catch (SubsystemException e) {
// Okay.
}
// Add the org.osgi.framework package requirement.
Requirement requirement = new BasicRequirement.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.directive(
PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE,
"(osgi.wiring.package=org.osgi.framework)")
.resource(EasyMock.createMock(Resource.class))
.build();
compositeA.addRequirements(Collections.singleton(requirement));
// Test that the bundles were copied over to the newly created region.
assertCompositeABefore(compositeA);
// Test that the parent connections were reestablished.
assertRefreshAndResolve(Collections.singletonList(getConstituentAsBundle(compositeA, BUNDLE_B, null, null)));
// Test that the child connections were reestablished.
assertRefreshAndResolve(Collections.singletonList(getConstituentAsBundle(getConstituentAsSubsystem(compositeA, APPLICATION_B, null, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION), BUNDLE_B, null, null)));
// Test that the installation of applicationA succeeds.
AriesSubsystem applicationA;
try {
applicationA = (AriesSubsystem)installSubsystemFromFile(compositeA, APPLICATION_A);
startSubsystem(applicationA);
} catch (SubsystemException e) {
fail("Subsystem should have installed and started");
}
assertCompositeAAfter(compositeA);
}
finally {
stopAndUninstallSubsystemSilently(compositeA);
}
}
/*
* Aries Subsystems uses Equinox Region Digraph as its isolation engine.
* Digraph has a "special" namespace value that tells the region to allow
* everything a bundle offers. This test ensures that a correctly formatted
* requirement in that namespace works as expected.
*/
@Test
public void testAddRequirementWithVisibleBundleNamespace() throws Exception {
Requirement requirement = new BasicRequirement.Builder()
.namespace(RegionFilter.VISIBLE_BUNDLE_NAMESPACE)
.directive(Namespace.REQUIREMENT_FILTER_DIRECTIVE, "(id=0)")
.resource(EasyMock.createMock(Resource.class)).build();
AriesSubsystem compositeA = (AriesSubsystem) installSubsystemFromFile(COMPOSITE_A);
try {
startSubsystem(compositeA);
// Test that the installation of applicationA fails.
try {
installSubsystemFromFile(compositeA, APPLICATION_A);
fail("Subsystem should not have installed due to unresolved org.osgi.framework package requirement");
} catch (SubsystemException e) {
// Okay.
}
// Add the requirement with the region digraph specific namespace.
compositeA.addRequirements(Collections.singleton(requirement));
// Test that the installation and startup of applicationA succeeds.
AriesSubsystem applicationA;
try {
applicationA = (AriesSubsystem) installSubsystemFromFile(
compositeA, APPLICATION_A);
startSubsystem(applicationA);
} catch (SubsystemException e) {
fail("Subsystem should have installed and started");
}
assertCompositeAAfter(compositeA);
} finally {
stopAndUninstallSubsystemSilently(compositeA);
}
}
@Test
public void testInstallIDirectory() {
File file = new File(COMPOSITE_A);
IDirectory directory = FileSystem.getFSRoot(file);
try {
AriesSubsystem compositeA = getRootAriesSubsystem().install(COMPOSITE_A, directory);
uninstallSubsystemSilently(compositeA);
}
catch (Exception e) {
fail("Installation from IDirectory should have succeeded");
}
}
@Test
public void testServiceRegistrations() {
Subsystem root1 = null;
try {
root1 = getRootSubsystem();
}
catch (Exception e) {
fail(Subsystem.class.getName() + " service not registered");
}
AriesSubsystem root2 = null;
try {
root2 = getRootAriesSubsystem();
}
catch (Exception e) {
fail(AriesSubsystem.class.getName() + " service not registered");
}
assertSame("Services should be the same instance", root1, root2);
}
private void assertCompositeAAfter(Subsystem compositeA) {
// applicationA, applicationB, bundleB, region context bundle
assertConstituents(4, compositeA);
assertConstituent(compositeA, APPLICATION_A, null, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION);
assertConstituent(compositeA, APPLICATION_B, null, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION);
assertConstituent(compositeA, BUNDLE_B);
assertNotNull("Bundle not in region", getRegion(compositeA).getBundle(BUNDLE_B, Version.emptyVersion));
assertConstituent(compositeA, "org.osgi.service.subsystem.region.context.1", Version.parseVersion("1"));
// applicationA, applicationB
assertChildren(2, compositeA);
assertApplicationA(assertChild(compositeA, APPLICATION_A));
assertApplicationB(assertChild(compositeA, APPLICATION_B));
}
private void assertCompositeABefore(Subsystem compositeA) {
// applicationB, bundleB, region context bundle
assertConstituents(3, compositeA);
assertConstituent(compositeA, APPLICATION_B, null, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION);
assertConstituent(compositeA, BUNDLE_B);
assertNotNull("Bundle not in region", getRegion(compositeA).getBundle(BUNDLE_B, Version.emptyVersion));
assertConstituent(compositeA, "org.osgi.service.subsystem.region.context.1", Version.parseVersion("1"));
// applicationB
assertChildren(1, compositeA);
assertApplicationB(assertChild(compositeA, APPLICATION_B));
}
private void assertApplicationA(Subsystem applicationA) {
// bundleA, region context bundle
assertConstituents(2, applicationA);
assertConstituent(applicationA, BUNDLE_A);
// The subsystem id is 4 instead of 3 due to the first installation that failed.
assertConstituent(applicationA, "org.osgi.service.subsystem.region.context.4", Version.parseVersion("1"));
assertChildren(0, applicationA);
}
private void assertApplicationB(Subsystem applicationB) {
// bundleB, region context bundle
assertConstituents(2, applicationB);
assertConstituent(applicationB, BUNDLE_B);
assertConstituent(applicationB, "org.osgi.service.subsystem.region.context.2", Version.parseVersion("1"));
assertChildren(0, applicationB);
}
}
| 8,726 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/ResolutionTest.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.subsystem.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.core.archive.Clause;
import org.apache.aries.subsystem.core.archive.RequireCapabilityHeader;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.resolver.ResolutionException;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
/*
* Contains a series of tests related to resolution.
*/
public class ResolutionTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: application.b.esa
* Subsystem-Content: bundle.d.jar
*/
private static final String APPLICATION_B = "application.b.esa";
/*
* Subsystem-SymbolicName: application.c.esa
* Subsystem-Content: bundle.e.jar
*/
private static final String APPLICATION_C = "application.c.esa";
/*
* Subsystem-SymbolicName: application.d.esa
* Subsystem-Content: bundle.f.jar
*/
private static final String APPLICATION_D = "application.d.esa";
/* Subsystem-SymbolicName: application.e.esa
* Subsystem-Content: bundle.g.jar
*/
private static final String APPLICATION_E = "application.e.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Require-Capability: a
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Provide-Capability: a
* Require-Capability: b
*/
private static final String BUNDLE_B = "bundle.b.jar";
/*
* Bundle-SymbolicName: bundle.c.jar
* Provide-Capability: b
*/
private static final String BUNDLE_C = "bundle.c.jar";
/*
* Bundle-SymbolicName: bundle.d.jar
* Bundle-RequiredExecutionEnvironment: JavaSE-100.100
*/
private static final String BUNDLE_D = "bundle.d.jar";
/*
* Bundle-SymbolicName: bundle.e.jar
* Bundle-RequiredExecutionEnvironment: J2SE-1.4, J2SE-1.5, J2SE-1.6,JavaSE-1.7
*/
private static final String BUNDLE_E = "bundle.e.jar";
/*
* Bundle-SymbolicName: bundle.f.jar
* Bundle-NativeCode: \
* native.file; osname=Linux; processor=x86, \
* native.file; osname=Linux; processor=x86-64, \
* native.file; osname=Win32; processor=x86, \
* native.file; osname=Win32; processor=x86-64, \
* native.file; osname="mac os x"; processor=x86-64
*/
private static final String BUNDLE_F = "bundle.f.jar";
/*
* Bundle-SymbolicName: bundle.f.jar
* Bundle-NativeCode: \
* native.file; osname=noMatch; processor=noMatch
*/
private static final String BUNDLE_G = "bundle.g.jar";
@Before
public void createApplications() throws Exception {
if (createdApplications) {
return;
};
createBundleA();
createBundleB();
createBundleC();
createBundleD();
createBundleE();
createBundleF();
createBundleG();
createApplicationA();
createApplicationB();
createApplicationC();
createApplicationD();
createApplicationE();
createdApplications = true;
}
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private static void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B, BUNDLE_D);
}
private static void createApplicationBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
createManifest(APPLICATION_B + ".mf", attributes);
}
private static void createApplicationC() throws IOException {
createApplicationCManifest();
createSubsystem(APPLICATION_C, BUNDLE_E);
}
private static void createApplicationCManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_C);
createManifest(APPLICATION_C + ".mf", attributes);
}
private static void createApplicationD() throws IOException {
createApplicationDManifest();
createSubsystem(APPLICATION_D, BUNDLE_F);
}
private static void createApplicationDManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_D);
createManifest(APPLICATION_D + ".mf", attributes);
}
private static void createApplicationE() throws IOException {
createApplicationEManifest();
createSubsystem(APPLICATION_E, BUNDLE_G);
}
private static void createApplicationEManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_E);
createManifest(APPLICATION_E + ".mf", attributes);
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), new Header(Constants.REQUIRE_CAPABILITY, "a"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B),
provideCapability("a"),
requireCapability("b"));
}
private void createBundleC() throws IOException {
createBundle(name(BUNDLE_C), provideCapability("b"));
}
@SuppressWarnings("deprecation")
private void createBundleD() throws IOException {
createBundle(name(BUNDLE_D), new Header(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, "JavaSE-100.100"));
}
@SuppressWarnings("deprecation")
private void createBundleE() throws IOException {
createBundle(name(BUNDLE_E), new Header(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT, "J2SE-1.4, J2SE-1.5, J2SE-1.6,JavaSE-1.7"));
}
private void createBundleF() throws IOException {
createBundle(Collections.singletonList("native.file"), name(BUNDLE_F), new Header(Constants.BUNDLE_NATIVECODE,
"native.file; osname=Linux; processor=x86,"
+ "native.file; osname=Linux; processor=x86-64,"
+ "native.file; osname=Win32; processor=x86,"
+ "native.file; osname=Win32; processor=x86-64,"
+ "native.file; osname=\"MacOSX\"; processor=x86-64"));
}
private void createBundleG() throws IOException {
createBundle(Collections.singletonList("native.file"), name(BUNDLE_G), new Header(Constants.BUNDLE_NATIVECODE,
"native.file; osname=noMatch; processor=noMatch"));
}
/*
* Test that the right regions are used when validating capabilities.
*
* Application A contains a content bundle requiring capability A. Bundle B
* provides capability A and is available as an installable resource from a
* repository service. Bundle B also requires capability B. Bundle C is an
* already installed resource in the root subsystem providing capability B.
* When validating capability A, the subsystem should use the root region as
* the from region, and its own region as the to region. When validating
* capability B, the subsystem should use the root region as the from region
* as well as for the to region.
*/
@Test
public void testContentWithNonConstituentDependencyWithNonConstituentDependency() throws Exception {
// Register a repository service containing bundle B requiring
// capability B and providing capability A.
registerRepositoryService(BUNDLE_B);
Subsystem root = getRootSubsystem();
// Install unmanaged bundle C providing capability B as a constituent
// of the root subsystem.
Bundle bundleC = installBundleFromFile(BUNDLE_C, root);
try {
// Install application A with content bundle A requiring
// capability A.
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
// Make sure the Require-Capability exists for capability a...
assertHeaderExists(applicationA, Constants.REQUIRE_CAPABILITY);
// ...but not for capability b.
RequireCapabilityHeader header = new RequireCapabilityHeader(applicationA.getSubsystemHeaders(null).get(Constants.REQUIRE_CAPABILITY));
assertEquals("Wrong number of clauses", 1, header.getClauses().size());
Clause clause = header.getClauses().iterator().next();
assertEquals("Wrong path", "a", clause.getPath());
assertEquals("Wrong resolution directive", Constants.RESOLUTION_MANDATORY, clause.getDirective(Constants.RESOLUTION_DIRECTIVE).getValue());
assertEquals("Wrong effective directive", Constants.EFFECTIVE_RESOLVE, clause.getDirective(Constants.EFFECTIVE_DIRECTIVE).getValue());
try {
// Make sure the runtime resolution works as well.
applicationA.start();
}
catch (SubsystemException e) {
fail("Application A should have started");
}
finally {
stopAndUninstallSubsystemSilently(applicationA);
}
}
catch (SubsystemException e) {
fail("Application A should have installed." + e.getMessage());
}
finally {
uninstallSilently(bundleC);
}
}
/*
* BREE headers must be converted into osgi.ee requirements.
*
* The subsystem should fail to resolve and install if the required
* execution environment is not present.
*/
@Test
public void testMissingBundleRequiredExecutionEnvironment() throws Exception {
Subsystem applicationB = null;
try {
applicationB = installSubsystemFromFile(APPLICATION_B);
fail("Missing BREE should result in installation failure");
}
catch (Exception e) {
e.printStackTrace();
assertTrue("Installation failure should be due to resolution error", e.getCause() instanceof ResolutionException);
}
finally {
uninstallSubsystemSilently(applicationB);
}
}
/*
* BREE headers must be converted into osgi.ee requirements.
*
* The subsystem should resolve and install if at least one of the specified
* execution environments is present.
*/
@Test
public void testMultipleBundleRequiredExecutionEnvironments() throws Exception {
Subsystem applicationC = null;
try {
applicationC = installSubsystemFromFile(APPLICATION_C);
}
catch (Exception e) {
e.printStackTrace();
fail("Installation should succeed when at least one BREE is present");
}
finally {
uninstallSubsystemSilently(applicationC);
}
}
@Test
public void testNativeCodeRequirement() throws Exception {
Subsystem applicationD = null;
try {
applicationD = installSubsystemFromFile(APPLICATION_D);
applicationD.start();
}
catch (Exception e) {
e.printStackTrace();
fail("Installation should succeed for Bundle-NativeCode");
}
finally {
uninstallSubsystemSilently(applicationD);
}
}
@Test
public void testMissingNativeCodeRequirement() throws Exception {
Subsystem applicationE = null;
try {
applicationE = installSubsystemFromFile(APPLICATION_E);
// TODO this should fail to intsall
} catch (SubsystemException e) {
e.printStackTrace();
fail("Installation should succeed for Bundle-NativeCode");
}
try {
applicationE.start();
fail("Expected to fail to install");
}
catch (Exception e) {
// expected
}
finally {
uninstallSubsystemSilently(applicationE);
}
}
}
| 8,727 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/InstallTest.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.subsystem.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.core.internal.BasicSubsystem;
import org.apache.aries.subsystem.itests.util.Utils;
import org.apache.aries.unittest.fixture.ArchiveFixture;
import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture;
import org.apache.aries.util.filesystem.FileSystem;
import org.apache.aries.util.filesystem.IDirectory;
import org.apache.aries.util.io.IOUtils;
import org.junit.Test;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
@ExamReactorStrategy(PerMethod.class)
public class InstallTest extends SubsystemTest {
public InputStream getResourceAsStream(String path) {
return SubsystemTest.class.getClassLoader().getResourceAsStream(path);
}
@Override
public void createApplications() throws Exception {
createCompositeDirEsa();
createApplication("feature3", "tb3.jar");
createApplication("feature2", "tb3.jar", "tb2.jar");
createBundleA();
createBundleB();
createApplicationA();
createCompositeA();
createFeatureA();
}
private void createCompositeDirEsa() throws IOException,
FileNotFoundException {
ZipFixture feature = ArchiveFixture
.newZip()
.binary("OSGI-INF/SUBSYSTEM.MF", getResourceAsStream("compositeDir" + "/OSGI-INF/SUBSYSTEM.MF"))
.binary("a.jar/META-INF/MANIFEST.MF", getResourceAsStream("compositeDir" + "/a.jar/META-INF/MANIFEST.MF"))
.binary("a.jar/a/A.class", getResourceAsStream("a/A.class"))
.binary("applicationDir.esa/OSGI-INF/SUBSYSTEM.MF", getResourceAsStream("compositeDir" + "/applicationDir/OSGI-INF/SUBSYSTEM.MF"))
.binary("applicationDir.esa/b.jar/META-INF/MANIFEST.MF", getResourceAsStream("compositeDir" + "/applicationDir/b.jar/META-INF/MANIFEST.MF"))
.binary("applicationDir.esa/b.jar/b/B.class", getResourceAsStream("b/B.class"))
.binary("applicationDir.esa/featureDir.esa/OSGI-INF/SUBSYSTEM.MF", getResourceAsStream(
"compositeDir" + "/applicationDir/featureDir/OSGI-INF/SUBSYSTEM.MF"))
.binary("applicationDir.esa/featureDir.esa/a.jar/META-INF/MANIFEST.MF", getResourceAsStream(
"compositeDir" + "/applicationDir/featureDir/a.jar/META-INF/MANIFEST.MF"))
.binary("applicationDir.esa/featureDir.esa/a.jar/a/A.class", getResourceAsStream("a/A.class"))
.binary("applicationDir.esa/featureDir.esa/b.jar/META-INF/MANIFEST.MF", getResourceAsStream(
"compositeDir" + "/applicationDir/featureDir/b.jar/META-INF/MANIFEST.MF"))
.binary("applicationDir.esa/featureDir.esa/b.jar/b/B.class", getResourceAsStream("b/B.class"));
feature.end();
FileOutputStream fos = new FileOutputStream("compositeDir" + ".esa");
try {
feature.writeOut(fos);
} finally {
Utils.closeQuietly(fos);
}
File userDir = new File(System.getProperty("user.dir"));
IDirectory idir = FileSystem.getFSRoot(userDir);
File compositeDir = new File(userDir, "compositeDir");
compositeDir.mkdir();
IOUtils.unpackZip(idir.getFile("compositeDir.esa"), compositeDir);
}
@Test
public void testReturnExistingSubsystemWithSameLocation() throws Exception {
Subsystem subsystem1 = installSubsystemFromFile("feature3.esa");
try {
Subsystem subsystem2 = subsystem1.install(subsystem1.getLocation());
assertSame(subsystem1, subsystem2);
}
finally {
uninstallSubsystemSilently(subsystem1);
}
}
/*
* Install a subsystem using a location string and a null input stream. The
* location string is a file URL pointing to a subsystem directory
* containing nested subsystem and bundle directories.
*/
@Test
public void testLocationAsDirectoryUrl() throws Exception {
File file = new File("compositeDir");
try {
Subsystem subsystem = installSubsystem(getRootSubsystem(), file.toURI().toString(), null, (Boolean[]) null);
try {
assertSymbolicName("org.apache.aries.subsystem.itests.composite.dir", subsystem);
assertConstituents(3, subsystem);
assertConstituent(subsystem, "org.apache.aries.subsystem.itests.composite.dir.bundle.a");
Bundle b = getConstituentAsBundle(
subsystem,
"org.apache.aries.subsystem.itests.composite.dir.bundle.a",
null, null);
assertLocation(subsystem.getLocation() + "!/" + "a.jar", b.getLocation());
assertClassLoadable("a.A", b);
assertChildren(1, subsystem);
Subsystem child = subsystem.getChildren().iterator().next();
assertSymbolicName(
"org.apache.aries.subsystem.itests.application.dir",
child);
assertConstituent(child, "org.apache.aries.subsystem.itests.composite.dir.bundle.b");
b = getConstituentAsBundle(
child,
"org.apache.aries.subsystem.itests.composite.dir.bundle.b",
null, null);
assertLocation(child.getLocation() + "!/" + "b.jar", b.getLocation());
assertClassLoadable("b.B", b);
assertChildren(1, child);
child = child.getChildren().iterator().next();
assertSymbolicName(
"org.apache.aries.subsystem.itests.feature.dir",
child);
assertConstituent(subsystem, "org.apache.aries.subsystem.itests.composite.dir.bundle.a");
b = getConstituentAsBundle(
child,
"org.apache.aries.subsystem.itests.composite.dir.bundle.a",
null, null);
assertLocation(child.getLocation() + "!/" + "a.jar", b.getLocation());
assertClassLoadable("a.A", b);
assertConstituent(child, "org.apache.aries.subsystem.itests.composite.dir.bundle.b", Version.parseVersion("1"));
b = getConstituentAsBundle(
child,
"org.apache.aries.subsystem.itests.composite.dir.bundle.b",
Version.parseVersion("1"), null);
assertLocation(child.getLocation() + "!/" + "b.jar", b.getLocation());
assertClassLoadable("b.B", b);
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
catch (Exception e) {
e.printStackTrace();
fail("Subsystem installation using directory URL as location failed");
}
}
/*
* Bundle-SymbolicName: bundle.a.jar
*/
private static final String BUNDLE_A = "bundle.a.jar";
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A));
}
/*
* No symbolic name. No manifest.
*/
private static final String APPLICATION_A = "application.a.esa";
private void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private void createApplicationAManifest() throws IOException {
File manifest = new File(APPLICATION_A + ".mf");
if (manifest.exists())
assertTrue("Could not delete manifest", manifest.delete());
}
@Test
public void testGeneratedSymbolicNameWithoutManifest() throws Exception {
String expected = "org.apache.aries.subsystem.1";
Subsystem a = installSubsystemFromFile(APPLICATION_A);
try {
assertSymbolicName(expected, a);
assertSymbolicName(expected, a.getSubsystemHeaders(null).get(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME));
}
finally {
uninstallSubsystemSilently(a);
}
}
/*
* Manifest with no symbolic name header.
*/
private static final String COMPOSITE_A = "composite.a.esa";
private static void createCompositeA() throws IOException {
createCompositeAManifest();
createSubsystem(COMPOSITE_A);
}
private static void createCompositeAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
createManifest(COMPOSITE_A + ".mf", attributes);
}
@Test
public void testGeneratedSymbolicNameWithManifest() throws Exception {
String expected = "org.apache.aries.subsystem.1";
Subsystem a = installSubsystemFromFile(COMPOSITE_A);
try {
assertSymbolicName(expected, a);
assertSymbolicName(expected, a.getSubsystemHeaders(null).get(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME));
}
finally {
uninstallSubsystemSilently(a);
}
}
/*
* A bundle whose file extension does not end with ".jar".
*
* Bundle-SymbolicName: bundle.b.war
*/
private static final String BUNDLE_B = "bundle.b.war";
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B));
}
/*
* Subsystem-SymbolicName: feature.a.esa
* Subsystem-Type: osgi.subsystem.feature
* Subsystem-Content: bundle.b.war
*/
private static final String FEATURE_A = "feature.a.esa";
private static void createFeatureA() throws IOException {
createFeatureAManifest();
createSubsystem(FEATURE_A, BUNDLE_B);
}
private static void createFeatureAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
createManifest(FEATURE_A + ".mf", attributes);
}
@Test
public void testSupportBundleResourcesNotEndingWithJar() throws Exception {
Subsystem featureA = installSubsystemFromFile(FEATURE_A);
try {
assertConstituents(1, featureA);
assertConstituent(featureA, BUNDLE_B);
}
finally {
uninstallSubsystemSilently(featureA);
}
}
@Test
public void testLocationAsEmptyString() throws Exception {
try {
Subsystem a = installSubsystemFromFile(getRootSubsystem(), new File(APPLICATION_A), "");
try {
BasicSubsystem basic = (BasicSubsystem)a;
String location = basic.getLocation();
assertEquals("Location value should be an empty string", "", location);
}
finally {
uninstallSubsystemSilently(a);
}
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
}
| 8,728 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/FeatureTest.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.subsystem.itests;
import java.util.Collection;
import junit.framework.AssertionFailedError;
import org.apache.aries.subsystem.core.internal.ResourceHelper;
import org.junit.Assert;
import org.junit.Test;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.Subsystem;
@ExamReactorStrategy(PerMethod.class)
public class FeatureTest extends SubsystemTest {
@Override
public void createApplications() throws Exception {
createApplication("feature2", new String[]{"tb2.jar", "tb3.jar"});
createApplication("feature1", new String[]{"tb1.jar", "feature2.esa", "tb3.jar"});
createApplication("feature3", new String[]{"tb3.jar"});
}
@Test
public void testFeature1() throws Exception {
Subsystem feature1 = installSubsystemFromFile("feature1.esa");
Subsystem feature2 = null;
AssertionError error = null;
try {
assertSymbolicName("org.apache.aries.subsystem.feature1", feature1);
assertVersion("1.0.0", feature1);
assertConstituents(3, feature1);
assertChildren(1, feature1);
feature2 = feature1.getChildren().iterator().next();
assertEvent(feature2, Subsystem.State.INSTALLING, 5000);
assertEvent(feature2, Subsystem.State.INSTALLED, 5000);
assertSymbolicName("org.apache.aries.subsystem.feature2", feature2);
assertVersion("1.0.0", feature2);
assertConstituent(feature2, "org.apache.aries.subsystem.itests.tb2", Version.parseVersion("2.0.0"), IdentityNamespace.TYPE_BUNDLE);
assertConstituent(feature2, "org.apache.aries.subsystem.itests.tb3", Version.parseVersion("1.0.0"), IdentityNamespace.TYPE_BUNDLE);
assertConstituents(2, feature2);
assertChildren(0, feature2);
startSubsystem(feature1);
assertEvent(feature2, Subsystem.State.RESOLVING, 5000);
assertEvent(feature2, Subsystem.State.RESOLVED, 5000);
assertEvent(feature2, Subsystem.State.STARTING, 5000);
assertEvent(feature2, Subsystem.State.ACTIVE, 5000);
stopSubsystem(feature1);
assertEvent(feature2, Subsystem.State.STOPPING, 5000);
assertEvent(feature2, Subsystem.State.RESOLVED, 5000);
}
catch (AssertionError e) {
error = e;
throw e;
}
finally {
try {
uninstallSubsystem(feature1);
if (feature2 != null) {
assertEvent(feature2, Subsystem.State.INSTALLED, 5000);
assertEvent(feature2, Subsystem.State.UNINSTALLING, 5000);
assertEvent(feature2, Subsystem.State.UNINSTALLED, 5000);
assertNotChild(feature1, feature2);
}
}
catch (AssertionError e) {
if (error == null)
throw e;
e.printStackTrace();
}
}
}
@Test
public void testPersistence() throws Exception {
Subsystem feature3Before = installSubsystemFromFile("feature3.esa");
Subsystem feature3After = null;
AssertionError error = null;
try {
assertFeature3(feature3Before);
// Uninstall then reinstall the subsystem for a more robust test of the subsystem ID persistence.
uninstallSubsystem(feature3Before);
feature3Before = installSubsystemFromFile("feature3.esa");
assertLastId(2);
assertFeature3(feature3Before);
Bundle bundle = getSubsystemCoreBundle();
bundle.stop();
resetLastId();
bundle.start();
Subsystem root = getRootSubsystem();
assertChildren(1, root);
feature3After = root.getChildren().iterator().next();
assertLastId(2);
assertFeature3(feature3After);
}
catch (AssertionError e) {
error = e;
throw e;
}
finally {
try {
if (feature3After != null) {
uninstallSubsystem(feature3After);
}
}
catch (AssertionError e) {
if (error == null)
throw e;
e.printStackTrace();
}
}
}
@Test
public void testSharedContent() throws Exception {
Subsystem feature1 = installSubsystemFromFile("feature1.esa");
AssertionError error = null;
try {
assertConstituent(feature1, "org.apache.aries.subsystem.itests.tb3", Version.parseVersion("1.0.0"), IdentityNamespace.TYPE_BUNDLE);
Subsystem feature2 = feature1.getChildren().iterator().next();
// TODO This needs to be better implemented and put into a utility method on the superclass.
while (!feature2.getState().equals(Subsystem.State.INSTALLED))
Thread.sleep(100);
assertConstituent(feature2, "org.apache.aries.subsystem.itests.tb3", Version.parseVersion("1.0.0"), IdentityNamespace.TYPE_BUNDLE);
uninstallSubsystem(feature2);
assertNotChild(feature1, feature2);
assertConstituent(feature1, "org.apache.aries.subsystem.itests.tb3", Version.parseVersion("1.0.0"), IdentityNamespace.TYPE_BUNDLE);
}
catch (AssertionError e) {
error = e;
throw e;
}
finally {
try {
uninstallSubsystem(feature1);
}
catch (AssertionError e) {
if (error == null)
throw e;
e.printStackTrace();
}
}
}
private void assertContainsConstituent(Collection<Resource> constituents, Resource constituent) {
for (Resource resource : constituents) {
if (ResourceHelper.areEqual(constituent, resource))
return;
}
Assert.fail("Constituent not found");
}
private void assertContainsChild(Collection<Subsystem> children, Subsystem child) {
for (Subsystem subsystem : children) {
try {
assertEquals(child, subsystem);
return;
}
catch (AssertionError e) {}
}
Assert.fail("Child not found");
}
private void assertEquals(Subsystem subsystem1, Subsystem subsystem2) {
assertChildrenEqual(subsystem1.getChildren(), subsystem2.getChildren());
assertConstituentsEqual(subsystem1.getConstituents(), subsystem2.getConstituents());
Assert.assertEquals("Headers were not equal", subsystem1.getSubsystemHeaders(null), subsystem2.getSubsystemHeaders(null));
Assert.assertEquals("Locations were not equal", subsystem1.getLocation(), subsystem2.getLocation());
assertParentsEqual(subsystem1.getParents(), subsystem2.getParents());
Assert.assertEquals("States were not equal", subsystem1.getState(), subsystem2.getState());
Assert.assertEquals("IDs were not equal", subsystem1.getSubsystemId(), subsystem2.getSubsystemId());
Assert.assertEquals("Symbolic names were not equal", subsystem1.getSymbolicName(), subsystem2.getSymbolicName());
Assert.assertEquals("Versions were not equal", subsystem1.getVersion(), subsystem2.getVersion());
}
private void assertParentsEqual(Subsystem parent1, Subsystem parent2) {
if (parent1 == null || parent2 == null) {
Assert.assertTrue("Parents were not equal", parent1 == null && parent2 == null);
return;
}
assertConstituentsEqual(parent1.getConstituents(), parent2.getConstituents());
Assert.assertEquals("Headers were not equal", parent1.getSubsystemHeaders(null), parent2.getSubsystemHeaders(null));
Assert.assertEquals("Locations were not equal", parent1.getLocation(), parent2.getLocation());
assertParentsEqual(parent1.getParents(), parent2.getParents());
Assert.assertEquals("States were not equal", parent1.getState(), parent2.getState());
Assert.assertEquals("IDs were not equal", parent1.getSubsystemId(), parent2.getSubsystemId());
Assert.assertEquals("Symbolic names were not equal", parent1.getSymbolicName(), parent2.getSymbolicName());
Assert.assertEquals("Versions were not equal", parent1.getVersion(), parent2.getVersion());
}
private void assertParentsEqual(Subsystem parent1, Collection<Subsystem> parents2) {
for (Subsystem parent2 : parents2) {
try {
assertParentsEqual(parent1, parent2);
return;
}
catch (AssertionFailedError e) {}
}
Assert.fail("Parent not found: " + parent1.getSymbolicName());
}
private void assertParentsEqual(Collection<Subsystem> parents1, Collection<Subsystem> parents2) {
Assert.assertEquals("Size not equal", parents1.size(), parents2.size());
for (Subsystem parent1 : parents1) {
assertParentsEqual(parent1, parents2);
}
}
private void assertConstituentsEqual(Collection<Resource> resources1, Collection<Resource> resources2) {
Assert.assertEquals("Constituent size does not match", resources1.size(), resources2.size());
for (Resource resource : resources1) {
assertContainsConstituent(resources2, resource);
}
}
private void assertChildrenEqual(Collection<Subsystem> subsystems1, Collection<Subsystem> subsystems2) {
Assert.assertEquals("Children size does not match", subsystems1.size(), subsystems2.size());
for (Subsystem subsystem : subsystems1) {
assertContainsChild(subsystems2, subsystem);
}
}
private void assertFeature3(Subsystem subsystem) {
assertChildren(0, subsystem);
assertConstituents(1, subsystem);
assertConstituent(subsystem, "org.apache.aries.subsystem.itests.tb3", Version.parseVersion("1.0.0"), IdentityNamespace.TYPE_BUNDLE);
// subsystem.getHeaders();
// subsystem.getHeaders("");
// subsystem.getState();
assertSymbolicName("org.apache.aries.subsystem.feature3", subsystem);
assertVersion("0.0.0", subsystem);
}
}
| 8,729 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/ModelledResourceManagerTest.java | package org.apache.aries.subsystem.itests;
import static org.junit.Assert.assertNull;
import org.apache.aries.itest.RichBundleContext;
import org.junit.Test;
import org.osgi.service.subsystem.Subsystem;
public class ModelledResourceManagerTest extends SubsystemTest {
public ModelledResourceManagerTest() {
super(false);
}
@Override
public void createApplications() throws Exception {
createApplication("feature3", new String[]{"tb3.jar"});
createApplication("application1", new String[]{"tb1.jar"});
}
public void setUp() throws Exception {
super.setUp();
RichBundleContext rootContext = context(getRootSubsystem());
assertNull("Modeller is installed", rootContext.getBundleByName("org.apache.aries.application.modeller"));
assertNull("Blueprint is installed", rootContext.getBundleByName("org.apache.aries.blueprint"));
assertNull("Proxy is installed", rootContext.getBundleByName("org.apache.aries.proxy"));
}
@Test
public void testNoModelledResourceManagerService() throws Exception {
Subsystem feature3 = installSubsystemFromFile("feature3.esa");
try {
Subsystem application1 = installSubsystemFromFile("application1.esa");
try {
startSubsystem(application1);
}
finally {
stopAndUninstallSubsystemSilently(application1);
}
}
finally {
uninstallSubsystemSilently(feature3);
}
}
}
| 8,730 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/HelloWorldTest.java | package org.apache.aries.subsystem.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.File;
import java.net.URI;
import java.util.Dictionary;
import java.util.Hashtable;
import org.apache.aries.itest.RichBundleContext;
import org.apache.aries.subsystem.itests.hello.api.Hello;
import org.apache.aries.util.filesystem.FileSystem;
import org.apache.aries.util.filesystem.IDirectory;
import org.apache.aries.util.filesystem.IDirectoryFinder;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemException;
public class HelloWorldTest extends SubsystemTest
{
/*
* An implementation of the IDirectoryFinder interface that provides the
* IDirectory that corresponds to some id URI. In practice this could come
* from anywhere (exploded archive on filesystem, in-memory, IDE etc) but
* for the test just use an archive file.
*/
static class TestIDirectoryFinder implements IDirectoryFinder {
static final String IDIR_FINDERID_VALUE = "TestIDirectoryFinder";
static final String IDIR_DIRECTORYID_VALUE = "hello.esa";
static final URI HELLO_ID_URI =
URI.create(IDIR_SCHEME + "://?" + IDIR_FINDERID_KEY + "=" + IDIR_FINDERID_VALUE
+ "&" + IDIR_DIRECTORYID_KEY + "=" + IDIR_DIRECTORYID_VALUE);
static final String HELLO_ID_STRING = HELLO_ID_URI.toString();
public IDirectory retrieveIDirectory(URI idirectoryId) {
if (HELLO_ID_URI.equals(idirectoryId)) {
File helloEsaFile = new File("hello.esa");
IDirectory helloEsaIDir = FileSystem.getFSRoot(helloEsaFile);
return helloEsaIDir;
} else {
return null;
}
}
}
@Override
public void createApplications() throws Exception {
createApplication("hello", "helloImpl.jar");
}
void checkHelloSubsystem(Subsystem helloSubsystem) throws Exception
{
helloSubsystem.start();
BundleContext bc = helloSubsystem.getBundleContext();
Hello h = new RichBundleContext(bc).getService(Hello.class);
String message = h.saySomething();
assertEquals ("Wrong message back", "something", message);
helloSubsystem.stop();
}
@Test
public void testHelloFromFile() throws Exception
{
Subsystem subsystem = installSubsystemFromFile("hello.esa");
try {
checkHelloSubsystem(subsystem);
} finally {
uninstallSubsystemSilently(subsystem);
}
}
@Test
public void testHelloFromIDirectory() throws Exception
{
// Sanity check, application should not install if no IDirectoryFinder
// services are registered, which should be the case on entry to this test.
try {
installSubsystem(getRootSubsystem(), TestIDirectoryFinder.HELLO_ID_STRING, null, (Boolean[]) null);
fail("installed esa application from idir without an idirfinder service, shouldn't be possible.");
} catch (SubsystemException se) {
// expected exception
}
// The root subsystem already exists and has a service tracker for
// IDirectoryFinder services, so it will be notified on service registration.
Dictionary<String, String> properties = new Hashtable<String, String>();
properties.put(IDirectoryFinder.IDIR_FINDERID_KEY, TestIDirectoryFinder.IDIR_FINDERID_VALUE);
ServiceRegistration serviceRegistration =
bundleContext.registerService(IDirectoryFinder.class, new TestIDirectoryFinder(), properties);
// Call the SubsystemTest.installSubsystem method that does not create a URL
// and stream from the location, as we just need the location string passed
// through to the installing root subsystem.
Subsystem subsystem = installSubsystem(getRootSubsystem(), TestIDirectoryFinder.HELLO_ID_STRING, null, (Boolean[]) null);
try {
checkHelloSubsystem(subsystem);
} finally {
uninstallSubsystemSilently(subsystem);
if (serviceRegistration!=null)
serviceRegistration.unregister();
}
}
}
| 8,731 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/Header.java | package org.apache.aries.subsystem.itests;
public class Header {
String key;
String value;
public Header(String key, String value) {
this.key = key;
this.value = value;
}
}
| 8,732 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/CompositeTest.java | /*
* 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.apache.aries.subsystem.itests;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class CompositeTest extends SubsystemTest {
private static final String BUNDLE_A = "bundle.a";
private static final String BUNDLE_B = "bundle.b";
private static final String BUNDLE_C = "bundle.c";
private static final String BUNDLE_D = "bundle.d";
private static final String BUNDLE_E = "bundle.e";
private static final String COMPOSITE_A = "composite.a";
private static final String COMPOSITE_B = "composite.b";
private static final String COMPOSITE_C = "composite.c";
private static final String COMPOSITE_D = "composite.d";
private static final String PACKAGE_X = "x";
@Override
public void createApplications() throws Exception {
createBundleA();
createBundleB();
createBundleC();
createBundleD();
createBundleE();
createCompositeA();
createCompositeB();
createCompositeC();
createCompositeD();
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), version("1.0.0"), exportPackage(PACKAGE_X + ";version=1.0"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), version("1.0.0"),
new Header(Constants.PROVIDE_CAPABILITY, "y; y=test; version:Version=1.0"));
}
private void createBundleC() throws IOException {
createBundle(name(BUNDLE_C), version("1.0.0"), importPackage(PACKAGE_X + ";version=\"[1.0,2.0)\""));
}
private void createBundleD() throws IOException {
createBundle(name(BUNDLE_D), requireBundle(BUNDLE_A));
}
private void createBundleE() throws IOException {
createBundle(name(BUNDLE_E), new Header(Constants.REQUIRE_CAPABILITY, "y; filter:=(y=test)"));
}
private static void createCompositeA() throws IOException {
createCompositeAManifest();
createSubsystem(COMPOSITE_A);
}
private static void createCompositeB() throws IOException {
createCompositeBManifest();
createSubsystem(COMPOSITE_B);
}
private static void createCompositeC() throws IOException {
createCompositeCManifest();
createSubsystem(COMPOSITE_C);
}
private static void createCompositeD() throws IOException {
createCompositeDManifest();
createSubsystem(COMPOSITE_D);
}
private static void createCompositeAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(Constants.EXPORT_PACKAGE, PACKAGE_X + "; version=1.0, does.not.exist; a=b");
createManifest(COMPOSITE_A + ".mf", attributes);
}
private static void createCompositeBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_B);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(Constants.REQUIRE_BUNDLE, BUNDLE_A + "; bundle-version=\"[1.0, 2.0)\", does.not.exist; bundle-version=\"[1.0, 2.0)\"");
createManifest(COMPOSITE_B + ".mf", attributes);
}
private static void createCompositeCManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_C);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(Constants.IMPORT_PACKAGE, PACKAGE_X + ", does.not.exist; a=b");
createManifest(COMPOSITE_C + ".mf", attributes);
}
private static void createCompositeDManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_D);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(Constants.REQUIRE_CAPABILITY, "y; filter:=\"(y=test)\", does.not.exist; filter:=\"(a=b)\"");
createManifest(COMPOSITE_D + ".mf", attributes);
}
@Test
public void testExportPackage() throws Exception {
Subsystem composite = installSubsystemFromFile(COMPOSITE_A);
try {
startSubsystem(composite);
Bundle bundleA = installBundleFromFile(BUNDLE_A, composite);
try {
Bundle bundleC = installBundleFromFile(BUNDLE_C);
try {
startBundle(bundleC);
}
finally {
bundleC.uninstall();
}
}
finally {
bundleA.uninstall();
}
}
finally {
stopSubsystemSilently(composite);
uninstallSubsystemSilently(composite);
}
}
@Test
public void testImportPackage() throws Exception {
Bundle bundleA = installBundleFromFile(BUNDLE_A);
try {
Subsystem compositeC = installSubsystemFromFile(COMPOSITE_C);
try {
Bundle bundleC = installBundleFromFile(BUNDLE_C, compositeC);
try {
startBundle(bundleC, compositeC);
}
finally {
bundleC.uninstall();
}
}
finally {
uninstallSubsystemSilently(compositeC);
}
}
finally {
bundleA.uninstall();
}
}
@Test
public void testRequireBundle() throws Exception {
Bundle bundleA = installBundleFromFile(BUNDLE_A);
try {
Subsystem compositeB = installSubsystemFromFile(COMPOSITE_B);
try {
Bundle bundleD = installBundleFromFile(BUNDLE_D, compositeB);
try {
startBundle(bundleD, compositeB);
}
finally {
bundleD.uninstall();
}
}
finally {
uninstallSubsystemSilently(compositeB);
}
}
finally {
bundleA.uninstall();
}
}
@Test
public void testRequireCapability() throws Exception {
Bundle bundleB = installBundleFromFile(BUNDLE_B);
try {
Subsystem compositeD = installSubsystemFromFile(COMPOSITE_D);
try {
Bundle bundleE = installBundleFromFile(BUNDLE_E, compositeD);
try {
startBundle(bundleE, compositeD);
}
finally {
bundleE.uninstall();
}
}
finally {
uninstallSubsystemSilently(compositeD);
}
}
finally {
bundleB.uninstall();
}
}
}
| 8,733 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/RegionNameTest.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.subsystem.itests;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.aries.subsystem.core.archive.Grammar;
import org.eclipse.equinox.region.Region;
import org.junit.Before;
import org.junit.Test;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* This test ensures that names given to subsystem regions follow a predictable
* pattern and will not inadvertently change without a discussion. At least one
* major Apache Aries Subsystems consumer has a business requirement relying on
* it.
*
* The current naming convention has the following pattern:
*
* subsystemSymbolicName;subsystemVersion;subsystemType;subsystemId
*/
public class RegionNameTest extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
*
* Included In Archive
* feature.a.esa
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: composite.a.esa
* Subsystem-Type: osgi.subsystem.composite
* Subsystem-Content: feature.a.esa
*/
private static final String COMPOSITE_A = "composite.a.esa";
/*
* Subsystem-SymbolicName: feature.a.esa
* Subsystem-Type: osgi.subsystem.feature
*/
private static final String FEATURE_A = "feature.a.esa";
private static final String regexp = Grammar.SYMBOLICNAME + ';' +
Grammar.VERSION + ";(?:" +
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + '|' +
SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE + ");[0-9]+";
private static final Pattern pattern = Pattern.compile(regexp);
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createFeatureA();
createApplicationA();
createCompositeA();
createdTestFiles = true;
}
private void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, FEATURE_A);
}
private void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createCompositeA() throws IOException {
createCompositeAManifest();
createSubsystem(COMPOSITE_A, FEATURE_A);
}
private void createCompositeAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, FEATURE_A + ";version=\"[0,0]\";type=osgi.subsystem.feature");
createManifest(COMPOSITE_A + ".mf", attributes);
}
private void createFeatureA() throws IOException {
createFeatureAManifest();
createSubsystem(FEATURE_A);
}
private void createFeatureAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
createManifest(FEATURE_A + ".mf", attributes);
}
@Test
public void testApplicationRegionName() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
testRegionName(applicationA);
Subsystem featureA = getChild(applicationA, FEATURE_A, null, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
testRegionName(featureA);
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testCompositeRegionName() throws Exception {
Subsystem compositeA = installSubsystemFromFile(COMPOSITE_A);
try {
testRegionName(compositeA);
Subsystem featureA = getChild(compositeA, FEATURE_A, null, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
testRegionName(featureA);
}
finally {
uninstallSubsystemSilently(compositeA);
}
}
private void testRegionName(Subsystem subsystem) throws Exception {
Method getRegion = subsystem.getClass().getDeclaredMethod("getRegion");
getRegion.setAccessible(true);
Region region = (Region)getRegion.invoke(subsystem);
String regionName = region.getName();
Matcher matcher = pattern.matcher(regionName);
boolean matches = matcher.matches();
assertTrue("Invalid region name", matches);
}
}
| 8,734 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/Manve2Repository.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 WARRANTIESOR CONDITIONS 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.subsystem.itests.util;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
public class Manve2Repository {
private File rootFile;
public Manve2Repository(File rootFile) {
this.rootFile = rootFile;
}
// list jar files of the repository
public SortedSet<String> listFiles() {
SortedSet<String> artifacts = new TreeSet<String>();
File[] groupIds = rootFile.listFiles();
for (int i = 0; i < groupIds.length; i++) {
File groupId = groupIds[i];
if (groupId.canRead() && groupId.isDirectory()) {
File[] versionDirs = groupId.listFiles();
for (int j = 0; j < versionDirs.length; j++) {
File versionDir = versionDirs[j];
if (versionDir.canRead() && versionDir.isDirectory()) {
artifacts.addAll(getArtifacts(null, versionDir, null, "jar", null));
}
}
}
}
return artifacts;
}
// reuse code from apache geronimo with slight modification
private List<String> getArtifacts(String groupId, File versionDir, String artifactMatch, String typeMatch, String versionMatch) {
// org/apache/xbean/xbean-classpath/2.2-SNAPSHOT/xbean-classpath-2.2-SNAPSHOT.jar
List<String> artifacts = new ArrayList<String>();
String artifactId = versionDir.getParentFile().getName();
File[] files = versionDir.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.canRead()) {
if (file.isDirectory()) {
File test = new File(file, "META-INF");
if(test.exists() && test.isDirectory() && test.canRead() && groupId != null) {
String version = versionDir.getName();
String fileHeader = artifactId + "-" + version + ".";
String fileName = file.getName();
if (fileName.startsWith(fileHeader)) {
// type is everything after the file header
String type = fileName.substring(fileHeader.length());
if (!type.endsWith(".sha1") && !type.endsWith(".md5")) {
if(artifactMatch != null && !artifactMatch.equals(artifactId)) {
continue;
}
if(typeMatch != null && !typeMatch.equals(type)) {
continue;
}
if(versionMatch != null && !versionMatch.equals(version)) {
continue;
}
artifacts.add(file.getPath());
}
}
} else { // this is just part of the path to the artifact
String nextGroupId;
if (groupId == null) {
nextGroupId = artifactId;
} else {
nextGroupId = groupId + "." + artifactId;
}
artifacts.addAll(getArtifacts(nextGroupId, file, artifactMatch, typeMatch, versionMatch));
}
} else if (groupId != null) {
String version = versionDir.getName();
String fileHeader = artifactId + "-" + version + ".";
String fileName = file.getName();
if (fileName.startsWith(fileHeader)) {
// type is everything after the file header
String type = fileName.substring(fileHeader.length());
if (!type.endsWith(".sha1") && !type.endsWith(".md5")) {
if(artifactMatch != null && !artifactMatch.equals(artifactId)) {
continue;
}
if(typeMatch != null && !typeMatch.equals(type)) {
continue;
}
if(versionMatch != null && !versionMatch.equals(version)) {
continue;
}
artifacts.add(file.getPath());
}
}
}
}
}
return artifacts;
}
}
| 8,735 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/Utils.java | /*
* 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.apache.aries.subsystem.itests.util;
import java.io.Closeable;
import org.osgi.framework.ServiceRegistration;
public class Utils {
public static void closeQuietly(Closeable closeable) {
if (closeable == null) return;
try {
closeable.close();
}
catch (Exception e) {}
}
public static void unregisterQuietly(ServiceRegistration reg) {
if (reg == null) return;
try {
reg.unregister();
}
catch (Exception e) {}
}
}
| 8,736 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/TestRepositoryContent.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.subsystem.itests.util;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.osgi.service.repository.RepositoryContent;
public class TestRepositoryContent extends TestResource implements RepositoryContent {
public static class Builder {
private final List<TestCapability.Builder> capabilities = new ArrayList<TestCapability.Builder>();
private final List<TestRequirement.Builder> requirements = new ArrayList<TestRequirement.Builder>();
private byte[] content;
public TestRepositoryContent build() {
return new TestRepositoryContent(capabilities, requirements, content);
}
public Builder capability(TestCapability.Builder value) {
capabilities.add(value);
return this;
}
public Builder content(byte[] value) {
content = value;
return this;
}
public Builder requirement(TestRequirement.Builder value) {
requirements.add(value);
return this;
}
}
private final byte[] content;
public TestRepositoryContent(
List<TestCapability.Builder> capabilities,
List<TestRequirement.Builder> requirements,
byte[] content) {
super(capabilities, requirements);
this.content = content;
}
@Override
public InputStream getContent() {
try {
return new ByteArrayInputStream(content);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 8,737 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/GenericMetadataWrapper.java | /*
* 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.apache.aries.subsystem.itests.util;
import org.apache.aries.util.manifest.ManifestHeaderProcessor.GenericMetadata;
public class GenericMetadataWrapper {
private final GenericMetadata metadata;
public GenericMetadataWrapper(GenericMetadata metadata) {
if (metadata == null)
throw new NullPointerException();
this.metadata = metadata;
}
public GenericMetadata getGenericMetadata() {
return metadata;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof GenericMetadataWrapper))
return false;
GenericMetadataWrapper that = (GenericMetadataWrapper)o;
return metadata.getNamespace().equals(that.metadata.getNamespace())
&& metadata.getAttributes().equals(that.metadata.getAttributes())
&& metadata.getDirectives().equals(that.metadata.getDirectives());
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + metadata.getNamespace().hashCode();
result = 31 * result + metadata.getAttributes().hashCode();
result = 31 * result + metadata.getDirectives().hashCode();
return result;
}
@Override
public String toString() {
return "GenericMetadata[" +
"namespace=" + metadata.getNamespace() + ", " +
"directives=" + metadata.getDirectives() + "," +
"attributes=" + metadata.getAttributes() + "," +
"]";
}
}
| 8,738 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/SubsystemArchiveBuilder.java | package org.apache.aries.subsystem.itests.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.ops4j.pax.tinybundles.core.TinyBundle;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.service.subsystem.SubsystemConstants;
import aQute.bnd.osgi.Constants;
public class SubsystemArchiveBuilder {
public static final String ESA_EXTENSION = ".esa";
public static final String JAR_EXTENSION = ".jar";
public static final String SUBSYSTEM_MANIFEST_FILE = "OSGI-INF/SUBSYSTEM.MF";
private final TinyBundle bundle;
private final Manifest manifest;
public SubsystemArchiveBuilder() {
bundle = TinyBundles.bundle();
manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
}
public InputStream build() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
baos.close();
return bundle
.add(SUBSYSTEM_MANIFEST_FILE, new ByteArrayInputStream(baos.toByteArray()))
.build();
}
public SubsystemArchiveBuilder bundle(String name, InputStream value) {
return file(name + JAR_EXTENSION, value);
}
public SubsystemArchiveBuilder content(String value) {
return header(SubsystemConstants.SUBSYSTEM_CONTENT, value);
}
public SubsystemArchiveBuilder exportPackage(String value) {
return header(Constants.EXPORT_PACKAGE, value);
}
public SubsystemArchiveBuilder exportService(String value) {
return header(SubsystemConstants.SUBSYSTEM_EXPORTSERVICE, value);
}
public SubsystemArchiveBuilder file(String name, InputStream value) {
bundle.add(name, value);
return this;
}
public SubsystemArchiveBuilder header(String name, String value) {
manifest.getMainAttributes().putValue(name, value);
return this;
}
public SubsystemArchiveBuilder importPackage(String value) {
return header(Constants.IMPORT_PACKAGE, value);
}
public SubsystemArchiveBuilder importService(String value) {
return header(SubsystemConstants.SUBSYSTEM_IMPORTSERVICE, value);
}
public SubsystemArchiveBuilder provideCapability(String value) {
return header(Constants.PROVIDE_CAPABILITY, value);
}
public SubsystemArchiveBuilder requireBundle(String value) {
return header(Constants.REQUIRE_BUNDLE, value);
}
public SubsystemArchiveBuilder requireCapability(String value) {
return header(Constants.REQUIRE_CAPABILITY, value);
}
public SubsystemArchiveBuilder subsystem(String name, InputStream value) {
return file(name + ESA_EXTENSION, value);
}
public SubsystemArchiveBuilder symbolicName(String value) {
return header(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, value);
}
public SubsystemArchiveBuilder type(String value) {
return header(SubsystemConstants.SUBSYSTEM_TYPE, value);
}
}
| 8,739 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/BundleArchiveBuilder.java | package org.apache.aries.subsystem.itests.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.ops4j.pax.tinybundles.core.InnerClassStrategy;
import org.ops4j.pax.tinybundles.core.TinyBundle;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import aQute.bnd.osgi.Constants;
public class BundleArchiveBuilder {
public static final String JAR_EXTENSION = ".jar";
private final TinyBundle bundle;
public BundleArchiveBuilder() {
bundle = TinyBundles.bundle();
}
public BundleArchiveBuilder activator(Class<?> clazz) {
bundle.set(Constants.BUNDLE_ACTIVATOR, clazz.getName());
bundle.add(clazz, InnerClassStrategy.NONE);
return this;
}
public InputStream build() {
return bundle.build();
}
public byte[] buildAsBytes() throws IOException {
InputStream is = build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[2048];
int count;
while ((count = is.read(bytes)) != -1) {
baos.write(bytes, 0, count);
}
is.close();
baos.close();
return baos.toByteArray();
}
public BundleArchiveBuilder clazz(Class<?> clazz) {
bundle.add(clazz, InnerClassStrategy.NONE);
return this;
}
public BundleArchiveBuilder exportPackage(String value) {
return header(Constants.EXPORT_PACKAGE, value);
}
public BundleArchiveBuilder header(String name, String value) {
bundle.set(name, value);
return this;
}
public BundleArchiveBuilder importPackage(String value) {
return header(Constants.IMPORT_PACKAGE, value);
}
public BundleArchiveBuilder provideCapability(String value) {
return header(Constants.PROVIDE_CAPABILITY, value);
}
public BundleArchiveBuilder requireBundle(String value) {
return header(Constants.REQUIRE_BUNDLE, value);
}
public BundleArchiveBuilder requireCapability(String value) {
return header(Constants.REQUIRE_CAPABILITY, value);
}
public BundleArchiveBuilder symbolicName(String value) {
return header(Constants.BUNDLE_SYMBOLICNAME, value);
}
}
| 8,740 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/RepositoryDescriptorGenerator.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.subsystem.itests.util;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.aries.application.Content;
import org.apache.aries.application.management.BundleInfo;
import org.apache.aries.subsystem.core.internal.ResourceHelper;
import org.apache.aries.util.manifest.ManifestHeaderProcessor;
import org.apache.felix.bundlerepository.Resource;
import org.osgi.framework.Constants;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Requirement;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
// copy from application obr with modification, intend to put this in common util folder when trunk becomes stable
public final class RepositoryDescriptorGenerator
{
public static Document generateRepositoryDescriptor(String name, Set<BundleInfo> bundles) throws ParserConfigurationException
{
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element root = doc.createElement("repository");
root.setAttribute("name", name);
doc.appendChild(root);
for (BundleInfo info : bundles) {
Element resource = doc.createElement("resource");
resource.setAttribute(Resource.VERSION, info.getVersion().toString());
resource.setAttribute("uri", info.getLocation());
resource.setAttribute(Resource.SYMBOLIC_NAME, info.getSymbolicName());
resource.setAttribute(Resource.PRESENTATION_NAME, info.getHeaders().get(Constants.BUNDLE_NAME));
resource.setAttribute(Resource.ID, info.getSymbolicName() + "/" + info.getVersion());
root.appendChild(resource);
addBundleCapability(doc, resource, info);
for (Content p : info.getExportPackage()) {
addPackageCapability(doc, resource, info, p);
}
for (Content p : info.getImportPackage()) {
addPackageRequirement(doc, resource, info, p);
}
for (Content p : info.getRequireBundle()) {
addBundleRequirement(doc, resource, info, p);
}
}
return doc;
}
public static Document generateRepositoryDescriptor(String name, Collection<org.osgi.resource.Resource> resources) throws ParserConfigurationException {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element rootElement = document.createElement("repository");
rootElement.setAttribute("name", name);
document.appendChild(rootElement);
for (org.osgi.resource.Resource resource : resources) {
Element element = document.createElement("resource");
String version = String.valueOf(ResourceHelper.getVersionAttribute(resource));
element.setAttribute(Resource.VERSION, version);
element.setAttribute("uri", ResourceHelper.getContentAttribute(resource));
String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource);
element.setAttribute(Resource.SYMBOLIC_NAME, symbolicName);
element.setAttribute(Resource.PRESENTATION_NAME, symbolicName);
element.setAttribute(Resource.ID, symbolicName + "/" + version);
rootElement.appendChild(element);
addRequirements(document, element, resource);
}
return document;
}
private static void addRequirements(Document document, Element rootElement, org.osgi.resource.Resource resource) {
for (Requirement requirement : resource.getRequirements(null))
addRequirement(document, rootElement, requirement);
}
private static void addRequirement(Document document, Element rootElement, Requirement requirement) {
Element element = document.createElement("require");
if (requirement.getNamespace().equals(BundleRevision.PACKAGE_NAMESPACE)) {
addPackageRequirement(element, requirement);
}
else {
throw new IllegalArgumentException("Unsupported requirement namespace: " + requirement.getNamespace());
}
rootElement.appendChild(element);
}
private static void addPackageRequirement(Element element, Requirement requirement) {
element.setAttribute("name", "package");
element.setAttribute("filter", requirement.getDirectives().get(Constants.FILTER_DIRECTIVE).replaceAll(BundleRevision.PACKAGE_NAMESPACE, "package"));
}
private static void addBundleRequirement(Document doc, Element resource, BundleInfo info, Content p)
{
Element requirement = doc.createElement("require");
requirement.setAttribute("name", "bundle");
requirement.setAttribute("extend", "false");
requirement.setAttribute("multiple", "false");
requirement.setAttribute("optional", "false");
requirement.setAttribute("filter", ManifestHeaderProcessor.generateFilter("bundle", p.getContentName(), p.getAttributes()));
resource.appendChild(requirement);
}
private static void addPackageRequirement(Document doc, Element resource, BundleInfo info, Content p)
{
Element requirement = doc.createElement("require");
requirement.setAttribute("name", "package");
requirement.setAttribute("extend", "false");
requirement.setAttribute("multiple", "false");
String optional = p.getDirective("optional");
if (optional == null) optional = "false";
requirement.setAttribute("optional", optional);
requirement.setAttribute("filter", ManifestHeaderProcessor.generateFilter("package", p.getContentName(), p.getAttributes()));
resource.appendChild(requirement);
}
private static void addPackageCapability(Document doc, Element resource, BundleInfo info, Content p)
{
Element capability = doc.createElement("capability");
capability.setAttribute("name", "package");
resource.appendChild(capability);
addProperty(doc, capability, "package", p.getContentName(), null);
addProperty(doc, capability, Constants.VERSION_ATTRIBUTE, p.getVersion().toString(), "version");
addProperty(doc, capability, Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE, info.getSymbolicName(), null);
addProperty(doc, capability, Constants.BUNDLE_VERSION_ATTRIBUTE, info.getVersion().toString(), "version");
for (Map.Entry<String, String> entry : p.getAttributes().entrySet()) {
if (!!!Constants.VERSION_ATTRIBUTE.equals(entry.getKey())) {
addProperty(doc, capability, entry.getKey(), entry.getValue(), null);
}
}
String mandatory = p.getDirective(Constants.MANDATORY_DIRECTIVE);
if (mandatory == null) mandatory = "";
addProperty(doc, capability, Constants.MANDATORY_DIRECTIVE, mandatory, "set");
}
private static void addBundleCapability(Document doc, Element resource, BundleInfo info)
{
Element capability = doc.createElement("capability");
capability.setAttribute("name", "bundle");
resource.appendChild(capability);
addProperty(doc, capability, Resource.SYMBOLIC_NAME, info.getSymbolicName(), null);
addProperty(doc, capability, Constants.VERSION_ATTRIBUTE, info.getVersion().toString(), "version");
addProperty(doc, capability, Resource.PRESENTATION_NAME, info.getHeaders().get(Constants.BUNDLE_NAME), null);
addProperty(doc, capability, Constants.BUNDLE_MANIFESTVERSION, "2", "version");
addProperty(doc, capability, Constants.FRAGMENT_ATTACHMENT_DIRECTIVE, info.getBundleDirectives().get(Constants.FRAGMENT_ATTACHMENT_DIRECTIVE), null);
addProperty(doc, capability, Constants.SINGLETON_DIRECTIVE, info.getBundleDirectives().get(Constants.SINGLETON_DIRECTIVE), null);
}
private static void addProperty(Document doc, Element capability, String name,
String value, String type)
{
Element p = doc.createElement("p");
p.setAttribute("n", name);
p.setAttribute("v", value);
if (type != null) p.setAttribute("t", type);
capability.appendChild(p);
}
} | 8,741 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/BundleInfoImpl.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 WARRANTIESOR CONDITIONS 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.subsystem.itests.util;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.apache.aries.application.Content;
import org.apache.aries.application.management.BundleInfo;
import org.apache.aries.util.io.IOUtils;
import org.apache.aries.util.manifest.ManifestHeaderProcessor;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
public class BundleInfoImpl implements BundleInfo {
private Map<String, String> attributeMap = new HashMap<String, String>();
private String path;
private Attributes attributes;
public BundleInfoImpl(String pathToJar) {
Manifest manifest = null;
try {
File jarFile = new File(pathToJar);
this.path = jarFile.toURI().toURL().toString();
JarFile f = new JarFile(new File(pathToJar));
try {
manifest = f.getManifest();
}
finally {
IOUtils.close(f);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
process(manifest);
}
private void process(Manifest manifest) {
if (manifest != null) {
this.attributes = manifest.getMainAttributes();
Set<Object> set = this.attributes.keySet();
for (Object entry : set) {
String key = entry.toString();
attributeMap.put(key, this.attributes.getValue(key));
}
}
}
public Map<String, String> getBundleAttributes() {
return attributeMap;
}
public Map<String, String> getBundleDirectives() {
// TODO Auto-generated method stub
return new HashMap<String, String>();
}
public Set<Content> getExportPackage() {
String exportPkgs = attributeMap.get(Constants.EXPORT_PACKAGE);
List<String> list = ManifestHeaderProcessor.split(exportPkgs, ",");
Set<Content> contents = new HashSet<Content>();
for (String content : list) {
contents.add(new ContentImpl(content));
}
return contents;
}
public Set<Content> getExportService() {
// TODO Auto-generated method stub
return null;
}
public Map<String, String> getHeaders() {
return attributeMap;
}
public Set<Content> getImportPackage() {
String importPkgs = attributeMap.get(Constants.IMPORT_PACKAGE);
List<String> list = ManifestHeaderProcessor.split(importPkgs, ",");
Set<Content> contents = new HashSet<Content>();
for (String content : list) {
contents.add(new ContentImpl(content));
}
return contents;
}
public Set<Content> getImportService() {
// TODO Auto-generated method stub
return null;
}
public String getLocation() {
return path;
}
public Set<Content> getRequireBundle() {
String requireBundle = attributeMap.get(Constants.REQUIRE_BUNDLE);
List<String> list = ManifestHeaderProcessor.split(requireBundle, ",");
Set<Content> contents = new HashSet<Content>();
for (String content : list) {
contents.add(new ContentImpl(content));
}
return contents;
}
public String getSymbolicName() {
return attributeMap.get(Constants.BUNDLE_SYMBOLICNAME);
}
public Version getVersion() {
return Version.parseVersion(attributeMap.get(Constants.BUNDLE_VERSION));
}
public Attributes getRawAttributes() {
return this.attributes;
}
}
| 8,742 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/RepositoryGenerator.java | /*
* 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.apache.aries.subsystem.itests.util;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.aries.application.Content;
import org.apache.aries.application.management.BundleInfo;
import org.apache.aries.subsystem.util.felix.FelixResourceAdapter;
import org.apache.aries.subsystem.util.felix.OsgiResourceAdapter;
import org.apache.felix.bundlerepository.Reason;
import org.apache.felix.bundlerepository.Repository;
import org.apache.felix.bundlerepository.RepositoryAdmin;
import org.apache.felix.bundlerepository.Resolver;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.SubsystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
public class RepositoryGenerator {
private static final Logger LOGGER = LoggerFactory
.getLogger(RepositoryGenerator.class);
private static final String REPOSITORY_FILE = "repository-subsystems.xml";
final private BundleContext context;
private RepositoryAdmin repositoryAdmin;
private static boolean generated = false;
private String obrPath;
public RepositoryGenerator(BundleContext context) {
this.context = context;
}
public RepositoryGenerator(BundleContext context, String obrPath) {
this.context = context;
this.obrPath = obrPath;
}
public void generateOBR() {
if (generated) {
return;
}
synchronized(this) {
if (obrPath == null) {
// set to a default obr file which is local m2 repo
String file = System.getProperty("user.home") + "/.m2/repository/";
if (new File(file).exists()) {
obrPath = file;
}
}
// if repository.xml already exists, no need to generate it
if (new File(obrPath + REPOSITORY_FILE).exists()) {
registerOBR();
generated = true;
return;
}
File rootFile = new File(obrPath);
if (!rootFile.exists() || !rootFile.isDirectory()) {
throw new IllegalArgumentException("obr path " + obrPath
+ " is not valid");
}
Manve2Repository repo = new Manve2Repository(rootFile);
SortedSet<String> ss = repo.listFiles();
Set<BundleInfo> infos = new HashSet<BundleInfo>();
for (String s : ss) {
BundleInfo info = new BundleInfoImpl(s);
infos.add(info);
}
Document doc;
try {
doc = RepositoryDescriptorGenerator.generateRepositoryDescriptor(
"Subsystem Repository description", infos);
FileOutputStream fout = new FileOutputStream(obrPath
+ REPOSITORY_FILE);
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(doc), new StreamResult(fout));
fout.close();
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(doc), new StreamResult(System.out));
} catch (Exception e) {
LOGGER.error("Exception occurred when generate obr", e);
e.printStackTrace();
}
registerOBR();
generated = true;
}
}
private void registerOBR() {
// set repositoryAdmin
ServiceReference ref = context.getServiceReference(RepositoryAdmin.class);
if (ref != null) {
this.repositoryAdmin = (RepositoryAdmin) context.getService(ref);
try {
this.repositoryAdmin.addRepository(new File(obrPath
+ REPOSITORY_FILE).toURI().toURL());
} catch (Exception e) {
LOGGER.warn("Exception occurred when register obr", e);
e.printStackTrace();
}
this.context.ungetService(ref);
} else {
LOGGER.error("Unable to register OBR as RepositoryAdmin service is not available");
}
}
/**
* the format of resource is like bundlesymbolicname;version=1.0.0, for example com.ibm.ws.eba.example.blog.api;version=1.0.0,
*/
@SuppressWarnings({ "rawtypes", "unused" })
public Resource find(String resource) throws SubsystemException {
generateOBR();
Content content = new ContentImpl(resource);
String symbolicName = content.getContentName();
// this version could possibly be a range
String version = content.getVersion().toString();
StringBuilder filterString = new StringBuilder();
filterString.append("(&(name" + "=" + symbolicName + "))");
filterString.append("(version" + "=" + version + "))");
//org.apache.felix.bundlerepository.Resource[] res = this.repositoryAdmin.discoverResources(filterString.toString());
Repository[] repos = this.repositoryAdmin.listRepositories();
org.apache.felix.bundlerepository.Resource res = null;
for (Repository repo : repos) {
org.apache.felix.bundlerepository.Resource[] resources = repo.getResources();
for (int i = 0; i < resources.length; i++) {
if (resources[i].getSymbolicName().equals(symbolicName)) {
if (resources[i].getVersion().compareTo(new Version(version)) == 0) {
res = resources[i];
break;
}
}
}
}
if (res == null) {
// throw new SubsystemException("unable to find the resource " + resource);
return null;
}
Map props = res.getProperties();
Object type = props.get(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE);
return new FelixResourceAdapter(res);
}
public List<Resource> resolve(List<Resource> subsystemContent,
List<Resource> subsystemResources) throws SubsystemException {
generateOBR();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Attempt to resolve subsystem content {} subsystem resource {}", subsystemContent.toString(), subsystemResources.toString());
}
Resolver obrResolver = this.repositoryAdmin.resolver();
// add subsystem content to the resolver
for (Resource res : subsystemContent) {
// org.apache.felix.bundlerepository.Resource obrRes = findOBRResource(res);
// obrResolver.add(obrRes);
obrResolver.add(new OsgiResourceAdapter(res));
}
// add subsystem resource to the resolver
for (Resource res : subsystemResources) {
// org.apache.felix.bundlerepository.Resource obrRes = findOBRResource(res);
// obrResolver.add(obrRes);
obrResolver.add(new OsgiResourceAdapter(res));
}
// Question: do we need to create the repository.xml for the subsystem and add the repo to RepoAdmin?
List<Resource> resources = new ArrayList<Resource>();
if (obrResolver.resolve()) {
for (org.apache.felix.bundlerepository.Resource res : obrResolver.getRequiredResources()) {
// resources.add(toResource(res));
resources.add(new FelixResourceAdapter(res));
}
// Question: should we handle optional resource differently?
for (org.apache.felix.bundlerepository.Resource res : obrResolver.getOptionalResources()) {
// resources.add(toResource(res));
resources.add(new FelixResourceAdapter(res));
}
} else {
// log the unsatisfied requirement
Reason[] reasons = obrResolver.getUnsatisfiedRequirements();
StringBuilder builder = new StringBuilder("Failed to resolve subsystem").append(System.getProperty("line.separator"));
for (Reason reason : reasons) {
LOGGER.warn("Unable to resolve subsystem content {} subsystem resource {} because of unsatisfied requirement {}",
new Object[] {subsystemContent.toString(), subsystemResources.toString(), reason.getRequirement().getName()});
builder
.append("resource = ")
.append(reason.getResource().getSymbolicName())
.append(", requirement = ")
.append(reason.getRequirement().getName())
.append(System.getProperty("line.separator"));
}
throw new SubsystemException(builder.toString());
}
return resources;
}
}
| 8,743 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/TestResource.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.subsystem.itests.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
public class TestResource implements Resource {
public static class Builder {
private final List<TestCapability.Builder> capabilities = new ArrayList<TestCapability.Builder>();
private final List<TestRequirement.Builder> requirements = new ArrayList<TestRequirement.Builder>();
public TestResource build() {
return new TestResource(capabilities, requirements);
}
public Builder capability(TestCapability.Builder value) {
capabilities.add(value);
return this;
}
public Builder requirement(TestRequirement.Builder value) {
requirements.add(value);
return this;
}
}
private final List<Capability> capabilities;
private final List<Requirement> requirements;
public TestResource(List<TestCapability.Builder> capabilities, List<TestRequirement.Builder> requirements) {
this.capabilities = new ArrayList<Capability>(capabilities.size());
for (TestCapability.Builder builder : capabilities)
this.capabilities.add(builder.resource(this).build());
this.requirements = new ArrayList<Requirement>(requirements.size());
for (TestRequirement.Builder builder : requirements)
this.requirements.add(builder.resource(this).build());
}
@Override
public List<Capability> getCapabilities(String namespace) {
if (namespace == null)
return Collections.unmodifiableList(capabilities);
ArrayList<Capability> result = new ArrayList<Capability>(capabilities.size());
for (Capability capability : capabilities)
if (namespace.equals(capability.getNamespace()))
result.add(capability);
result.trimToSize();
return Collections.unmodifiableList(result);
}
@Override
public List<Requirement> getRequirements(String namespace) {
if (namespace == null)
return Collections.unmodifiableList(requirements);
ArrayList<Requirement> result = new ArrayList<Requirement>(requirements.size());
for (Requirement requirement : requirements)
if (namespace.equals(requirement.getNamespace()))
result.add(requirement);
result.trimToSize();
return Collections.unmodifiableList(result);
}
}
| 8,744 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/ContentImpl.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 WARRANTIESOR CONDITIONS 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.subsystem.itests.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.application.Content;
import org.apache.aries.util.VersionRange;
import org.apache.aries.util.manifest.ManifestHeaderProcessor;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
/**
* Implementation of Content, copied from org.apache.aries.application.utils folder with
* intention to common this out to a common util folder
*
*/
public final class ContentImpl implements Content
{
private String contentName;
protected Map<String, String> attributes;
private Map<String, String> directives;
private Map<String, String> nameValueMap;
/**
*
* @param content Application-Content, Import-Package content
*/
public ContentImpl(String content) {
Map<String, Map<String, String>> appContentsMap = ManifestHeaderProcessor.parseImportString(content);
if (appContentsMap.size() != 1) {
throw new IllegalArgumentException("Invalid content string " + content);
}
for (Map.Entry<String, Map<String, String>> entry : appContentsMap.entrySet()) {
this.contentName = entry.getKey();
this.nameValueMap= entry.getValue();
setup();
break;
}
}
public ContentImpl (String bundleSymbolicName, Version version) {
this.contentName = bundleSymbolicName;
this.nameValueMap = new HashMap<String, String>();
nameValueMap.put("version", version.toString());
setup();
}
/**
*
* @param contentName
* @param nameValueMap
*/
public ContentImpl(String contentName, Map<String, String> nameValueMap) {
this.contentName = contentName;
this.nameValueMap= nameValueMap;
setup();
}
public String getContentName() {
return this.contentName;
}
public Map<String, String> getAttributes() {
return Collections.unmodifiableMap(this.attributes);
}
public Map<String, String> getDirectives() {
return Collections.unmodifiableMap(this.directives);
}
public String getAttribute(String key) {
String toReturn = this.attributes.get(key);
return toReturn;
}
/**
* add key value to the attributes map
* @param key
* @param value
*/
public void addAttribute(String key, String value) {
this.attributes.put(key, value);
}
public String getDirective(String key) {
String toReturn = this.directives.get(key);
return toReturn;
}
public Map<String, String> getNameValueMap() {
Map<String, String> nvm = new HashMap<String, String>();
for (String key : this.nameValueMap.keySet()) {
nvm.put(key, this.nameValueMap.get(key));
}
return nvm;
}
/**
* add key value to the directives map
* @param key
* @param value
*/
public void addDirective(String key, String value) {
this.directives.put(key, value);
}
public VersionRange getVersion() {
VersionRange vi = null;
if (this.attributes.get(Constants.VERSION_ATTRIBUTE) != null
&& this.attributes.get(Constants.VERSION_ATTRIBUTE).length() > 0) {
vi = ManifestHeaderProcessor.parseVersionRange(this.attributes.get(Constants.VERSION_ATTRIBUTE));
} else {
// what if version is not specified? let's interpret it as 0.0.0
vi = ManifestHeaderProcessor.parseVersionRange("0.0.0");
}
return vi;
}
@Override
public String toString()
{
return this.contentName + ";" + this.nameValueMap.toString();
}
@Override
public boolean equals(Object other)
{
if (other == this) return true;
if (other == null) return false;
if (other instanceof ContentImpl) {
ContentImpl otherContent = (ContentImpl)other;
Map<String,String> attributesWithoutVersion = attributes;
if (attributes.containsKey("version")) {
attributesWithoutVersion = new HashMap<String, String>(attributes);
attributesWithoutVersion.remove("version");
}
Map<String, String> otherAttributesWithoutVersion = otherContent.attributes;
if (otherContent.attributes.containsKey("version")) {
otherAttributesWithoutVersion = new HashMap<String, String>(otherContent.attributes);
otherAttributesWithoutVersion.remove("version");
}
return contentName.equals(otherContent.contentName) &&
attributesWithoutVersion.equals(otherAttributesWithoutVersion) &&
directives.equals(otherContent.directives) &&
getVersion().equals(otherContent.getVersion());
}
return false;
}
@Override
public int hashCode()
{
return contentName.hashCode();
}
/**
* set up directives and attributes
*/
protected void setup() {
this.attributes = new HashMap<String, String>();
this.directives = new HashMap<String, String>();
for (String key : this.nameValueMap.keySet()) {
if (key.endsWith(":")) {
this.directives.put(key.substring(0, key.length() - 1), this.nameValueMap.get(key));
} else {
this.attributes.put(key, this.nameValueMap.get(key));
}
}
}
}
| 8,745 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/TestCapability.java | /*
* 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.apache.aries.subsystem.itests.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.osgi.resource.Capability;
import org.osgi.resource.Resource;
public class TestCapability implements Capability {
public static class Builder {
private final Map<String, Object> attributes = new HashMap<String, Object>();
private final Map<String, String> directives = new HashMap<String, String>();
private String namespace;
private Resource resource;
public Builder attribute(String name, Object value) {
attributes.put(name, value);
return this;
}
public TestCapability build() {
return new TestCapability(namespace, attributes, directives, resource);
}
public Builder directive(String name, String value) {
directives.put(name, value);
return this;
}
public Builder namespace(String value) {
namespace = value;
return this;
}
public Builder resource(Resource value) {
resource = value;
return this;
}
}
private final Map<String, Object> attributes;
private final Map<String, String> directives;
private final String namespace;
private final Resource resource;
public TestCapability(
String namespace,
Map<String, Object> attributes,
Map<String, String> directives,
Resource resource) {
this.namespace = namespace;
this.attributes = new HashMap<String, Object>(attributes);
this.directives = new HashMap<String, String>(directives);
this.resource = resource;
}
@Override
public Map<String, Object> getAttributes() {
return Collections.unmodifiableMap(attributes);
}
@Override
public Map<String, String> getDirectives() {
return Collections.unmodifiableMap(directives);
}
@Override
public String getNamespace() {
return namespace;
}
@Override
public Resource getResource() {
return resource;
}
}
| 8,746 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/TestRepository.java | /*
* 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.apache.aries.subsystem.itests.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.aries.subsystem.core.internal.ResourceHelper;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.repository.ExpressionCombiner;
import org.osgi.service.repository.Repository;
import org.osgi.service.repository.RequirementBuilder;
import org.osgi.service.repository.RequirementExpression;
import org.osgi.util.promise.Promise;
public class TestRepository implements Repository {
public static class Builder {
private final Collection<Resource> resources = new HashSet<Resource>();
public TestRepository build() {
return new TestRepository(resources);
}
public Builder resource(Resource value) {
resources.add(value);
return this;
}
}
private final Collection<Resource> resources;
public TestRepository(Collection<Resource> resources) {
this.resources = resources;
}
@Override
public Map<Requirement, Collection<Capability>> findProviders(Collection<? extends Requirement> requirements) {
Map<Requirement, Collection<Capability>> result = new HashMap<Requirement, Collection<Capability>>();
for (Requirement requirement : requirements) {
for (Resource resource : resources) {
List<Capability> capabilities = resource.getCapabilities(requirement.getNamespace());
for (Capability capability : capabilities) {
if (ResourceHelper.matches(requirement, capability)) {
Collection<Capability> c = result.get(requirement);
if (c == null) {
c = new HashSet<Capability>();
result.put(requirement, c);
}
c.add(capability);
}
}
}
}
return result;
}
@Override
public Promise<Collection<Resource>> findProviders(RequirementExpression expression) {
throw new UnsupportedOperationException();
}
@Override
public ExpressionCombiner getExpressionCombiner() {
throw new UnsupportedOperationException();
}
@Override
public RequirementBuilder newRequirementBuilder(String namespace) {
throw new UnsupportedOperationException();
}
}
| 8,747 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/util/TestRequirement.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.subsystem.itests.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
public class TestRequirement implements Requirement {
public static class Builder {
private final Map<String, Object> attributes = new HashMap<String, Object>();
private final Map<String, String> directives = new HashMap<String, String>();
private String namespace;
private Resource resource;
public Builder attribute(String name, Object value) {
attributes.put(name, value);
return this;
}
public TestRequirement build() {
return new TestRequirement(namespace, attributes, directives, resource);
}
public Builder directive(String name, String value) {
directives.put(name, value);
return this;
}
public Builder namespace(String value) {
namespace = value;
return this;
}
public Builder resource(Resource value) {
resource = value;
return this;
}
}
private final Map<String, Object> attributes;
private final Map<String, String> directives;
private final String namespace;
private final Resource resource;
public TestRequirement(
String namespace,
Map<String, Object> attributes,
Map<String, String> directives,
Resource resource) {
this.namespace = namespace;
this.attributes = new HashMap<String, Object>(attributes);
this.directives = new HashMap<String, String>(directives);
this.resource = resource;
}
@Override
public Map<String, Object> getAttributes() {
return Collections.unmodifiableMap(attributes);
}
@Override
public Map<String, String> getDirectives() {
return Collections.unmodifiableMap(directives);
}
@Override
public String getNamespace() {
return namespace;
}
@Override
public Resource getResource() {
return resource;
}
}
| 8,748 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1442Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertEquals;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.aries.subsystem.core.internal.Activator;
import org.apache.aries.subsystem.core.internal.SystemRepository;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.BundleArchiveBuilder;
import org.apache.aries.subsystem.itests.util.SubsystemArchiveBuilder;
import org.apache.aries.subsystem.itests.util.TestRequirement;
import org.junit.Test;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
@ExamReactorStrategy(PerMethod.class)
public class Aries1442Test extends SubsystemTest {
@Test
public void testNewlyInstalledFeature() throws Exception {
assertFeature(createFeature());
}
@Test
public void testPersistedFeature() throws Exception {
createFeature();
restartSubsystemsImplBundle();
Subsystem root = getRootSubsystem();
Subsystem feature = getChild(root, "feature", null, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
assertFeature(feature);
}
private Subsystem createFeature() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem feature = installSubsystem(
root,
"feature",
new SubsystemArchiveBuilder()
.symbolicName("feature")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE)
.bundle(
"a",
new BundleArchiveBuilder()
.symbolicName("a")
.exportPackage("a")
.build())
.build(),
true
);
uninstallableSubsystems.add(feature);
startSubsystem(feature, true);
stoppableSubsystems.add(feature);
return feature;
}
private void assertFeature(Subsystem feature) {
Resource resource = (Resource)feature;
List<Capability> identityCapabilities = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE);
String message = "Wrong number of osgi.identity capabilities";
assertEquals(message, 1, identityCapabilities.size());
Collection<Capability> capabilities = resource.getCapabilities(null);
int count = 0;
for (Capability capability : capabilities) {
if (IdentityNamespace.IDENTITY_NAMESPACE.equals(capability.getNamespace())) {
count++;
}
}
assertEquals(message, 1, count);
SystemRepository repository = Activator.getInstance().getSystemRepository();
Requirement requirement = new TestRequirement.Builder()
.namespace("osgi.identity")
.directive("filter", "(osgi.identity=a)")
.build();
Map<Requirement, Collection<Capability>> providers = repository.findProviders(
Collections.singleton(requirement));
capabilities = providers.get(requirement);
assertEquals(message, 1, capabilities.size());
}
}
| 8,749 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1338Test.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.subsystem.itests.defect;
import static org.junit.Assert.fail;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.BundleArchiveBuilder;
import org.apache.aries.subsystem.itests.util.SubsystemArchiveBuilder;
import org.junit.Test;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemException;
public class Aries1338Test extends SubsystemTest {
@Test
public void test() throws Exception {
test("x;y;z;version=1", "x;version=1,y;version=1,z;version=1", false);
}
@Test
public void testMissingExportPackageX() throws Exception {
test("x;y;z;version=1", "y;version=1,z;version=1", true);
}
@Test
public void testMissingExportPackageY() throws Exception {
test("x;y;z;version=1", "x;version=1,z;version=1", true);
}
@Test
public void testMissingExportPackageZ() throws Exception {
test("x;y;z;version=1", "x;version=1,y;version=1", true);
}
@Test
public void testWrongVersionExportPackageX() throws Exception {
test("x;y;z;version=\"[1,2)\"", "x;version=0,y;version=1,z;version=1.1", true);
}
@Test
public void testWrongVersionExportPackageY() throws Exception {
test("x;y;z;version=\"[1,2)\"", "x;version=1.9,y;version=2,z;version=1.1", true);
}
@Test
public void testWrongVersionExportPackageZ() throws Exception {
test("x;y;z;version=\"[1,2)\"", "x;version=1.9,y;version=1.0.1,z", true);
}
private void test(String importPackage, String exportPackage, boolean shouldFail) throws Exception {
Subsystem root = getRootSubsystem();
try {
Subsystem subsystem = installSubsystem(
root,
"subsystem",
new SubsystemArchiveBuilder()
.symbolicName("subsystem")
.bundle(
"a",
new BundleArchiveBuilder()
.symbolicName("a")
.importPackage(importPackage)
.build())
.bundle(
"b",
new BundleArchiveBuilder()
.symbolicName("b")
.exportPackage(exportPackage)
.build())
.build());
uninstallableSubsystems.add(subsystem);
if (shouldFail) {
fail("Subsystem should not have installed");
}
}
catch (SubsystemException e) {
e.printStackTrace();
if (!shouldFail) {
fail("Subsystem should have installed");
}
}
}
}
| 8,750 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1434Test.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.subsystem.itests.defect;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* https://issues.apache.org/jira/browse/ARIES-1434
*
* org.osgi.framework.BundleException: Region
* 'application.a.esa;0.0.0;osgi.subsystem.application;1' is already connected
* to region 'composite.a.esa;0.0.0;osgi.subsystem.composite;2
*
*/
public class Aries1434Test extends SubsystemTest {
private static final String APPLICATION_A = "application.a.esa";
private static final String COMPOSITE_A = "composite.a.esa";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createCompositeA();
createApplicationA();
createdTestFiles = true;
}
private void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, COMPOSITE_A);
}
private void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createCompositeA() throws IOException {
createCompositeAManifest();
createSubsystem(COMPOSITE_A);
}
private void createCompositeAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(Constants.EXPORT_PACKAGE, "x");
createManifest(COMPOSITE_A + ".mf", attributes);
}
@Test
public void testResolvedChild() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
Subsystem compositeA = getChild(applicationA, COMPOSITE_A, null, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
startSubsystem(compositeA);
stopSubsystem(compositeA);
try {
assertState(State.RESOLVED, compositeA);
startSubsystem(applicationA);
try {
assertState(State.ACTIVE, applicationA);
assertState(State.ACTIVE, compositeA);
}
finally {
stopSubsystemSilently(applicationA);
}
}
finally {
stopSubsystemSilently(compositeA);
}
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testActiveChild() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
Subsystem compositeA = getChild(applicationA, COMPOSITE_A, null, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
startSubsystem(compositeA);
try {
assertState(State.ACTIVE, compositeA);
startSubsystem(applicationA);
try {
assertState(State.ACTIVE, applicationA);
assertState(State.ACTIVE, compositeA);
}
finally {
stopSubsystemSilently(applicationA);
}
}
finally {
stopSubsystemSilently(compositeA);
}
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
}
| 8,751 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1435Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.TestCapability;
import org.apache.aries.subsystem.itests.util.TestRepository;
import org.apache.aries.subsystem.itests.util.TestRepositoryContent;
import org.eclipse.equinox.region.Region;
import org.eclipse.equinox.region.RegionDigraph;
import org.eclipse.equinox.region.RegionDigraph.FilteredRegion;
import org.eclipse.equinox.region.RegionFilter;
import org.junit.Before;
import org.junit.Test;
import org.ops4j.pax.tinybundles.core.InnerClassStrategy;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.framework.hooks.weaving.WeavingHook;
import org.osgi.framework.hooks.weaving.WovenClass;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.resource.Resource;
import org.osgi.service.repository.Repository;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* https://issues.apache.org/jira/browse/ARIES-1435
*
* Sharing policy updates for dynamic imports, if necessary, should proceed up
* the subsystem region tree.
*/
public class Aries1435Test extends SubsystemTest {
private static final String APPLICATION_A = "application.a.esa";
private static final String APPLICATION_B = "application.b.esa";
private static final String APPLICATION_C = "application.c.esa";
private static final String APPLICATION_D = "application.d.esa";
private static final String APPLICATION_E = "application.e.esa";
private static final String BUNDLE_A = "bundle.a.jar";
private static final String BUNDLE_B = "bundle.b.jar";
private static final String COMPOSITE_A = "composite.a.esa";
private static final String COMPOSITE_B = "composite.b.esa";
private static final String COMPOSITE_C = "composite.c.esa";
private static final String COMPOSITE_D = "composite.d.esa";
private static final String COMPOSITE_E = "composite.e.esa";
private static final String COMPOSITE_F = "composite.f.esa";
private static final String FEATURE_A = "feature.a.esa";
private static final String FEATURE_B = "feature.b.esa";
private static final String FEATURE_C = "feature.c.esa";
private static final String FEATURE_D = "feature.d.esa";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createApplicationB();
createApplicationA();
createCompositeA();
createCompositeB();
createApplicationC();
createFeatureA();
createFeatureB();
createApplicationD();
createCompositeC();
createFeatureC();
createCompositeD();
createFeatureD();
createApplicationE();
createCompositeE();
createCompositeF();
createdTestFiles = true;
}
private AtomicBoolean weavingHookCalled;
@Override
public void setUp() throws Exception {
super.setUp();
try {
serviceRegistrations.add(
bundleContext.registerService(
Repository.class,
createTestRepository(),
null));
}
catch (IOException e) {
throw new RuntimeException(e);
}
weavingHookCalled = new AtomicBoolean();
}
@Test
public void testApplicationWithParentApplication() throws Exception {
testDynamicImport(APPLICATION_B, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, APPLICATION_A);
}
@Test
public void testApplicationWithParentComposite() throws Exception {
testDynamicImport(APPLICATION_B, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, COMPOSITE_A);
}
@Test
public void testApplicationWithParentFeature() throws Exception {
testDynamicImport(APPLICATION_B, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, FEATURE_A);
}
@Test
public void testApplicationWithParentRoot() throws Exception {
testDynamicImport(APPLICATION_B, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, null);
}
@Test
public void testChildExportsPackage() throws Exception {
registerWeavingHook("b");
Subsystem applicationB = installSubsystemFromFile(APPLICATION_B);
try {
Subsystem compositeE = installSubsystemFromFile(applicationB, COMPOSITE_E);
try {
startSubsystem(compositeE);
try {
testSharingPolicy(applicationB, "b", true);
testDynamicImport(applicationB, "b.B");
testSharingPolicy(applicationB, "b", true);
testSharingPolicy(compositeE, "b", false);
testSharingPolicy(getRootSubsystem(), "b", false);
}
finally {
stopSubsystemSilently(compositeE);
}
}
finally {
uninstallSubsystemSilently(compositeE);
}
}
finally {
uninstallSubsystemSilently(applicationB);
}
}
@Test
public void testCompositeWithParentApplication() throws Exception {
testDynamicImport(COMPOSITE_B, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE, APPLICATION_C);
}
@Test
public void testCompositeWithParentComposite() throws Exception {
testDynamicImport(COMPOSITE_B, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE, COMPOSITE_C);
}
@Test
public void testCompositeWithParentFeature() throws Exception {
testDynamicImport(COMPOSITE_B, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE, FEATURE_C);
}
@Test
public void testDisconnectedEdgeWithParent() throws Exception {
registerWeavingHook("b");
Bundle bundleB = getRootSubsystem().getBundleContext().installBundle(
BUNDLE_B, new ByteArrayInputStream(createBundleBContent()));
try {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
Subsystem applicationB = getChild(applicationA, APPLICATION_B);
uninstallSubsystem(applicationB);
removeConnectionWithParent(applicationA);
applicationB = installSubsystemFromFile(applicationA, APPLICATION_B);
try {
try {
testDynamicImport(applicationB, "b.B");
fail("Dynamic import should have failed");
}
catch (AssertionError e) {
// Okay.
}
testSharingPolicy(applicationB, "b", true);
testSharingPolicy(applicationA, "b", false);
testSharingPolicy(getRootSubsystem(), "b", false);
}
finally {
uninstallSubsystemSilently(applicationB);
}
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
finally {
uninstallSilently(bundleB);
}
}
@Test
public void testFeatureWithParentApplication() throws Exception {
testDynamicImport(FEATURE_B, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE, APPLICATION_D);
}
@Test
public void testFeatureWithParentComposite() throws Exception {
testDynamicImport(FEATURE_B, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE, COMPOSITE_D);
}
@Test
public void testFeatureWithParentFeature() throws Exception {
testDynamicImport(FEATURE_B, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE, FEATURE_D);
}
@Test
public void testNoProviders() throws Exception {
registerWeavingHook("b");
Subsystem applicationB = installSubsystemFromFile(APPLICATION_B);
try {
Bundle bundleA = getConstituentAsBundle(applicationB, BUNDLE_A, null, null);
bundleA.loadClass("a.A");
try {
bundleA.loadClass("b.B");
fail("Class should not have loaded");
}
catch (ClassNotFoundException e) {
// Okay.
}
testSharingPolicy(applicationB, "b", false);
}
finally {
uninstallSubsystemSilently(applicationB);
}
}
@Test
public void testWildcardEverything() throws Exception {
registerWeavingHook("b", "*");
Subsystem compositeB = installSubsystemFromFile(COMPOSITE_B);
try {
Bundle bundleB = compositeB.getBundleContext().installBundle(
BUNDLE_B,
new ByteArrayInputStream(createBundleBContent()));
try {
Subsystem applicationB = installSubsystemFromFile(compositeB, APPLICATION_B);
Subsystem featureB = installSubsystemFromFile(applicationB, FEATURE_B);
Subsystem applicationE = installSubsystemFromFile(featureB, APPLICATION_E);
testSharingPolicy(applicationE, "b", false);
testSharingPolicy(applicationE, "org.osgi.framework.Constants", false);
testSharingPolicy(applicationB, "b", false);
testSharingPolicy(applicationB, "org.osgi.framework.Constants", false);
testSharingPolicy(compositeB, "b", false);
testSharingPolicy(compositeB, "org.osgi.framework.Constants", false);
testSharingPolicy(getRootSubsystem(), "b", false);
testSharingPolicy(getRootSubsystem(), "org.osgi.framework.Constants", false);
testDynamicImport(applicationE, "b.B");
testDynamicImport(applicationE, "org.osgi.framework.Constants");
testDynamicImport(featureB, "b.B");
testDynamicImport(featureB, "org.osgi.framework.Constants");
testDynamicImport(applicationB, "b.B");
testDynamicImport(applicationB, "org.osgi.framework.Constants");
testDynamicImport(compositeB, "b.B");
testDynamicImport(compositeB, "org.osgi.framework.Constants");
testSharingPolicy(applicationE, "b", true);
testSharingPolicy(applicationE, "org.osgi.framework.Constants", true);
testSharingPolicy(applicationB, "b", true);
testSharingPolicy(applicationB, "org.osgi.framework.Constants", true);
testSharingPolicy(compositeB, "b", true);
testSharingPolicy(compositeB, "org.osgi.framework.Constants", true);
testSharingPolicy(getRootSubsystem(), "b", false);
testSharingPolicy(getRootSubsystem(), "org.osgi.framework.Constants", false);
uninstallSubsystemSilently(applicationE);
uninstallSubsystemSilently(featureB);
uninstallSubsystemSilently(applicationB);
}
finally {
uninstallSilently(bundleB);
}
}
finally {
uninstallSubsystemSilently(compositeB);
}
}
@Test
public void testWildcardEverythingInPackage() throws Exception {
registerWeavingHook("b.*");
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
Bundle bundleB = applicationA.getBundleContext().installBundle(
BUNDLE_B,
new ByteArrayInputStream(createBundleBContent()));
try {
Subsystem applicationB = getChild(applicationA, APPLICATION_B);
testSharingPolicy(applicationB, "b", false);
testSharingPolicy(applicationB, "b.a", false);
testSharingPolicy(applicationA, "b", false);
testSharingPolicy(applicationA, "b.a", false);
testSharingPolicy(getRootSubsystem(), "b", false);
testSharingPolicy(getRootSubsystem(), "b.a", false);
testDynamicImport(applicationB, "b.a.A");
testSharingPolicy(applicationB, "b", false);
testSharingPolicy(applicationB, "b.a", true);
testSharingPolicy(applicationA, "b", false);
testSharingPolicy(applicationA, "b.a", true);
testSharingPolicy(getRootSubsystem(), "b", false);
testSharingPolicy(getRootSubsystem(), "b.a", false);
}
finally {
uninstallSilently(bundleB);
}
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testWovenSubsystemContainsProvider() throws Exception {
registerWeavingHook("b");
Subsystem applicationE = installSubsystemFromFile(APPLICATION_E);
try {
assertConstituent(applicationE, BUNDLE_B);
testDynamicImport(applicationE, "b.B");
testSharingPolicy(applicationE, "b", false);
}
finally {
uninstallSubsystemSilently(applicationE);
}
}
@Test
public void testWovenSubsystemParentContainsProvider() throws Exception {
registerWeavingHook("b");
Subsystem compositeE = installSubsystemFromFile(COMPOSITE_E);
try {
assertNotConstituent(getRootSubsystem(), BUNDLE_B);
assertConstituent(compositeE, BUNDLE_B);
Subsystem applicationB = getChild(compositeE, APPLICATION_B);
assertNotConstituent(applicationB, BUNDLE_B);
testDynamicImport(applicationB, "b.B");
testSharingPolicy(compositeE, "b", false);
testSharingPolicy(applicationB, "b", true);
}
finally {
uninstallSubsystemSilently(compositeE);
}
}
@Test
public void testWovenSubsystemParentPolicyAllowsProvider() throws Exception {
registerWeavingHook("b");
Subsystem root = getRootSubsystem();
BundleContext context = root.getBundleContext();
Bundle bundleB = context.installBundle(BUNDLE_B, new ByteArrayInputStream(createBundleBContent()));
try {
Subsystem applicationB1 = installSubsystemFromFile(root, new File(APPLICATION_B), APPLICATION_B + "1");
try {
Subsystem compositeF = installSubsystemFromFile(applicationB1, COMPOSITE_F);
try {
assertPackageFiltersInParentConnection(compositeF, applicationB1, 2, 1);
Subsystem applicationB2 = installSubsystemFromFile(compositeF, new File(APPLICATION_B), APPLICATION_B + "2");
try {
testDynamicImport(applicationB2, "b.B");
testSharingPolicy(applicationB2, "b", true);
testSharingPolicy(compositeF, "b", true);
assertPackageFiltersInParentConnection(compositeF, applicationB1, 2, 1);
testSharingPolicy(applicationB1, "b", true);
testSharingPolicy(root, "b", false);
}
finally {
uninstallSubsystemSilently(applicationB2);
}
}
finally {
uninstallSubsystemSilently(compositeF);
}
}
finally {
uninstallSubsystemSilently(applicationB1);
}
}
finally {
uninstallSilently(bundleB);
}
}
private void assertPackageFiltersInParentConnection(Subsystem subsystem, Subsystem parent, int expectedEdges, int expectedFilters) {
Region parentRegion = getRegion(parent);
Region region = getRegion(subsystem);
Set<FilteredRegion> edges = region.getEdges();
assertEquals("Wrong number of edges", expectedEdges, edges.size());
for (FilteredRegion edge : region.getEdges()) {
if (!edge.getRegion().equals(parentRegion)) {
continue;
}
RegionFilter filter = edge.getFilter();
Map<String, Collection<String>> policy = filter.getSharingPolicy();
Collection<String> packages = policy.get(PackageNamespace.PACKAGE_NAMESPACE);
assertNotNull("Wrong number of packages", packages);
assertEquals("Wrong number of packages", expectedFilters, packages.size());
return;
}
fail("No connection to parent found");
}
private void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, APPLICATION_B);
}
private void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B);
}
private void createApplicationBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(APPLICATION_B + ".mf", attributes);
}
private void createApplicationC() throws IOException {
createApplicationCManifest();
createSubsystem(APPLICATION_C, COMPOSITE_B);
}
private void createApplicationCManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_C);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, COMPOSITE_B + ";type=osgi.subsystem.composite");
createManifest(APPLICATION_C + ".mf", attributes);
}
private void createApplicationD() throws IOException {
createApplicationDManifest();
createSubsystem(APPLICATION_D, FEATURE_B);
}
private void createApplicationDManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_D);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, FEATURE_B + ";type=osgi.subsystem.feature");
createManifest(APPLICATION_D + ".mf", attributes);
}
private void createApplicationE() throws IOException {
createApplicationEManifest();
createSubsystem(APPLICATION_E);
}
private void createApplicationEManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_E);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A + ',' + BUNDLE_B);
createManifest(APPLICATION_E + ".mf", attributes);
}
private byte[] createBundleAContent() throws Exception {
InputStream is = TinyBundles
.bundle()
.add(getClass().getClassLoader().loadClass("a.A"), InnerClassStrategy.NONE)
.set(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_A)
.build(TinyBundles.withBnd());
return createBundleContent(is);
}
private Resource createBundleAResource() throws Exception {
return new TestRepositoryContent.Builder()
.capability(
new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(IdentityNamespace.IDENTITY_NAMESPACE, BUNDLE_A)
.attribute(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, IdentityNamespace.TYPE_BUNDLE)
.attribute(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE, Version.emptyVersion))
.content(createBundleAContent())
.build();
}
private byte[] createBundleBContent() throws Exception {
InputStream is = TinyBundles
.bundle()
.add(getClass().getClassLoader().loadClass("b.B"), InnerClassStrategy.NONE)
.add(getClass().getClassLoader().loadClass("b.a.A"), InnerClassStrategy.NONE)
.set(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_B)
.set(Constants.EXPORT_PACKAGE, "b,b.a")
.build(TinyBundles.withBnd());
return createBundleContent(is);
}
private byte[] createBundleContent(InputStream is) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int length;
while ((length = is.read(bytes)) != -1) {
baos.write(bytes, 0, length);
}
is.close();
baos.close();
return baos.toByteArray();
}
private Resource createBundleBResource() throws Exception {
return new TestRepositoryContent.Builder()
.capability(
new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(IdentityNamespace.IDENTITY_NAMESPACE, BUNDLE_B)
.attribute(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, IdentityNamespace.TYPE_BUNDLE)
.attribute(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE, Version.emptyVersion))
.capability(
new TestCapability.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.attribute(PackageNamespace.PACKAGE_NAMESPACE, "b")
.attribute(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE, Version.emptyVersion))
.capability(
new TestCapability.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.attribute(PackageNamespace.PACKAGE_NAMESPACE, "b.a")
.attribute(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE, Version.emptyVersion))
.content(createBundleBContent())
.build();
}
private void createCompositeA() throws IOException {
createCompositeAManifest();
createSubsystem(COMPOSITE_A, APPLICATION_B);
}
private void createCompositeAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, APPLICATION_B +
";type=osgi.subsystem.application;version=\"[0,0]\"");
createManifest(COMPOSITE_A + ".mf", attributes);
}
private void createCompositeB() throws IOException {
createCompositeBManifest();
createSubsystem(COMPOSITE_B);
}
private void createCompositeBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_B);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A + ";version=\"[0,0]\"");
createManifest(COMPOSITE_B + ".mf", attributes);
}
private void createCompositeC() throws IOException {
createCompositeCManifest();
createSubsystem(COMPOSITE_C, COMPOSITE_B);
}
private void createCompositeCManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_C);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, COMPOSITE_B + ";type=osgi.subsystem.composite;version=\"[0,0]\"");
createManifest(COMPOSITE_C + ".mf", attributes);
}
private void createCompositeD() throws IOException {
createCompositeDManifest();
createSubsystem(COMPOSITE_D, FEATURE_B);
}
private void createCompositeDManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_D);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, FEATURE_B + ";type=osgi.subsystem.feature;version=\"[0,0]\"");
createManifest(COMPOSITE_D + ".mf", attributes);
}
private void createCompositeE() throws IOException {
createCompositeEManifest();
createSubsystem(COMPOSITE_E, APPLICATION_B);
}
private void createCompositeEManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_E);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, APPLICATION_B +
";type=osgi.subsystem.application;version=\"[0,0]\"," +
BUNDLE_B + ";version=\"[0,0]\"");
attributes.put(Constants.EXPORT_PACKAGE, "b");
createManifest(COMPOSITE_E + ".mf", attributes);
}
private void createCompositeF() throws IOException {
createCompositeFManifest();
createSubsystem(COMPOSITE_F);
}
private void createCompositeFManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_F);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(Constants.IMPORT_PACKAGE, "b;resolution:=optional");
createManifest(COMPOSITE_F + ".mf", attributes);
}
private void createFeatureA() throws IOException {
createFeatureAManifest();
createSubsystem(FEATURE_A, APPLICATION_B);
}
private void createFeatureAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
createManifest(FEATURE_A + ".mf", attributes);
}
private void createFeatureB() throws IOException {
createFeatureBManifest();
createSubsystem(FEATURE_B);
}
private void createFeatureBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_B);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(FEATURE_B + ".mf", attributes);
}
private void createFeatureC() throws IOException {
createFeatureCManifest();
createSubsystem(FEATURE_C, COMPOSITE_B);
}
private void createFeatureCManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_C);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
createManifest(FEATURE_C + ".mf", attributes);
}
private void createFeatureD() throws IOException {
createFeatureDManifest();
createSubsystem(FEATURE_D, FEATURE_B);
}
private void createFeatureDManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_D);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
createManifest(FEATURE_D + ".mf", attributes);
}
private Repository createTestRepository() throws Exception {
return new TestRepository.Builder()
.resource(createBundleAResource())
.resource(createBundleBResource())
.build();
}
private void registerWeavingHook(final String...dynamicImport) {
serviceRegistrations.add(bundleContext.registerService(
WeavingHook.class,
new WeavingHook() {
@Override
public void weave(WovenClass wovenClass) {
Bundle bundle = wovenClass.getBundleWiring().getBundle();
String symbolicName = bundle.getSymbolicName();
if (BUNDLE_A.equals(symbolicName)) {
weavingHookCalled.set(true);
List<String> dynamicImports = wovenClass.getDynamicImports();
dynamicImports.addAll(Arrays.asList(dynamicImport));
}
}
},
null));
}
private void testDynamicImport(String child, String type, String parent) throws Exception {
testDynamicImport(child, type, parent, "org.osgi.framework");
}
private void testDynamicImport(String child, String type, String parent, String dynamicImport) throws Exception {
registerWeavingHook(dynamicImport);
Subsystem p = installSubsystemFromFile(parent == null ? child : parent);
try {
if (parent != null) {
assertChild(p, child, null, type);
final Subsystem s = getConstituentAsSubsystem(p, child, null, type);
testDynamicImport(s);
}
else {
testDynamicImport(p);
}
}
finally {
uninstallSubsystemSilently(p);
}
}
private void testDynamicImport(Subsystem subsystem) throws Exception {
testDynamicImport(subsystem, "org.osgi.framework.Constants");
}
private void testDynamicImport(Subsystem subsystem, String clazz) throws Exception {
assertConstituent(subsystem, BUNDLE_A);
Bundle bundleA = getConstituentAsBundle(subsystem, BUNDLE_A, null, null);
bundleA.loadClass("a.A");
assertTrue("Weaving hook not called", weavingHookCalled.get());
try {
bundleA.loadClass(clazz);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
fail("Dynamic import not visible");
}
}
private void testSharingPolicy(Subsystem subsystem, String dynamicImport, boolean allowed) {
Region region = getRegion(subsystem);
Set<FilteredRegion> filteredRegions = region.getEdges();
Map<String, Object> map = new HashMap<String, Object>();
map.put(PackageNamespace.PACKAGE_NAMESPACE, dynamicImport);
map.put(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE, Version.emptyVersion);
boolean wasAllowed = false;
for (FilteredRegion filteredRegion : filteredRegions) {
RegionFilter filter = filteredRegion.getFilter();
if (allowed) {
if (filter.isAllowed(PackageNamespace.PACKAGE_NAMESPACE, map)) {
wasAllowed = true;
break;
}
}
else {
assertFalse("Sharing policy should not have been updated",
filter.isAllowed(PackageNamespace.PACKAGE_NAMESPACE, map));
}
}
if (allowed && !wasAllowed) {
fail("Sharing policy should have been updated");
}
}
@Test
public void testConnectedNonSubsystemRegions() throws Exception {
registerWeavingHook("b");
Bundle bundleB = getRootSubsystem().getBundleContext().installBundle(
BUNDLE_B, new ByteArrayInputStream(createBundleBContent()));
uninstallableBundles.add(bundleB);
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
uninstallableSubsystems.add(applicationA);
Subsystem applicationB = getChild(applicationA, APPLICATION_B);
uninstallSubsystem(applicationB);
removeConnectionWithParent(applicationA);
Region region = getRegion(applicationA);
RegionDigraph digraph = region.getRegionDigraph();
Region r1 = digraph.createRegion("R1");
deletableRegions.add(r1);
region.connectRegion(r1, digraph.createRegionFilterBuilder().allow("y", "(y=x)").build());
Region r2a = digraph.createRegion("R2A");
deletableRegions.add(r2a);
Bundle bundleB1 = r2a.installBundleAtLocation(BUNDLE_B + '1', new ByteArrayInputStream(createBundleBContent()));
uninstallableBundles.add(bundleB1);
Region r2b = digraph.createRegion("R2B");
deletableRegions.add(r2b);
r2b.connectRegion(r2a, digraph.createRegionFilterBuilder().allow("osgi.wiring.package", "(&(osgi.wiring.package=b)(version=0))").build());
region.connectRegion(r2b, digraph.createRegionFilterBuilder().allow("osgi.wiring.package", "(&(osgi.wiring.package=b)(version=0))").build());
applicationB = installSubsystemFromFile(applicationA, APPLICATION_B);
uninstallableSubsystems.add(applicationB);
try {
testDynamicImport(applicationB, "b.B");
}
catch (AssertionError e) {
fail("Dynamic import should have succeeded");
}
testSharingPolicy(applicationB, "b", true);
testSharingPolicy(applicationA, "b", true);
testSharingPolicy(getRootSubsystem(), "b", false);
}
}
| 8,752 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1417Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Map;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.namespace.implementation.ImplementationNamespace;
import org.osgi.namespace.service.ServiceNamespace;
import org.osgi.resource.Capability;
public class Aries1417Test extends SubsystemTest {
@Test
public void testOsgiImplementation() throws Exception {
Bundle bundle = getSubsystemCoreBundle();
BundleRevision revision = bundle.adapt(BundleRevision.class);
List<Capability> capabilities = revision.getCapabilities(ImplementationNamespace.IMPLEMENTATION_NAMESPACE);
assertEquals("Wrong capabilities", 1, capabilities.size());
Capability capability = capabilities.get(0);
Map<String, Object> attributes = capability.getAttributes();
assertEquals("Wrong namespace value", "osgi.subsystem", attributes.get(ImplementationNamespace.IMPLEMENTATION_NAMESPACE));
Object version = attributes.get(ImplementationNamespace.CAPABILITY_VERSION_ATTRIBUTE);
assertTrue("Wrong version type", version instanceof Version);
assertEquals("Wrong version", Version.parseVersion("1.1"), version);
assertEquals("Wrong uses", "org.osgi.service.subsystem", capability.getDirectives().get(ImplementationNamespace.CAPABILITY_USES_DIRECTIVE));
}
@Test
public void testOsgiService() throws Exception {
Bundle bundle = getSubsystemCoreBundle();
BundleRevision revision = bundle.adapt(BundleRevision.class);
List<Capability> capabilities = revision.getCapabilities(ServiceNamespace.SERVICE_NAMESPACE);
assertEquals("Wrong capabilities", 1, capabilities.size());
Capability capability = capabilities.get(0);
Map<String, Object> attributes = capability.getAttributes();
Object objectClass = attributes.get(ServiceNamespace.CAPABILITY_OBJECTCLASS_ATTRIBUTE);
assertTrue("Wrong objectClass type", objectClass instanceof List);
@SuppressWarnings({ "rawtypes" })
List objectClassList = (List)objectClass;
assertEquals("Wrong objectClass size", 2, objectClassList.size());
Object objectClass1 = objectClassList.get(0);
assertTrue("Wrong objectClass type", objectClass1 instanceof String);
assertEquals("Wrong objectClass", "org.osgi.service.subsystem.Subsystem", objectClass1);
Object objectClass2 = objectClassList.get(1);
assertTrue("Wrong objectClass type", objectClass2 instanceof String);
assertEquals("Wrong objectClass", "org.apache.aries.subsystem.AriesSubsystem", objectClass2);
assertEquals("Wrong uses", "org.osgi.service.subsystem,org.apache.aries.subsystem", capability.getDirectives().get(ServiceNamespace.CAPABILITY_USES_DIRECTIVE));
}
}
| 8,753 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1416Test.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.subsystem.itests.defect;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.itests.Header;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
/*
* https://issues.apache.org/jira/browse/ARIES-1416
*
* BundleException "bundle is already installed" when the Preferred-Provider
* subsystem header points to a bundle.
*/
public class Aries1416Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
* Preferred-Provider: bundle.b.jar;type=osgi.bundle
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: feature.a.esa
* Subsystem-Content: application.a.esa
*/
private static final String FEATURE_A = "feature.a.esa";
/*
* Subsystem-SymbolicName: feature.b.esa
* Subsystem-Content: application.a.esa
*/
private static final String FEATURE_B = "feature.b.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Require-Capability: b
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Provide-Capability: b
*/
private static final String BUNDLE_B = "bundle.b.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createBundleB();
createApplicationA();
createFeatureA();
createFeatureB();
createdTestFiles = true;
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), new Header(Constants.REQUIRE_CAPABILITY, "b"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), new Header(Constants.PROVIDE_CAPABILITY, "b"));
}
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A, BUNDLE_B);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
attributes.put(SubsystemConstants.PREFERRED_PROVIDER, BUNDLE_B + ";type=osgi.bundle");
createManifest(APPLICATION_A + ".mf", attributes);
}
private static void createFeatureA() throws IOException {
createFeatureAManifest();
createSubsystem(FEATURE_A, BUNDLE_B, APPLICATION_A);
}
private static void createFeatureAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_B + ',' +
APPLICATION_A + ";type=osgi.subsystem.application");
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
createManifest(FEATURE_A + ".mf", attributes);
}
private static void createFeatureB() throws IOException {
createFeatureBManifest();
createSubsystem(FEATURE_B, BUNDLE_B, APPLICATION_A);
}
private static void createFeatureBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_B);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_B + ',' +
APPLICATION_A + ";type=osgi.subsystem.application");
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
createManifest(FEATURE_B + ".mf", attributes);
}
@Test
public void testSystemRepositoryBundlePreferredProvider() throws Exception {
Subsystem root = getRootSubsystem();
// Install bundle B providing capability b into the root subsystem's
// region.
Bundle bundleB = installBundleFromFile(BUNDLE_B, root);
try {
// Install application A containing content bundle A requiring
// capability b and dependency bundle B providing capability b.
// Bundle B is not content but will become part of the local
// repository. The preferred provider is bundle B. Bundle B from the
// system repository should be used. Bundle B from the local
// repository should not be provisioned.
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
uninstallSubsystemSilently(applicationA);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
finally {
uninstallSilently(bundleB);
}
}
@Test
public void testSharedContentBundlePreferredProvider() throws Exception {
// Install feature A containing bundle B and application A both in the
// archive and as content into the root subsystem region. Bundle B
// provides capability b. Application A contains bundle A requiring
// capability b both in the archive and as content. Preferred provider
// bundle B is also included in the archive but not as content.
Subsystem featureA = installSubsystemFromFile(FEATURE_A);
try {
// Install feature B having the same characteristics as feature A
// described above into the root subsystem region. Bundle B will
// become shared content of features A and B. Shared content bundle
// B from the system repository should be used as the preferred
// provider. Bundle B from the local repository should not be
// provisioned.
Subsystem featureB = installSubsystemFromFile(FEATURE_B);
uninstallSubsystemSilently(featureB);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
finally {
uninstallSubsystemSilently(featureA);
}
}
}
| 8,754 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1429Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.aries.subsystem.AriesSubsystem;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.TestRequirement;
import org.junit.Before;
import org.junit.Test;
import org.ops4j.pax.tinybundles.core.InnerClassStrategy;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.hooks.weaving.WeavingHook;
import org.osgi.framework.hooks.weaving.WovenClass;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.resource.Requirement;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
/*
* https://issues.apache.org/jira/browse/ARIES-1429
*
* NullPointerException at org.apache.aries.subsystem.core.internal.WovenClassListener.modified
* at org.apache.aries.subsystem.core.internal.RegionUpdater.addRequirements.
*/
public class Aries1429Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
*/
private static final String BUNDLE_A = "bundle.a.jar";
private static boolean createdTestFiles;
private void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A);
}
private void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createApplicationA();
createdTestFiles = true;
}
@Test
public void testMissingParentChildEdgeTolerated() throws Exception {
final AtomicBoolean weavingHookCalled = new AtomicBoolean();
final AtomicReference<FrameworkEvent> frameworkEvent = new AtomicReference<FrameworkEvent>();
bundleContext.registerService(
WeavingHook.class,
new WeavingHook() {
@Override
public void weave(WovenClass wovenClass) {
Bundle bundle = wovenClass.getBundleWiring().getBundle();
if (BUNDLE_A.equals(bundle.getSymbolicName())) {
wovenClass.getDynamicImports().add("com.acme.tnt");
weavingHookCalled.set(true);
}
}
},
null);
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
removeConnectionWithParent(applicationA);
BundleContext context = applicationA.getBundleContext();
Bundle bundleA = context.installBundle(
BUNDLE_A,
TinyBundles
.bundle()
.add(getClass().getClassLoader().loadClass("a.A"), InnerClassStrategy.NONE)
.set(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_A)
.build(TinyBundles.withBnd()));
bundleContext.addFrameworkListener(
new FrameworkListener() {
@Override
public void frameworkEvent(FrameworkEvent event) {
if (FrameworkEvent.ERROR == event.getType()
&& getSubsystemCoreBundle().equals(event.getBundle())) {
frameworkEvent.set(event);
if (event.getThrowable() != null) {
event.getThrowable().printStackTrace();
}
}
}
});
bundleA.loadClass("a.A");
assertTrue("Weaving hook not called", weavingHookCalled.get());
Thread.sleep(1000);
assertNull("An exception was thrown", frameworkEvent.get());
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testMissingParentChildEdgeNotTolerated() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
removeConnectionWithParent(applicationA);
try {
((AriesSubsystem)applicationA).addRequirements(
Collections.singletonList(
(Requirement) new TestRequirement.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.attribute(PackageNamespace.PACKAGE_NAMESPACE, "org.osgi.framework")
.build()));
fail("No exception received");
}
catch (SubsystemException e) {
Throwable cause = e.getCause();
assertNotNull("Wrong cause", cause);
assertEquals("Wrong cause", IllegalStateException.class, cause.getClass());
}
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
}
| 8,755 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1428Test.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.subsystem.itests.defect;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
/*
* https://issues.apache.org/jira/browse/ARIES-1428
*
* org.osgi.framework.BundleException: Could not resolve module: <module> Bundle
* was filtered by a resolver hook.
*/
public class Aries1428Test extends SubsystemTest {
/*
* Bundle-SymbolicName: bundle.a.jar
*/
private static final String BUNDLE_A = "bundle.a.jar";
private void createBundleA() throws IOException {
createBundle(
name(BUNDLE_A));
}
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createdTestFiles = true;
}
@Test
public void testBundleNotPartOfSubsystemInstallationResolves() throws Exception {
final Bundle core = getSubsystemCoreBundle();
core.stop();
bundleContext.addServiceListener(
new ServiceListener() {
@Override
public void serviceChanged(ServiceEvent event) {
if (event.getType() == ServiceEvent.REGISTERED) {
File file = new File(BUNDLE_A);
try {
Bundle bundleA = bundleContext.installBundle(
file.toURI().toString(), new FileInputStream(file));
bundleA.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
},
"(objectClass=org.osgi.service.subsystem.Subsystem)"
);
core.start();
assertBundleState(Bundle.RESOLVED | Bundle.ACTIVE, BUNDLE_A, getRootSubsystem());
}
}
| 8,756 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1383Test.java | package org.apache.aries.subsystem.itests.defect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.apache.aries.subsystem.AriesSubsystem;
import org.apache.aries.subsystem.core.archive.AriesProvisionDependenciesDirective;
import org.apache.aries.subsystem.core.archive.SubsystemTypeHeader;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.BundleArchiveBuilder;
import org.apache.aries.subsystem.itests.util.SubsystemArchiveBuilder;
import org.apache.aries.subsystem.itests.util.TestCapability;
import org.apache.aries.subsystem.itests.util.TestRepository;
import org.apache.aries.subsystem.itests.util.TestRepositoryContent;
import org.apache.aries.subsystem.itests.util.TestRequirement;
import org.easymock.internal.matchers.Null;
import org.junit.Test;
import org.ops4j.pax.tinybundles.core.InnerClassStrategy;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.Version;
import org.osgi.framework.hooks.resolver.ResolverHook;
import org.osgi.framework.hooks.resolver.ResolverHookFactory;
import org.osgi.framework.namespace.BundleNamespace;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.service.repository.Repository;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
/*
* https://issues.apache.org/jira/browse/ARIES-1383
*
* Provide option to disable the provisioning of dependencies at install time.
*
* For tests containing a numerical value in the name, see the description of
* ARIES-1383 for an explanation.
*/
public class Aries1383Test extends SubsystemTest {
private static final String SYMBOLICNAME_PREFIX = Aries1383Test.class.getSimpleName() + '.';
private static final String APPLICATION_A = SYMBOLICNAME_PREFIX + "application.a";
private static final String APPLICATION_B = SYMBOLICNAME_PREFIX + "application.b";
private static final String APPLICATION_DEPENDENCY_IN_ARCHIVE = SYMBOLICNAME_PREFIX + "application.dependency.in.archive";
private static final String APPLICATION_EMPTY = SYMBOLICNAME_PREFIX + "application.empty";
private static final String APPLICATION_INSTALL_FAILED = SYMBOLICNAME_PREFIX + "application.install.failed";
private static final String APPLICATION_INVALID_PROVISION_DEPENDENCIES = SYMBOLICNAME_PREFIX + "application.invalid.provision.dependency";
private static final String APPLICATION_MISSING_DEPENDENCY = SYMBOLICNAME_PREFIX + "application.missing.dependency";
private static final String APPLICATION_PROVISION_DEPENDENCIES_INSTALL = SYMBOLICNAME_PREFIX + "application.provision.dependencies.install";
private static final String APPLICATION_START_FAILURE = SYMBOLICNAME_PREFIX + "application.start.failure";
private static final String BUNDLE_A = SYMBOLICNAME_PREFIX + "bundle.a";
private static final String BUNDLE_B = SYMBOLICNAME_PREFIX + "bundle.b";
private static final String BUNDLE_C = SYMBOLICNAME_PREFIX + "bundle.c";
private static final String BUNDLE_D = SYMBOLICNAME_PREFIX + "bundle.d";
private static final String BUNDLE_INVALID_MANIFEST = SYMBOLICNAME_PREFIX + "bundle.invalid.manifest";
private static final String BUNDLE_START_FAILURE = SYMBOLICNAME_PREFIX + "bundle.start.failure";
private static final String ESA_EXTENSION = ".esa";
private static final String FEATURE_PROVISION_DEPENDENCIES_INSTALL = "feature.provision.dependencies.install";
private static final String FEATURE_PROVISION_DEPENDENCIES_RESOLVE = "feature.provision.dependencies.resolve";
private static final String JAR_EXTENSION = ".jar";
private static final String MANIFEST_VERSION = "1.0";
private static final String PACKAGE_A = SYMBOLICNAME_PREFIX + "a";
private static final String PACKAGE_B = SYMBOLICNAME_PREFIX + "b";
private static final String PACKAGE_C = SYMBOLICNAME_PREFIX + "c";
private static final String PACKAGE_D = SYMBOLICNAME_PREFIX + "d";
private static final String SUBSYSTEM_MANIFEST_FILE = "OSGI-INF/SUBSYSTEM.MF";
/*
* (1) A set of subsystems with interleaving content dependencies are able
* to be independently, simultaneously, and successfully installed and
* started.
*/
@Test
public void test1() throws Exception {
Subsystem root = getRootSubsystem();
final Subsystem c1 = installSubsystem(
root,
"c1",
new SubsystemArchiveBuilder()
.symbolicName("c1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE + ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.build(),
false
);
uninstallableSubsystems.add(c1);
c1.start();
stoppableSubsystems.add(c1);
@SuppressWarnings("unchecked")
Callable<Subsystem>[] installCallables = new Callable[] {
new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem result = installSubsystem(
c1,
"a1",
new SubsystemArchiveBuilder()
.symbolicName("a1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("b1")
.bundle(
"b1",
new BundleArchiveBuilder()
.symbolicName("b1")
.importPackage("b2")
.build())
.build(),
false);
uninstallableSubsystems.add(result);
return result;
}
},
new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem result = installSubsystem(
c1,
"f1",
new SubsystemArchiveBuilder()
.symbolicName("f1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE + ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("b2")
.bundle(
"b2",
new BundleArchiveBuilder()
.symbolicName("b2")
.exportPackage("b2")
.importPackage("b3")
.build())
.build(),
false);
uninstallableSubsystems.add(result);
return result;
}
},
new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem result = installSubsystem(
c1,
"f2",
new SubsystemArchiveBuilder()
.symbolicName("f2")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE + ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("b4")
.bundle(
"b4",
new BundleArchiveBuilder()
.symbolicName("b4")
.exportPackage("b4")
.importPackage("b2")
.importPackage("b3")
.build())
.build(),
false);
uninstallableSubsystems.add(result);
return result;
}
},
new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem result = installSubsystem(
c1,
"c2",
new SubsystemArchiveBuilder()
.symbolicName("c2")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE + ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("b3;version=\"[0,0]\"")
.exportPackage("b3")
.importPackage("b4")
.bundle(
"b3",
new BundleArchiveBuilder()
.symbolicName("b3")
.exportPackage("b3")
.importPackage("b4")
.build())
.build(),
false);
uninstallableSubsystems.add(result);
return result;
}
}
};
ExecutorService executor = Executors.newFixedThreadPool(4);
List<Future<Subsystem>> installFutures = executor.invokeAll(Arrays.asList(installCallables));
final Subsystem a1 = installFutures.get(0).get();
assertConstituent(a1, "b1");
final Subsystem f1 = installFutures.get(1).get();
assertConstituent(f1, "b2");
final Subsystem f2 = installFutures.get(2).get();
assertConstituent(f2, "b4");
final Subsystem c2 = installFutures.get(3).get();
assertConstituent(c2, "b3");
@SuppressWarnings("unchecked")
Callable<Null>[] startCallables = new Callable[] {
new Callable<Null>() {
@Override
public Null call() throws Exception {
a1.start();
assertEvent(a1, State.INSTALLED, subsystemEvents.poll(a1.getSubsystemId(), 5000));
assertEvent(a1, State.RESOLVING, subsystemEvents.poll(a1.getSubsystemId(), 5000));
assertEvent(a1, State.RESOLVED, subsystemEvents.poll(a1.getSubsystemId(), 5000));
stoppableSubsystems.add(a1);
return null;
}
},
new Callable<Null>() {
@Override
public Null call() throws Exception {
f1.start();
assertEvent(f1, State.INSTALLED, subsystemEvents.poll(f1.getSubsystemId(), 5000));
assertEvent(f1, State.RESOLVING, subsystemEvents.poll(f1.getSubsystemId(), 5000));
assertEvent(f1, State.RESOLVED, subsystemEvents.poll(f1.getSubsystemId(), 5000));
stoppableSubsystems.add(f1);
return null;
}
},
new Callable<Null>() {
@Override
public Null call() throws Exception {
f2.start();
assertEvent(f2, State.INSTALLED, subsystemEvents.poll(f2.getSubsystemId(), 5000));
assertEvent(f2, State.RESOLVING, subsystemEvents.poll(f2.getSubsystemId(), 5000));
assertEvent(f2, State.RESOLVED, subsystemEvents.poll(f2.getSubsystemId(), 5000));
stoppableSubsystems.add(f2);
return null;
}
},
new Callable<Null>() {
@Override
public Null call() throws Exception {
c2.start();
assertEvent(c2, State.INSTALLED, subsystemEvents.poll(c2.getSubsystemId(), 5000));
assertEvent(c2, State.RESOLVING, subsystemEvents.poll(c2.getSubsystemId(), 5000));
assertEvent(c2, State.RESOLVED, subsystemEvents.poll(c2.getSubsystemId(), 5000));
stoppableSubsystems.add(c2);
return null;
}
}
};
List<Future<Null>> startFutures = executor.invokeAll(Arrays.asList(startCallables));
startFutures.get(0).get();
startFutures.get(1).get();
startFutures.get(2).get();
startFutures.get(3).get();
}
/*
* (2) Subsystem with apache-aries-provision-dependencies:=resolve is in the
* INSTALLING state after a successful installation.
*/
@Test
public void test2() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystem(root, APPLICATION_EMPTY, applicationEmpty(), false);
try {
assertState(State.INSTALLING, subsystem);
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
/*
* (3) Subsystem with apache-aries-provision-dependencies:=resolve is available
* as a service after a successful installation.
*/
@Test
public void test3() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystem(root, APPLICATION_EMPTY, applicationEmpty(), false);
try {
assertReferences(
Subsystem.class,
"(&(subsystem.symbolicName="
+ APPLICATION_EMPTY
+ ")(subsystem.version=0.0.0)(subsystem.type="
+ SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION
+ ")(subsystem.state="
+ State.INSTALLING
+ "))",
1);
assertReferences(
AriesSubsystem.class,
"(&(subsystem.symbolicName="
+ APPLICATION_EMPTY
+ ")(subsystem.version=0.0.0)(subsystem.type="
+ SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION
+ ")(subsystem.state="
+ State.INSTALLING
+ "))",
1);
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
/*
* (4) Subsystem with apache-aries-provision-dependencies:=resolve does not
* have its dependencies installed after a successful installation.
*/
@Test
public void test4() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystem(root, APPLICATION_DEPENDENCY_IN_ARCHIVE, applicationDependencyInArchive(), false);
try {
assertConstituent(subsystem, BUNDLE_A);
assertNotConstituent(subsystem, BUNDLE_B);
assertNotConstituent(root, BUNDLE_B);
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
/*
* (5) Subsystem with apache-aries-provision-dependencies:=resolve undergoes
* the following state transitions when starting: INSTALLING -> INSTALLED
* -> RESOLVING -> RESOLVED -> STARTING -> ACTIVE.
*/
@Test
public void test5() throws Exception {
Subsystem root = getRootSubsystem();
subsystemEvents.clear();
Subsystem subsystem = root.install(
"application",
new SubsystemArchiveBuilder()
.header(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, "application")
.header(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.build()
);
try {
long id = subsystem.getSubsystemId();
assertEvent(subsystem, State.INSTALLING, subsystemEvents.poll(id, 5000));
assertNull(subsystemEvents.poll(id, 1));
subsystem.start();
try {
assertEvent(subsystem, State.INSTALLED, subsystemEvents.poll(id, 5000));
assertEvent(subsystem, State.RESOLVING, subsystemEvents.poll(id, 5000));
assertEvent(subsystem, State.RESOLVED, subsystemEvents.poll(id, 5000));
assertEvent(subsystem, State.STARTING, subsystemEvents.poll(id, 5000));
assertEvent(subsystem, State.ACTIVE, subsystemEvents.poll(id, 5000));
assertNull(subsystemEvents.poll(id, 1));
}
finally {
stopSubsystemSilently(subsystem);
}
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
/*
* (6) Subsystem with apache-aries-provision-dependencies:=resolve has its
* dependencies installed after a successful start.
*/
@Test
public void test6() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = root.install(
"application",
new SubsystemArchiveBuilder()
.symbolicName("application")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("bundle1")
.bundle(
"bundle1",
new BundleArchiveBuilder()
.symbolicName("bundle1")
.exportPackage("a")
.importPackage("b")
.build())
.bundle(
"bundle2",
new BundleArchiveBuilder()
.symbolicName("bundle2")
.exportPackage("b")
.build())
.build()
);
try {
assertNotConstituent(root, "bundle2");
startSubsystem(subsystem, false);
try {
assertConstituent(root, "bundle2");
}
finally {
stopSubsystemSilently(subsystem);
}
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
/*
* (7) Subsystem with apache-aries-provision-dependencies:=resolve is in the
* INSTALL_FAILED state after an unsuccessful installation.
*/
@Test
public void test7() throws Exception {
Subsystem root = getRootSubsystem();
subsystemEvents.clear();
try {
Subsystem subsystem = root.install(APPLICATION_INSTALL_FAILED, applicationInstallFailed());
uninstallSubsystemSilently(subsystem);
fail("Subsystem should not have installed");
}
catch (SubsystemException e) {
e.printStackTrace();
long id = lastSubsystemId();
assertEvent(id, APPLICATION_INSTALL_FAILED, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLING, subsystemEvents.poll(id, 5000),
ServiceEvent.REGISTERED);
assertEvent(id, APPLICATION_INSTALL_FAILED, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALL_FAILED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_INSTALL_FAILED, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.UNINSTALLING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_INSTALL_FAILED, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.UNINSTALLED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
}
}
/*
* (8) Subsystem with apache-aries-provision-dependencies:=resolve is not
* available as a service after an unsuccessful installation.
*/
@Test
public void test8() throws Exception {
Subsystem root = getRootSubsystem();
try {
Subsystem subsystem = installSubsystem(root, APPLICATION_INSTALL_FAILED, applicationInstallFailed(), false);
uninstallSubsystemSilently(subsystem);
fail("Subsystem should not have installed");
}
catch (SubsystemException e) {
e.printStackTrace();
assertEquals("Subsystem service should not exist", 0,
bundleContext.getServiceReferences(
Subsystem.class,
"(" + SubsystemConstants.SUBSYSTEM_ID_PROPERTY + "=" + lastSubsystemId() + ")"
).size());
}
}
/*
* (9) Subsystem with apache-aries-provision-dependencies:=resolve is in the
* INSTALLING state when dependencies cannot be provisioned after invoking
* the start method.
*/
@Test
public void test9() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystem(root, APPLICATION_MISSING_DEPENDENCY, applicationMissingDependency(), false);
try {
startSubsystem(subsystem, false);
stopSubsystemSilently(subsystem);
fail("Subsystem should not have started");
}
catch (SubsystemException e) {
e.printStackTrace();
assertState(State.INSTALLING, subsystem);
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
/*
* (10) Subsystem fails installation if the apache-aries-provision-dependencies
* directive has a value other than "install" or "resolve".
*/
@Test
public void test10() throws Exception {
Subsystem root = getRootSubsystem();
try {
Subsystem subsystem = installSubsystem(
root,
APPLICATION_INVALID_PROVISION_DEPENDENCIES,
applicationInvalidProvisionDependencies(),
false);
uninstallSubsystemSilently(subsystem);
fail("Subsystem should not have installed");
}
catch (SubsystemException e) {
e.printStackTrace();
}
}
/*
* (11) Subsystem with apache-aries-provision-dependencies:=resolve undergoes
* the following state transitions when starting fails due to a runtime
* resolution failure: INSTALLING -> INSTALLED -> RESOLVING -> INSTALLED.
*/
@Test
public void test11() throws Exception {
Subsystem root = getRootSubsystem();
subsystemEvents.clear();
Subsystem subsystem = root.install(APPLICATION_DEPENDENCY_IN_ARCHIVE, applicationDependencyInArchive());
ServiceRegistration<ResolverHookFactory> registration = bundleContext.registerService(
ResolverHookFactory.class,
new ResolverHookFactory() {
@Override
public ResolverHook begin(Collection<BundleRevision> triggers) {
return new ResolverHook() {
@Override
public void filterResolvable(Collection<BundleRevision> candidates) {
for (Iterator<BundleRevision> i = candidates.iterator(); i.hasNext();) {
BundleRevision revision = i.next();
if (revision.getSymbolicName().equals(BUNDLE_B)) {
i.remove();
}
}
}
@Override
public void filterSingletonCollisions(
BundleCapability singleton,
Collection<BundleCapability> collisionCandidates) {
// Nothing.
}
@Override
public void filterMatches(
BundleRequirement requirement,
Collection<BundleCapability> candidates) {
// Nothing.
}
@Override
public void end() {
// Nothing.
}
};
}
},
null
);
try {
subsystem.start();
stopSubsystemSilently(subsystem);
fail("Subsystem should not have started");
}
catch (SubsystemException e) {
e.printStackTrace();
long id = lastSubsystemId();
assertEvent(id, APPLICATION_DEPENDENCY_IN_ARCHIVE, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLING, subsystemEvents.poll(id, 5000),
ServiceEvent.REGISTERED);
assertEvent(id, APPLICATION_DEPENDENCY_IN_ARCHIVE, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_DEPENDENCY_IN_ARCHIVE, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_DEPENDENCY_IN_ARCHIVE, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
}
finally {
registration.unregister();
uninstallSubsystemSilently(subsystem);
}
}
/*
* (12) Subsystem with apache-aries-provision-dependencies:=resolve undergoes
* the following state transitions when starting fails due to a start
* failure: INSTALLING -> INSTALLED -> RESOLVING -> RESOLVED -> STARTING ->
* RESOLVED.
*/
@Test
public void test12() throws Exception {
Subsystem root = getRootSubsystem();
subsystemEvents.clear();
Subsystem subsystem = root.install(APPLICATION_START_FAILURE, applicationStartFailure());
try {
subsystem.start();
stopSubsystemSilently(subsystem);
fail("Subsystem should not have started");
}
catch (SubsystemException e) {
e.printStackTrace();
long id = lastSubsystemId();
assertEvent(id, APPLICATION_START_FAILURE, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLING, subsystemEvents.poll(id, 5000),
ServiceEvent.REGISTERED);
assertEvent(id, APPLICATION_START_FAILURE, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_START_FAILURE, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_START_FAILURE, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_START_FAILURE, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.STARTING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_START_FAILURE, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
/*
* (13) The root subsystem has apache-aries-provision-dependencies:=install.
*/
@Test
public void test13() throws Exception {
Subsystem root = getRootSubsystem();
Map<String, String> headers = root.getSubsystemHeaders(null);
String headerStr = headers.get(SubsystemConstants.SUBSYSTEM_TYPE);
SubsystemTypeHeader header = new SubsystemTypeHeader(headerStr);
AriesProvisionDependenciesDirective directive = header.getAriesProvisionDependenciesDirective();
assertEquals(
"Wrong directive",
AriesProvisionDependenciesDirective.INSTALL,
directive);
}
/*
* (14) Subsystem with explicit apache-aries-provision-dependencies:=install
* works as before.
*/
@Test
public void test14() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystem(root, APPLICATION_PROVISION_DEPENDENCIES_INSTALL,
applicationProvisionDependenciesInstall(), true);
try {
assertConstituent(subsystem, BUNDLE_A);
assertConstituent(root, BUNDLE_B);
startSubsystem(subsystem, true);
stopSubsystem(subsystem);
}
finally {
uninstallSubsystem(subsystem);
}
}
/*
* (15) Unscoped subsystem with a value of apache-aries-provision-dependencies
* that is different than the scoped parent fails installation.
*/
@Test
public void test15a() throws Exception {
Subsystem root = getRootSubsystem();
try {
Subsystem subsystem = installSubsystem(root, FEATURE_PROVISION_DEPENDENCIES_RESOLVE,
featureProvisionDependenciesResolve(), false);
uninstallSubsystemSilently(subsystem);
fail("Subsystem should not have installed");
}
catch (SubsystemException e) {
e.printStackTrace();
}
}
/*
* (15) Unscoped subsystem with a value of apache-aries-provision-dependencies
* that is different than the scoped parent fails installation.
*/
@Test
public void test15b() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem application = installSubsystem(root, APPLICATION_PROVISION_DEPENDENCIES_INSTALL,
applicationProvisionDependenciesInstall(), true);
try {
Subsystem feature = installSubsystem(application, FEATURE_PROVISION_DEPENDENCIES_RESOLVE,
featureProvisionDependenciesResolve(), false);
uninstallSubsystemSilently(feature);
fail("Subsystem should not have installed");
}
catch (SubsystemException e) {
e.printStackTrace();
}
finally {
uninstallSubsystemSilently(application);
}
}
/*
* (16) Unscoped subsystem with a value of apache-aries-provision-dependencies
* that is the same as the scoped parent installs successfully.
*/
@Test
public void test16a() throws Exception {
Subsystem root = getRootSubsystem();
try {
Subsystem subsystem = installSubsystem(
root,
FEATURE_PROVISION_DEPENDENCIES_INSTALL,
new SubsystemArchiveBuilder()
.symbolicName("application")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ AriesProvisionDependenciesDirective.INSTALL.toString())
.build(),
true);
uninstallSubsystemSilently(subsystem);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
/*
* (16) Unscoped subsystem with a value of apache-aries-provision-dependencies
* that is the same as the scoped parent installs successfully.
*/
@Test
public void test16b() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem application = installSubsystem(
root,
"application",
new SubsystemArchiveBuilder()
.symbolicName("application")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ AriesProvisionDependenciesDirective.INSTALL.toString())
.build(),
true);
try {
Subsystem feature = installSubsystem(
application,
"feature",
new SubsystemArchiveBuilder()
.symbolicName("feature")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE + ';'
+ AriesProvisionDependenciesDirective.INSTALL.toString())
.build(),
true);
uninstallSubsystemSilently(feature);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
finally {
uninstallSubsystemSilently(application);
}
}
/*
* (16) Unscoped subsystem with a value of apache-aries-provision-dependencies
* that is the same as the scoped parent installs successfully.
*/
@Test
public void test16c() throws Exception {
Subsystem root = getRootSubsystem();
try {
Subsystem subsystem = installSubsystem(
root,
"application",
new SubsystemArchiveBuilder()
.symbolicName("application")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.subsystem(
"feature",
new SubsystemArchiveBuilder()
.symbolicName("feature")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE + ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.build())
.build(),
false);
uninstallSubsystemSilently(subsystem);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
/*
* (17) Scoped subsystem with a value of apache-aries-provision-dependencies
* that is the same as the scoped parent behaves accordingly.
*/
@Test
public void test17() throws Exception {
Subsystem root = getRootSubsystem();
subsystemEvents.clear();
Subsystem parent = root.install(APPLICATION_B, applicationB());
try {
long id = parent.getSubsystemId();
assertEvent(id, APPLICATION_B, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLING, subsystemEvents.poll(id, 5000),
ServiceEvent.REGISTERED);
assertNull("Unexpected event", subsystemEvents.poll(id, 1));
assertNotConstituent(root, BUNDLE_B);
assertConstituent(parent, BUNDLE_A);
Subsystem child = getChild(parent, APPLICATION_A);
assertNotNull("Missing child", child);
id = child.getSubsystemId();
assertEvent(id, APPLICATION_A, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLING, subsystemEvents.poll(id, 5000),
ServiceEvent.REGISTERED);
assertNull("Unexpected event", subsystemEvents.poll(id, 1));
assertNotConstituent(root, BUNDLE_D);
assertConstituent(child, BUNDLE_A);
assertConstituent(child, BUNDLE_C);
parent.start();
try {
id = parent.getSubsystemId();
assertEvent(id, APPLICATION_B, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_B, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_B, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_B, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.STARTING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_B, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.ACTIVE, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertNull("Unexpected event", subsystemEvents.poll(id, 1));
assertConstituent(root, BUNDLE_B);
id = child.getSubsystemId();
assertEvent(id, APPLICATION_A, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_A, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_A, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_A, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.STARTING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, APPLICATION_A, Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.ACTIVE, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertNull("Unexpected event", subsystemEvents.poll(id, 1));
assertConstituent(root, BUNDLE_D);
}
finally {
stopSubsystemSilently(parent);
}
}
finally {
uninstallSubsystemSilently(parent);
}
}
/*
* (18) Scoped subsystem with a value of apache-aries-provision-dependencies
* that overrides the scoped parent behaves accordingly.
*/
@Test
public void test18() throws Exception {
Subsystem root = getRootSubsystem();
subsystemEvents.clear();
Subsystem parent = root.install(
"parent",
new SubsystemArchiveBuilder()
.symbolicName("parent")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION
+ ';'
+ AriesProvisionDependenciesDirective.INSTALL.toString()
+ ';'
+ SubsystemConstants.PROVISION_POLICY_DIRECTIVE
+ ":="
+ SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES)
.content("bundle1")
.bundle(
"bundle1",
new BundleArchiveBuilder()
.symbolicName("bundle1")
.importPackage("a")
.build())
.bundle(
"bundle2",
new BundleArchiveBuilder()
.symbolicName("bundle2")
.exportPackage("a")
.build())
.build()
);
try {
long id = parent.getSubsystemId();
assertEvent(id, "parent", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLING, subsystemEvents.poll(id, 5000),
ServiceEvent.REGISTERED);
assertEvent(id, "parent", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertNull("Unexpected event", subsystemEvents.poll(id, 1));
assertConstituent(parent, "bundle2");
assertConstituent(parent, "bundle1");
parent.start();
Subsystem child = parent.install(
"child",
new SubsystemArchiveBuilder()
.symbolicName("child")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("bundle3")
.bundle(
"bundle3",
new BundleArchiveBuilder()
.symbolicName("bundle3")
.importPackage("b")
.build())
.bundle(
"bundle4",
new BundleArchiveBuilder()
.symbolicName("bundle4")
.exportPackage("b")
.build())
.build()
);
id = child.getSubsystemId();
assertEvent(id, "child", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLING, subsystemEvents.poll(id, 5000),
ServiceEvent.REGISTERED);
assertNull("Unexpected event", subsystemEvents.poll(id, 1));
assertNotConstituent(parent, "bundle4");
assertConstituent(child, "bundle3");
child.start();
try {
id = parent.getSubsystemId();
assertEvent(id, "parent", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, "parent", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, "parent", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.STARTING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, "parent", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.ACTIVE, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertNull("Unexpected event", subsystemEvents.poll(id, 1));
id = child.getSubsystemId();
assertEvent(id, "child", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.INSTALLED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, "child", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, "child", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.RESOLVED, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, "child", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.STARTING, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertEvent(id, "child", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION,
State.ACTIVE, subsystemEvents.poll(id, 5000),
ServiceEvent.MODIFIED);
assertNull("Unexpected event", subsystemEvents.poll(id, 1));
assertConstituent(parent, "bundle4");
}
finally {
stopSubsystemSilently(parent);
}
}
finally {
uninstallSubsystemSilently(parent);
}
}
/*
* (19) Scoped subsystem with only features as parents is able to override
* the value of apache-aries-provision-dependencies.
*/
@Test
public void test19() throws Exception {
Subsystem root = getRootSubsystem();
subsystemEvents.clear();
Subsystem feature1 = installSubsystem(
root,
"feature1",
new SubsystemArchiveBuilder()
.symbolicName("feature1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE)
.build()
);
try {
Subsystem feature2 = installSubsystem(
root,
"feature2",
new SubsystemArchiveBuilder()
.symbolicName("feature2")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE
+ ';'
+ AriesProvisionDependenciesDirective.INSTALL.toString())
.build()
);
try {
SubsystemArchiveBuilder applicationArchive = new SubsystemArchiveBuilder()
.symbolicName("application")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString()
+ ';'
+ SubsystemConstants.PROVISION_POLICY_DIRECTIVE
+ ":="
+ SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES)
.content("bundle1")
.bundle(
"bundle1",
new BundleArchiveBuilder()
.symbolicName("bundle1")
.importPackage("a")
.build())
.bundle(
"bundle2",
new BundleArchiveBuilder()
.symbolicName("bundle2")
.exportPackage("a")
.build());
Subsystem application1 = feature1.install("application", applicationArchive.build());
Subsystem application2 = feature2.install("application", applicationArchive.build());
assertSame("Wrong subsystem", application1, application2);
assertEquals("Wrong subsystem", application1, application2);
assertChild(feature1, "application");
assertChild(feature2, "application");
long id = application1.getSubsystemId();
assertEvent(id, "application", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, State.INSTALLING,
subsystemEvents.poll(id, 5000), ServiceEvent.REGISTERED);
assertNull("Unexpected event", subsystemEvents.poll(id, 1));
assertConstituent(application1, "bundle1");
assertNotConstituent(application1, "bundle2");
application1.start();
try {
assertEvent(id, "application", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, State.INSTALLED,
subsystemEvents.poll(id, 5000), ServiceEvent.MODIFIED);
assertEvent(id, "application", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, State.RESOLVING,
subsystemEvents.poll(id, 5000), ServiceEvent.MODIFIED);
assertEvent(id, "application", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, State.RESOLVED,
subsystemEvents.poll(id, 5000), ServiceEvent.MODIFIED);
assertEvent(id, "application", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, State.STARTING,
subsystemEvents.poll(id, 5000), ServiceEvent.MODIFIED);
assertEvent(id, "application", Version.emptyVersion,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, State.ACTIVE,
subsystemEvents.poll(id, 5000), ServiceEvent.MODIFIED);
assertNull("Unexpected event", subsystemEvents.poll(id, 1));
assertConstituent(application1, "bundle2");
}
finally {
stopSubsystemSilently(application1);
}
}
finally {
uninstallSubsystemSilently(feature2);
}
}
finally {
uninstallSubsystemSilently(feature1);
}
}
/*
* (20) Install a scoped subsystem, S1, with
* apache-aries-provision-dependencies:=resolve. Install two features, F1 and
* F2, independently as children of S1. F1 has bundle B1 as content. F2 has
* bundle B2 as content. B2 has B1 as a dependency. B1 should be a
* constituent of F1 but not of the root subsystem.
*/
@Test
public void test20() throws Exception {
serviceRegistrations.add(bundleContext.registerService(
Repository.class,
new TestRepository.Builder()
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"b1")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.content(new BundleArchiveBuilder()
.symbolicName("b1")
.exportPackage("a")
.buildAsBytes())
.build())
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"b2")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.content(new BundleArchiveBuilder()
.symbolicName("b2")
.importPackage("a")
.buildAsBytes())
.build())
.build(),
null));
Subsystem root = getRootSubsystem();
Subsystem s1 = installSubsystem(
root,
"s1",
new SubsystemArchiveBuilder()
.symbolicName("s1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.build(),
false
);
uninstallableSubsystems.add(s1);
startSubsystem(s1, false);
stoppableSubsystems.add(s1);
Subsystem f2 = installSubsystem(
s1,
"f2",
new SubsystemArchiveBuilder()
.symbolicName("f2")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE)
.content("b2")
.build(),
false
);
uninstallableSubsystems.add(f2);
assertChild(s1, "f2", null, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
assertConstituent(f2, "b2");
Subsystem f1 = installSubsystem(
s1,
"f1",
new SubsystemArchiveBuilder()
.symbolicName("f1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE)
.content("b1")
.build(),
false
);
uninstallableSubsystems.add(f1);
assertChild(s1, "f1", null, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
assertConstituent(f1, "b1");
assertNotConstituent(root, "b1");
}
/*
* (21) Install a scoped subsystem, S1, with
* apache-aries-provision-dependencies:=resolve. Install two features, F1 and
* F2, independently as children of S1. F1 has bundle B1 and B2 as content.
* F2 has bundle B2 and B3 as content. B2 is shared content. B1 has a
* dependency on bundle B4, B2 has a dependency on bundle B5. B3 has a
* dependency on bundle B6. Start F1. Dependency bundles B4 and B5 should be
* provisioned but not B6.
*/
@Test
public void test21() throws Exception {
serviceRegistrations.add(bundleContext.registerService(
Repository.class,
new TestRepository.Builder()
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"b1")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.requirement(new TestRequirement.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.directive(
PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE,
"(osgi.wiring.package=b4)"))
.content(new BundleArchiveBuilder()
.symbolicName("b1")
.importPackage("b4")
.buildAsBytes())
.build())
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"b2")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.requirement(new TestRequirement.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.directive(
PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE,
"(osgi.wiring.package=b5)"))
.content(new BundleArchiveBuilder()
.symbolicName("b2")
.importPackage("b5")
.buildAsBytes())
.build())
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"b3")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.requirement(new TestRequirement.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.directive(
PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE,
"(osgi.wiring.package=b6)"))
.content(new BundleArchiveBuilder()
.symbolicName("b3")
.importPackage("b6")
.buildAsBytes())
.build())
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"b4")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.capability(new TestCapability.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.attribute(
PackageNamespace.PACKAGE_NAMESPACE,
"b4"))
.content(new BundleArchiveBuilder()
.symbolicName("b4")
.exportPackage("b4")
.buildAsBytes())
.build())
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"b5")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.capability(new TestCapability.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.attribute(
PackageNamespace.PACKAGE_NAMESPACE,
"b5"))
.content(new BundleArchiveBuilder()
.symbolicName("b5")
.exportPackage("b5")
.buildAsBytes())
.build())
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"b6")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.capability(new TestCapability.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.attribute(
PackageNamespace.PACKAGE_NAMESPACE,
"b6"))
.content(new BundleArchiveBuilder()
.symbolicName("b6")
.exportPackage("b6")
.buildAsBytes())
.build())
.build(),
null));
Subsystem root = getRootSubsystem();
Subsystem s1 = installSubsystem(
root,
"s1",
new SubsystemArchiveBuilder()
.symbolicName("s1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString()
+ ';'
+ SubsystemConstants.PROVISION_POLICY_DIRECTIVE
+ ":="
+ SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES)
.build(),
false
);
uninstallableSubsystems.add(s1);
startSubsystem(s1, false);
stoppableSubsystems.add(s1);
Subsystem f2 = installSubsystem(
s1,
"f2",
new SubsystemArchiveBuilder()
.symbolicName("f2")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE)
.content("b2,b3")
.build(),
false
);
uninstallableSubsystems.add(f2);
assertChild(s1, "f2", null, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
assertConstituent(s1, "f2", null, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
assertConstituent(f2, "b2");
assertConstituent(f2, "b3");
Subsystem f1 = installSubsystem(
s1,
"f1",
new SubsystemArchiveBuilder()
.symbolicName("f1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE)
.content("b1,b2")
.build(),
false
);
uninstallableSubsystems.add(f1);
assertChild(s1, "f1", null, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
assertConstituent(s1, "f1", null, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
assertConstituent(f1, "b1");
assertConstituent(f1, "b2");
startSubsystem(f1, false);
stoppableSubsystems.add(f1);
assertState(EnumSet.of(State.RESOLVED, State.ACTIVE), f2);
assertConstituent(s1, "b4");
assertConstituent(s1, "b5");
assertConstituent(s1, "b6");
}
@Test
public void testFullLifeCycle() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystem(root, APPLICATION_EMPTY, applicationEmpty(), false);
startSubsystem(subsystem, false);
stopSubsystem(subsystem);
uninstallSubsystem(subsystem);
}
@Test
public void testImplicitlyInstalledChildOverridesProvisionDependencies() throws Exception {
Subsystem root = getRootSubsystem();
subsystemEvents.clear();
try {
Subsystem subsystem = root.install(
"parent",
new SubsystemArchiveBuilder()
.symbolicName("parent")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';' +
AriesProvisionDependenciesDirective.INSTALL.toString())
.subsystem(
"child",
new SubsystemArchiveBuilder()
.symbolicName("child")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';' +
AriesProvisionDependenciesDirective.RESOLVE.toString())
.build())
.build());
uninstallSubsystemSilently(subsystem);
fail("Subsystem should not have installed");
}
catch (SubsystemException e) {
e.printStackTrace();
}
}
@Test
public void testInstall() throws Exception {
Subsystem root = getRootSubsystem();
try {
Subsystem subsystem = installSubsystem(root, APPLICATION_EMPTY, applicationEmpty(), false);
uninstallSubsystemSilently(subsystem);
}
catch (Exception e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
@Test
public void testInstallChildIntoInstallingParent() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystem(root, APPLICATION_DEPENDENCY_IN_ARCHIVE, applicationDependencyInArchive(), false);
try {
assertState(State.INSTALLING, subsystem);
installSubsystem(subsystem, APPLICATION_A, applicationA(), false);
fail("Subsystem should not have installed");
}
catch (SubsystemException e) {
e.printStackTrace();
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
@Test
public void testStart() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystem(root, APPLICATION_EMPTY, applicationEmpty(), false);
try {
startSubsystem(subsystem, false);
stopSubsystemSilently(subsystem);
}
catch (Exception e) {
e.printStackTrace();
fail("Subsystem should have started");
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
@Test
public void testStop() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystem(root, APPLICATION_EMPTY, applicationEmpty(), false);
try {
startSubsystem(subsystem, false);
try {
stopSubsystem(subsystem);
}
catch (Exception e) {
e.printStackTrace();
fail("Subsystem should have stopped");
}
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
@Test
public void testUninstall() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystem(root, APPLICATION_EMPTY, applicationEmpty(), false);
try {
uninstallSubsystem(subsystem);
}
catch (Exception e) {
e.printStackTrace();
fail("Subsystem should have uninstalled");
}
}
private InputStream applicationA() throws Exception {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
attributes.putValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.putValue(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';' +
AriesProvisionDependenciesDirective.RESOLVE.toString());
attributes.putValue(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A + ',' + BUNDLE_C);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
baos.close();
return TinyBundles
.bundle()
.add(SUBSYSTEM_MANIFEST_FILE, new ByteArrayInputStream(baos.toByteArray()))
.add(BUNDLE_A + JAR_EXTENSION, bundleA())
.add(BUNDLE_B + JAR_EXTENSION, bundleB())
.add(BUNDLE_C + JAR_EXTENSION, bundleC())
.add(BUNDLE_D + JAR_EXTENSION, bundleD())
.build();
}
private InputStream applicationB() throws Exception {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
attributes.putValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
attributes.putValue(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';' +
AriesProvisionDependenciesDirective.RESOLVE.toString());
attributes.putValue(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A + ',' + APPLICATION_A + ";type=osgi.subsystem.application");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
baos.close();
return TinyBundles
.bundle()
.add(SUBSYSTEM_MANIFEST_FILE, new ByteArrayInputStream(baos.toByteArray()))
.add(BUNDLE_A + JAR_EXTENSION, bundleA())
.add(BUNDLE_B + JAR_EXTENSION, bundleB())
.add(APPLICATION_A + ESA_EXTENSION, applicationA())
.build();
}
private InputStream applicationDependencyInArchive() throws Exception {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
attributes.putValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_DEPENDENCY_IN_ARCHIVE);
attributes.putValue(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';' +
AriesProvisionDependenciesDirective.RESOLVE.toString());
attributes.putValue(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
baos.close();
return TinyBundles
.bundle()
.add(SUBSYSTEM_MANIFEST_FILE, new ByteArrayInputStream(baos.toByteArray()))
.add(BUNDLE_A + JAR_EXTENSION, bundleA())
.add(BUNDLE_B + JAR_EXTENSION, bundleB())
.build();
}
private InputStream applicationEmpty() throws Exception {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), MANIFEST_VERSION);
attributes.putValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_EMPTY);
attributes.putValue(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';' +
AriesProvisionDependenciesDirective.RESOLVE.toString());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
baos.close();
return TinyBundles
.bundle()
.add(SUBSYSTEM_MANIFEST_FILE, new ByteArrayInputStream(baos.toByteArray()))
.build();
}
private InputStream applicationInstallFailed() throws Exception {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), MANIFEST_VERSION);
attributes.putValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_INSTALL_FAILED);
attributes.putValue(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';' +
AriesProvisionDependenciesDirective.RESOLVE.toString());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
baos.close();
return TinyBundles
.bundle()
.add(SUBSYSTEM_MANIFEST_FILE, new ByteArrayInputStream(baos.toByteArray()))
.add(BUNDLE_INVALID_MANIFEST + JAR_EXTENSION, bundleInvalidManifest())
.build();
}
private InputStream applicationInvalidProvisionDependencies() throws Exception {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
attributes.putValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_INVALID_PROVISION_DEPENDENCIES);
attributes.putValue(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';' +
AriesProvisionDependenciesDirective.NAME + ":=foo");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
baos.close();
return TinyBundles
.bundle()
.add(SUBSYSTEM_MANIFEST_FILE, new ByteArrayInputStream(baos.toByteArray()))
.build();
}
private InputStream applicationMissingDependency() throws Exception {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
attributes.putValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_MISSING_DEPENDENCY);
attributes.putValue(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';' +
AriesProvisionDependenciesDirective.RESOLVE.toString());
attributes.putValue(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
baos.close();
return TinyBundles
.bundle()
.add(SUBSYSTEM_MANIFEST_FILE, new ByteArrayInputStream(baos.toByteArray()))
.add(BUNDLE_A + JAR_EXTENSION, bundleA())
.build();
}
private InputStream applicationProvisionDependenciesInstall() throws Exception {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
attributes.putValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_PROVISION_DEPENDENCIES_INSTALL);
attributes.putValue(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';' +
AriesProvisionDependenciesDirective.INSTALL.toString());
attributes.putValue(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
baos.close();
return TinyBundles
.bundle()
.add(SUBSYSTEM_MANIFEST_FILE, new ByteArrayInputStream(baos.toByteArray()))
.add(BUNDLE_A + JAR_EXTENSION, bundleA())
.add(BUNDLE_B + JAR_EXTENSION, bundleB())
.build();
}
private InputStream applicationStartFailure() throws Exception {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
attributes.putValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_START_FAILURE);
attributes.putValue(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';' +
AriesProvisionDependenciesDirective.RESOLVE.toString());
attributes.putValue(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_START_FAILURE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
baos.close();
return TinyBundles
.bundle()
.add(SUBSYSTEM_MANIFEST_FILE, new ByteArrayInputStream(baos.toByteArray()))
.add(BUNDLE_START_FAILURE + JAR_EXTENSION, bundleStartFailure())
.build();
}
private void assertReferences(Class<?> clazz, String filter, int expected) throws Exception {
ServiceReference<?>[] references = bundleContext.getAllServiceReferences(clazz.getName(), filter);
if (expected < 1) {
assertNull("References exist", references);
}
else {
assertNotNull("No references", references);
assertEquals("No references or more than one", expected, references.length);
}
}
private InputStream bundleA() {
return TinyBundles
.bundle()
.set(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_A)
.set(Constants.EXPORT_PACKAGE, PACKAGE_A)
.set(Constants.IMPORT_PACKAGE, PACKAGE_B)
.build();
}
private InputStream bundleB() {
return TinyBundles
.bundle()
.set(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_B)
.set(Constants.EXPORT_PACKAGE, PACKAGE_B)
.build();
}
private InputStream bundleC() {
return TinyBundles
.bundle()
.set(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_C)
.set(Constants.EXPORT_PACKAGE, PACKAGE_C)
.set(Constants.IMPORT_PACKAGE, PACKAGE_B)
.set(Constants.IMPORT_PACKAGE, PACKAGE_D)
.build();
}
private InputStream bundleD() {
return TinyBundles
.bundle()
.set(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_D)
.set(Constants.EXPORT_PACKAGE, PACKAGE_D)
.build();
}
private InputStream bundleInvalidManifest() {
return TinyBundles
.bundle()
.set(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_INVALID_MANIFEST)
.set(Constants.PROVIDE_CAPABILITY, "osgi.ee;osgi.ee=J2SE-1.4")
.build();
}
private InputStream bundleStartFailure() {
return TinyBundles
.bundle()
.set(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_START_FAILURE)
.set(Constants.BUNDLE_ACTIVATOR, BundleStartFailureActivator.class.getName())
.add(BundleStartFailureActivator.class, InnerClassStrategy.NONE)
.build();
}
private InputStream featureProvisionDependenciesResolve() throws Exception {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
attributes.putValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_PROVISION_DEPENDENCIES_RESOLVE);
attributes.putValue(SubsystemConstants.SUBSYSTEM_TYPE,
SubsystemConstants.SUBSYSTEM_TYPE_FEATURE + ';' +
AriesProvisionDependenciesDirective.RESOLVE.toString());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
manifest.write(baos);
baos.close();
return TinyBundles
.bundle()
.add(SUBSYSTEM_MANIFEST_FILE, new ByteArrayInputStream(baos.toByteArray()))
.build();
}
public static interface TestService {}
public static class TestServiceImpl implements TestService {}
public static class TestServiceClientActivator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception {
ServiceReference<TestService> ref = null;
for (int i = 0; i < 80; i++) { // 20 seconds with 250ms sleep.
ref = context.getServiceReference(TestService.class);
if (ref == null) {
Thread.sleep(250);
continue;
}
break;
}
try {
TestService service = context.getService(ref);
service.getClass();
}
finally {
context.ungetService(ref);
}
}
@Override
public void stop(BundleContext context) throws Exception {
}
}
public static class TestServiceImplActivator implements BundleActivator {
private ServiceRegistration<TestService> reg;
@Override
public void start(BundleContext context) throws Exception {
reg = context.registerService(
TestService.class,
new TestServiceImpl(),
null);
}
@Override
public void stop(BundleContext context) throws Exception {
reg.unregister();
}
}
private static class BundleStartFailureActivator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception {
throw new IllegalStateException();
}
@Override
public void stop(BundleContext context) throws Exception {
// Nothing.
}
}
@Test
public void testInterleavingContentDependencies() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem c1 = installSubsystem(
root,
"c1",
new SubsystemArchiveBuilder()
.symbolicName("c1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("c1b1;version=\"[0,0]\"")
.exportPackage("c1b1")
.importPackage("c2b1")
.bundle(
"c1b1",
new BundleArchiveBuilder()
.symbolicName("c1b1")
.exportPackage("c1b1")
.importPackage("c2b1")
.build())
.build(),
false
);
uninstallableSubsystems.add(c1);
Subsystem c2 = installSubsystem(
root,
"c2",
new SubsystemArchiveBuilder()
.symbolicName("c2")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("c2b1;version=\"[0,0]\"")
.exportPackage("c2b1")
.importPackage("c1b1")
.bundle(
"c2b1",
new BundleArchiveBuilder()
.symbolicName("c2b1")
.exportPackage("c2b1")
.importPackage("c1b1")
.build())
.build(),
false
);
uninstallableSubsystems.add(c2);
startSubsystem(c1, false);
stoppableSubsystems.add(c1);
assertState(EnumSet.of(State.RESOLVED, State.ACTIVE), c2);
stoppableSubsystems.add(c2);
}
@Test
public void testRestart2() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem c1 = installSubsystem(
root,
"c1",
new SubsystemArchiveBuilder()
.symbolicName("c1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("c1b1;version=\"[0,0]\"")
.exportPackage("c1b1")
.importPackage("c2b1")
.bundle(
"c1b1",
new BundleArchiveBuilder()
.symbolicName("c1b1")
.exportPackage("c1b1")
.importPackage("c2b1")
.build())
.build(),
false
);
uninstallableSubsystems.add(c1);
Subsystem c2 = installSubsystem(
root,
"c2",
new SubsystemArchiveBuilder()
.symbolicName("c2")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("c2b1;version=\"[0,0]\"")
.exportPackage("c2b1")
.importPackage("c1b1")
.bundle(
"c2b1",
new BundleArchiveBuilder()
.symbolicName("c2b1")
.exportPackage("c2b1")
.importPackage("c1b1")
.build())
.build(),
false
);
uninstallableSubsystems.add(c2);
assertChild(root, "c1", null, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
assertChild(root, "c2", null, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
restartSubsystemsImplBundle();
root = getRootSubsystem();
c1 = getChild(root, "c1", null, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
assertNotNull("Missing child", c1);
uninstallableSubsystems.add(c1);
c2 = getChild(root, "c2", null, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
assertNotNull("Missing child", c2);
uninstallableSubsystems.add(c2);
startSubsystem(c1, false);
stoppableSubsystems.add(c1);
try {
assertState(EnumSet.of(State.RESOLVED, State.ACTIVE), c2);
}
catch (AssertionError e) {
System.out.println(c2.getState());
}
}
@Test
public void testRestart() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem a1 = installSubsystem(
root,
"a1",
new SubsystemArchiveBuilder()
.symbolicName("a1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("b1,c1;type=osgi.subsystem.composite")
.bundle(
"b1",
new BundleArchiveBuilder()
.symbolicName("b1")
.importPackage("b2")
.build())
.bundle(
"b2",
new BundleArchiveBuilder()
.symbolicName("b2")
.exportPackage("b2")
.build())
.subsystem(
"c1",
new SubsystemArchiveBuilder()
.symbolicName("c1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("b1;version=\"[0,0]\"")
.importPackage("b2")
.bundle(
"b1",
new BundleArchiveBuilder()
.symbolicName("b1")
.importPackage("b2")
.build())
.build())
.build(),
false);
uninstallableSubsystems.add(a1);
assertChild(root, "a1");
assertState(State.INSTALLING, a1);
Subsystem c1 = getChild(a1, "c1", null, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
assertNotNull("Missing child", c1);
assertState(State.INSTALLING, c1);
restartSubsystemsImplBundle();
root = getRootSubsystem();
a1 = getChild(root, "a1");
assertNotNull("Missing child", a1);
uninstallableSubsystems.add(a1);
assertState(State.INSTALLING, a1);
assertConstituent(a1, "b1");
assertNotConstituent(root, "b2");
c1 = getChild(a1, "c1", null, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
assertNotNull("Missing child", c1);
uninstallableSubsystems.add(c1);
assertConstituent(c1, "b1");
startSubsystem(c1, false);
stoppableSubsystems.add(c1);
assertState(State.INSTALLED, a1);
stoppableSubsystems.add(a1);
assertConstituent(root, "b2");
}
@Test
public void test4e3bCompliance() throws Exception {
serviceRegistrations.add(bundleContext.registerService(
Repository.class,
new TestRepository.Builder()
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"a")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.capability(new TestCapability.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.attribute(
PackageNamespace.PACKAGE_NAMESPACE,
"x")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion))
.capability(new TestCapability.Builder()
.namespace(BundleNamespace.BUNDLE_NAMESPACE)
.attribute(
BundleNamespace.BUNDLE_NAMESPACE,
"a")
.attribute(
BundleNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE,
Version.emptyVersion))
.content(new BundleArchiveBuilder()
.symbolicName("a")
.exportPackage("x")
.buildAsBytes())
.build())
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"b")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.capability(new TestCapability.Builder()
.namespace("y"))
.content(new BundleArchiveBuilder()
.symbolicName("b")
.header("Provide-Capability", "y")
.buildAsBytes())
.build())
.build(),
null));
Subsystem root = getRootSubsystem();
try {
Subsystem s1 = installSubsystem(
root,
"s1",
new SubsystemArchiveBuilder()
.symbolicName("s1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE)
.subsystem(
"s3",
new SubsystemArchiveBuilder()
.symbolicName("s3")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE)
.subsystem(
"s2",
new SubsystemArchiveBuilder()
.symbolicName("s2")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION)
.bundle(
"c",
new BundleArchiveBuilder()
.symbolicName("c")
.importPackage("x")
.build())
.bundle(
"d",
new BundleArchiveBuilder()
.symbolicName("d")
.header("Require-Bundle", "a")
.build())
.bundle(
"e",
new BundleArchiveBuilder()
.symbolicName("e")
.header("Require-Capability", "y")
.build())
.build())
.build())
.build(),
true);
uninstallableSubsystems.add(s1);
fail("Subsystem should not have installed");
}
catch (SubsystemException e) {
e.printStackTrace();
}
}
@Test
public void testMatchingCapabilityInDisconnectedRegion() throws Exception {
Subsystem root = getRootSubsystem();
BundleArchiveBuilder b1Builder = new BundleArchiveBuilder()
.symbolicName("b1")
.exportPackage("b1");
Bundle b1 = root.getBundleContext().installBundle("b1", b1Builder.build());
try {
Subsystem a1 = installSubsystem(
root,
"a1",
new SubsystemArchiveBuilder()
.symbolicName("a1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString()
+ ';'
+ SubsystemConstants.PROVISION_POLICY_DIRECTIVE
+ ":="
+ SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES)
.build(),
false
);
uninstallableSubsystems.add(a1);
startSubsystem(a1, false);
stoppableSubsystems.add(a1);
removeConnectionWithParent(a1);
Subsystem a2 = installSubsystem(
a1,
"a2",
new SubsystemArchiveBuilder()
.symbolicName("a2")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION)
.content("b2")
.bundle(
"b2",
new BundleArchiveBuilder()
.symbolicName("b2")
.importPackage("b1")
.build())
.bundle(
"b1",
b1Builder.build())
.build(),
false
);
uninstallableSubsystems.add(a2);
assertState(State.INSTALLING, a2);
assertNotConstituent(a1, "b1");
try {
startSubsystem(a2, false);
stoppableSubsystems.add(a2);
assertConstituent(a1, "b1");
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have started");
}
}
finally {
uninstallSilently(b1);
}
}
@Test
public void testProvideCapabilityNamespaceOnly() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem c1 = installSubsystem(
root,
"c1",
new SubsystemArchiveBuilder()
.symbolicName("c1")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE)
.provideCapability("y")
.build());
uninstallableSubsystems.add(c1);
try {
startSubsystem(c1);
stoppableSubsystems.add(c1);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have started");
}
}
@Test
public void testComApiComImplAppClient() throws Exception {
Subsystem root = getRootSubsystem();
final Subsystem shared = installSubsystem(
root,
"shared",
new SubsystemArchiveBuilder()
.symbolicName("shared")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString()
+ ';'
+ SubsystemConstants.PROVISION_POLICY_DIRECTIVE
+ ":="
+ SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES)
.importPackage("org.osgi.framework")
.build(),
false
);
uninstallableSubsystems.add(shared);
shared.start();
stoppableSubsystems.add(shared);
@SuppressWarnings("unchecked")
Callable<Subsystem>[] installCallables = new Callable[] {
new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem result = installSubsystem(
shared,
"client",
new SubsystemArchiveBuilder()
.symbolicName("client")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION)
.bundle(
"client",
new BundleArchiveBuilder()
.symbolicName("client")
.importPackage("org.apache.aries.subsystem.itests.defect")
.requireCapability("osgi.service;filter:=\"(objectClass="
+ TestService.class.getName()
+ ")\";effective:=active")
.build())
.build(),
false);
uninstallableSubsystems.add(result);
return result;
}
},
new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem result = installSubsystem(
shared,
"impl",
new SubsystemArchiveBuilder()
.symbolicName("impl")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE)
.content("impl;version=\"[0,0]\"")
.provideCapability("osgi.service;objectClass:List<String>=\""
+ TestService.class.getName()
+ "\"")
.importPackage("org.osgi.framework")
.requireBundle("api")
.bundle(
"impl",
new BundleArchiveBuilder()
.symbolicName("impl")
.provideCapability("osgi.service;objectClass:List<String>=\""
+ TestService.class.getName()
+ "\"")
.importPackage("org.osgi.framework")
.requireBundle("api")
.clazz(TestServiceImpl.class)
.activator(TestServiceImplActivator.class)
.build())
.build(),
false);
uninstallableSubsystems.add(result);
return result;
}
},
new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem result = installSubsystem(
shared,
"api",
new SubsystemArchiveBuilder()
.symbolicName("api")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE)
.content("api;version=\"[0,0]\"")
.exportPackage("org.apache.aries.subsystem.itests.defect")
.provideCapability("osgi.wiring.bundle;osgi.wiring.bundle=api;bundle-version=0")
.bundle(
"api",
new BundleArchiveBuilder()
.symbolicName("api")
.exportPackage("org.apache.aries.subsystem.itests.defect")
.clazz(TestService.class)
.build())
.build(),
false);
uninstallableSubsystems.add(result);
return result;
}
}
};
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Future<Subsystem>> installFutures = executor.invokeAll(Arrays.asList(installCallables));
final Subsystem a1 = installFutures.get(0).get();
final Subsystem c1 = installFutures.get(1).get();
final Subsystem c2 = installFutures.get(2).get();
@SuppressWarnings("unchecked")
Callable<Void>[] startCallables = new Callable[] {
new Callable<Void>() {
@Override
public Void call() throws Exception {
a1.start();
stoppableSubsystems.add(a1);
assertEvent(a1, State.INSTALLED, subsystemEvents.poll(a1.getSubsystemId(), 5000));
assertEvent(a1, State.RESOLVING, subsystemEvents.poll(a1.getSubsystemId(), 5000));
assertEvent(a1, State.RESOLVED, subsystemEvents.poll(a1.getSubsystemId(), 5000));
assertEvent(a1, State.STARTING, subsystemEvents.poll(a1.getSubsystemId(), 5000));
assertEvent(a1, State.ACTIVE, subsystemEvents.poll(a1.getSubsystemId(), 5000));
return null;
}
},
new Callable<Void>() {
@Override
public Void call() throws Exception {
c1.start();
stoppableSubsystems.add(c1);
assertEvent(c1, State.INSTALLED, subsystemEvents.poll(c1.getSubsystemId(), 5000));
assertEvent(c1, State.RESOLVING, subsystemEvents.poll(c1.getSubsystemId(), 5000));
assertEvent(c1, State.RESOLVED, subsystemEvents.poll(c1.getSubsystemId(), 5000));
assertEvent(c1, State.STARTING, subsystemEvents.poll(c1.getSubsystemId(), 5000));
assertEvent(c1, State.ACTIVE, subsystemEvents.poll(c1.getSubsystemId(), 5000));
return null;
}
},
new Callable<Void>() {
@Override
public Void call() throws Exception {
c2.start();
stoppableSubsystems.add(c2);
assertEvent(c2, State.INSTALLED, subsystemEvents.poll(c2.getSubsystemId(), 5000));
assertEvent(c2, State.RESOLVING, subsystemEvents.poll(c2.getSubsystemId(), 5000));
assertEvent(c2, State.RESOLVED, subsystemEvents.poll(c2.getSubsystemId(), 5000));
assertEvent(c2, State.STARTING, subsystemEvents.poll(c2.getSubsystemId(), 5000));
assertEvent(c2, State.ACTIVE, subsystemEvents.poll(c2.getSubsystemId(), 5000));
return null;
}
}
};
List<Future<Void>> startFutures = executor.invokeAll(Arrays.asList(startCallables));
startFutures.get(0).get();
startFutures.get(1).get();
startFutures.get(2).get();
}
@Test
public void testComApiComImplComClient() throws Exception {
Subsystem root = getRootSubsystem();
final Subsystem shared = installSubsystem(
root,
"shared",
new SubsystemArchiveBuilder()
.symbolicName("shared")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString()
+ ';'
+ SubsystemConstants.PROVISION_POLICY_DIRECTIVE
+ ":="
+ SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES)
.importPackage("org.osgi.framework")
.build(),
false
);
uninstallableSubsystems.add(shared);
shared.start();
stoppableSubsystems.add(shared);
@SuppressWarnings("unchecked")
Callable<Subsystem>[] installCallables = new Callable[] {
new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem result = installSubsystem(
shared,
"client",
new SubsystemArchiveBuilder()
.symbolicName("client")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE)
.content("client;version=\"[0,0]\"")
.importPackage("org.osgi.framework")
.requireCapability("osgi.service;filter:=\"(objectClass="
+ TestService.class.getName()
+ ")\";effective:=active")
.importService(TestService.class.getName())
.requireBundle("api,impl")
.bundle(
"client",
new BundleArchiveBuilder()
.symbolicName("client")
.importPackage("org.osgi.framework")
.requireCapability("osgi.service;filter:=\"(objectClass="
+ TestService.class.getName()
+ ")\";effective:=active")
.requireBundle("api,impl")
.activator(TestServiceClientActivator.class)
.build())
.build(),
false);
return result;
}
},
new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem result = installSubsystem(
shared,
"impl",
new SubsystemArchiveBuilder()
.symbolicName("impl")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE)
.content("impl;version=\"[0,0]\"")
.provideCapability("osgi.service;objectClass:List<String>=\""
+ TestService.class.getName()
+ "\"")
.exportService(TestService.class.getName())
.importPackage("org.osgi.framework")
.requireBundle("api")
.provideCapability("osgi.wiring.bundle;osgi.wiring.bundle=impl;bundle-version=0")
.bundle(
"impl",
new BundleArchiveBuilder()
.symbolicName("impl")
.provideCapability("osgi.service;objectClass:List<String>=\""
+ TestService.class.getName()
+ "\"")
.importPackage("org.osgi.framework")
.requireBundle("api")
.clazz(TestServiceImpl.class)
.activator(TestServiceImplActivator.class)
.build())
.build(),
false);
return result;
}
},
new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem result = installSubsystem(
shared,
"api",
new SubsystemArchiveBuilder()
.symbolicName("api")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE)
.content("api;version=\"[0,0]\"")
.exportPackage("org.apache.aries.subsystem.itests.defect")
.provideCapability("osgi.wiring.bundle;osgi.wiring.bundle=api;bundle-version=0")
.bundle(
"api",
new BundleArchiveBuilder()
.symbolicName("api")
.exportPackage("org.apache.aries.subsystem.itests.defect")
.clazz(TestService.class)
.build())
.build(),
false);
return result;
}
}
};
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Future<Subsystem>> installFutures = executor.invokeAll(Arrays.asList(installCallables));
final Subsystem client = installFutures.get(0).get();
final Subsystem impl = installFutures.get(1).get();
final Subsystem api = installFutures.get(2).get();
@SuppressWarnings("unchecked")
Callable<Void>[] startCallables = new Callable[] {
new Callable<Void>() {
@Override
public Void call() throws Exception {
client.start();
assertEvent(client, State.INSTALLED, subsystemEvents.poll(client.getSubsystemId(), 5000));
assertEvent(client, State.RESOLVING, subsystemEvents.poll(client.getSubsystemId(), 5000));
assertEvent(client, State.RESOLVED, subsystemEvents.poll(client.getSubsystemId(), 5000));
assertEvent(client, State.STARTING, subsystemEvents.poll(client.getSubsystemId(), 5000));
assertEvent(client, State.ACTIVE, subsystemEvents.poll(client.getSubsystemId(), 5000));
return null;
}
},
new Callable<Void>() {
@Override
public Void call() throws Exception {
impl.start();
assertEvent(impl, State.INSTALLED, subsystemEvents.poll(impl.getSubsystemId(), 5000));
assertEvent(impl, State.RESOLVING, subsystemEvents.poll(impl.getSubsystemId(), 5000));
assertEvent(impl, State.RESOLVED, subsystemEvents.poll(impl.getSubsystemId(), 5000));
assertEvent(impl, State.STARTING, subsystemEvents.poll(impl.getSubsystemId(), 5000));
assertEvent(impl, State.ACTIVE, subsystemEvents.poll(impl.getSubsystemId(), 5000));
return null;
}
},
new Callable<Void>() {
@Override
public Void call() throws Exception {
api.start();
assertEvent(api, State.INSTALLED, subsystemEvents.poll(api.getSubsystemId(), 5000));
assertEvent(api, State.RESOLVING, subsystemEvents.poll(api.getSubsystemId(), 5000));
assertEvent(api, State.RESOLVED, subsystemEvents.poll(api.getSubsystemId(), 5000));
assertEvent(api, State.STARTING, subsystemEvents.poll(api.getSubsystemId(), 5000));
assertEvent(api, State.ACTIVE, subsystemEvents.poll(api.getSubsystemId(), 5000));
return null;
}
}
};
List<Future<Void>> startFutures = executor.invokeAll(Arrays.asList(startCallables));
startFutures.get(0).get();
startFutures.get(1).get();
startFutures.get(2).get();
}
@Test
public void testAutoInstallDependenciesComposite() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem b = installSubsystem(
root,
"b",
new SubsystemArchiveBuilder()
.symbolicName("b")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString())
.content("a;version=\"[0,0]\"")
.exportPackage("a")
.importPackage("b")
.bundle(
"a",
new BundleArchiveBuilder()
.symbolicName("a")
.importPackage("b")
.exportPackage("a")
.build())
.bundle(
"b",
new BundleArchiveBuilder()
.symbolicName("b")
.exportPackage("b")
.build())
.build(),
false
);
uninstallableSubsystems.add(b);
try {
Subsystem a = installSubsystem(
root,
"a",
new SubsystemArchiveBuilder()
.symbolicName("a")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION)
.bundle(
"a",
new BundleArchiveBuilder()
.symbolicName("a")
.importPackage("a")
.build())
.build(),
true
);
uninstallableSubsystems.add(a);
assertState(EnumSet.of(State.INSTALLED, State.RESOLVED), b);
}
catch (Exception e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
@Test
public void testAutoInstallDependenciesFeature() throws Exception {
Subsystem root = getRootSubsystem();
Subsystem shared = installSubsystem(
root,
"shared",
new SubsystemArchiveBuilder()
.symbolicName("shared")
.type(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE
+ ';'
+ AriesProvisionDependenciesDirective.RESOLVE.toString()
+ ';'
+ SubsystemConstants.PROVISION_POLICY_DIRECTIVE
+ ":="
+ SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES)
.build(),
false
);
uninstallableSubsystems.add(shared);
startSubsystem(shared, false);
Subsystem b = installSubsystem(
shared,
"b",
new SubsystemArchiveBuilder()
.symbolicName("b")
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE)
.content("a")
.bundle(
"a",
new BundleArchiveBuilder()
.symbolicName("a")
.importPackage("b")
.exportPackage("a")
.build())
.bundle(
"b",
new BundleArchiveBuilder()
.symbolicName("b")
.exportPackage("b")
.build())
.build(),
false
);
try {
installSubsystem(
shared,
"a",
new SubsystemArchiveBuilder()
.symbolicName("a")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION
+ ';'
+ AriesProvisionDependenciesDirective.INSTALL.toString())
.bundle(
"a",
new BundleArchiveBuilder()
.symbolicName("a")
.importPackage("a")
.build())
.build(),
true
);
assertState(EnumSet.of(State.INSTALLED, State.RESOLVED), b);
}
catch (Exception e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
}
| 8,757 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1423Test.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.subsystem.itests.defect;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.itests.Header;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Before;
import org.junit.Test;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
/*
* https://issues.apache.org/jira/browse/ARIES-1423
*
* IllegalArgumentException when GenericHeader has no clauses
*/
public class Aries1423Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
*
* Included In Archive
* bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Build-Plan:
* Build-Number:
*/
private static final String BUNDLE_A = "bundle.a.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createApplicationA();
createdTestFiles = true;
}
private void createBundleA() throws IOException {
createBundle(
name(BUNDLE_A),
new Header("Build-Plan", ""),
new Header("Build-Number", "") {});
}
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put("Build-Plan", "");
attributes.put("Build-Number", "");
createManifest(APPLICATION_A + ".mf", attributes);
}
@Test
public void testEmptyNonOsgiHeaders() throws Exception {
try {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
uninstallSubsystemSilently(applicationA);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
}
| 8,758 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1328Test.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.subsystem.itests.defect;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
/*
* https://issues.apache.org/jira/browse/ARIES-1419
*
* Provide-Capability header parser does not support typed attributes.
*/
public class Aries1328Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
*
* Included In Archive:
* bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Require-Capability: osgi.service;filter:="(objectClass=service.a)",
* osgi.service;filter:="(objectClass=service.b)";effective:=resolve
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Provide-Capability: osgi.service;objectClass=service.a",
* osgi.service;objectClass=service.b
*/
private static final String BUNDLE_B = "bundle.b.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createBundleB();
createApplicationA();
createdTestFiles = true;
}
private void createBundleA() throws IOException {
createBundle(
name(BUNDLE_A),
requireCapability("osgi.service;filter:=\"(objectClass=service.a)\"" +
", osgi.service;filter:=\"(objectClass=service.b)\";effective:=resolve"));
}
private void createBundleB() throws IOException {
createBundle(
name(BUNDLE_B),
provideCapability("osgi.service;objectClass=service.a, osgi.service;objectClass=service.b"));
}
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
@Test
public void testServiceAndRequireCapabilityInServiceNamespaceVisibilityInImportSharingPolicy() throws Exception {
Bundle bundleB = installBundleFromFile(BUNDLE_B);
try {
// Install application A containing content bundle A requiring two
// service capabilities each with effective:=resolve. Both the
// services and service capabilities should be visible to the
// bundle.
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
// Start the application to ensure the runtime resolution
// succeeds.
applicationA.start();
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have started");
}
finally {
stopAndUninstallSubsystemSilently(applicationA);
}
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
finally {
uninstallSilently(bundleB);
}
}
}
| 8,759 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1425Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.core.archive.DeployedContentHeader;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
/*
* https://issues.apache.org/jira/browse/ARIES-1425
*
* Support both osgi.bundle and osgi.fragment resource types when given a
* Subsystem-Content header clause with an unspecified type attribute.
*/
public class Aries1425Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar, bundle.b.jar
*
* Included In Archive
* bundle.a.fragment.jar
* bundle.b.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: application.b.esa
* Subsystem-Content: bundle.a.jar
*
* Included In Archive
* bundle.a.fragment.jar
* bundle.a.bundle.jar
*/
private static final String APPLICATION_B = "application.b.esa";
/*
* Subsystem-SymbolicName: application.c.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_C = "application.c.esa";
/*
* Subsystem-SymbolicName: application.d.esa
* Subsystem-Content: bundle.a.jar, bundle.b.jar
*
* Included In Archive
* bundle.a.fragment.jar
*/
private static final String APPLICATION_D = "application.d.esa";
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.a.jar
* Fragment-Host: bundle.b.jar
*/
private static final String BUNDLE_A_FRAGMENT = "bundle.a.fragment.jar";
/*
* Bundle-SymbolicName: bundle.a.jar
*/
private static final String BUNDLE_A_BUNDLE = "bundle.a.bundle.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
*/
private static final String BUNDLE_B = "bundle.b.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleABundle();
createBundleAFragment();
createBundleB();
createApplicationA();
createApplicationB();
createApplicationC();
createApplicationD();
createdTestFiles = true;
}
private void createBundleABundle() throws IOException {
Map<String, String> headers = new HashMap<String, String>();
headers.put(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_A);
createBundle(BUNDLE_A_BUNDLE, Collections.<String>emptyList(), headers);
}
private void createBundleAFragment() throws IOException {
Map<String, String> headers = new HashMap<String, String>();
headers.put(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_A);
headers.put(Constants.FRAGMENT_HOST, BUNDLE_B);
createBundle(BUNDLE_A_FRAGMENT, Collections.<String>emptyList(), headers);
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B));
}
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A_FRAGMENT, BUNDLE_B);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A + ',' + BUNDLE_B);
createManifest(APPLICATION_A + ".mf", attributes);
}
private static void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B, BUNDLE_A_FRAGMENT, BUNDLE_A_BUNDLE);
}
private static void createApplicationBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(APPLICATION_B + ".mf", attributes);
}
private static void createApplicationC() throws IOException {
createApplicationCManifest();
createSubsystem(APPLICATION_C);
}
private static void createApplicationCManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_C);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(APPLICATION_C + ".mf", attributes);
}
private static void createApplicationD() throws IOException {
createApplicationDManifest();
createSubsystem(APPLICATION_D, BUNDLE_A_FRAGMENT);
}
private static void createApplicationDManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_D);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(APPLICATION_D + ".mf", attributes);
}
@Test
public void testFragmentSelected() throws Exception {
try {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
assertConstituent(applicationA, BUNDLE_A, null, IdentityNamespace.TYPE_FRAGMENT);
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
@Test
public void testFragmentResolved() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
applicationA.start();
try {
Bundle bundleA = getConstituentAsBundle(applicationA, BUNDLE_A, null, IdentityNamespace.TYPE_FRAGMENT);
assertBundleState(bundleA, Bundle.RESOLVED);
}
finally {
stopSubsystemSilently(applicationA);
}
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testDeployedContentHeader() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
Map<String, String> headers = applicationA.getDeploymentHeaders();
String header = headers.get(SubsystemConstants.DEPLOYED_CONTENT);
DeployedContentHeader dch = new DeployedContentHeader(header);
boolean foundClause = false;
for (DeployedContentHeader.Clause clause : dch.getClauses()) {
if (BUNDLE_A.equals(clause.getSymbolicName())) {
assertEquals("Wrong type", IdentityNamespace.TYPE_FRAGMENT, clause.getType());
foundClause = true;
break;
}
}
assertTrue("Missing clause", foundClause);
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testProvisionResourceHeader() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
Map<String, String> headers = applicationA.getDeploymentHeaders();
String header = headers.get(SubsystemConstants.PROVISION_RESOURCE);
assertFalse("Fragment content treated as dependency", header != null && header.contains(BUNDLE_A));
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testBundleSelectedFromLocalRepository() throws Exception {
Subsystem applicationB = installSubsystemFromFile(APPLICATION_B);
try {
assertNotConstituent(applicationB, BUNDLE_A, null, IdentityNamespace.TYPE_FRAGMENT);
assertConstituent(applicationB, BUNDLE_A, null, IdentityNamespace.TYPE_BUNDLE);
}
finally {
uninstallSubsystemSilently(applicationB);
}
}
@Test
public void testBundleSelectedFromRemoteRepository() throws Exception {
// Make sure the repository containing the fragment comes first.
registerRepositoryService(BUNDLE_A_FRAGMENT);
registerRepositoryService(BUNDLE_A_BUNDLE);
Subsystem applicationC = installSubsystemFromFile(APPLICATION_C);
try {
assertNotConstituent(applicationC, BUNDLE_A, null, IdentityNamespace.TYPE_FRAGMENT);
assertConstituent(applicationC, BUNDLE_A, null, IdentityNamespace.TYPE_BUNDLE);
}
finally {
uninstallSubsystemSilently(applicationC);
}
}
@Test
public void testFragmentFromLocalRepoSelectedBeforeBundleRemoteRepository() throws Exception {
registerRepositoryService(BUNDLE_A_BUNDLE, BUNDLE_B);
Subsystem applicationD = installSubsystemFromFile(APPLICATION_D);
try {
assertNotConstituent(applicationD, BUNDLE_A, null, IdentityNamespace.TYPE_BUNDLE);
assertConstituent(applicationD, BUNDLE_A, null, IdentityNamespace.TYPE_FRAGMENT);
}
finally {
uninstallSubsystemSilently(applicationD);
}
}
}
| 8,760 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1399Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Before;
import org.junit.Test;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.SynchronousBundleListener;
import org.osgi.service.subsystem.Subsystem;
import aQute.bnd.osgi.Constants;
/*
* https://issues.apache.org/jira/browse/ARIES-1399
*
* Trunk fails OSGi R6 CT
*/
public class Aries1399Test extends SubsystemTest {
/*
* Bundle-SymbolicName: bundle.a.jar
*/
private static final String BUNDLE_A = "bundle.a.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createdTestFiles = true;
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A));
}
@Test
public void testBundleEventOrder() throws Exception {
Subsystem root = getRootSubsystem();
BundleContext context = root.getBundleContext();
final List<BundleEvent> events = Collections.synchronizedList(new ArrayList<BundleEvent>());
context.addBundleListener(
new SynchronousBundleListener() {
@Override
public void bundleChanged(BundleEvent event) {
events.add(event);
}
});
Bundle bundle = context.installBundle(
"bundle",
TinyBundles.bundle().set(Constants.BUNDLE_SYMBOLICNAME, "bundle").build());
try {
bundle.start();
// INSTALLED, RESOLVED, STARTING, STARTED
assertEquals(4, events.size());
assertEquals(BundleEvent.INSTALLED, events.get(0).getType());
assertEquals(BundleEvent.RESOLVED, events.get(1).getType());
assertEquals(BundleEvent.STARTING, events.get(2).getType());
assertEquals(BundleEvent.STARTED, events.get(3).getType());
}
finally {
uninstallSilently(bundle);
}
}
}
| 8,761 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1445Test.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.subsystem.itests.defect;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.BundleArchiveBuilder;
import org.apache.aries.subsystem.itests.util.SubsystemArchiveBuilder;
import org.apache.aries.subsystem.itests.util.TestCapability;
import org.apache.aries.subsystem.itests.util.TestRepository;
import org.apache.aries.subsystem.itests.util.TestRepositoryContent;
import org.apache.aries.subsystem.itests.util.TestRequirement;
import org.junit.Test;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.namespace.service.ServiceNamespace;
import org.osgi.service.repository.Repository;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
public class Aries1445Test extends SubsystemTest {
@Test
public void testFeatureFeature() throws Exception {
test(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
}
@Test
public void testApplicationApplication() throws Exception {
test(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION);
}
@Test
public void testCompositeComposite() throws Exception {
test(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
}
@Test
public void testFeatureApplication() throws Exception {
test(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION);
}
@Test
public void testCompositeFeature() throws Exception {
test(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
}
private void test(String type1, String type2) throws Exception {
serviceRegistrations.add(bundleContext.registerService(
Repository.class,
new TestRepository.Builder()
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"b")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.capability(new TestCapability.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.attribute(
PackageNamespace.PACKAGE_NAMESPACE,
"b.package")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion))
.requirement(new TestRequirement.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.directive(
PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE,
"(osgi.wiring.package=c.package)"))
.requirement(new TestRequirement.Builder()
.namespace(ServiceNamespace.SERVICE_NAMESPACE)
.directive(
ServiceNamespace.REQUIREMENT_FILTER_DIRECTIVE,
"(objectClass=foo.Bar)")
.directive(
ServiceNamespace.REQUIREMENT_EFFECTIVE_DIRECTIVE,
ServiceNamespace.EFFECTIVE_ACTIVE))
.content(new BundleArchiveBuilder()
.symbolicName("b")
.exportPackage("b.package")
.importPackage("c.package")
.requireCapability("osgi.service;filter:=\"(objectClass=foo.Bar)\";effective:=active")
.buildAsBytes())
.build())
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"c")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.capability(new TestCapability.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.attribute(
PackageNamespace.PACKAGE_NAMESPACE,
"c.package")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion))
.content(new BundleArchiveBuilder()
.symbolicName("c")
.exportPackage("c.package")
.buildAsBytes())
.build())
.resource(new TestRepositoryContent.Builder()
.capability(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(
IdentityNamespace.IDENTITY_NAMESPACE,
"d")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.attribute(
IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE,
IdentityNamespace.TYPE_BUNDLE))
.capability(new TestCapability.Builder()
.namespace(ServiceNamespace.SERVICE_NAMESPACE)
.attribute(
Constants.OBJECTCLASS,
"foo.Bar")
.attribute(
IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE,
Version.emptyVersion)
.directive(
ServiceNamespace.CAPABILITY_EFFECTIVE_DIRECTIVE,
ServiceNamespace.EFFECTIVE_ACTIVE))
.content(new BundleArchiveBuilder()
.symbolicName("d")
.provideCapability("osgi.service;objectClass=foo.Bar;effective:=active")
.buildAsBytes())
.build())
.build(),
null));
Subsystem root = getRootSubsystem();
Subsystem s1 = installSubsystem(
root,
"s1",
buildSubsystem(root, "s1", type1));
uninstallableSubsystems.add(s1);
startSubsystem(s1);
stoppableSubsystems.add(s1);
Subsystem s2 = installSubsystem(
root,
"s2",
buildSubsystem(root, "s2", type2));
uninstallableSubsystems.add(s2);
stopSubsystem(s1);
stoppableSubsystems.remove(s1);
uninstallSubsystem(s1);
uninstallableSubsystems.remove(s1);
getSystemBundleAsFrameworkWiring().refreshBundles(null, (FrameworkListener)null);
try {
s2.start();
stoppableSubsystems.add(s2);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have started");
}
// Test the effective:=active service capability and requirement. Bundle
// D should have had a reference count of 2 and not uninstalled as part
// of S1. Because effective:=active does not effect runtime resolution,
// we must ensure it is still a constituent of root.
assertConstituent(root, "d");
}
private InputStream buildSubsystem(Subsystem parent, String symbolicName, String type) throws IOException {
SubsystemArchiveBuilder builder = new SubsystemArchiveBuilder();
builder.symbolicName(symbolicName);
builder.type(type);
if (SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE.equals(type)) {
builder.importPackage("b.package");
}
builder.bundle(
"a",
new BundleArchiveBuilder()
.symbolicName("a")
.importPackage("b.package")
.build());
return builder.build();
}
}
| 8,762 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1381Test.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.subsystem.itests.defect;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
/*
* https://issues.apache.org/jira/browse/ARIES-1368
*
* java.lang.ClassCastException: org.apache.aries.subsystem.core.archive.GenericDirective
* cannot be cast to org.apache.aries.subsystem.core.archive.VersionRangeAttribute
*/
public class Aries1381Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: composite.a.esa
* Import-Package: foo;version:="[5.0,6.0)",z;version="2.3";version:="3.2"
*
* Included in archive:
* bundle.b.jar
* bundle.c.jar
*/
private static final String COMPOSITE_A = "composite.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Export-Package: foo,z;version=2.3"
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Export-Package: x,y;version=1.5
*/
private static final String BUNDLE_B = "bundle.b.jar";
/*
* Bundle-SymbolicName: bundle.c.jar
* Import-Package: x;version:="[5.0,6.0)",y;version="[1.5,2.0)";version:="[1.0,1.5)"
*/
private static final String BUNDLE_C = "bundle.c.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createBundleB();
createBundleC();
createCompositeA();
createdTestFiles = true;
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), exportPackage("foo,z;version=2.3"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), exportPackage("x,y;version=1.5"));
}
private void createBundleC() throws IOException {
createBundle(name(BUNDLE_C), importPackage("x;version:=\"[5.0,6.0)\",y;version=\"[1.5,2.0)\";version:=\"[1.0,1.5)\""));
}
private static void createCompositeA() throws IOException {
createCompositeAManifest();
createSubsystem(COMPOSITE_A, BUNDLE_B, BUNDLE_C);
}
private static void createCompositeAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, COMPOSITE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_B + ";version=\"[0,0]\"," + BUNDLE_C + ";version=\"[0,0]\"");
attributes.put(Constants.IMPORT_PACKAGE, "foo;version:=\"[5.0,6.0)\",z;version=\"2.3\";version:=\"3.2\"");
createManifest(COMPOSITE_A + ".mf", attributes);
}
@Test
public void testVersionAttributeVerusVersionDirective() throws Exception {
Bundle bundleA = installBundleFromFile(BUNDLE_A);
try {
Subsystem compositeA = installSubsystemFromFile(COMPOSITE_A);
uninstallSubsystemSilently(compositeA);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
finally {
uninstallSilently(bundleA);
}
}
@Override
public void setUp() throws Exception {
super.setUp();
}
}
| 8,763 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1421Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.core.archive.ImportPackageHeader;
import org.apache.aries.subsystem.core.archive.RequireBundleHeader;
import org.apache.aries.subsystem.core.archive.RequireCapabilityHeader;
import org.apache.aries.subsystem.core.archive.SubsystemImportServiceHeader;
import org.apache.aries.subsystem.core.internal.BasicSubsystem;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import aQute.bnd.osgi.Constants;
/*
* https://issues.apache.org/jira/browse/ARIES-1421
*
* SimpleFilter attribute extraction can not handle version ranges.
*/
public class Aries1421Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
*
* Included In Archive
* bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Import-Package: org.osgi.framework;version="[1.7,2)",
* org.osgi.service.coordinator,
* org.osgi.service.resolver;version=1;bundle-version="[0,10)"
* Require-Bundle: org.apache.aries.subsystem;bundle-version="[1,1000)";visibility:=private;resolution:=optional,
* org.eclipse.equinox.region,
* org.eclipse.equinox.coordinator;version=1;resolution:=mandatory
* Require-Capability: osgi.service;filter:="(objectClass=foo)";effective:=active;resolution:=optional,
* osgi.service;filter:="(&(objectClass=bar)(a=b))";resolution:=optional;effective:=active
*/
private static final String BUNDLE_A = "bundle.a.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createApplicationA();
createdTestFiles = true;
}
private void createBundleA() throws IOException {
createBundle(
name(BUNDLE_A),
importPackage("org.osgi.framework;version=\"[1.7,2)\""
+ ", org.osgi.service.coordinator"
+ ", org.osgi.service.resolver;version=1;bundle-version=\"[0,10)\""),
requireBundle("org.apache.aries.subsystem;bundle-version=\"[1,1000)\""
+ ";visibility:=private;resolution:=optional,"
+ "org.eclipse.equinox.region,"
+ "org.eclipse.equinox.coordinator;bundle-version=1;resolution:=mandatory"),
requireCapability("osgi.service;filter:=\"(objectClass=foo)\";effective:=active;resolution:=optional,"
+ "osgi.service;filter:=\"(&(objectClass=bar)(a=b))\";resolution:=optional;effective:=active"));
}
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
@Test
public void testImportPackageVersionRanges() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
Bundle bundleA = getConstituentAsBundle(applicationA, BUNDLE_A, null, null);
String expectedStr = bundleA.getHeaders().get(Constants.IMPORT_PACKAGE);
ImportPackageHeader expected = new ImportPackageHeader(expectedStr);
Map<String, String> headers = ((BasicSubsystem)applicationA).getDeploymentHeaders();
String actualStr = headers.get(Constants.IMPORT_PACKAGE);
ImportPackageHeader actual = new ImportPackageHeader(actualStr);
assertEquals("Wrong header", expected, actual);
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testRequireBundleVersionRanges() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
Bundle bundleA = getConstituentAsBundle(applicationA, BUNDLE_A, null, null);
String expectedStr = bundleA.getHeaders().get(Constants.REQUIRE_BUNDLE);
RequireBundleHeader expected = new RequireBundleHeader(expectedStr);
Map<String, String> headers = ((BasicSubsystem)applicationA).getDeploymentHeaders();
String actualStr = headers.get(Constants.REQUIRE_BUNDLE);
RequireBundleHeader actual = new RequireBundleHeader(actualStr);
assertEquals("Wrong header", expected, actual);
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testSubsystemImportService() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
String expectedStr = "foo;resolution:=optional,bar;filter:=\"(a=b)\";resolution:=optional";
SubsystemImportServiceHeader expected = new SubsystemImportServiceHeader(expectedStr);
Map<String, String> headers = ((BasicSubsystem)applicationA).getDeploymentHeaders();
String actualStr = headers.get(SubsystemConstants.SUBSYSTEM_IMPORTSERVICE);
SubsystemImportServiceHeader actual = new SubsystemImportServiceHeader(actualStr);
assertEquals("Wrong header", expected, actual);
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testRequireCapability() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
Bundle bundleA = getConstituentAsBundle(applicationA, BUNDLE_A, null, null);
String expectedStr = bundleA.getHeaders().get(Constants.REQUIRE_CAPABILITY);
RequireCapabilityHeader expected = new RequireCapabilityHeader(expectedStr);
Map<String, String> headers = ((BasicSubsystem)applicationA).getDeploymentHeaders();
String actualStr = headers.get(Constants.REQUIRE_CAPABILITY);
RequireCapabilityHeader actual = new RequireCapabilityHeader(actualStr);
assertEquals("Wrong header", expected, actual);
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
}
| 8,764 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1522Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileWriter;
import java.net.URL;
import org.apache.aries.subsystem.core.archive.AriesProvisionDependenciesDirective;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.SubsystemArchiveBuilder;
import org.apache.felix.bundlerepository.DataModelHelper;
import org.apache.felix.bundlerepository.Repository;
import org.apache.felix.bundlerepository.RepositoryAdmin;
import org.apache.felix.bundlerepository.Resource;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
public class Aries1522Test extends SubsystemTest {
private RepositoryAdmin repositoryAdmin;
private URL url;
@Override
public void setUp() throws Exception {
super.setUp();
BundleContext context = context();
ServiceReference<RepositoryAdmin> ref = context.getServiceReference(RepositoryAdmin.class);
assertNotNull("The RepositoryAdmin service does not exist", ref);
try {
repositoryAdmin = (RepositoryAdmin)context.getService(ref);
DataModelHelper helper = repositoryAdmin.getHelper();
url = createRepositoryXml(helper);
Repository repository = repositoryAdmin.addRepository(url);
Resource resource = repository.getResources()[0];
System.out.println(resource.getURI());
}
finally {
context.ungetService(ref);
}
}
@Override
public void tearDown() throws Exception {
repositoryAdmin.removeRepository(url.toString());
super.tearDown();
}
@Test
public void testApacheAriesProvisionDependenciesInstall() throws Exception {
test(AriesProvisionDependenciesDirective.INSTALL);
}
@Test
public void testApacheAriesProvisionDependenciesResolve() throws Exception {
test(AriesProvisionDependenciesDirective.RESOLVE);
}
private void test(AriesProvisionDependenciesDirective provisionDependencies) throws Exception {
boolean flag = AriesProvisionDependenciesDirective.INSTALL.equals(provisionDependencies);
Subsystem root = getRootSubsystem();
try {
Subsystem subsystem = installSubsystem(
root,
"subsystem",
new SubsystemArchiveBuilder()
.symbolicName("subsystem")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ provisionDependencies.toString())
.content("org.apache.aries.subsystem.itests.aries1523host,org.apache.aries.subsystem.itests.aries1523fragment")
.bundle(
"aries1523host",
getClass().getClassLoader().getResourceAsStream("aries1523/aries1523host.jar"))
.build(),
flag
);
try {
startSubsystem(subsystem, flag);
stopSubsystem(subsystem);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have started");
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
private URL createRepositoryXml(DataModelHelper helper) throws Exception {
File dir;
String cwd = new File("").getAbsolutePath();
if (cwd.endsWith(File.separator + "target")) {
dir = new File("test-classes/aries1523");
}
else {
dir = new File("target/test-classes/aries1523");
}
File jar = new File(dir, "aries1523fragment.jar");
assertTrue("The fragment jar does not exist: " + jar.getAbsolutePath(), jar.exists());
Resource resource = helper.createResource(jar.toURI().toURL());
Repository repository = helper.repository(new Resource[] {resource});
File file = new File(dir, "repository.xml");
FileWriter fw = new FileWriter(file);
try {
helper.writeRepository(repository, fw);
return file.toURI().toURL();
}
finally {
fw.close();
}
}
}
| 8,765 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1523Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileWriter;
import java.net.URL;
import org.apache.aries.subsystem.core.archive.AriesProvisionDependenciesDirective;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.SubsystemArchiveBuilder;
import org.apache.felix.bundlerepository.DataModelHelper;
import org.apache.felix.bundlerepository.Repository;
import org.apache.felix.bundlerepository.RepositoryAdmin;
import org.apache.felix.bundlerepository.Resource;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
public class Aries1523Test extends SubsystemTest {
private RepositoryAdmin repositoryAdmin;
private URL url;
@Override
public void setUp() throws Exception {
super.setUp();
BundleContext context = context();
ServiceReference<RepositoryAdmin> ref = context.getServiceReference(RepositoryAdmin.class);
assertNotNull("The RepositoryAdmin service does not exist", ref);
try {
repositoryAdmin = (RepositoryAdmin)context.getService(ref);
DataModelHelper helper = repositoryAdmin.getHelper();
url = createRepositoryXml(helper);
Repository repository = repositoryAdmin.addRepository(url);
Resource resource = repository.getResources()[0];
System.out.println(resource.getURI());
}
finally {
context.ungetService(ref);
}
}
@Override
public void tearDown() throws Exception {
repositoryAdmin.removeRepository(url.toString());
super.tearDown();
}
@Test
public void testApacheAriesProvisionDependenciesInstall() throws Exception {
test(AriesProvisionDependenciesDirective.INSTALL);
}
@Test
public void testApacheAriesProvisionDependenciesResolve() throws Exception {
test(AriesProvisionDependenciesDirective.RESOLVE);
}
private void test(AriesProvisionDependenciesDirective provisionDependencies) throws Exception {
boolean flag = AriesProvisionDependenciesDirective.INSTALL.equals(provisionDependencies);
Subsystem root = getRootSubsystem();
try {
Subsystem subsystem = installSubsystem(
root,
"subsystem",
new SubsystemArchiveBuilder()
.symbolicName("subsystem")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ provisionDependencies.toString())
.content("org.apache.aries.subsystem.itests.aries1523host,org.apache.aries.subsystem.itests.aries1523fragment")
.bundle(
"aries1523fragment",
getClass().getClassLoader().getResourceAsStream("aries1523/aries1523fragment.jar"))
.build(),
flag
);
try {
startSubsystem(subsystem, flag);
stopSubsystem(subsystem);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have started");
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
private URL createRepositoryXml(DataModelHelper helper) throws Exception {
File dir;
String cwd = new File("").getAbsolutePath();
if (cwd.endsWith(File.separator + "target")) {
dir = new File("test-classes/aries1523");
}
else {
dir = new File("target/test-classes/aries1523");
}
File jar = new File(dir, "aries1523host.jar");
assertTrue("The host jar does not exist: " + jar.getAbsolutePath(), jar.exists());
Resource resource = helper.createResource(jar.toURI().toURL());
Repository repository = helper.repository(new Resource[] {resource});
File file = new File(dir, "repository.xml");
FileWriter fw = new FileWriter(file);
try {
helper.writeRepository(repository, fw);
return file.toURI().toURL();
}
finally {
fw.close();
}
}
}
| 8,766 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1441Test.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.subsystem.itests.defect;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.BundleArchiveBuilder;
import org.apache.aries.subsystem.itests.util.SubsystemArchiveBuilder;
import org.junit.Test;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
@ExamReactorStrategy(PerMethod.class)
public class Aries1441Test extends SubsystemTest {
@Test
public void testApplication() throws Exception {
test(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION);
}
@Test
public void testComposite() throws Exception {
test(SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
}
@Test
public void testFeature() throws Exception {
test(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
}
private void test(String type) throws Exception {
SubsystemArchiveBuilder builder = new SubsystemArchiveBuilder()
.symbolicName("subsystem")
.type(type)
.content("a;version=\"[0,0]\"")
.bundle(
"a",
new BundleArchiveBuilder()
.symbolicName("a")
.importPackage("org.osgi.framework")
.importPackage("b")
.build()
)
.bundle(
"b",
new BundleArchiveBuilder()
.symbolicName("b")
.exportPackage("b")
.build()
);
if (SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE.equals(type)) {
builder.importPackage("org.osgi.framework,b");
}
Subsystem root = getRootSubsystem();
Subsystem subsystem = installSubsystem(root, "subsystem", builder.build());
uninstallableSubsystems.add(subsystem);
startSubsystem(subsystem);
stoppableSubsystems.add(subsystem);
Bundle core = getSubsystemCoreBundle();
core.stop();
stoppableSubsystems.remove(subsystem);
uninstallableSubsystems.remove(subsystem);
assertBundleState(getSystemBundle(), org.osgi.framework.Bundle.ACTIVE);
core.start();
root = getRootSubsystem();
subsystem = getChild(root, "subsystem", null, type);
stopSubsystem(subsystem);
assertBundleState(Bundle.RESOLVED, "b", root);
uninstallSubsystem(subsystem);
assertNotConstituent(root, "b");
}
}
| 8,767 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1408Test.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.subsystem.itests.defect;
import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.apache.aries.subsystem.itests.Header;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.TestCapability;
import org.apache.aries.subsystem.itests.util.TestRepository;
import org.apache.aries.subsystem.itests.util.TestRepositoryContent;
import org.apache.aries.subsystem.itests.util.TestRequirement;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Resource;
import org.osgi.service.repository.Repository;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
/*
* https://issues.apache.org/jira/browse/ARIES-1408
*
* The RequireCapabilityHeader currently only supports requirements defined by
* the Aries implementation
*/
public class Aries1408Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Require-Capability: foo
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Provide-Capability: foo
*/
private static final String BUNDLE_B = "bundle.b.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleB();
createApplicationA();
createdTestFiles = true;
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), new Header(Constants.PROVIDE_CAPABILITY, "foo;foo=bar"));
}
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
@Test
public void testRequirementFromRemoteRepositoryConvertsToRequireCapability() throws Exception {
Bundle bundleB = installBundleFromFile(BUNDLE_B);
try {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
uninstallSubsystemSilently(applicationA);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
finally {
uninstallSilently(bundleB);
}
}
@Override
public void setUp() throws Exception {
super.setUp();
try {
serviceRegistrations.add(
bundleContext.registerService(
Repository.class,
createTestRepository(),
null));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
private byte[] createBundleAContent() throws IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_A);
manifest.getMainAttributes().putValue(Constants.REQUIRE_CAPABILITY, "foo;filter:=\'(foo=bar)\"");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jos = new JarOutputStream(baos, manifest);
jos.close();
return baos.toByteArray();
}
private Resource createBundleAResource() throws IOException {
return new TestRepositoryContent.Builder()
.capability(
new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(IdentityNamespace.IDENTITY_NAMESPACE, BUNDLE_A)
.attribute(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE, Version.emptyVersion)
.attribute(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, IdentityNamespace.TYPE_BUNDLE))
.requirement(
new TestRequirement.Builder()
.namespace("foo")
.directive(Constants.FILTER_DIRECTIVE, "(foo=bar)"))
.content(createBundleAContent())
.build();
}
private Repository createTestRepository() throws IOException {
return new TestRepository.Builder()
.resource(createBundleAResource())
.build();
}
}
| 8,768 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1084Test.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.subsystem.itests.defect;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.apache.aries.subsystem.core.archive.DeploymentManifest;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.TestCapability;
import org.apache.aries.subsystem.itests.util.TestRepository;
import org.apache.aries.subsystem.itests.util.TestRepositoryContent;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Resource;
import org.osgi.service.repository.Repository;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* https://issues.apache.org/jira/browse/ARIES-1084
*
* Subsystem : Failure on restart after framework crash
*/
public class Aries1084Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: feature.a.esa
* Subsystem-Content: bundle.a.jar
*
* Included in archive:
* bundle.a.jar
*/
private static final String FEATURE_A = "feature.a.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
*/
private static final String BUNDLE_A = "bundle.a.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createFeatureA();
createdTestFiles = true;
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A));
}
private void createFeatureA() throws IOException {
createFeatureAManifest();
createSubsystem(FEATURE_A, BUNDLE_A);
}
private void createFeatureAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, FEATURE_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A);
createManifest(FEATURE_A + ".mf", attributes);
}
@Test
public void testBundleStartsWhenSubsystemLeftInInvalidState() throws Exception {
Subsystem featureA = installSubsystemFromFile(FEATURE_A);
try {
startSubsystem(featureA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureA);
Bundle core = getSubsystemCoreBundle();
File file = core.getBundleContext().getDataFile(
featureA.getSubsystemId() + "/OSGI-INF/DEPLOYMENT.MF");
core.stop();
DeploymentManifest manifest = new DeploymentManifest(file);
FileOutputStream fos = new FileOutputStream(file);
try {
new DeploymentManifest.Builder()
.manifest(manifest)
.state(Subsystem.State.ACTIVE)
.build()
.write(fos);
}
finally {
fos.close();
}
core.start();
featureA = getChild(getRootSubsystem(), FEATURE_A);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, featureA);
}
finally {
stopAndUninstallSubsystemSilently(featureA);
}
}
private Repository createTestRepository() throws IOException {
return new TestRepository.Builder()
.resource(createBundleAResource())
.build();
}
private byte[] createBundleAContent() throws IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_A);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jos = new JarOutputStream(baos, manifest);
jos.close();
return baos.toByteArray();
}
private Resource createBundleAResource() throws IOException {
return new TestRepositoryContent.Builder()
.capability(
new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(IdentityNamespace.IDENTITY_NAMESPACE, BUNDLE_A))
.content(createBundleAContent())
.build();
}
@Override
public void setUp() throws Exception {
super.setUp();
try {
serviceRegistrations.add(
bundleContext.registerService(
Repository.class,
createTestRepository(),
null));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 8,769 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1538Test.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.subsystem.itests.defect;
import static org.junit.Assert.fail;
import org.apache.aries.subsystem.core.archive.AriesProvisionDependenciesDirective;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.BundleArchiveBuilder;
import org.apache.aries.subsystem.itests.util.SubsystemArchiveBuilder;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
public class Aries1538Test extends SubsystemTest {
@Test
public void testEffectiveActiveApacheAriesProvisionDependenciesInstall() throws Exception {
testEffectiveActive(AriesProvisionDependenciesDirective.INSTALL);
}
@Test
public void testEffectiveActiveApacheAriesProvisionDependenciesResolve() throws Exception {
testEffectiveActive(AriesProvisionDependenciesDirective.RESOLVE);
}
@Test
public void testSubstitutableExportApacheAriesProvisionDependenciesInstall() throws Exception {
testSubstitutableExport(AriesProvisionDependenciesDirective.INSTALL);
}
@Test
public void testSubstituableExportApacheAriesProvisionDependenciesResolve() throws Exception {
testSubstitutableExport(AriesProvisionDependenciesDirective.RESOLVE);
}
@Test
public void testHostFragmentCircularDependencyApacheAriesProvisionDependenciesInstall() throws Exception {
testHostFragmentCircularDependency(AriesProvisionDependenciesDirective.INSTALL);
}
@Test
public void testHostFragmentCircularDependencyApacheAriesProvisionDependenciesResolve() throws Exception {
testHostFragmentCircularDependency(AriesProvisionDependenciesDirective.RESOLVE);
}
private void testEffectiveActive(AriesProvisionDependenciesDirective provisionDependencies) throws Exception {
boolean flag = AriesProvisionDependenciesDirective.INSTALL.equals(provisionDependencies);
BundleArchiveBuilder bab = new BundleArchiveBuilder();
bab.symbolicName("bundle");
bab.requireCapability("osgi.service;filter:=\"(&(objectClass=java.lang.Object)(foo=bar))\";effective:=active");
bab.exportPackage("foo");
Subsystem root = getRootSubsystem();
Bundle a = root.getBundleContext().installBundle(
"a",
bab.build());
uninstallableBundles.add(a);
startBundle(a);
try {
Subsystem subsystem = installSubsystem(
root,
"subsystem",
new SubsystemArchiveBuilder()
.symbolicName("subsystem")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ provisionDependencies.toString())
.bundle(
"b",
new BundleArchiveBuilder()
.symbolicName("b")
.importPackage("foo")
.build())
.build(),
flag
);
uninstallableSubsystems.add(subsystem);
startSubsystem(subsystem, flag);
stoppableSubsystems.add(subsystem);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed and started");
}
}
private void testSubstitutableExport(AriesProvisionDependenciesDirective provisionDependencies) throws Exception {
boolean flag = AriesProvisionDependenciesDirective.INSTALL.equals(provisionDependencies);
BundleArchiveBuilder hostBuilder = new BundleArchiveBuilder();
hostBuilder.symbolicName("host");
BundleArchiveBuilder fragmentBuilder = new BundleArchiveBuilder();
fragmentBuilder.symbolicName("fragment");
fragmentBuilder.exportPackage("foo");
fragmentBuilder.importPackage("foo");
fragmentBuilder.header("Fragment-Host", "host");
Subsystem root = getRootSubsystem();
Bundle host = root.getBundleContext().installBundle(
"host",
hostBuilder.build());
uninstallableBundles.add(host);
Bundle fragment = root.getBundleContext().installBundle(
"fragment",
fragmentBuilder.build());
uninstallableBundles.add(fragment);
startBundle(host);
try {
Subsystem subsystem = installSubsystem(
root,
"subsystem",
new SubsystemArchiveBuilder()
.symbolicName("subsystem")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ provisionDependencies.toString())
.bundle(
"a",
new BundleArchiveBuilder()
.symbolicName("a")
.importPackage("foo")
.build())
.build(),
flag
);
uninstallableSubsystems.add(subsystem);
startSubsystem(subsystem, flag);
stoppableSubsystems.add(subsystem);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed and started");
}
}
private void testHostFragmentCircularDependency(AriesProvisionDependenciesDirective provisionDependencies) throws Exception {
boolean flag = AriesProvisionDependenciesDirective.INSTALL.equals(provisionDependencies);
BundleArchiveBuilder hostBuilder = new BundleArchiveBuilder();
hostBuilder.symbolicName("host");
hostBuilder.exportPackage("foo");
hostBuilder.importPackage("bar");
BundleArchiveBuilder fragmentBuilder = new BundleArchiveBuilder();
fragmentBuilder.symbolicName("fragment");
fragmentBuilder.exportPackage("bar");
fragmentBuilder.importPackage("foo");
fragmentBuilder.header("Fragment-Host", "host");
Subsystem root = getRootSubsystem();
Bundle host = root.getBundleContext().installBundle(
"host",
hostBuilder.build());
uninstallableBundles.add(host);
Bundle fragment = root.getBundleContext().installBundle(
"fragment",
fragmentBuilder.build());
uninstallableBundles.add(fragment);
startBundle(host);
try {
Subsystem subsystem = installSubsystem(
root,
"subsystem",
new SubsystemArchiveBuilder()
.symbolicName("subsystem")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ provisionDependencies.toString())
.bundle(
"a",
new BundleArchiveBuilder()
.symbolicName("a")
.importPackage("foo")
.build())
.build(),
flag
);
uninstallableSubsystems.add(subsystem);
startSubsystem(subsystem, flag);
stoppableSubsystems.add(subsystem);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed and started");
}
}
}
| 8,770 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1404Test.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.subsystem.itests.defect;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.itests.Header;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
/*
* https://issues.apache.org/jira/browse/ARIES-1404
*
* Restart of the osgi container does not restart subsystem core because of an
* error related to missing resource
* org.apache.aries.subsystem.resource.synthesized.
*/
public class Aries1404Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: application.b.esa
* Subsystem-Content: bundle.b.jar
* Application-ImportService: b
*/
private static final String APPLICATION_B = "application.b.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Require-Capability: a;resolution:=optional
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Require-Capability: osgi.service;filter:="(objectClass=b)"
*/
private static final String BUNDLE_B = "bundle.b.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createBundleB();
createApplicationA();
createApplicationB();
createdTestFiles = true;
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), new Header(Constants.REQUIRE_CAPABILITY, "a;resolution:=optional"));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), new Header(Constants.REQUIRE_CAPABILITY, "osgi.service;filter:=\"(objectClass=b)\""));
}
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private static void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B, BUNDLE_B);
}
private static void createApplicationBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
attributes.put("Application-ImportService", "b");
createManifest(APPLICATION_B + ".mf", attributes);
}
@Test
public void testProvisionedSyntheticResourceWithOptionalRequirement() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
try {
restartSubsystemsImplBundle();
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Core bundle should have restarted");
}
}
finally {
stopAndUninstallSubsystemSilently(applicationA);
}
}
@Test
public void testProvisionedSyntheticResourceWithMandatoryRequirementAndApplicationImportService() throws Exception {
Subsystem applicationB = installSubsystemFromFile(APPLICATION_B);
try {
try {
restartSubsystemsImplBundle();
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Core bundle should have restarted");
}
}
finally {
stopAndUninstallSubsystemSilently(applicationB);
}
}
}
| 8,771 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1419Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.subsystem.core.archive.RequireCapabilityHeader;
import org.apache.aries.subsystem.core.internal.BasicSubsystem;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
import aQute.bnd.osgi.Constants;
/*
* https://issues.apache.org/jira/browse/ARIES-1419
*
* Provide-Capability header parser does not support typed attributes.
*/
public class Aries1419Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
*
* Included In Archive
* bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: application.b.esa
*
* Included In Archive
* bundle.c.jar
*/
private static final String APPLICATION_B = "application.b.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Require-Capability: "a;resolution:=optional;filter:=\"(b=c)\";d=e;
* f:String=g;h:Long=21474836470;i:Double=3.4028234663852886E39;
* j:Version=2.1;k:List=\"foo,bar,acme\";l:List<Version>=\"1.1,2.2,3.3\""
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Provide-Capability: "a;d=e;f:String=g;h:Long=21474836470;
* i:Double=3.4028234663852886E39;j:Version=2.1;k:List=\"foo,bar,acme\";
* l:List<Version>=\"1.1,2.2,3.3\""
*/
private static final String BUNDLE_B = "bundle.b.jar";
/*
* Bundle-SymbolicName: bundle.c.jar
* Require-Capability: "a;filter:="(d=e)"
*/
private static final String BUNDLE_C = "bundle.c.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createBundleB();
createBundleC();
createApplicationA();
createApplicationB();
createdTestFiles = true;
}
private void createBundleA() throws IOException {
createBundle(
name(BUNDLE_A),
requireCapability("a;resolution:=optional;filter:=\"(b=c)\""
+ ";d=e;f:String=g;h:Long=21474836470;i:Double=3.4028234663852886E39"
+ ";j:Version=2.1;k:List=\"foo,bar,acme\";l:List<Version>=\"1.1,2.2,3.3\""));
}
private void createBundleB() throws IOException {
createBundle(
name(BUNDLE_B),
provideCapability("a;b=c;d=e;f:String=g;h:Long=21474836470"
+ ";i:Double=3.4028234663852886E39;j:Version=2.1;"
+ "k:List=\"foo,bar,acme\";l:List<Version>=\"1.1,2.2,3.3\""));
}
private void createBundleC() throws IOException {
createBundle(
name(BUNDLE_C),
requireCapability("a;filter:=\"(&(b=c)(d=e)(f=g)(h<=21474836470)"
+ "(!(i>=3.4028234663852886E40))(&(j>=2)(!(version>=3)))"
+ "(|(k=foo)(k=bar)(k=acme))(&(l=1.1.0)(l=2.2)))\""));
}
private static void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private static void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
createManifest(APPLICATION_A + ".mf", attributes);
}
private static void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B, BUNDLE_C);
}
private static void createApplicationBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
createManifest(APPLICATION_B + ".mf", attributes);
}
@Test
public void testRequireCapability() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
Bundle bundleA = getConstituentAsBundle(applicationA, BUNDLE_A, null, null);
String expectedStr = bundleA.getHeaders().get(Constants.REQUIRE_CAPABILITY);
RequireCapabilityHeader expected = new RequireCapabilityHeader(expectedStr);
Map<String, String> headers = ((BasicSubsystem)applicationA).getDeploymentHeaders();
String actualStr = headers.get(Constants.REQUIRE_CAPABILITY);
RequireCapabilityHeader actual = new RequireCapabilityHeader(actualStr);
assertEquals("Wrong header", expected, actual);
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testProvideCapability() throws Exception {
Bundle bundleB = installBundleFromFile(BUNDLE_B);
try {
Subsystem applicationB = installSubsystemFromFile(APPLICATION_B);
uninstallSubsystemSilently(applicationB);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
finally {
uninstallSilently(bundleB);
}
}
}
| 8,772 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1451Test.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.subsystem.itests.defect;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.TestCapability;
import org.apache.aries.subsystem.itests.util.TestRepository;
import org.apache.aries.subsystem.itests.util.TestRequirement;
import org.apache.aries.subsystem.itests.util.TestResource;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Constants;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.resource.Resource;
import org.osgi.service.repository.Repository;
import org.osgi.service.repository.RepositoryContent;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class Aries1451Test extends SubsystemTest {
private static final String APPLICATION_A = "application.a.esa";
private static final String BUNDLE_A = "bundle.a.jar";
private static final String BUNDLE_B = "bundle.b.jar";
private static final String PACKAGE_REQUIREMENT = "org.apache.aries.test.bundlebrequirement";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createApplicationA();
createdTestFiles = true;
//set up repository to satisfy BUNDLE_A's package requirement for a package in BUNDLE_B use
// a RepositoryContent test with implementation that is private.
try {
serviceRegistrations.add(
bundleContext.registerService(
Repository.class,
createTestRepository(),
null));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), importPackage(PACKAGE_REQUIREMENT));
}
private void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A + ";type=osgi.bundle");
createManifest(APPLICATION_A + ".mf", attributes);
}
@Test
public void testInstallWithAccessProtectedRepository() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
startSubsystem(applicationA);
}
finally {
stopAndUninstallSubsystemSilently(applicationA);
}
}
private Repository createTestRepository() throws IOException {
return new TestRepository.Builder()
.resource(createTestBundleResource())
.build();
}
private byte[] createTestBundleContent() throws IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, BUNDLE_B);
manifest.getMainAttributes().putValue(Constants.EXPORT_PACKAGE, PACKAGE_REQUIREMENT);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jos = new JarOutputStream(baos, manifest);
jos.close();
return baos.toByteArray();
}
//This resource must have private visibility for the test
private Resource createTestBundleResource() throws IOException {
List<TestCapability.Builder> capabilities = new ArrayList<TestCapability.Builder>() {
private static final long serialVersionUID = 1L;
{
add(new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(IdentityNamespace.IDENTITY_NAMESPACE, BUNDLE_B)
.attribute(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, IdentityNamespace.TYPE_BUNDLE));
add(new TestCapability.Builder()
.namespace(PackageNamespace.PACKAGE_NAMESPACE)
.attribute(PackageNamespace.PACKAGE_NAMESPACE, PACKAGE_REQUIREMENT)
.attribute(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE, "0.0.0"));
}
};
return new PrivateRepositoryContent(capabilities, Collections.<TestRequirement.Builder>emptyList(),
createTestBundleContent());
}
private class PrivateRepositoryContent extends TestResource implements RepositoryContent {
private final byte[] content;
public PrivateRepositoryContent(List<TestCapability.Builder> capabilities,
List<TestRequirement.Builder> requirements, byte[] content) {
super(capabilities, requirements);
this.content = content;
}
@Override
public InputStream getContent() {
try {
return new ByteArrayInputStream(content);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| 8,773 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1426Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.util.Collection;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import org.apache.aries.subsystem.core.archive.GenericHeader;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.coordinator.Coordinator;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* https://issues.apache.org/jira/browse/ARIES-1426
*
* Implementation specific subsystem header Application-ImportService should not
* affect the sharing policy.
*/
public class Aries1426Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Application-ImportService: org.osgi.service.coordinator.Coordinator
*
* Included In Archive
* bundle.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: application.b.esa
*
* Included In Archive
* bundle.b.jar
*/
private static final String APPLICATION_B = "application.b.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
* Require-Capability: osgi.service;filter:="(objectClass=org.osgi.service.coordinator.Coordinator)"
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: bundle.b.jar
* Require-Capability: osgi.service;filter:="(&(objectClass=java.lang.Object)(a=b))";resolution:=optional
*/
private static final String BUNDLE_B = "bundle.b.jar";
private void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A);
}
private void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put("Application-ImportService", "org.osgi.service.coordinator.Coordinator");
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B, BUNDLE_B);
}
private void createApplicationBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
createManifest(APPLICATION_B + ".mf", attributes);
}
@Override
public void createApplications() throws Exception {
createBundleA();
createBundleB();
createApplicationA();
createApplicationB();
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A), requireCapability("osgi.service;"
+ "filter:=\"(objectClass=org.osgi.service.coordinator.Coordinator)\""));
}
private void createBundleB() throws IOException {
createBundle(name(BUNDLE_B), requireCapability("osgi.service;"
+ "filter:=\"(&(objectClass=java.lang.Object)(a=b))\";resolution:=optional"));
}
@Test
public void testNoEffectOnSharingPolicy() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
Map<String, String> headers = applicationA.getDeploymentHeaders();
// There should be no subsystem Require-Capability header because
// the Application-ImportService header included the only relevant
// bundle clause.
assertNull("Wrong Require-Capability", headers.get(Constants.REQUIRE_CAPABILITY));
// There should be no subsystem Subsystem-ImportService header
// because the Application-ImportService header included the only
// relevant bundle clause.
assertNull("Wrong Subsystem-ImportService", headers.get(SubsystemConstants.SUBSYSTEM_IMPORTSERVICE));
org.apache.aries.subsystem.core.archive.Header<?> expected =
new SubsystemContentHeader("bundle.a.jar;version=\"[0,0]\"");
org.apache.aries.subsystem.core.archive.Header<?> actual =
new SubsystemContentHeader(headers.get(SubsystemConstants.SUBSYSTEM_CONTENT));
// The Subsystem-Content header should not include any synthesized
// resources used to process Application-ImportService.
assertEquals("Wrong Subsystem-Content", expected, actual);
expected = new GenericHeader("Application-ImportService", "org.osgi.service.coordinator.Coordinator");
actual = new GenericHeader("Application-ImportService", headers.get("Application-ImportService"));
// The Application-ImportService header should be included in the
// deployment manifest.
assertEquals("Wrong Application-ImportService", expected, actual);
BundleContext context = applicationA.getBundleContext();
// The Coordinator service should not be visible to the application
// region because Application-ImportService does not affect the
// sharing policy and nothing outside of the subsystems
// implementation made it visible.
assertNull("Coordinator service should not be visible", context.getServiceReference(Coordinator.class));
}
finally {
uninstallSubsystemSilently(applicationA);
}
}
@Test
public void testIncludeUnsatisfiedOptionalServiceDependencyInSharingPolicy() throws Exception {
Subsystem applicationB = installSubsystemFromFile(APPLICATION_B);
try {
BundleContext context = getRootSubsystem().getBundleContext();
Dictionary<String, String> properties = new Hashtable<String, String>();
properties.put("a", "b");
ServiceRegistration<Object> registration = context.registerService(Object.class, new Object(), properties);
try {
context = applicationB.getBundleContext();
Collection<ServiceReference<Object>> references = context.getServiceReferences(Object.class, "(a=b)");
assertFalse("Service not visible", references.isEmpty());
}
finally {
registration.unregister();
}
}
finally {
uninstallSubsystemSilently(applicationB);
}
}
}
| 8,774 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1608Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileWriter;
import java.net.URL;
import org.apache.aries.subsystem.core.archive.AriesProvisionDependenciesDirective;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.SubsystemArchiveBuilder;
import org.apache.felix.bundlerepository.DataModelHelper;
import org.apache.felix.bundlerepository.Repository;
import org.apache.felix.bundlerepository.RepositoryAdmin;
import org.apache.felix.bundlerepository.Resource;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
public class Aries1608Test extends SubsystemTest {
private RepositoryAdmin repositoryAdmin;
private URL url;
@Override
public void setUp() throws Exception {
super.setUp();
BundleContext context = context();
ServiceReference<RepositoryAdmin> ref = context.getServiceReference(RepositoryAdmin.class);
assertNotNull("The RepositoryAdmin service does not exist", ref);
try {
repositoryAdmin = (RepositoryAdmin)context.getService(ref);
DataModelHelper helper = repositoryAdmin.getHelper();
url = createRepositoryXml(helper);
Repository repository = repositoryAdmin.addRepository(url);
Resource resource = repository.getResources()[0];
System.out.println(resource.getURI());
}
finally {
context.ungetService(ref);
}
}
@Override
public void tearDown() throws Exception {
repositoryAdmin.removeRepository(url.toString());
super.tearDown();
}
@Test
public void testApacheAriesProvisionDependenciesInstall() throws Exception {
test(AriesProvisionDependenciesDirective.INSTALL);
}
@Test
public void testApacheAriesProvisionDependenciesResolve() throws Exception {
test(AriesProvisionDependenciesDirective.RESOLVE);
}
private void test(AriesProvisionDependenciesDirective provisionDependencies) throws Exception {
boolean flag = AriesProvisionDependenciesDirective.INSTALL.equals(provisionDependencies);
Subsystem root = getRootSubsystem();
try {
Subsystem subsystem = installSubsystem(
root,
"subsystem",
new SubsystemArchiveBuilder()
.symbolicName("subsystem")
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION + ';'
+ provisionDependencies.toString())
.content("org.apache.aries.subsystem.itests.aries1608provider,org.apache.aries.subsystem.itests.aries1608required")
.bundle(
"aries1608required",
getClass().getClassLoader().getResourceAsStream("aries1608/aries1608required.jar"))
.build(),
flag
);
try {
startSubsystem(subsystem, flag);
stopSubsystem(subsystem);
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have started");
}
finally {
uninstallSubsystemSilently(subsystem);
}
}
catch (SubsystemException e) {
e.printStackTrace();
fail("Subsystem should have installed");
}
}
private URL createRepositoryXml(DataModelHelper helper) throws Exception {
File dir;
String cwd = new File("").getAbsolutePath();
if (cwd.endsWith(File.separator + "target")) {
dir = new File("test-classes/aries1608");
}
else {
dir = new File("target/test-classes/aries1608");
}
File jar = new File(dir, "aries1608provider.jar");
assertTrue("The bundle jar does not exist: " + jar.getAbsolutePath(), jar.exists());
Resource resource = helper.createResource(jar.toURI().toURL());
Repository repository = helper.repository(new Resource[] {resource});
File file = new File(dir, "repository.xml");
FileWriter fw = new FileWriter(file);
try {
helper.writeRepository(repository, fw);
return file.toURI().toURL();
}
finally {
fw.close();
}
}
}
| 8,775 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/defect/Aries1368Test.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.subsystem.itests.defect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.apache.aries.subsystem.itests.Header;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.apache.aries.subsystem.itests.util.TestCapability;
import org.apache.aries.subsystem.itests.util.TestRepository;
import org.apache.aries.subsystem.itests.util.TestRepositoryContent;
import org.apache.aries.subsystem.itests.util.TestRequirement;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.framework.namespace.HostNamespace;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Capability;
import org.osgi.resource.Resource;
import org.osgi.service.repository.Repository;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* https://issues.apache.org/jira/browse/ARIES-1368
*
* Fragment resources receive the osgi.identity capability type of osgi.bundle but should receive osgi.fragment.
* Also, osgi.wiring.host capabilities and requirements are not computed for bundle or fragment resources.
*/
public class Aries1368Test extends SubsystemTest {
/*
* Subsystem-SymbolicName: application.a.esa
* Subsystem-Content: bundle.a.jar;type=osgi.bundle, fragment.a.jar;type=osgi.fragment
*
* Included in archive:
* bundle.a.jar
* fragment.a.jar
*/
private static final String APPLICATION_A = "application.a.esa";
/*
* Subsystem-SymbolicName: application.b.esa
* Subsystem-Content: bundle.a.jar;type=osgi.bundle, fragment.a.jar;type=osgi.fragment
*
* Included in archive:
* bundle.a.jar
*
* Included in remote repository:
* fragment.a.jar
*/
private static final String APPLICATION_B = "application.b.esa";
/*
* Bundle-SymbolicName: bundle.a.jar
*/
private static final String BUNDLE_A = "bundle.a.jar";
/*
* Bundle-SymbolicName: fragment.a.jar
* Fragment-Host: bundle.a.jar
*/
private static final String FRAGMENT_A = "fragment.a.jar";
private static boolean createdTestFiles;
@Before
public void createTestFiles() throws Exception {
if (createdTestFiles)
return;
createBundleA();
createFragmentA();
createApplicationA();
createApplicationB();
createdTestFiles = true;
}
private void createBundleA() throws IOException {
createBundle(name(BUNDLE_A));
}
private void createFragmentA() throws IOException {
createBundle(name(FRAGMENT_A), new Header(Constants.FRAGMENT_HOST, BUNDLE_A));
}
private void createApplicationA() throws IOException {
createApplicationAManifest();
createSubsystem(APPLICATION_A, BUNDLE_A, FRAGMENT_A);
}
private void createApplicationAManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A + ";type=osgi.bundle," + FRAGMENT_A + ";type=osgi.fragment");
createManifest(APPLICATION_A + ".mf", attributes);
}
private void createApplicationB() throws IOException {
createApplicationBManifest();
createSubsystem(APPLICATION_B, BUNDLE_A);
}
private void createApplicationBManifest() throws IOException {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, BUNDLE_A + ";type=osgi.bundle," + FRAGMENT_A + ";type=osgi.fragment");
createManifest(APPLICATION_B + ".mf", attributes);
}
@Test
public void testApplicationWithFragmentInArchiveWithSubsystemContentHeaderWithType() throws Exception {
Subsystem applicationA = installSubsystemFromFile(APPLICATION_A);
try {
assertConstituents(3, applicationA);
startSubsystem(applicationA);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, applicationA);
assertBundleState(Bundle.RESOLVED, FRAGMENT_A, applicationA);
Bundle bundle = context(applicationA).getBundleByName(FRAGMENT_A);
assertNotNull("Bundle not found: " + FRAGMENT_A, bundle);
Resource resource = bundle.adapt(BundleRevision.class);
Capability capability = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE).get(0);
assertEquals(
"Wrong type",
IdentityNamespace.TYPE_FRAGMENT,
capability.getAttributes().get(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE));
}
finally {
stopAndUninstallSubsystemSilently(applicationA);
}
}
@Test
public void testApplicationWithFragmentInRepositoryWithSubsystemContentHeaderWithType() throws Exception {
Subsystem applicationB = installSubsystemFromFile(APPLICATION_B);
try {
assertConstituents(3, applicationB);
startSubsystem(applicationB);
assertBundleState(Bundle.ACTIVE, BUNDLE_A, applicationB);
assertBundleState(Bundle.RESOLVED, FRAGMENT_A, applicationB);
Bundle bundle = context(applicationB).getBundleByName(FRAGMENT_A);
assertNotNull("Bundle not found: " + FRAGMENT_A, bundle);
Resource resource = bundle.adapt(BundleRevision.class);
Capability capability = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE).get(0);
String type = String.valueOf(capability.getAttributes().get(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE));
assertEquals("Wrong type", IdentityNamespace.TYPE_FRAGMENT, type);
}
finally {
stopAndUninstallSubsystemSilently(applicationB);
}
}
private Repository createTestRepository() throws IOException {
return new TestRepository.Builder()
.resource(createTestBundleFragmentResource())
.build();
}
private byte[] createTestBundleFragmentContent() throws IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, FRAGMENT_A);
manifest.getMainAttributes().putValue(Constants.FRAGMENT_HOST, BUNDLE_A);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jos = new JarOutputStream(baos, manifest);
jos.close();
return baos.toByteArray();
}
private Resource createTestBundleFragmentResource() throws IOException {
return new TestRepositoryContent.Builder()
.capability(
new TestCapability.Builder()
.namespace(IdentityNamespace.IDENTITY_NAMESPACE)
.attribute(IdentityNamespace.IDENTITY_NAMESPACE, FRAGMENT_A)
.attribute(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, IdentityNamespace.TYPE_FRAGMENT)
.attribute(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE, Version.emptyVersion))
.requirement(
new TestRequirement.Builder()
.namespace(HostNamespace.HOST_NAMESPACE)
.attribute(HostNamespace.HOST_NAMESPACE, BUNDLE_A))
.content(createTestBundleFragmentContent())
.build();
}
@Override
public void setUp() throws Exception {
super.setUp();
try {
serviceRegistrations.add(
bundleContext.registerService(
Repository.class,
createTestRepository(),
null));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 8,776 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/performance/BigApplicationTest.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.subsystem.itests.performance;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.aries.subsystem.core.archive.PreferredProviderHeader;
import org.apache.aries.subsystem.core.archive.SubsystemManifest;
import org.junit.Test;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class BigApplicationTest extends AbstractPerformanceTest {
public static void main(String[] args) throws IOException {
BigApplicationTest test = new BigApplicationTest();
InputStream is = test.createApplication("application");
FileOutputStream fos = new FileOutputStream("application.esa");
copy(is, fos);
is.close();
fos.close();
}
@Test
@org.junit.Ignore
public void testBigApplication() throws Exception {
runTrials(createCallables());
}
private InputStream createApplication(String symbolicName) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
addBundles(zos, "preferredbundle", "package", Constants.EXPORT_PACKAGE);
addBundles(zos, "exportbundle", "package", Constants.EXPORT_PACKAGE);
addBundles(zos, "importbundle", "package", Constants.IMPORT_PACKAGE);
zos.putNextEntry(new ZipEntry("OSGI-INF/SUBSYSTEM.MF"));
StringBuilder preferredProviders = new StringBuilder("preferredbundle0;type=osgi.bundle");
for (int i = 1; i < BUNDLE_COUNT; i++) {
preferredProviders.append(",preferredbundle").append(i).append(";type=osgi.bundle");
}
new SubsystemManifest.Builder()
.symbolicName(symbolicName)
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION)
.header(new PreferredProviderHeader(preferredProviders.toString()))
.build()
.write(zos);
zos.closeEntry();
zos.close();
return new ByteArrayInputStream(baos.toByteArray());
}
private Collection<Callable<Subsystem>> createCallables() {
Callable<Subsystem> callable = new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem subsystem = getRootSubsystem().install("application", createApplication("application"));
return subsystem;
}
};
return Collections.singletonList(callable);
}
}
| 8,777 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/performance/AbstractPerformanceTest.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.subsystem.itests.performance;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.easymock.internal.matchers.Null;
import org.ops4j.pax.tinybundles.core.TinyBundle;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
public abstract class AbstractPerformanceTest extends SubsystemTest {
protected static final int ARRAY_SIZE_BYTES = 2048;
protected static final int BUNDLE_COUNT = 25;
protected static final int PACKAGE_COUNT = 10;
protected static final int THREAD_COUNT = 1;
protected static final int TRIAL_COUNT = 1;
protected final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
protected void addBundles(ZipOutputStream zos, String symbolicNamePrefix, String packageNamePrefix, String importOrExport) throws IOException {
for (int i = 0; i < BUNDLE_COUNT; i++) {
String symbolicName = symbolicNamePrefix + i;
zos.putNextEntry(new ZipEntry(symbolicName + ".jar"));
InputStream is = createBundle(symbolicName, packageNamePrefix, importOrExport);
copy(is, zos);
is.close();
zos.closeEntry();
}
}
protected static double average(long[] values) {
double sum = 0;
for (long value : values) {
sum += value;
}
return sum / values.length;
}
protected static void copy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[ARRAY_SIZE_BYTES];
int read;
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
}
protected InputStream createBundle(String symbolicName, String packageNamePrefix, String importOrExport) {
TinyBundle tinyBundle = TinyBundles.bundle();
tinyBundle.set(Constants.BUNDLE_SYMBOLICNAME, symbolicName);
StringBuilder builder = new StringBuilder(packageNamePrefix + 0);
for (int i = 1; i < PACKAGE_COUNT; i++) {
builder.append(',');
builder.append(packageNamePrefix + i);
}
tinyBundle.set(importOrExport, builder.toString());
InputStream is = tinyBundle.build();
return is;
}
protected static Collection<Callable<Null>> createUninstallSubsystemCallables(Collection<Future<Subsystem>> futures) {
Collection<Callable<Null>> callables = new ArrayList<Callable<Null>>(futures.size());
for (Future<Subsystem> future : futures) {
try {
final Subsystem subsystem = future.get();
callables.add(new Callable<Null>() {
@Override
public Null call() throws Exception {
subsystem.uninstall();
return null;
}
});
}
catch (Exception e) {}
}
return callables;
}
protected void runTrials(Collection<Callable<Subsystem>> callables) throws InterruptedException {
long[] times = new long[TRIAL_COUNT];
for (int i = 0; i < TRIAL_COUNT; i++) {
long start = System.currentTimeMillis();
Collection<Future<Subsystem>> futures = executor.invokeAll(callables);
long end = System.currentTimeMillis();
times[i] = end - start;
System.out.println("Trial " + i + " took " + times[i] + " ms");
uninstallSubsystems(futures);
}
System.out.println("Average time across " + TRIAL_COUNT + " trials: " + average(times) + " ms");
executor.shutdownNow();
}
protected void uninstallSubsystems(Collection<Future<Subsystem>> futures) throws InterruptedException {
Collection<Callable<Null>> callables = createUninstallSubsystemCallables(futures);
executor.invokeAll(callables);
}
}
| 8,778 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/performance/ManyFeaturesWithSharedBundlesTest.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.subsystem.itests.performance;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.aries.subsystem.core.archive.PreferredProviderHeader;
import org.apache.aries.subsystem.core.archive.SubsystemManifest;
import org.junit.Test;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
public class ManyFeaturesWithSharedBundlesTest extends AbstractPerformanceTest {
private static final int FEATURE_COUNT = 50;
public static void main(String[] args) throws IOException {
ManyFeaturesWithSharedBundlesTest test = new ManyFeaturesWithSharedBundlesTest();
InputStream is = test.createFeature("feature");
FileOutputStream fos = new FileOutputStream("feature.esa");
copy(is, fos);
is.close();
fos.close();
}
@Test
@org.junit.Ignore
public void testInstallAllFeatures() throws Exception {
Collection<Callable<Subsystem>> callables = createInstallFeatureCallables();
runTrials(callables);
}
@Test
@org.junit.Ignore
public void testInstallOneFeatureAfterAll() throws Exception {
Collection<Callable<Subsystem>> callables = createInstallFeatureCallables();
Collection<Future<Subsystem>> futures = executor.invokeAll(callables);
Callable<Subsystem> callable = new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem feature = getRootSubsystem().install("onefeature", createFeature("onefeature"));
return feature;
}
};
runTrials(Collections.singletonList(callable));
uninstallSubsystems(futures);
}
private InputStream createApplication(String symbolicName) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
addBundles(zos, "applicationbundle", "package", Constants.IMPORT_PACKAGE);
zos.putNextEntry(new ZipEntry("OSGI-INF/SUBSYSTEM.MF"));
StringBuilder preferredProviders = new StringBuilder("featurebundle0;type=osgi.bundle");
for (int i = 1; i < BUNDLE_COUNT; i++) {
preferredProviders.append(",featurebundle").append(i).append(";type=osgi.bundle");
}
new SubsystemManifest.Builder()
.symbolicName(symbolicName)
.type(SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION)
.header(new PreferredProviderHeader(preferredProviders.toString()))
.build()
.write(zos);
zos.closeEntry();
zos.close();
return new ByteArrayInputStream(baos.toByteArray());
}
private InputStream createFeature(String symbolicName) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
addBundles(zos, "featurebundle", "package", Constants.EXPORT_PACKAGE);
zos.putNextEntry(new ZipEntry("application.esa"));
copy(createApplication("application"), zos);
zos.closeEntry();
zos.putNextEntry(new ZipEntry("OSGI-INF/SUBSYSTEM.MF"));
new SubsystemManifest.Builder()
.symbolicName(symbolicName)
.type(SubsystemConstants.SUBSYSTEM_TYPE_FEATURE)
.build()
.write(zos);
zos.closeEntry();
zos.close();
return new ByteArrayInputStream(baos.toByteArray());
}
private Collection<Callable<Subsystem>> createInstallFeatureCallables() {
Collection<Callable<Subsystem>> callables = new ArrayList<Callable<Subsystem>>(FEATURE_COUNT);
for (int i = 0; i < FEATURE_COUNT; i++) {
final int count = i;
callables.add(new Callable<Subsystem>() {
@Override
public Subsystem call() throws Exception {
Subsystem feature = getRootSubsystem().install("feature" + count, createFeature("feature" + count));
System.out.println("Installed feature " + count);
return feature;
}
});
}
return callables;
}
}
| 8,779 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/bundles | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/itests/bundles/blueprint/BPHelloImpl.java | /*
* 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.apache.aries.subsystem.itests.bundles.blueprint;
import org.apache.aries.subsystem.itests.hello.api.Hello;
public class BPHelloImpl implements Hello
{
private String _message;
public void setMessage(String msg)
{
_message = msg;
}
private String _initMessage;
public void setInitMessage(String initMsg)
{
_initMessage = initMsg;
}
public void init()
{
System.out.println(_initMessage);
}
@Override
public String saySomething()
{
return _message;
}
}
| 8,780 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt/itests/SubsystemDependency_4E2Test.java | package org.apache.aries.subsystem.ctt.itests;
import static org.osgi.service.subsystem.SubsystemConstants.SUBSYSTEM_SYMBOLICNAME;
import static org.osgi.service.subsystem.SubsystemConstants.SUBSYSTEM_TYPE;
import static org.osgi.service.subsystem.SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION;
import static org.osgi.service.subsystem.SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE;
import static org.osgi.service.subsystem.SubsystemConstants.SUBSYSTEM_TYPE_FEATURE;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Constants;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* 2. A non-Root subsystem has acceptDependencies policy
a. - Register repository R2
- Using the Root subsystem, install a composite subsystem S1 with
- no content bundles
- acceptTransitive policy
- no sharing policy
- Using the subsystem S1, install an application S2 with
- content bundles C, D and E
- note sharing policy gets computed
- Verify that bundles A and B got installed into the S1 Subsystem
- Verify the wiring of C, D and E wire to A->x, A, B->y respectively
- Repeat test with S2 as a composite that imports package x, requires bundle A and required capability y
- Repeat test with S2 as a feature
b. - same as 4E2a except S2 is a content resource of S1
- There are 6 combinations to test
- app_app, app_comp, app_feat, comp_app, comp_comp, comp_feat
3. Invalid sharing policy prevents dependency installation
a. - Register repository R2
- Using the Root subsystem, install a composite subsystem S1 with
- no content bundles
- NO acceptDependency policy
- no sharing policy
- Using the subsystem S1, install an application S2 with
- content bundles C, D and E
- note the sharing policy gets computed
- Verify the installation of S2 fails because there is no valid place to install the
required transitive resources A and B that allow S2 constituents to have access.
- Verify resources A and B are not installed in the Root subsystem.
- Repeat test with S2 as a composite that imports package x, requires bundle A and requires capability y.
- Repeat test with S2 as a feature
c. - same as 4E3a except S1 is a composite that has S2 in its Subsystem-Content; S1 fails to install
*/
public class SubsystemDependency_4E2Test extends SubsystemDependencyTestBase
{
private static final String SUBSYSTEM_4E2_S1_COMP = "sdt_composite4e2_s1.esa";
private static final String SUBSYSTEM_4E2_S2_APP = "sdt_application4e2_s2.esa";
private static final String SUBSYSTEM_4E2_S2_COMP = "sdt_composite4e2_s2.esa";
private static final String SUBSYSTEM_4E2_S2_FEATURE = "sdt_feature4e2_s2.esa";
@Override
public void createApplications() throws Exception {
super.createApplications();
createComposite4E2_S1();
createApplication4E2_S2();
createComposite4E2_S2();
createFeature4E2_S2();
registerRepositoryR2();
}
/*
* - Using the Root subsystem, install a composite subsystem S1 with
- no content bundles
- acceptTransitive policy
- no sharing policy
- Using the subsystem S1, install an application S2 with
- content bundles C, D and E
- note sharing policy gets computed
- Verify that bundles A and B got installed into the S1 Subsystem
*/
@Test
public void test4E2A_where_S2isAnApplication() throws Exception
{
Subsystem s1 = installSubsystemFromFile (SUBSYSTEM_4E2_S1_COMP);
startSubsystem(s1);
Subsystem s2 = installSubsystemFromFile (s1, SUBSYSTEM_4E2_S2_APP);
startSubsystem(s2);
verifyBundlesInstalled (s1.getBundleContext(), "s1", BUNDLE_A, BUNDLE_B);
// - Verify the wiring of C, D and E wire to A->x, A, B->y respectively
checkBundlesCDandEWiredToAandB(s2);
stop(s1, s2);
}
/* Repeat test [4e2a.app] with S2 as a composite
* that imports package x, requires bundle A and required capability y
*/
@Test
public void test4E2A_where_S2isAComposite() throws Exception
{
Subsystem s1 = installSubsystemFromFile (SUBSYSTEM_4E2_S1_COMP);
startSubsystem(s1);
Subsystem s2 = installSubsystemFromFile (s1, SUBSYSTEM_4E2_S2_COMP);
startSubsystem(s2);
verifyBundlesInstalled (s1.getBundleContext(), "s1", BUNDLE_A, BUNDLE_B);
// - Verify the wiring of C, D and E wire to A->x, A, B->y respectively
checkBundlesCDandEWiredToAandB(s2);
stop(s1, s2);
}
/*
* - Repeat test [4e2a.app] with S2 as a feature
*/
@Test
public void test4E2A_where_S2isAFeature() throws Exception
{
Subsystem s1 = installSubsystemFromFile (SUBSYSTEM_4E2_S1_COMP);
startSubsystem(s1);
Subsystem s2 = installSubsystemFromFile (s1, SUBSYSTEM_4E2_S2_FEATURE);
startSubsystem(s2);
verifyBundlesInstalled (s1.getBundleContext(), "s1", BUNDLE_A, BUNDLE_B);
// - Verify the wiring of C, D and E wire to A->x, A, B->y respectively
checkBundlesCDandEWiredToAandB(s2);
stop(s1, s2);
}
/*
* 4e2b: - same as 4E2a except S2 is a content resource of S1
- There are 6 combinations to test
- app_app, app_comp, app_feat, comp_app, comp_comp, comp_feat
*/
@Test
public void FourE2b_App_App() throws Exception
{
combinationTest_4e2b ("4e2b_App_App.esa", SUBSYSTEM_TYPE_APPLICATION,
SUBSYSTEM_4E2_S2_APP, SUBSYSTEM_TYPE_APPLICATION);
}
@Test
public void FourE2b_App_Comp() throws Exception
{
combinationTest_4e2b ("4e2b_App_Comp.esa", SUBSYSTEM_TYPE_APPLICATION,
SUBSYSTEM_4E2_S2_COMP, SUBSYSTEM_TYPE_COMPOSITE);
}
@Test
public void FourE2b_App_Feature() throws Exception
{
combinationTest_4e2b ("4e2b_App_Feature.esa", SUBSYSTEM_TYPE_APPLICATION,
SUBSYSTEM_4E2_S2_FEATURE, SUBSYSTEM_TYPE_FEATURE);
}
@Test
public void FourE2b_Comp_App() throws Exception
{
combinationTest_4e2b ("4e2b_App_App.esa", SUBSYSTEM_TYPE_APPLICATION,
SUBSYSTEM_4E2_S2_APP, SUBSYSTEM_TYPE_APPLICATION);
}
@Test
public void FourE2b_Comp_Comp() throws Exception
{
combinationTest_4e2b ("4e2b_Comp_Comp.esa", SUBSYSTEM_TYPE_COMPOSITE,
SUBSYSTEM_4E2_S2_COMP, SUBSYSTEM_TYPE_COMPOSITE);
}
@Test
public void FourE2b_Comp_Feature() throws Exception
{
combinationTest_4e2b ("4e2b_Comp_Feature.esa", SUBSYSTEM_TYPE_COMPOSITE,
SUBSYSTEM_4E2_S2_FEATURE, SUBSYSTEM_TYPE_FEATURE);
}
/*
* Build a subsystem called combinedSubsystemName with a parent of parentType and a child of childType
* Start the subsystem
* - Verify that bundles A and B got installed into the S1 Subsystem
* - Verify the wiring of C, D and E wire to A->x, A, B->y respectively
* Stop and uninstall the combination
*/
private void combinationTest_4e2b (String combinedSubsystemName, String parentType, String childName, String childType) throws Exception
{
createCombinedSubsystem (combinedSubsystemName, parentType, childName, childType);
Subsystem s = installSubsystemFromFile(combinedSubsystemName);
startSubsystem(s);
verifyBundlesInstalled (s.getBundleContext(), "s1", BUNDLE_A, BUNDLE_B);
Collection<Subsystem> children = s.getChildren();
// we only expect one child
Subsystem child = children.iterator().next();
checkBundlesCDandEWiredToAandB (child);
stopSubsystem(s);
uninstallSubsystem(s);
}
private void createCombinedSubsystem (String symbolicName, String parentType, String childSubsystem, String childSubsystemType) throws Exception
{
File f = new File (symbolicName);
if (!f.exists()) {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SUBSYSTEM_SYMBOLICNAME, symbolicName);
attributes.put(SubsystemConstants.SUBSYSTEM_VERSION, "1.0.0");
attributes.put(SUBSYSTEM_TYPE, parentType
+ ";" + SubsystemConstants.PROVISION_POLICY_DIRECTIVE
+ ":=" + SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES);
StringBuffer subsystemContent = new StringBuffer();
subsystemContent.append (childSubsystem + ";" + Constants.VERSION_ATTRIBUTE
+ "=\"[1.0.0,1.0.0]\";");
// I'm not sure that this is the best "type" attribute to use, but it will do.
subsystemContent.append(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE + "=");
subsystemContent.append(childSubsystemType);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, subsystemContent.toString());
// This seems to be necessary to get Comp_Comp and Comp_Feature to work
if (parentType == SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE) {
attributes.put(Constants.IMPORT_PACKAGE, "x");
attributes.put(Constants.REQUIRE_BUNDLE, BUNDLE_A);
attributes.put(Constants.REQUIRE_CAPABILITY, "y");
}
createManifest(symbolicName + ".mf", attributes);
createSubsystem(symbolicName, childSubsystem);
}
}
/*
* Stop s2, stop s1, uninstall s2, uninstall s1
*/
private void stop(Subsystem s1, Subsystem s2) throws Exception
{
stopSubsystem(s2);
stopSubsystem(s1);
uninstallSubsystem(s2);
uninstallSubsystem(s1);
}
/* a feature S2 with
* - content bundles C, D and E
*/
private static void createFeature4E2_S2() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SUBSYSTEM_SYMBOLICNAME, SUBSYSTEM_4E2_S2_FEATURE);
attributes.put(SubsystemConstants.SUBSYSTEM_VERSION, "1.0.0");
attributes.put(SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
String appContent = BUNDLE_C + ", " + BUNDLE_D + ", " + BUNDLE_E;
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, appContent);
createManifest(SUBSYSTEM_4E2_S2_FEATURE + ".mf", attributes);
createSubsystem(SUBSYSTEM_4E2_S2_FEATURE);
}
/* an application S2 with
* - content bundles C, D and E
*/
private static void createApplication4E2_S2() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SUBSYSTEM_SYMBOLICNAME, SUBSYSTEM_4E2_S2_APP);
attributes.put(SubsystemConstants.SUBSYSTEM_VERSION, "1.0.0");
attributes.put(SUBSYSTEM_TYPE, SUBSYSTEM_TYPE_APPLICATION);
String appContent = BUNDLE_C + ", " + BUNDLE_D + ", " + BUNDLE_E;
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, appContent);
createManifest(SUBSYSTEM_4E2_S2_APP + ".mf", attributes);
createSubsystem(SUBSYSTEM_4E2_S2_APP);
}
/*
* a composite [S2]
* that imports package x, requires bundle A and required capability y
*/
private static void createComposite4E2_S2() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SUBSYSTEM_SYMBOLICNAME, SUBSYSTEM_4E2_S2_COMP);
attributes.put(SubsystemConstants.SUBSYSTEM_VERSION, "1.0.0");
attributes.put(SUBSYSTEM_TYPE, SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(Constants.IMPORT_PACKAGE, "x");
attributes.put(Constants.REQUIRE_BUNDLE, BUNDLE_A);
attributes.put(Constants.REQUIRE_CAPABILITY, "y");
String appContent = BUNDLE_C + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\""
+ ", " + BUNDLE_D + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\""
+ ", " + BUNDLE_E + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\"";
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, appContent);
createManifest(SUBSYSTEM_4E2_S2_COMP + ".mf", attributes);
createSubsystem(SUBSYSTEM_4E2_S2_COMP);
}
/*
* a composite subsystem S1 with
* - no content bundles
* - acceptTransitive policy
* - no sharing policy
*/
private static void createComposite4E2_S1() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SUBSYSTEM_SYMBOLICNAME, SUBSYSTEM_4E2_S1_COMP);
attributes.put(SubsystemConstants.SUBSYSTEM_VERSION, "1.0.0");
attributes.put(SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE
+ ";" + SubsystemConstants.PROVISION_POLICY_DIRECTIVE
+ ":=" + SubsystemConstants.PROVISION_POLICY_ACCEPT_DEPENDENCIES);
createManifest(SUBSYSTEM_4E2_S1_COMP + ".mf", attributes);
createSubsystem(SUBSYSTEM_4E2_S1_COMP);
}
}
| 8,781 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt/itests/SubsystemDependencyTestBase.java | package org.apache.aries.subsystem.ctt.itests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.osgi.framework.namespace.BundleNamespace.BUNDLE_NAMESPACE;
import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.aries.subsystem.itests.Header;
import org.apache.aries.subsystem.itests.SubsystemTest;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.service.subsystem.Subsystem;
/*
* A set of tests to cover OSGi Subsystems CTT section 4, "Subsystem Dependency Tests"
* This is going to look a bit like ProvisionPolicyTest with a bit of
* DependencyLifecycle thrown in.
*
* - The following bundles are used for the tests
- Bundle A that export package x
- Bundle B that provides capability y
- Bundle C that imports package x
- Bundle D that requires bundle A
- Bundle E that requires capability y
- Bundle F that export package x
- Bundle G that provides capability y
- The following repositories are defined
- Repository R1
- Bundle A
- Bundle B
- Bundle C
- Bundle D
- Bundle E
- Bundle F
- Bundle G
- Repository R2
- Bundle A
- Bundle B
- Bundle C
- Bundle D
- Bundle E
*/
@ExamReactorStrategy(PerMethod.class)
public abstract class SubsystemDependencyTestBase extends SubsystemTest
{
protected static String BUNDLE_A = "sdt_bundle.a.jar";
protected static String BUNDLE_B = "sdt_bundle.b.jar";
protected static String BUNDLE_C = "sdt_bundle.c.jar";
protected static String BUNDLE_D = "sdt_bundle.d.jar";
protected static String BUNDLE_E = "sdt_bundle.e.jar";
protected static String BUNDLE_F = "sdt_bundle.f.jar";
protected static String BUNDLE_G = "sdt_bundle.g.jar";
@Override
protected void createApplications() throws Exception {
// We'd like to do this in an @BeforeClass method, but files written in @BeforeClass
// go into the project's target/ directory whereas those written in @Before go into
// paxexam's temp directory, which is where they're needed.
createBundleA();
createBundleB();
createBundleC();
createBundleD();
createBundleE();
createBundleF();
createBundleG();
}
private void createBundleA() throws Exception
{
createBundle(name(BUNDLE_A), version("1.0.0"), exportPackage("x"));
}
private void createBundleB() throws Exception
{
// TODO: see comment below about bug=true
createBundle(name(BUNDLE_B), version("1.0.0"), new Header(Constants.PROVIDE_CAPABILITY, "y;y=randomNamespace"));
}
private void createBundleC() throws Exception
{
createBundle(name(BUNDLE_C), version("1.0.0"), importPackage("x"));
}
private void createBundleD() throws Exception
{
createBundle(name(BUNDLE_D), version("1.0.0"), requireBundle(BUNDLE_A));
}
// TODO:
/*
* According to the OSGi Core Release 5 spec section 3.3.6 page 35,
* "A filter is optional, if no filter directive is specified the requirement always matches."
*
* If omitted, we first get an NPE in DependencyCalculator.MissingCapability.initializeAttributes().
* If that's fixed, we get exceptions of the form,
*
* Caused by: java.lang.IllegalArgumentException: The filter must not be null.
* at org.eclipse.equinox.internal.region.StandardRegionFilterBuilder.allow(StandardRegionFilterBuilder.java:49)
* at org.apache.aries.subsystem.core.internal.SubsystemResource.setImportIsolationPolicy(SubsystemResource.java:655)
*
* This looks to be an Equinox defect - at least in the level of 3.8.0 currently being used by these tests.
*/
private void createBundleE() throws Exception
{
createBundle(name(BUNDLE_E), version("1.0.0"), new Header(Constants.REQUIRE_CAPABILITY, "y"));
}
private void createBundleF() throws Exception
{
createBundle(name(BUNDLE_F), version("1.0.0"), exportPackage("x"));
}
// TODO: see comment above about bug=true
private void createBundleG() throws Exception
{
createBundle(name(BUNDLE_G), version("1.0.0"), new Header(Constants.PROVIDE_CAPABILITY, "y;y=randomNamespace"));
}
protected void registerRepositoryR1() throws Exception
{
registerRepositoryService(BUNDLE_A, BUNDLE_B,
BUNDLE_C, BUNDLE_D, BUNDLE_E, BUNDLE_F, BUNDLE_G);
}
protected void registerRepositoryR2() throws Exception
{
registerRepositoryService(BUNDLE_A, BUNDLE_B,
BUNDLE_C, BUNDLE_D, BUNDLE_E);
}
/**
* - Verify that bundles C, D and E in subsystem s wire to A->x, A, B->y respectively
*/
protected void checkBundlesCDandEWiredToAandB (Subsystem s)
{
verifySinglePackageWiring (s, BUNDLE_C, "x", BUNDLE_A);
verifyRequireBundleWiring (s, BUNDLE_D, BUNDLE_A);
verifyCapabilityWiring (s, BUNDLE_E, "y", BUNDLE_B);
}
/**
* Check that wiredBundleName in subsystem s is wired to a single package,
* expectedPackage, from expectedProvidingBundle
* @param s
* @param wiredBundleName
* @param expectedPackage
* @param expectedProvidingBundle
*/
protected void verifySinglePackageWiring (Subsystem s, String wiredBundleName, String expectedPackage, String expectedProvidingBundle)
{
Bundle wiredBundle = context(s).getBundleByName(wiredBundleName);
assertNotNull ("Bundle not found", wiredBundleName);
BundleWiring wiring = (BundleWiring) wiredBundle.adapt(BundleWiring.class);
List<BundleWire> wiredPackages = wiring.getRequiredWires(PACKAGE_NAMESPACE);
assertEquals ("Only one package expected", 1, wiredPackages.size());
String packageName = (String)
wiredPackages.get(0).getCapability().getAttributes().get(PACKAGE_NAMESPACE);
assertEquals ("Wrong package found", expectedPackage, packageName);
String providingBundle = wiredPackages.get(0).getProvider().getSymbolicName();
assertEquals ("Package provided by wrong bundle", expectedProvidingBundle, providingBundle);
}
/**
* Verify that the Require-Bundle of wiredBundleName in subsystem s is met by a wire
* to expectedProvidingBundleName
* @param s
* @param wiredBundleName
* @param expectedProvidingBundleName
*/
protected void verifyRequireBundleWiring (Subsystem s, String wiredBundleName, String expectedProvidingBundleName)
{
Bundle wiredBundle = context(s).getBundleByName(BUNDLE_D);
assertNotNull ("Target bundle " + wiredBundleName + " not found", wiredBundle);
BundleWiring wiring = (BundleWiring) wiredBundle.adapt(BundleWiring.class);
List<BundleWire> wiredBundles = wiring.getRequiredWires(BUNDLE_NAMESPACE);
assertEquals ("Only one bundle expected", 1, wiredBundles.size());
String requiredBundleName = (String)
wiredBundles.get(0).getCapability().getAttributes().get(BUNDLE_NAMESPACE);
assertEquals ("Wrong bundle requirement", BUNDLE_A, requiredBundleName);
String providingBundle = wiredBundles.get(0).getProvider().getSymbolicName();
assertEquals ("Wrong bundle provider", expectedProvidingBundleName, providingBundle);
}
/**
* Verify that a bundle with wiredBundleName imports a single capability in namespace
* from expectedProvidingBundleName
* @param s
* @param wiredBundleName
* @param namespace
* @param expectedProvidingBundleName
*/
protected void verifyCapabilityWiring (Subsystem s, String wiredBundleName,
String namespace, String expectedProvidingBundleName)
{
Bundle wiredBundle = context(s).getBundleByName(wiredBundleName);
assertNotNull ("Targt bundle " + wiredBundleName + " not found", wiredBundleName);
BundleWiring wiring = (BundleWiring) wiredBundle.adapt(BundleWiring.class);
List<BundleWire> wiredProviders = wiring.getRequiredWires(namespace);
assertEquals("Only one wire for capability namespace " + namespace +" expected",
1, wiredProviders.size());
String capabilityNamespace = (String)
wiredProviders.get(0).getCapability().getNamespace();
assertEquals ("Wrong namespace", namespace, capabilityNamespace);
String providingBundle = wiredProviders.get(0).getProvider().getSymbolicName();
assertEquals ("Wrong bundle provider", expectedProvidingBundleName, providingBundle);
}
/**
* Verify that bundles with names bundleNames are installed into the subsystem with subsystemName
* and bundle context bc
* @param bc
* @param subsystemName
* @param bundleNames
*/
protected void verifyBundlesInstalled (BundleContext bc, String subsystemName, String ... bundleNames)
{
for (String bundleName: bundleNames) {
boolean bundleFound = false;
inner: for (Bundle b: bc.getBundles()) {
if (b.getSymbolicName().equals(bundleName)) {
bundleFound = true;
break inner;
}
}
assertTrue ("Bundle " + bundleName + " not found in subsystem " + subsystemName, bundleFound);
}
}
/**
* Check that no new bundles have been provisioned by [x]
* @param failText where the failure occurred
* @param rootBundlesBefore Bundles before [x]
* @param rootBundlesAfter Bundles after [x]
*/
protected void checkNoNewBundles(String failText, Bundle[] rootBundlesBefore, Bundle[] rootBundlesAfter) {
Set<String> bundlesBefore = new HashSet<String>();
for (Bundle b : rootBundlesBefore) {
bundlesBefore.add(b.getSymbolicName() + "_" + b.getVersion().toString());
}
Set<String> bundlesAfter = new HashSet<String>();
for (Bundle b : rootBundlesAfter) {
bundlesAfter.add(b.getSymbolicName() + "_" + b.getVersion().toString());
}
boolean unchanged = bundlesBefore.containsAll(bundlesAfter) &&
bundlesAfter.containsAll(bundlesBefore);
if (!unchanged) {
bundlesAfter.removeAll(bundlesBefore);
fail ("Extra bundles provisioned in " + failText + " : " + bundlesAfter);
}
}
}
| 8,782 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt/itests/SubsystemDependency_4DTest.java | package org.apache.aries.subsystem.ctt.itests;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* D) Test that Local Repository takes priority over registered repositories
- Register repository R2
- Using the Root subsystem, install a scoped subsystem with the following content bundles
- Bundle C
- Bundle E
and the following resources in the Local Repository
- Bundle F
- Bundle G
- Verify that bundles F and G got installed into the Root Subsystem
- Verify the wiring of C and E wire to F->x and G->y respectively
- Verify that bundles A and B did not get installed into the Root Subsystem
*/
public class SubsystemDependency_4DTest extends SubsystemDependencyTestBase
{
private static final String SUBSYSTEM_4D = "sdt_application4d.esa";
private Subsystem subsystem;
@Override
public void createApplications() throws Exception {
super.createApplications();
createApplication4d();
registerRepositoryR2();
}
// - Verify that bundles F and G got installed into the Root Subsystem
@Test
public void verifyBundesFandGinstalledIntoRootSubsystem() throws Exception
{
startSubsystem();
verifyBundlesInstalled (bundleContext, "Root", BUNDLE_F, BUNDLE_G);
stopSubsystem();
}
// - Verify the wiring of C and E wire to F->x and G->y respectively
@Test
public void verifyBundleCWiredToPackageXFromBundleF() throws Exception
{
startSubsystem();
verifySinglePackageWiring (subsystem, BUNDLE_C, "x", BUNDLE_F);
stopSubsystem();
}
@Test
public void verifyBundleEWiredToCapability_yFromBundleG() throws Exception
{
startSubsystem();
verifyCapabilityWiring (subsystem, BUNDLE_E, "y", BUNDLE_G);
stopSubsystem();
}
// - Verify that bundles A and B did not get installed into the Root Subsystem
@Test
public void verifyBundlesAandBNotInstalledInRootSubsystem() throws Exception
{
startSubsystem();
Bundle[] bundles = bundleContext.getBundles();
for (Bundle b: bundles) {
assertTrue ("Bundle A should not have been provisioned!", !b.getSymbolicName().equals(BUNDLE_A));
assertTrue ("Bundle B should not have been provisioned!", !b.getSymbolicName().equals(BUNDLE_B));
}
stopSubsystem();
}
// doing this within @Before doesn't work :(
private void startSubsystem() throws Exception
{
subsystem = installSubsystemFromFile(SUBSYSTEM_4D);
startSubsystem(subsystem);
}
private void stopSubsystem() throws Exception
{
stopSubsystem(subsystem);
uninstallSubsystem(subsystem);
}
private static void createApplication4d() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, SUBSYSTEM_4D);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION);
String appContent = BUNDLE_C + "," + BUNDLE_E;
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, appContent);
createManifest(SUBSYSTEM_4D + ".mf", attributes);
createSubsystem(SUBSYSTEM_4D, BUNDLE_F, BUNDLE_G);
}
}
| 8,783 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt/itests/SubsystemDependency_4BTest.java | package org.apache.aries.subsystem.ctt.itests;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* B) Test with no pre-installed transitive resources
- Register repository R2
- Using the Root subsystem, install a scoped subsystem with the following content bundles and no local repository
- Bundle C
- Bundle D
- Bundle E
- Verify that bundles A and B got installed into the Root Subsystem
- Verify the wiring of C, D and E wire to A->x, A, B->y respectively
*/
public class SubsystemDependency_4BTest extends SubsystemDependencyTestBase
{
protected static String APPLICATION_B="sdt_application.b.esa";
@Override
public void createApplications() throws Exception {
super.createApplications();
createTestApplicationB();
}
@Before
public void registerRepo() throws Exception {
registerRepositoryR2();
}
// - Verify that bundles A and B got installed into the Root Subsystem
@Test
public void verifyBundlesAandBinstalledIntoRootRegion() throws Exception
{
System.out.println ("Into verifyBundlesAandBinstalledIntoRootRegion");
Subsystem s = installSubsystemFromFile(APPLICATION_B);
startSubsystem(s);
Bundle[] bundles = bundleContext.getBundles();
Collection<String> bundleNames = new ArrayList<String>();
for (Bundle b : bundles) {
bundleNames.add(b.getSymbolicName());
}
assertTrue ("Bundle A should have been provisioned to the root region", bundleNames.contains(BUNDLE_A));
assertTrue ("Bundle B should have been provisioned to the root region", bundleNames.contains(BUNDLE_B));
stopSubsystem(s);
}
@Test
public void verifyBundleCWiredToPackage_xFromBundleA() throws Exception
{
Subsystem s = installSubsystemFromFile(APPLICATION_B);
startSubsystem(s);
verifySinglePackageWiring (s, BUNDLE_C, "x", BUNDLE_A);
stopSubsystem(s);
}
@Test
public void verifyBundleDWiredToBundleA() throws Exception
{
Subsystem s = installSubsystemFromFile(APPLICATION_B);
startSubsystem(s);
verifyRequireBundleWiring (s, BUNDLE_D, BUNDLE_A);
stopSubsystem(s);
}
@Test
public void verifyBundleEWiredToCapability_yFromBundleB() throws Exception
{
Subsystem s = installSubsystemFromFile(APPLICATION_B);
startSubsystem(s);
verifyCapabilityWiring (s, BUNDLE_E, "y", BUNDLE_B);
stopSubsystem(s);
}
private static void createTestApplicationB() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_B);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
String appContent = BUNDLE_C + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\""
+ ", " + BUNDLE_D + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\""
+ ", " + BUNDLE_E + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\"";
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, appContent);
attributes.put(Constants.IMPORT_PACKAGE, "x");
attributes.put(Constants.REQUIRE_BUNDLE, BUNDLE_A);
attributes.put(Constants.REQUIRE_CAPABILITY, "y");
createManifest(APPLICATION_B + ".mf", attributes);
createSubsystem(APPLICATION_B);
}
}
| 8,784 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt/itests/SubsystemDependency_4CTest.java | package org.apache.aries.subsystem.ctt.itests;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
C) Test with pre-installed transitive resources
- Register repository R1
- Using the Root subsystem, install a composite subsystem S1 with the following content bundles (with no import/export policy)
- Bundle A
- Bundle B
- Using the subsystem S1, install a composite S2 that imports package x, requires bundle A and required capability y
- Verify the wiring of C, D and E wire to A->x, A, B->y respectively
- Verify no new bundles are installed into the Root or S1 subsystems
*/
@ExamReactorStrategy(PerMethod.class)
public class SubsystemDependency_4CTest extends SubsystemDependencyTestBase
{
private static final String SUBSYSTEM_S1 = "sdt_composite.s1.esa";
private static final String SUBSYSTEM_S2 = "sdt_composite.s2.esa";
private Subsystem s1;
private Subsystem s2;
@Override
protected void createApplications() throws Exception {
super.createApplications();
createSubsystemS1();
createSubsystemS2();
registerRepositoryR1();
}
// doing this within @Before doesn't work :(
private void startSubsystems() throws Exception
{
s1 = installSubsystemFromFile(SUBSYSTEM_S1);
startSubsystem(s1);
s2 = installSubsystemFromFile(s1, SUBSYSTEM_S2);
startSubsystem(s2);
}
private void stopSubsystems() throws Exception
{
stopSubsystem(s2);
stopSubsystem(s1);
//uninstallSubsystem(s2);
//uninstallSubsystem(s1);
}
// Using the subsystem S1, install a composite S2 that
// imports package x,
// requires bundle A
// and required capability y
// - Verify the wiring of C, D and E wire to A->x, A, B->y respectively
@Test
public void verify() throws Exception
{
startSubsystems();
verifySinglePackageWiring (s2, BUNDLE_C, "x", BUNDLE_A);
verifyRequireBundleWiring (s2, BUNDLE_D, BUNDLE_A);
verifyCapabilityWiring (s2, BUNDLE_E, "y", BUNDLE_B);
stopSubsystems();
}
@Test
public void verifyNoUnexpectedBundlesProvisioned() throws Exception
{
Bundle[] rootBundlesBefore = bundleContext.getBundles();
s1 = installSubsystemFromFile(SUBSYSTEM_S1);
startSubsystem(s1);
Bundle[] s1BundlesBefore = bundleContext.getBundles();
s2 = installSubsystemFromFile(s1, SUBSYSTEM_S2);
startSubsystem(s2);
Bundle[] rootBundlesAfter = bundleContext.getBundles();
Bundle[] s1BundlesAfter = bundleContext.getBundles();
checkNoNewBundles ("rootBundles", rootBundlesBefore, rootBundlesAfter);
checkNoNewBundles ("s1Bundles", s1BundlesBefore, s1BundlesAfter);
stopSubsystems();
}
/*
* a composite subsystem S1 with the following content bundles (with no import/export policy)
- Bundle A
- Bundle B
*/
private static void createSubsystemS1() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, SUBSYSTEM_S1);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
String appContent = BUNDLE_A + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\""
+ ", " + BUNDLE_B + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\"";
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, appContent);
createManifest(SUBSYSTEM_S1 + ".mf", attributes);
createSubsystem(SUBSYSTEM_S1);
}
/*
* a composite S2 that
* imports package x,
* requires bundle A
* and required capability y
*
* Although the test plan is silent as to the content of S2, I think we have to assume
* that it contains bundles C, D and E
*/
private static void createSubsystemS2() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, SUBSYSTEM_S2);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
String appContent = BUNDLE_C + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\""
+ ", " + BUNDLE_D + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\""
+ ", " + BUNDLE_E + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\"";
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, appContent);
attributes.put(Constants.IMPORT_PACKAGE, "x");
attributes.put(Constants.REQUIRE_BUNDLE, BUNDLE_A);
attributes.put(Constants.REQUIRE_CAPABILITY, "y");
createManifest(SUBSYSTEM_S2 + ".mf", attributes);
createSubsystem(SUBSYSTEM_S2);
}
}
| 8,785 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt/itests/SubsystemDependency_4E1Test.java | package org.apache.aries.subsystem.ctt.itests;
import static org.osgi.service.subsystem.SubsystemConstants.SUBSYSTEM_SYMBOLICNAME;
import static org.osgi.service.subsystem.SubsystemConstants.SUBSYSTEM_TYPE;
import static org.osgi.service.subsystem.SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION;
import static org.osgi.service.subsystem.SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE;
import static org.osgi.service.subsystem.SubsystemConstants.SUBSYSTEM_TYPE_FEATURE;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Constants;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* E) Test acceptDependencies policy
1. Root is the only acceptDependencies policy
a. - Register repository R2
- Using the Root subsystem, install a composite subsystem S1 with
- no content bundles
- imports package x, requires bundle A and requires capability y
- Using the subsystem S1, install an application S2 with
- content bundles C, D and E
- Verify that bundles A and B got installed into the Root Subsystem
- Verify the wiring of C, D and E wire to A->x, A, B->y respectively
- Repeat test with S2 as a composite that imports package x, requires bundle A and required capability y
- Repeat test with S2 as a feature
b. - same as 4E1a except S2 is a content resource of S1
- There are 6 combinations to test
- app_app, app_comp, app_feat, comp_app, comp_comp, comp_feat
*/
public class SubsystemDependency_4E1Test extends SubsystemDependencyTestBase
{
private static final String SUBSYSTEM_4E_S1_COMP = "sdt_composite4e_s1.esa";
private static final String SUBSYSTEM_4E_S2_APP = "sdt_application4e_s2.esa";
private static final String SUBSYSTEM_4E_S2_COMP = "sdt_composite4e_s2.esa";
private static final String SUBSYSTEM_4E_S2_FEATURE = "sdt_feature4e_s2.esa";
@Override
public void createApplications() throws Exception
{
super.createApplications();
createComposite4E_S1();
createApplication4E_S2();
createComposite4E_S2();
createFeature4E_S2();
registerRepositoryR2();
}
/*
* Using the subsystem S1, install an application S2 with
- content bundles C, D and E
- Verify that bundles A and B got installed into the Root Subsystem
*/
@Test
public void verifyBundlesAandBInstalledIntoRootSubsystem() throws Exception
{
Subsystem s1 = installSubsystemFromFile(SUBSYSTEM_4E_S1_COMP);
startSubsystem(s1);
Subsystem s2 = installSubsystemFromFile(s1, SUBSYSTEM_4E_S2_APP);
startSubsystem(s2);
verifyBundlesInstalled (bundleContext, "Root", BUNDLE_A, BUNDLE_B);
stop(s1, s2);
}
@Test
public void verifyExpectedWiringsForS2_App() throws Exception
{
Subsystem s1 = installSubsystemFromFile(SUBSYSTEM_4E_S1_COMP);
startSubsystem(s1);
Subsystem s2 = installSubsystemFromFile(s1, SUBSYSTEM_4E_S2_APP);
startSubsystem(s2);
// - Verify the wiring of C, D and E wire to A->x, A, B->y respectively
verifySinglePackageWiring (s2, BUNDLE_C, "x", BUNDLE_A);
verifyRequireBundleWiring (s2, BUNDLE_D, BUNDLE_A);
verifyCapabilityWiring (s2, BUNDLE_E, "y", BUNDLE_B);
stop(s1, s2);
}
// - Repeat test with S2 as a composite that
// imports package x, requires bundle A and required capability y
@Test
public void verifyExpectedWiringsForS2_Composite() throws Exception
{
Subsystem s1 = installSubsystemFromFile(SUBSYSTEM_4E_S1_COMP);
startSubsystem(s1);
Subsystem s2 = installSubsystemFromFile(s1, SUBSYSTEM_4E_S2_COMP);
startSubsystem(s2);
checkBundlesCDandEWiredToAandB(s2);
stop(s1, s2);
}
// - Repeat test with S2 as a feature
@Test
public void verifyExpectedWiringsForS2_Feature() throws Exception
{
Subsystem s1 = installSubsystemFromFile(SUBSYSTEM_4E_S1_COMP);
startSubsystem(s1);
Subsystem s2 = installSubsystemFromFile(s1, SUBSYSTEM_4E_S2_FEATURE);
startSubsystem(s2);
checkBundlesCDandEWiredToAandB (s2);
stop(s1, s2);
}
// b. - same as 4E1a except S2 is a content resource of S1
// - There are 6 combinations to test
// - app_app, app_comp, app_feat, comp_app, comp_comp, comp_feat
@Test
public void FourE1b_App_App() throws Exception
{
combinationTest ("4eS1_App_App.esa", SUBSYSTEM_TYPE_APPLICATION, SUBSYSTEM_4E_S2_APP, SUBSYSTEM_TYPE_APPLICATION);
}
@Test
public void FourE1b_App_Comp() throws Exception
{
combinationTest ("4eS1_App_Comp.esa", SUBSYSTEM_TYPE_APPLICATION, SUBSYSTEM_4E_S2_COMP, SUBSYSTEM_TYPE_COMPOSITE);
}
@Test
public void FourE1b_App_Feature() throws Exception
{
combinationTest ("4eS1_App_Feature.esa", SUBSYSTEM_TYPE_APPLICATION, SUBSYSTEM_4E_S2_FEATURE, SUBSYSTEM_TYPE_FEATURE);
}
@Test
public void FourE1b_Comp_App() throws Exception
{
combinationTest ("4eS1_Comp_App.esa", SUBSYSTEM_TYPE_COMPOSITE, SUBSYSTEM_4E_S2_APP, SUBSYSTEM_TYPE_APPLICATION);
}
@Test
public void FourE1b_Comp_Comp() throws Exception
{
combinationTest ("4eS1_Comp_Comp.esa", SUBSYSTEM_TYPE_COMPOSITE, SUBSYSTEM_4E_S2_COMP, SUBSYSTEM_TYPE_COMPOSITE);
}
@Test
public void FourE1b_Comp_Feature() throws Exception
{
combinationTest ("4eS1_Comp_Feature.esa", SUBSYSTEM_TYPE_COMPOSITE, SUBSYSTEM_4E_S2_FEATURE, SUBSYSTEM_TYPE_FEATURE);
}
/*
* Build a subsystem called combinedSubsystemName with a parent of parentType and a child of childType
* Start the subsystem
* runChecks on the comination
* Stop and uninstall the combination
*/
private void combinationTest (String combinedSubsystemName, String parentType, String childName, String childType) throws Exception
{
createCombinedSubsystem (combinedSubsystemName, parentType, childName, childType);
Subsystem s = installSubsystemFromFile(combinedSubsystemName);
startSubsystem(s);
Collection<Subsystem> children = s.getChildren();
// we only expect one child
Subsystem child = children.iterator().next();
checkBundlesCDandEWiredToAandB (child);
stopSubsystem(s);
uninstallSubsystem(s);
}
/*
* Create a nested parent/child subsystem with symbolicName, where parent is of type and child is the
* previously-created childSubsystem
*/
private void createCombinedSubsystem (String symbolicName, String parentType, String childSubsystem, String childSubsystemType) throws Exception
{
File f = new File (symbolicName);
if (!f.exists()) {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SUBSYSTEM_SYMBOLICNAME, symbolicName);
attributes.put(SubsystemConstants.SUBSYSTEM_VERSION, "1.0.0");
attributes.put(SUBSYSTEM_TYPE, parentType);
if (parentType == SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE) {
attributes.put(Constants.IMPORT_PACKAGE, "x");
attributes.put(Constants.REQUIRE_BUNDLE, BUNDLE_A);
attributes.put(Constants.REQUIRE_CAPABILITY, "y");
}
StringBuffer subsystemContent = new StringBuffer();
subsystemContent.append (childSubsystem + ";" + Constants.VERSION_ATTRIBUTE
+ "=\"[1.0.0,1.0.0]\";");
// I'm not sure that this is the best "type" attribute to use, but it will do.
subsystemContent.append(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE + "=");
subsystemContent.append(childSubsystemType);
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, subsystemContent.toString());
createManifest(symbolicName + ".mf", attributes);
createSubsystem(symbolicName, childSubsystem);
}
}
private void stop(Subsystem s1, Subsystem s2) throws Exception
{
stopSubsystem(s2);
stopSubsystem(s1);
uninstallSubsystem(s2);
uninstallSubsystem(s1);
}
/*
* a composite subsystem S1 with
- no content bundles
- imports package x, requires bundle A and requires capability y
*/
private static void createComposite4E_S1() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SUBSYSTEM_SYMBOLICNAME, SUBSYSTEM_4E_S1_COMP);
attributes.put(SubsystemConstants.SUBSYSTEM_VERSION, "1.0.0");
attributes.put(SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
attributes.put(Constants.IMPORT_PACKAGE, "x");
attributes.put(Constants.REQUIRE_BUNDLE, BUNDLE_A);
attributes.put(Constants.REQUIRE_CAPABILITY, "y");
createManifest(SUBSYSTEM_4E_S1_COMP + ".mf", attributes);
createSubsystem(SUBSYSTEM_4E_S1_COMP);
}
/* an application S2 with
- content bundles C, D and E */
private static void createApplication4E_S2() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SUBSYSTEM_SYMBOLICNAME, SUBSYSTEM_4E_S2_APP);
attributes.put(SubsystemConstants.SUBSYSTEM_VERSION, "1.0.0");
attributes.put(SUBSYSTEM_TYPE, SUBSYSTEM_TYPE_APPLICATION);
String appContent = BUNDLE_C + ", " + BUNDLE_D + ", " + BUNDLE_E;
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, appContent);
createManifest(SUBSYSTEM_4E_S2_APP + ".mf", attributes);
createSubsystem(SUBSYSTEM_4E_S2_APP);
}
/* a feature S2 with
- content bundles C, D and E */
private static void createFeature4E_S2() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SUBSYSTEM_SYMBOLICNAME, SUBSYSTEM_4E_S2_FEATURE);
attributes.put(SubsystemConstants.SUBSYSTEM_VERSION, "1.0.0");
attributes.put(SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_FEATURE);
String appContent = BUNDLE_C + ", " + BUNDLE_D + ", " + BUNDLE_E;
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, appContent);
createManifest(SUBSYSTEM_4E_S2_FEATURE + ".mf", attributes);
createSubsystem(SUBSYSTEM_4E_S2_FEATURE);
}
/* a composite S2 that
// imports package x, requires bundle A and required capability y */
private static void createComposite4E_S2() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SUBSYSTEM_SYMBOLICNAME, SUBSYSTEM_4E_S2_COMP);
attributes.put(SubsystemConstants.SUBSYSTEM_VERSION, "1.0.0");
attributes.put(SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE);
String appContent = BUNDLE_C + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\""
+ ", " + BUNDLE_D + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\""
+ ", " + BUNDLE_E + ";" + Constants.VERSION_ATTRIBUTE + "=\"[1.0.0,1.0.0]\"";
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, appContent);
attributes.put(Constants.IMPORT_PACKAGE, "x");
attributes.put(Constants.REQUIRE_BUNDLE, BUNDLE_A);
attributes.put(Constants.REQUIRE_CAPABILITY, "y");
createManifest(SUBSYSTEM_4E_S2_COMP + ".mf", attributes);
createSubsystem(SUBSYSTEM_4E_S2_COMP);
}
}
| 8,786 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt | Create_ds/aries/subsystem/subsystem-itests/src/test/java/org/apache/aries/subsystem/ctt/itests/SubsystemDependency_4ATest.java | package org.apache.aries.subsystem.ctt.itests;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.service.subsystem.Subsystem;
import org.osgi.service.subsystem.SubsystemConstants;
/*
* First block: section 4A
*
A) Test a transitively closed subsystem deploys no transitive resources
- Register repository R1
- Using the Root subsystem, install a scoped subsystem with the following content bundles and no local repository
- Bundle A
- Bundle B
- Bundle C
- Bundle D
- Bundle E
- Verify the wiring of C, D and E wire to A->x, A, B->y respectively
- Verify no new bundles are installed into the Root subsystem (particularly bundles F and G)
*/
public class SubsystemDependency_4ATest extends SubsystemDependencyTestBase
{
protected static String APPLICATION_A="sdt_application.a.esa";
@Override
public void createApplications() throws Exception {
super.createApplications();
createTestApplicationA();
registerRepositoryR1();
}
@Test
public void verifyBundleCWiredToPackageXFromBundleA() throws Exception
{
Subsystem s = installSubsystemFromFile(APPLICATION_A);
startSubsystem(s);
verifySinglePackageWiring (s, BUNDLE_C, "x", BUNDLE_A);
stopSubsystem(s);
uninstallSubsystem(s);
}
@Test
public void verifyBundleDWiredToBundleA() throws Exception
{
Subsystem s = installSubsystemFromFile(APPLICATION_A);
startSubsystem(s);
verifyRequireBundleWiring (s, BUNDLE_D, BUNDLE_A);
stopSubsystem(s);
uninstallSubsystem(s);
}
@Test
public void verifyBundleEWiredToCapability_yFromBundleB() throws Exception
{
Subsystem s = installSubsystemFromFile (APPLICATION_A);
startSubsystem(s);
verifyCapabilityWiring (s, BUNDLE_E, "y", BUNDLE_B);
stopSubsystem(s);
uninstallSubsystem(s);
}
/*
* Verify no new bundles are installed into the Root subsystem
* (particularly bundles F and G)
*
*/
@Test
public void verifyNoUnexpectedBundlesProvisioned() throws Exception
{
Bundle[] rootBundlesBefore = bundleContext.getBundles();
Subsystem s = installSubsystemFromFile(APPLICATION_A);
startSubsystem(s);
Bundle[] rootBundlesAfter = bundleContext.getBundles();
for (Bundle b: rootBundlesAfter) {
assertTrue ("Bundle F should not have been provisioned!", !b.getSymbolicName().equals(BUNDLE_F));
assertTrue ("Bundle G should not have been provisioned!", !b.getSymbolicName().equals(BUNDLE_G));
}
checkNoNewBundles("SubsystemDependency_4ATest", rootBundlesBefore, rootBundlesAfter);
stopSubsystem(s);
uninstallSubsystem(s);
}
private static void createTestApplicationA() throws Exception
{
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, APPLICATION_A);
attributes.put(SubsystemConstants.SUBSYSTEM_TYPE, SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION);
String appContent = BUNDLE_A +","+ BUNDLE_B + "," + BUNDLE_C
+ "," + BUNDLE_D + "," + BUNDLE_E;
attributes.put(SubsystemConstants.SUBSYSTEM_CONTENT, appContent);
createManifest(APPLICATION_A + ".mf", attributes);
createSubsystem(APPLICATION_A);
}
}
| 8,787 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/cmContentBundleZ/org/apache/aries/subsystem/itests/cmcontent | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/cmContentBundleZ/org/apache/aries/subsystem/itests/cmcontent/impl/BlahManagedService.java | package org.apache.aries.subsystem.itests.cmcontent.impl;
import java.util.Dictionary;
import java.util.Hashtable;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
public class BlahManagedService implements ManagedService {
private final BundleContext bundleContext;
public BlahManagedService(BundleContext context) {
bundleContext = context;
}
@Override
public void updated(Dictionary<String, ?> p) throws ConfigurationException {
if ("test2".equals(p.get("configVal")) &&
"test123".equals(p.get("configVal2"))) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put("test.pid", p.get(Constants.SERVICE_PID));
bundleContext.registerService(String.class, "Blah!", props);
}
if ("Hello".equals(p.get("configVal"))) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put("test.pid", p.get(Constants.SERVICE_PID));
bundleContext.registerService(String.class, "Hello", props);
}
}
}
| 8,788 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/cmContentBundleZ/org/apache/aries/subsystem/itests/cmcontent | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/cmContentBundleZ/org/apache/aries/subsystem/itests/cmcontent/impl/BarManagedService.java | package org.apache.aries.subsystem.itests.cmcontent.impl;
import java.util.Dictionary;
import java.util.Hashtable;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
public class BarManagedService implements ManagedService {
private final BundleContext bundleContext;
public BarManagedService(BundleContext context) {
bundleContext = context;
}
@Override
public void updated(Dictionary<String, ?> p) throws ConfigurationException {
if ("test".equals(p.get("configVal"))) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put("test.pid", p.get(Constants.SERVICE_PID));
bundleContext.registerService(String.class, "Bar!", props);
}
}
}
| 8,789 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/cmContentBundleZ/org/apache/aries/subsystem/itests/cmcontent | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/cmContentBundleZ/org/apache/aries/subsystem/itests/cmcontent/impl/Activator.java | package org.apache.aries.subsystem.itests.cmcontent.impl;
import java.util.Dictionary;
import java.util.Hashtable;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ManagedService;
public class Activator implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception {
Dictionary<String, Object> blahProps = new Hashtable<String, Object>();
blahProps.put(Constants.SERVICE_PID, "com.blah.Blah");
context.registerService(ManagedService.class, new BlahManagedService(context), blahProps);
Dictionary<String, Object> barProps = new Hashtable<String, Object>();
barProps.put(Constants.SERVICE_PID, "org.foo.Bar");
context.registerService(ManagedService.class, new BarManagedService(context), barProps);
}
@Override
public void stop(BundleContext context) throws Exception {
}
}
| 8,790 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/tb2/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/tb2/org/apache/aries/subsystem/itests/tb2/Empty.java | package org.apache.aries.subsystem.itests.tb2;
public class Empty {
}
| 8,791 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/tb3/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/tb3/org/apache/aries/subsystem/itests/tb3/Empty.java | package org.apache.aries.subsystem.itests.tb3;
public class Empty {
}
| 8,792 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/tb4/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/tb4/org/apache/aries/subsystem/itests/tb4/Activator.java | /*
* 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.apache.aries.subsystem.itests.tb4;
import java.util.Dictionary;
import java.util.Hashtable;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.util.tracker.ServiceTracker;
public class Activator implements BundleActivator {
private ServiceTracker<String, String> st;
@Override
public void start(BundleContext context) throws Exception {
Filter filter = context.createFilter(
"(&(objectClass=java.lang.String)(test=testCompositeServiceImports))");
st = new ServiceTracker<String, String>(context, filter, null);
st.open();
String svc = st.waitForService(5000);
if ("testCompositeServiceImports".equals(svc)) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put("test", "tb4");
context.registerService(String.class, "tb4", props);
}
}
@Override
public void stop(BundleContext context) throws Exception {
st.close();
}
}
| 8,793 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/tb1/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/tb1/org/apache/aries/subsystem/itests/tb1/Empty.java | package org.apache.aries.subsystem.itests.tb1;
public class Empty {
}
| 8,794 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/dynamicImport/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/dynamicImport/org/apache/aries/subsystem/itests/dynamicImport/DynamicImportHelloImpl.java | package org.apache.aries.subsystem.itests.dynamicImport;
import org.apache.aries.subsystem.itests.hello.api.Hello;
public class DynamicImportHelloImpl implements Hello {
public DynamicImportHelloImpl()
{
System.out.println ("DynamicImportHelloImpl constructed");
}
@Override
public String saySomething() {
return "Hello, this is something";
}
}
| 8,795 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/dynamicImport/org/apache/aries/subsystem/itests | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/dynamicImport/org/apache/aries/subsystem/itests/dynamicImport/Activator.java | package org.apache.aries.subsystem.itests.dynamicImport;
import org.apache.aries.subsystem.itests.hello.api.Hello;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
public class Activator implements BundleActivator
{
ServiceRegistration _sr = null;
@Override
public void start(BundleContext bc) throws Exception
{
System.out.println ("into " + this.getClass().getCanonicalName() + ".start()");
Hello helloService = new DynamicImportHelloImpl();
_sr = bc.registerService(Hello.class, helloService, null);
System.out.println ("exiting " + this.getClass().getCanonicalName() + ".start()");
}
@Override
public void stop(BundleContext bc) throws Exception
{
if (_sr != null) {
_sr.unregister();
}
}
}
| 8,796 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/helloImpl/org/apache/aries/subsystem/itests/hello | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/helloImpl/org/apache/aries/subsystem/itests/hello/impl/Activator.java | /*
* 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.apache.aries.subsystem.itests.hello.impl;
import org.apache.aries.subsystem.itests.hello.api.Hello;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
public class Activator implements BundleActivator {
ServiceRegistration _sr = null;
@Override
public void start(BundleContext bc) throws Exception
{
Hello helloService = new HelloImpl();
_sr = bc.registerService(Hello.class, helloService, null);
}
@Override
public void stop(BundleContext bc) throws Exception
{
if (_sr != null) {
_sr.unregister();
}
}
}
| 8,797 |
0 | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/helloImpl/org/apache/aries/subsystem/itests/hello | Create_ds/aries/subsystem/subsystem-itests/src/test/bundles/helloImpl/org/apache/aries/subsystem/itests/hello/impl/HelloImpl.java | /*
* 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.apache.aries.subsystem.itests.hello.impl;
import org.apache.aries.subsystem.itests.hello.api.Hello;
public class HelloImpl implements Hello {
@Override
public String saySomething() {
return "something";
}
}
| 8,798 |
0 | Create_ds/aries/application/application-runtime-framework-management/src/test/java/org/apache/aries/application/runtime/framework | Create_ds/aries/application/application-runtime-framework-management/src/test/java/org/apache/aries/application/runtime/framework/management/BundleFrameworkManagerTest.java | package org.apache.aries.application.runtime.framework.management;
import java.util.Arrays;
import org.apache.aries.application.management.AriesApplication;
import org.apache.aries.application.management.spi.framework.BundleFramework;
import org.apache.aries.application.management.spi.framework.BundleFrameworkConfiguration;
import org.apache.aries.application.management.spi.framework.BundleFrameworkConfigurationFactory;
import org.apache.aries.application.management.spi.framework.BundleFrameworkFactory;
import org.apache.aries.application.management.spi.repository.BundleRepository.BundleSuggestion;
import org.apache.aries.application.runtime.framework.management.BundleFrameworkManagerImpl;
import org.apache.aries.unittest.mocks.MethodCall;
import org.apache.aries.unittest.mocks.Skeleton;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import static junit.framework.Assert.*;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
public class BundleFrameworkManagerTest {
private BundleFrameworkManagerImpl sut;
private Skeleton frameworkFactory;
@Before
public void setup() {
sut = new BundleFrameworkManagerImpl();
BundleFrameworkConfigurationFactory bfcf = Skeleton.newMock(BundleFrameworkConfigurationFactory.class);
sut.setBundleFrameworkConfigurationFactory(bfcf);
BundleFrameworkFactory bff = Skeleton.newMock(BundleFrameworkFactory.class);
sut.setBundleFrameworkFactory(bff);
frameworkFactory = Skeleton.getSkeleton(bff);
sut.init();
}
@Test
public void testFailedInstall() throws Exception {
/*
* Mock up a failing framework install
*/
BundleFramework fwk = Skeleton.newMock(new Object() {
public Bundle install(BundleSuggestion suggestion, AriesApplication app) throws BundleException {
throw new BundleException("Expected failure");
}
}, BundleFramework.class);
frameworkFactory.setReturnValue(
new MethodCall(BundleFrameworkFactory.class, "createBundleFramework",
BundleContext.class, BundleFrameworkConfiguration.class),
fwk);
try {
sut.installIsolatedBundles(Arrays.asList(Skeleton.newMock(BundleSuggestion.class)),
Skeleton.newMock(AriesApplication.class));
fail("Expected a BundleException");
} catch (BundleException be) {
// when a failure occurred we need to have cleaned up the new framework, otherwise it is
// left as floating debris
Skeleton.getSkeleton(fwk).assertCalled(new MethodCall(BundleFramework.class, "close"));
}
}
}
| 8,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.