index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/AbstractListenerComponentValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import static junit.framework.Assert.assertNotNull;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeType;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
abstract class AbstractListenerComponentValidator extends AbstractCompositeDataValidator {
// a TargetValidator can be one of BeanValidator, ReferenceValidator, RefValidator
TargetValidator listenerComponentValidator = null;
protected AbstractListenerComponentValidator(CompositeType type){
super(type);
}
public void setListenerComponentValidator(TargetValidator targetValidator){
this.listenerComponentValidator = targetValidator;
}
public void validate(CompositeData target){
super.validate(target);
assertNotNull("This Validator must have a TargetValidator to validate listener component", listenerComponentValidator);
listenerComponentValidator.validate(Util.decode((Byte[])target.get(BlueprintMetadataMBean.LISTENER_COMPONENT)));
}
}
| 8,000 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/CollectionValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
import javax.management.openmbean.CompositeData;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
public class CollectionValidator extends AbstractCompositeDataValidator implements NonNullObjectValueValidator {
private List<ObjectValueValidator> collectionValueValidators = new ArrayList<ObjectValueValidator>();
public CollectionValidator(String collectionClass){
super(BlueprintMetadataMBean.COLLECTION_METADATA_TYPE);
setExpectValue(BlueprintMetadataMBean.COLLECTION_CLASS, collectionClass);
}
public CollectionValidator(String collectionClass, String valueType){
super(BlueprintMetadataMBean.COLLECTION_METADATA_TYPE);
setExpectValue(BlueprintMetadataMBean.COLLECTION_CLASS, collectionClass);
setExpectValue(BlueprintMetadataMBean.VALUE_TYPE, valueType);
}
public void addCollectionValueValidators (ObjectValueValidator...objectValueValidators){
for (ObjectValueValidator objectValueValidator: objectValueValidators)
collectionValueValidators.add(objectValueValidator);
}
public void validate(CompositeData target){
super.validate(target);
if (collectionValueValidators.size() != 0){
Byte[][] allWrapValues = (Byte[][])target.get(BlueprintMetadataMBean.VALUES);
if ( collectionValueValidators.size() != allWrapValues.length )
fail("The quantity of the values is not the same, expect " +collectionValueValidators.size()+" but got "+ allWrapValues.length);
for(int i=0;i<collectionValueValidators.size();i++){
collectionValueValidators.get(i).validate(Util.decode(allWrapValues[i]));
}
}
}
}
| 8,001 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/TargetValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
public interface TargetValidator extends Validator {
}
| 8,002 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/AbstractCompositeDataValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeType;
abstract public class AbstractCompositeDataValidator {
private CompositeType type;
private Map<String, Object> expectValues;
protected AbstractCompositeDataValidator(CompositeType type){
this.type = type;
expectValues = new HashMap<String, Object>();
}
void setExpectValue(String key, Object value){
expectValues.put(key, value);
}
public void validate(CompositeData target){
if (!type.equals(target.getCompositeType()))
fail("Expect type is " + type + ", but target type is " +target.getCompositeType());
Set<String> keys = expectValues.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
assertEquals(expectValues.get(key), target.get(key));
}
}
} | 8,003 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/Validator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import javax.management.openmbean.CompositeData;
public interface Validator {
public void validate(CompositeData target);
}
| 8,004 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/AbstractArgumentPropertyValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeType;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
abstract class AbstractArgumentPropertyValidator extends AbstractCompositeDataValidator {
// if not set, means do not care about the value
private ObjectValueValidator objectValueValidator = null;
public AbstractArgumentPropertyValidator(CompositeType type){
super(type);
}
public void setObjectValueValidator(ObjectValueValidator objectValueValidator){
this.objectValueValidator = objectValueValidator;
}
public void validate(CompositeData target){
super.validate(target);
if (objectValueValidator != null){
Byte[] byteArrayValue = (Byte[])target.get(BlueprintMetadataMBean.VALUE);
CompositeData value = Util.decode(byteArrayValue);
objectValueValidator.validate(value);
}
}
}
| 8,005 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/RefValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
public class RefValidator extends AbstractCompositeDataValidator implements NonNullObjectValueValidator, TargetValidator {
public RefValidator(String componentId){
super(BlueprintMetadataMBean.REF_METADATA_TYPE);
setExpectValue(BlueprintMetadataMBean.COMPONENT_ID, componentId);
}
}
| 8,006 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/BeanPropertyValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
public class BeanPropertyValidator extends AbstractArgumentPropertyValidator{
public BeanPropertyValidator(String name){
super(BlueprintMetadataMBean.BEAN_PROPERTY_TYPE);
setExpectValue(BlueprintMetadataMBean.NAME, name);
}
} | 8,007 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/ServiceValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import static junit.framework.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import javax.management.openmbean.CompositeData;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
public class ServiceValidator extends AbstractCompositeDataValidator implements NonNullObjectValueValidator {
// a TargetValidator can be one of BeanValidator, ReferenceValidator, RefValidator
TargetValidator serviceComponentValidator = null;
List<MapEntryValidator> servicePropertyValidators = new ArrayList<MapEntryValidator>();
List<RegistrationListenerValidator> registrationListenerValidators = new ArrayList<RegistrationListenerValidator>();
public ServiceValidator(int autoExport){
super(BlueprintMetadataMBean.SERVICE_METADATA_TYPE);
this.setExpectValue(BlueprintMetadataMBean.AUTO_EXPORT, autoExport);
}
public void setServiceComponentValidator(TargetValidator targetValidator){
this.serviceComponentValidator = targetValidator;
}
public void addMapEntryValidator(MapEntryValidator... validators){
for (MapEntryValidator validator : validators)
this.servicePropertyValidators.add(validator);
}
public void addRegistrationListenerValidator(RegistrationListenerValidator... validators){
for (RegistrationListenerValidator validator : validators)
this.registrationListenerValidators.add(validator);
}
public void validate(CompositeData target){
super.validate(target);
assertNotNull("ServiceValidator must have a TargetValidator for service component", serviceComponentValidator);
serviceComponentValidator.validate(Util.decode((Byte[])target.get(BlueprintMetadataMBean.SERVICE_COMPONENT)));
if (servicePropertyValidators.size()!=0){
CompositeData[] serviceProperties = (CompositeData[])target.get(BlueprintMetadataMBean.SERVICE_PROPERTIES);
if ( servicePropertyValidators.size() != serviceProperties.length )
fail("The quantity of the service properties is not the same, expect " +servicePropertyValidators.size()+" but got "+ serviceProperties.length);
for (int i=0; i<servicePropertyValidators.size(); i++)
servicePropertyValidators.get(i).validate(serviceProperties[i]);
}
if (registrationListenerValidators.size() != 0){
CompositeData[] registrationListeners = (CompositeData[])target.get(BlueprintMetadataMBean.REGISTRATION_LISTENERS);
if ( registrationListenerValidators.size() != registrationListeners.length )
fail("The quantity of the registration listeners is not the same, expect " +registrationListenerValidators.size()+" but got "+ registrationListeners.length);
for (int i=0; i<registrationListenerValidators.size(); i++)
registrationListenerValidators.get(i).validate(registrationListeners[i]);
}
}
}
| 8,008 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/RegistrationListenerValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
public class RegistrationListenerValidator extends AbstractListenerComponentValidator {
public RegistrationListenerValidator(String registrationMethod,String unregistrationMethod){
super(BlueprintMetadataMBean.REGISTRATION_LISTENER_TYPE);
this.setExpectValue(BlueprintMetadataMBean.REGISTRATION_METHOD, registrationMethod);
this.setExpectValue(BlueprintMetadataMBean.UNREGISTRATION_METHOD, unregistrationMethod);
}
}
| 8,009 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/MapEntryValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import javax.management.openmbean.CompositeData;
import static junit.framework.Assert.*;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
public class MapEntryValidator extends AbstractCompositeDataValidator {
NonNullObjectValueValidator keyValidator = null;
ObjectValueValidator valueValidator = null;
public MapEntryValidator(){
super(BlueprintMetadataMBean.MAP_ENTRY_TYPE);
}
public void setKeyValueValidator(NonNullObjectValueValidator keyValidator, ObjectValueValidator valueValidator){
this.keyValidator = keyValidator;
this.valueValidator = valueValidator;
}
public void validate(CompositeData target){
super.validate(target); //do nothing
assertNotNull("keyValidator can not be null", keyValidator);
assertNotNull("valueValidator can not be null", valueValidator);
keyValidator.validate(Util.decode((Byte[])target.get(BlueprintMetadataMBean.KEY)));
valueValidator.validate(Util.decode((Byte[])target.get(BlueprintMetadataMBean.VALUE)));
}
}
| 8,010 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/NonNullObjectValueValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
public interface NonNullObjectValueValidator extends ObjectValueValidator{
}
| 8,011 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/ObjectValueValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
public interface ObjectValueValidator extends Validator{
}
| 8,012 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/ReferenceListValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
public class ReferenceListValidator extends AbstractServiceReferenceValidator {
public ReferenceListValidator (String interfaceName){
super(BlueprintMetadataMBean.REFERENCE_LIST_METADATA_TYPE);
this.setExpectValue(BlueprintMetadataMBean.INTERFACE, interfaceName);
}
public ReferenceListValidator (String interfaceName, int availability){
super(BlueprintMetadataMBean.REFERENCE_LIST_METADATA_TYPE);
this.setExpectValue(BlueprintMetadataMBean.INTERFACE, interfaceName);
this.setExpectValue(BlueprintMetadataMBean.AVAILABILITY, availability);
}
}
| 8,013 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/BeanArgumentValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
public class BeanArgumentValidator extends AbstractArgumentPropertyValidator{
public BeanArgumentValidator(int index, String valueType){
super(BlueprintMetadataMBean.BEAN_ARGUMENT_TYPE);
setExpectValue(BlueprintMetadataMBean.INDEX, index);
setExpectValue(BlueprintMetadataMBean.VALUE_TYPE, valueType);
}
} | 8,014 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/BlueprintEventValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import org.apache.aries.jmx.blueprint.BlueprintStateMBean;
public class BlueprintEventValidator extends AbstractCompositeDataValidator{
public BlueprintEventValidator(long bundleId, long extenderBundleId, int eventType){
super(BlueprintStateMBean.OSGI_BLUEPRINT_EVENT_TYPE);
setExpectValue(BlueprintStateMBean.BUNDLE_ID, bundleId);
setExpectValue(BlueprintStateMBean.EXTENDER_BUNDLE_ID, extenderBundleId);
setExpectValue(BlueprintStateMBean.EVENT_TYPE, eventType);
}
} | 8,015 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/ValueValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
public class ValueValidator extends AbstractCompositeDataValidator implements NonNullObjectValueValidator{
public ValueValidator(String stringValue){
super(BlueprintMetadataMBean.VALUE_METADATA_TYPE);
setExpectValue(BlueprintMetadataMBean.STRING_VALUE, stringValue);
}
public ValueValidator(String stringValue, String type){
super(BlueprintMetadataMBean.VALUE_METADATA_TYPE);
setExpectValue(BlueprintMetadataMBean.STRING_VALUE, stringValue);
setExpectValue(BlueprintMetadataMBean.TYPE, type);
}
}
| 8,016 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/AbstractServiceReferenceValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.test.blueprint.framework;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeType;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
abstract class AbstractServiceReferenceValidator extends AbstractCompositeDataValidator implements NonNullObjectValueValidator {
private List<ReferenceListenerValidator> referenceListenerValidators = new ArrayList<ReferenceListenerValidator>();
protected AbstractServiceReferenceValidator(CompositeType type) {
super(type);
}
public void addReferenceListenerValidator(ReferenceListenerValidator... validators){
for (ReferenceListenerValidator validator : validators)
this.referenceListenerValidators.add(validator);
}
public void validate(CompositeData target){
super.validate(target);
if (referenceListenerValidators.size() != 0){
CompositeData[] referenceListeners = (CompositeData[])target.get(BlueprintMetadataMBean.REFERENCE_LISTENERS);
if ( referenceListenerValidators.size() != referenceListeners.length )
fail("The quantity of the listeners is not the same, expect " +referenceListenerValidators.size()+" but got "+ referenceListeners.length);
for (int i=0; i<referenceListenerValidators.size(); i++)
referenceListenerValidators.get(i).validate(referenceListeners[i]);
}
}
}
| 8,017 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundlea/Activator.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.test.bundlea;
import java.util.Dictionary;
import java.util.Hashtable;
import org.apache.aries.jmx.test.bundlea.api.InterfaceA;
import org.apache.aries.jmx.test.bundlea.impl.A;
import org.apache.aries.jmx.test.bundleb.api.InterfaceB;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ManagedService;
import org.osgi.util.tracker.ServiceTracker;
/**
*
*
* @version $Rev$ $Date$
*/
public class Activator implements BundleActivator {
ServiceTracker tracker;
/* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
tracker = new ServiceTracker(context, InterfaceB.class.getName(), null);
tracker.open();
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_PID, "org.apache.aries.jmx.test.ServiceA");
String[] interfaces = new String[] { InterfaceA.class.getName(), ManagedService.class.getName() };
context.registerService(interfaces, new A(tracker), props);
}
/* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
tracker.close();
}
}
| 8,018 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundlea | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundlea/impl/A2.java | package org.apache.aries.jmx.test.bundlea.impl;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 A2 {
}
| 8,019 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundlea | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundlea/impl/A.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.test.bundlea.impl;
import java.util.Dictionary;
import org.apache.aries.jmx.test.bundlea.api.InterfaceA;
import org.apache.aries.jmx.test.bundleb.api.InterfaceB;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.util.tracker.ServiceTracker;
/**
*
*
* @version $Rev$ $Date$
*/
@SuppressWarnings("rawtypes")
public class A implements InterfaceA {
private ServiceTracker tracker;
private Dictionary props;
public A(ServiceTracker tracker) {
this.tracker = tracker;
}
/* (non-Javadoc)
* @see org.apache.aries.jmx.test.bundlea.api.InterfaceA#invoke()
*/
public boolean invoke() {
if (tracker.getService() != null) {
InterfaceB service = (InterfaceB) tracker.getService();
return service.invoke();
} else {
return false;
}
}
public void updated(Dictionary dictionary) throws ConfigurationException {
this.props = dictionary;
}
// test cback
public Dictionary getConfig() {
return this.props;
}
}
| 8,020 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundlea | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundlea/api/InterfaceA.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.test.bundlea.api;
import java.util.Dictionary;
import org.osgi.service.cm.ManagedService;
/**
*
*
* @version $Rev$ $Date$
*/
@SuppressWarnings("rawtypes")
public interface InterfaceA extends ManagedService {
boolean invoke();
Dictionary getConfig();
}
| 8,021 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/framework/ServiceStateMBeanTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.options;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.AttributeChangeNotification;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import junit.framework.Assert;
import org.apache.aries.jmx.AbstractIntegrationTest;
import org.apache.aries.jmx.codec.PropertyData;
import org.apache.aries.jmx.test.bundlea.api.InterfaceA;
import org.apache.aries.jmx.test.bundleb.api.InterfaceB;
import org.junit.Before;
import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
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.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.jmx.JmxConstants;
import org.osgi.jmx.framework.ServiceStateMBean;
import org.osgi.service.cm.ManagedService;
import org.osgi.service.cm.ManagedServiceFactory;
/**
*
*
* @version $Rev$ $Date$
*/
@ExamReactorStrategy(PerMethod.class)
public class ServiceStateMBeanTest extends AbstractIntegrationTest {
private ObjectName objectName;
private ServiceStateMBean mbean;
@Configuration
public Option[] configuration() {
return options(
// new VMOption( "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000" ),
// new TimeoutOption( 0 ),
jmxRuntime(),
bundlea(),
bundleb()
);
}
@Before
public void doSetUp() {
waitForMBean(ServiceStateMBean.OBJECTNAME);
objectName = waitForMBean(ServiceStateMBean.OBJECTNAME);
mbean = getMBean(objectName, ServiceStateMBean.class);
assertNotNull(mbean);
}
@Test
public void testObjectName() throws Exception {
Set<ObjectName> names = mbeanServer.queryNames(new ObjectName(ServiceStateMBean.OBJECTNAME + ",*"), null);
assertEquals(1, names.size());
ObjectName name = names.iterator().next();
Hashtable<String, String> props = name.getKeyPropertyList();
assertEquals(context().getProperty(Constants.FRAMEWORK_UUID), props.get("uuid"));
assertEquals(context().getBundle(0).getSymbolicName(), props.get("framework"));
}
@Test
public void testMBeanInterface() throws Exception {
//get bundles
Bundle a = getBundleByName("org.apache.aries.jmx.test.bundlea");
assertBundleStarted(a);
Bundle b = getBundleByName("org.apache.aries.jmx.test.bundleb");
assertBundleStarted(b);
// get services
ServiceReference refA = bundleContext.getServiceReference(InterfaceA.class.getName());
assertNotNull(refA);
long serviceAId = (Long) refA.getProperty(Constants.SERVICE_ID);
assertTrue(serviceAId > -1);
ServiceReference refB = bundleContext.getServiceReference(InterfaceB.class.getName());
assertNotNull(refB);
long serviceBId = (Long) refB.getProperty(Constants.SERVICE_ID);
assertTrue(serviceBId > -1);
ServiceReference[] refs = bundleContext.getServiceReferences(ManagedServiceFactory.class.getName(), "(" + Constants.SERVICE_PID + "=jmx.test.B.factory)");
assertNotNull(refs);
assertEquals(1, refs.length);
ServiceReference msf = refs[0];
// getBundleIdentifier
assertEquals(a.getBundleId(), mbean.getBundleIdentifier(serviceAId));
//getObjectClass
String[] objectClass = mbean.getObjectClass(serviceAId);
assertEquals(2, objectClass.length);
List<String> classNames = Arrays.asList(objectClass);
assertTrue(classNames.contains(InterfaceA.class.getName()));
assertTrue(classNames.contains(ManagedService.class.getName()));
// getProperties
TabularData serviceProperties = mbean.getProperties(serviceBId);
assertNotNull(serviceProperties);
assertEquals(JmxConstants.PROPERTIES_TYPE, serviceProperties.getTabularType());
assertTrue(serviceProperties.values().size() > 1);
assertEquals("org.apache.aries.jmx.test.ServiceB",
PropertyData.from(serviceProperties.get(new Object[] { Constants.SERVICE_PID })).getValue());
// getUsingBundles
long[] usingBundles = mbean.getUsingBundles(serviceBId);
assertEquals(1, usingBundles.length);
assertEquals(a.getBundleId(), usingBundles[0]);
// listServices
ServiceReference[] allSvsRefs = bundleContext.getAllServiceReferences(null, null);
TabularData allServices = mbean.listServices();
assertNotNull(allServices);
assertEquals(allSvsRefs.length, allServices.values().size());
// notifications
final List<Notification> received = new ArrayList<Notification>();
final List<AttributeChangeNotification> attributeChanges = new ArrayList<AttributeChangeNotification>();
mbeanServer.addNotificationListener(objectName, new NotificationListener() {
public void handleNotification(Notification notification, Object handback) {
if (notification instanceof AttributeChangeNotification) {
attributeChanges.add((AttributeChangeNotification) notification);
} else {
received.add(notification);
}
}
}, null, null);
assertNotNull(refB);
assertNotNull(msf);
b.stop();
refB = bundleContext.getServiceReference(InterfaceB.class.getName());
refs = bundleContext.getServiceReferences(ManagedServiceFactory.class.getName(), "(" + Constants.SERVICE_PID + "=jmx.test.B.factory)");
assertNull(refs);
assertNull(refB);
b.start();
refB = bundleContext.getServiceReference(InterfaceB.class.getName());
refs = bundleContext.getServiceReferences(ManagedServiceFactory.class.getName(), "(" + Constants.SERVICE_PID + "=jmx.test.B.factory)");
assertNotNull(refB);
assertNotNull(refs);
assertEquals(1, refs.length);
waitForListToReachSize(received, 4);
assertEquals(4, received.size());
assertEquals(4, attributeChanges.size());
}
private void assertBundleStarted(Bundle bundle) {
Assert.assertEquals("Bundle " + bundle.getSymbolicName() + " should be started but is in state " + bundle.getState(),
Bundle.ACTIVE, bundle.getState());
}
@Test
public void testAttributeChangeNotifications() throws Exception {
final List<AttributeChangeNotification> attributeChanges = new ArrayList<AttributeChangeNotification>();
mbeanServer.addNotificationListener(objectName, new NotificationListener() {
public void handleNotification(Notification notification, Object handback) {
if (notification instanceof AttributeChangeNotification) {
attributeChanges.add((AttributeChangeNotification) notification);
}
}
}, null, null);
assertEquals("Precondition", 0, attributeChanges.size());
long[] idsWithout = mbean.getServiceIds();
String svc = "A String Service";
ServiceRegistration reg = bundleContext.registerService(String.class.getName(), svc, null);
long id = (Long) reg.getReference().getProperty(Constants.SERVICE_ID);
long[] idsWith = new long[idsWithout.length + 1];
System.arraycopy(idsWithout, 0, idsWith, 0, idsWithout.length);
idsWith[idsWith.length - 1] = id;
Arrays.sort(idsWith);
waitForListToReachSize(attributeChanges, 1);
AttributeChangeNotification ac = attributeChanges.get(0);
assertEquals("ServiceIds", ac.getAttributeName());
long seq1 = ac.getSequenceNumber();
assertTrue(Arrays.equals(idsWithout, (long []) ac.getOldValue()));
assertTrue(Arrays.equals(idsWith, (long []) ac.getNewValue()));
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put("somekey", "someval");
reg.setProperties(props);
// Setting the properties updates the service registration, however it should not cause the attribute notification
Thread.sleep(500); // Give the system a bit of time to send potential notifications
assertEquals("Changing the service registration should not cause an attribute notification",
1, attributeChanges.size());
reg.unregister();
waitForListToReachSize(attributeChanges, 2);
AttributeChangeNotification ac2 = attributeChanges.get(1);
assertEquals("ServiceIds", ac2.getAttributeName());
assertEquals(seq1 +1, ac2.getSequenceNumber());
assertTrue(Arrays.equals(idsWith, (long []) ac2.getOldValue()));
assertTrue(Arrays.equals(idsWithout, (long []) ac2.getNewValue()));
}
@Test
public void testGetServiceIds() throws Exception {
ServiceReference[] allSvsRefs = bundleContext.getAllServiceReferences(null, null);
long[] expectedServiceIds = new long[allSvsRefs.length];
for (int i=0; i < allSvsRefs.length; i++) {
expectedServiceIds[i] = (Long) allSvsRefs[i].getProperty(Constants.SERVICE_ID);
}
long[] actualServiceIds = mbean.getServiceIds();
Arrays.sort(expectedServiceIds);
Arrays.sort(actualServiceIds);
assertTrue(Arrays.equals(expectedServiceIds, actualServiceIds));
}
@Test
public void testGetServiceAndGetProperty() throws Exception {
ServiceReference sref = bundleContext.getServiceReference(InterfaceA.class);
// Get service to increase service references
context().getService(sref);
Long serviceID = (Long) sref.getProperty(Constants.SERVICE_ID);
CompositeData svcData = mbean.getService(serviceID);
assertEquals(serviceID, svcData.get(ServiceStateMBean.IDENTIFIER));
assertEquals(sref.getBundle().getBundleId(), svcData.get(ServiceStateMBean.BUNDLE_IDENTIFIER));
Set<String> expectedClasses = new HashSet<String>(Arrays.asList(InterfaceA.class.getName(), ManagedService.class.getName()));
Set<String> actualClasses = new HashSet<String>(Arrays.asList((String []) svcData.get(ServiceStateMBean.OBJECT_CLASS)));
assertEquals(expectedClasses, actualClasses);
Bundle[] ub = sref.getUsingBundles();
assertEquals("Precondition", 1, ub.length);
assertTrue(Arrays.equals(new Long[] {ub[0].getBundleId()}, (Long[]) svcData.get("UsingBundles")));
// Test mbean.getProperty()
String pid = (String) sref.getProperty(Constants.SERVICE_PID);
CompositeData pidData = mbean.getProperty(serviceID, Constants.SERVICE_PID);
assertEquals(pid, pidData.get("Value"));
assertEquals("String", pidData.get("Type"));
CompositeData idData = mbean.getProperty(serviceID, Constants.SERVICE_ID);
assertEquals("" + serviceID, idData.get("Value"));
assertEquals("Long", idData.get("Type"));
CompositeData ocData = mbean.getProperty(serviceID, Constants.OBJECTCLASS);
String form1 = InterfaceA.class.getName() + "," + ManagedService.class.getName();
String form2 = ManagedService.class.getName() + "," + InterfaceA.class.getName();
assertTrue(ocData.get("Value").equals(form1) ||
ocData.get("Value").equals(form2));
assertEquals("Array of String", ocData.get("Type"));
context().ungetService(sref);
}
@Test
@SuppressWarnings("unchecked")
public void testServicePropertiesInListServices() throws Exception {
ServiceReference[] refs = bundleContext.getAllServiceReferences(InterfaceA.class.getName(), null);
assertEquals("Precondition", 1, refs.length);
ServiceReference ref = refs[0];
TabularData svcTab = mbean.listServices();
CompositeData svcData = svcTab.get(new Object [] {ref.getProperty(Constants.SERVICE_ID)});
Set<String> expectedOCs = new HashSet<String>(Arrays.asList(
InterfaceA.class.getName(), ManagedService.class.getName()));
Set<String> actualOCs = new HashSet<String>(
Arrays.asList((String [])svcData.get(Constants.OBJECTCLASS)));
assertEquals(expectedOCs, actualOCs);
Map<String, Object> expectedProperties = new HashMap<String, Object>();
for (String key : ref.getPropertyKeys()) {
Object value = ref.getProperty(key);
if (value.getClass().isArray())
continue;
expectedProperties.put(key, value);
}
Map<String, Object> actualProperties = new HashMap<String, Object>();
TabularData actualProps = (TabularData) svcData.get(ServiceStateMBean.PROPERTIES);
for (CompositeData cd : (Collection<CompositeData>) actualProps.values()) {
Object type = cd.get(JmxConstants.TYPE);
if (JmxConstants.STRING.equals(type)) {
actualProperties.put((String) cd.get(JmxConstants.KEY), cd.get(JmxConstants.VALUE));
} else if (JmxConstants.LONG.equals(type)) {
actualProperties.put((String) cd.get(JmxConstants.KEY), Long.valueOf(cd.get(JmxConstants.VALUE).toString()));
}
}
assertEquals(expectedProperties, actualProperties);
}
@Test
public void testListServices() throws Exception {
String filter = "(" + Constants.SERVICE_PID + "=*)";
ServiceReference[] refs = bundleContext.getAllServiceReferences(null, filter);
TabularData svcData = mbean.listServices(null, filter);
assertEquals(refs.length, svcData.size());
ServiceReference sref = bundleContext.getServiceReference(InterfaceA.class);
TabularData svcTab = mbean.listServices(InterfaceA.class.getName(), null);
assertEquals(1, svcTab.size());
CompositeData actualSvc = (CompositeData) svcTab.values().iterator().next();
CompositeData expectedSvc = mbean.getService((Long) sref.getProperty(Constants.SERVICE_ID));
assertEquals(expectedSvc, actualSvc);
}
@SuppressWarnings("unchecked")
@Test
public void testListServicesSelectiveItems() throws Exception {
String filter = "(|(service.pid=org.apache.aries.jmx.test.ServiceB)(service.pid=jmx.test.B.factory))";
ServiceReference[] refs = bundleContext.getAllServiceReferences(null, filter);
TabularData svcData = mbean.listServices(null, filter, ServiceStateMBean.BUNDLE_IDENTIFIER);
assertEquals(refs.length, svcData.size());
long id = refs[0].getBundle().getBundleId();
for (ServiceReference ref : refs) {
assertEquals("Precondition", id, ref.getBundle().getBundleId());
}
for (CompositeData cd : new ArrayList<CompositeData>((Collection<CompositeData>) svcData.values())) {
assertEquals(id, cd.get(ServiceStateMBean.BUNDLE_IDENTIFIER));
assertNotNull(cd.get(ServiceStateMBean.IDENTIFIER));
assertNull(cd.get(ServiceStateMBean.OBJECT_CLASS));
assertNull(cd.get(ServiceStateMBean.USING_BUNDLES));
}
}
private void waitForListToReachSize(List<?> list, int targetSize) throws InterruptedException {
int i = 0;
while (list.size() < targetSize && i < 3) {
Thread.sleep(1000);
i++;
}
}
}
| 8,022 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/framework/BundleStateMBeanTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.options;
import static org.osgi.jmx.framework.BundleStateMBean.OBJECTNAME;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import javax.management.AttributeChangeNotification;
import javax.management.AttributeChangeNotificationFilter;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import org.apache.aries.jmx.AbstractIntegrationTest;
import org.apache.aries.jmx.codec.BundleData.Header;
import org.junit.Before;
import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
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.framework.Version;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.jmx.framework.BundleStateMBean;
/**
* @version $Rev$ $Date$
*/
@ExamReactorStrategy(PerMethod.class)
public class BundleStateMBeanTest extends AbstractIntegrationTest {
private ObjectName objectName;
private BundleStateMBean mbean;
private Bundle a;
private Bundle b;
private Bundle fragc;
private Bundle d;
@Configuration
public Option[] configuration() {
return options(
// new VMOption("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"),
// new TimeoutOption( 0 ),
jmxRuntime(),
bundlea(),
bundleb(),
fragmentc(),
bundled(),
bundlee());
}
@Before
public void doSetUp() throws Exception {
objectName = waitForMBean(BundleStateMBean.OBJECTNAME);
mbean = getMBean(BundleStateMBean.OBJECTNAME, BundleStateMBean.class);
//get bundles
a = getBundleByName("org.apache.aries.jmx.test.bundlea");
b = getBundleByName("org.apache.aries.jmx.test.bundleb");
fragc = getBundleByName("org.apache.aries.jmx.test.fragc");
d = getBundleByName("org.apache.aries.jmx.test.bundled");
}
@Test
public void testObjectName() throws Exception {
Set<ObjectName> names = mbeanServer.queryNames(new ObjectName(BundleStateMBean.OBJECTNAME + ",*"), null);
assertEquals(1, names.size());
ObjectName name = names.iterator().next();
Hashtable<String, String> props = name.getKeyPropertyList();
assertEquals(context().getProperty(Constants.FRAMEWORK_UUID), props.get("uuid"));
assertEquals(context().getBundle(0).getSymbolicName(), props.get("framework"));
}
@Test
public void testMBeanInterface() throws Exception {
// exportedPackages
String[] exports = mbean.getExportedPackages(a.getBundleId());
assertEquals(2, exports.length);
List<String> packages = Arrays.asList(exports);
assertTrue(packages.contains("org.apache.aries.jmx.test.bundlea.api;2.0.0"));
assertTrue(packages.contains("org.apache.aries.jmx.test.fragmentc;0.0.0"));
// fragments
long[] fragments = mbean.getFragments(a.getBundleId());
assertEquals(1, fragments.length);
assertEquals(fragc.getBundleId() , fragments[0]);
// headers
TabularData headers = mbean.getHeaders(b.getBundleId());
assertNotNull(headers);
assertEquals(BundleStateMBean.HEADERS_TYPE, headers.getTabularType());
assertTrue(headers.values().size() >= 4 );
assertEquals("org.apache.aries.jmx.test.bundleb", Header.from(headers.get(new Object[] {Constants.BUNDLE_SYMBOLICNAME})).getValue());
// hosts
long[] hosts = mbean.getHosts(fragc.getBundleId());
assertEquals(1, hosts.length);
assertEquals(a.getBundleId() , hosts[0]);
//imported packages
String[] imports = mbean.getImportedPackages(a.getBundleId());
assertTrue(imports.length >= 3);
List<String> importedPackages = Arrays.asList(imports);
Version version = getPackageVersion("org.osgi.framework");
assertTrue(importedPackages.contains("org.osgi.framework;" + version.toString()));
assertTrue(importedPackages.contains("org.apache.aries.jmx.test.bundleb.api;1.1.0"));
//last modified
assertTrue(mbean.getLastModified(b.getBundleId()) > 0);
//location
assertEquals(b.getLocation(), mbean.getLocation(b.getBundleId()));
//registered services
long[] serviceIds = mbean.getRegisteredServices(a.getBundleId());
assertEquals(1, serviceIds.length);
//required bundles
long[] required = mbean.getRequiredBundles(d.getBundleId());
assertEquals(1, required.length);
assertEquals(a.getBundleId(), required[0]);
//requiring bundles
long[] requiring = mbean.getRequiringBundles(a.getBundleId());
assertEquals(2, requiring.length);
assertTrue(fragc.getSymbolicName(), arrayContains(fragc.getBundleId(), requiring));
assertTrue(d.getSymbolicName(), arrayContains(d.getBundleId(), requiring));
//services in use
long[] servicesInUse = mbean.getServicesInUse(a.getBundleId());
assertEquals(1, servicesInUse.length);
//start level
long startLevel = mbean.getStartLevel(b.getBundleId());
assertTrue(startLevel >= 0);
//state
assertEquals("ACTIVE", mbean.getState(b.getBundleId()));
//isFragment
assertFalse(mbean.isFragment(b.getBundleId()));
assertTrue(mbean.isFragment(fragc.getBundleId()));
//isRemovalPending
assertFalse(mbean.isRemovalPending(b.getBundleId()));
// isRequired
assertTrue(mbean.isRequired(a.getBundleId()));
assertTrue(mbean.isRequired(b.getBundleId()));
// listBundles
TabularData bundlesTable = mbean.listBundles();
assertNotNull(bundlesTable);
assertEquals(BundleStateMBean.BUNDLES_TYPE, bundlesTable.getTabularType());
assertEquals(bundleContext.getBundles().length, bundlesTable.values().size());
// notifications
final List<Notification> received = new ArrayList<Notification>();
mbeanServer.addNotificationListener(objectName, new NotificationListener() {
public void handleNotification(Notification notification, Object handback) {
received.add(notification);
}
}, null, null);
assertEquals(Bundle.ACTIVE, b.getState());
b.stop();
assertEquals(Bundle.RESOLVED, b.getState());
b.start();
assertEquals(Bundle.ACTIVE, b.getState());
int i = 0;
while (received.size() < 2 && i < 3) {
Thread.sleep(1000);
i++;
}
assertEquals(2, received.size());
}
@Test
public void testAttributeChangeNotifications() throws Exception {
final List<AttributeChangeNotification> attributeChanges = new ArrayList<AttributeChangeNotification>();
AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter();
filter.disableAllAttributes();
filter.enableAttribute("BundleIds");
mbeanServer.addNotificationListener(objectName, new NotificationListener() {
public void handleNotification(Notification notification, Object handback) {
attributeChanges.add((AttributeChangeNotification) notification);
}
}, filter, null);
long[] idsWithout = mbean.getBundleIds();
assertEquals("Precondition", 0, attributeChanges.size());
Manifest mf = new Manifest();
mf.getMainAttributes().putValue("Bundle-ManifestVersion", "2");
mf.getMainAttributes().putValue("Bundle-SymbolicName", "empty-test-bundle");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jos = new JarOutputStream(baos, mf);
jos.closeEntry();
jos.close();
InputStream bais = new ByteArrayInputStream(baos.toByteArray());
Bundle bundle = bundleContext.installBundle("http://somelocation", bais);
long[] idsWith = new long[idsWithout.length + 1];
System.arraycopy(idsWithout, 0, idsWith, 0, idsWithout.length);
idsWith[idsWith.length - 1] = bundle.getBundleId();
Arrays.sort(idsWith);
waitForListToReachSize(attributeChanges, 1);
assertEquals(1, attributeChanges.size());
AttributeChangeNotification ac = attributeChanges.get(0);
assertEquals("BundleIds", ac.getAttributeName());
long oldSequence = ac.getSequenceNumber();
assertTrue(Arrays.equals(idsWithout, (long []) ac.getOldValue()));
assertTrue(Arrays.equals(idsWith, (long []) ac.getNewValue()));
bundle.uninstall();
waitForListToReachSize(attributeChanges, 2);
AttributeChangeNotification ac2 = attributeChanges.get(1);
assertEquals("BundleIds", ac2.getAttributeName());
assertEquals(oldSequence +1, ac2.getSequenceNumber());
assertTrue(Arrays.equals(idsWith, (long []) ac2.getOldValue()));
assertTrue(Arrays.equals(idsWithout, (long []) ac2.getNewValue()));
}
@Test
public void testBundleIDsAttribute() throws Exception{
Set<Long> expectedIDs = new HashSet<Long>();
for (Bundle b : context().getBundles()) {
expectedIDs.add(b.getBundleId());
}
BundleStateMBean mbean = getMBean(OBJECTNAME, BundleStateMBean.class);
long[] actual = mbean.getBundleIds();
Set<Long> actualIDs = new HashSet<Long>();
for (long id : actual) {
actualIDs.add(id);
}
assertEquals(expectedIDs, actualIDs);
}
@Test
@SuppressWarnings({ "unchecked" })
public void testHeaderLocalization() throws Exception {
Bundle bundleE = context().getBundleByName("org.apache.aries.jmx.test.bundlee");
CompositeData cd = mbean.getBundle(bundleE.getBundleId());
long id = (Long) cd.get(BundleStateMBean.IDENTIFIER);
assertEquals("Description", mbean.getHeader(id, Constants.BUNDLE_DESCRIPTION));
assertEquals("Description", mbean.getHeader(id, Constants.BUNDLE_DESCRIPTION, "en"));
assertEquals("Omschrijving", mbean.getHeader(id, Constants.BUNDLE_DESCRIPTION, "nl"));
TabularData td = mbean.getHeaders(id);
boolean found = false;
for (CompositeData d : (Collection<CompositeData>) td.values()) {
if (Constants.BUNDLE_DESCRIPTION.equals(d.get(BundleStateMBean.KEY))) {
assertEquals("Description", d.get(BundleStateMBean.VALUE));
found = true;
break;
}
}
assertTrue(found);
TabularData tdNL = mbean.getHeaders(id, "nl");
boolean foundNL = false;
for (CompositeData d : (Collection<CompositeData>) tdNL.values()) {
if (Constants.BUNDLE_DESCRIPTION.equals(d.get(BundleStateMBean.KEY))) {
assertEquals("Omschrijving", d.get(BundleStateMBean.VALUE));
foundNL = true;
break;
}
}
assertTrue(foundNL);
}
private Version getPackageVersion(String packageName) {
Bundle systemBundle = context().getBundle(0);
BundleWiring wiring = (BundleWiring) systemBundle.adapt(BundleWiring.class);
List<BundleCapability> packages = wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE);
for (BundleCapability pkg : packages) {
Map<String, Object> attrs = pkg.getAttributes();
if (attrs.get(BundleRevision.PACKAGE_NAMESPACE).equals(packageName)) {
return (Version) attrs.get(Constants.VERSION_ATTRIBUTE);
}
}
throw new IllegalStateException("Package version not found for " + packageName);
}
private static boolean arrayContains(long value, long[] values) {
for (long i : values) {
if (i == value) {
return true;
}
}
return false;
}
private void waitForListToReachSize(List<?> list, int targetSize) throws InterruptedException {
int i = 0;
while (list.size() < targetSize && i < 3) {
Thread.sleep(1000);
i++;
}
}
}
| 8,023 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/framework/FrameworkMBeanTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.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 static org.ops4j.pax.exam.CoreOptions.provision;
import static org.ops4j.pax.tinybundles.core.TinyBundles.bundle;
import static org.ops4j.pax.tinybundles.core.TinyBundles.withBnd;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import org.apache.aries.jmx.AbstractIntegrationTest;
import org.apache.aries.jmx.codec.BatchActionResult;
import org.junit.Before;
import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
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.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleRevisions;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.framework.wiring.FrameworkWiring;
import org.osgi.jmx.framework.FrameworkMBean;
/**
* @version $Rev$ $Date$
*/
@ExamReactorStrategy(PerMethod.class)
public class FrameworkMBeanTest extends AbstractIntegrationTest {
private FrameworkMBean framework;
@Configuration
public Option[] configuration() {
return CoreOptions.options(
// new VMOption( "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000" ),
// new TimeoutOption( 0 ),
jmxRuntime(),
bundlea1(),
bundleb1()
);
}
protected Option bundlea1() {
return provision(bundle()
.add(org.apache.aries.jmx.test.bundlea.api.InterfaceA.class)
.add(org.apache.aries.jmx.test.bundlea.impl.A2.class)
.set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.jmx.test.bundlea")
.set(Constants.BUNDLE_VERSION, "1")
.set(Constants.EXPORT_PACKAGE, "org.apache.aries.jmx.test.bundlea.api")
.build(withBnd()));
}
protected Option bundleb1() {
return provision(bundle()
.add(org.apache.aries.jmx.test.bundleb.api.InterfaceB.class)
.set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.jmx.test.bundleb")
.set(Constants.IMPORT_PACKAGE, "org.apache.aries.jmx.test.bundlea.api," +
"org.apache.aries.jmx.test.bundlea.impl;resolution:=optional")
.build(withBnd()));
}
@Before
public void doSetUp() throws BundleException {
for (Bundle bundle : context().getBundles()) {
System.out.println(bundle.getBundleId() + " " + bundle.getSymbolicName() + " " + bundle.getState());
};
waitForMBean(FrameworkMBean.OBJECTNAME);
framework = getMBean(FrameworkMBean.OBJECTNAME, FrameworkMBean.class);
}
@Test
public void testObjectName() throws Exception {
Set<ObjectName> names = mbeanServer.queryNames(new ObjectName(FrameworkMBean.OBJECTNAME + ",*"), null);
assertEquals(1, names.size());
ObjectName name = names.iterator().next();
Hashtable<String, String> props = name.getKeyPropertyList();
assertEquals(context().getProperty(Constants.FRAMEWORK_UUID), props.get("uuid"));
assertEquals(context().getBundle(0).getSymbolicName(), props.get("framework"));
}
@Test
public void testGetProperty() throws Exception {
String expectedVer = context().getProperty(Constants.FRAMEWORK_VERSION);
String actualVer = framework.getProperty(Constants.FRAMEWORK_VERSION);
assertEquals(expectedVer, actualVer);
String expectedTmp = context().getProperty("java.io.tmpdir");
String actualTmp = framework.getProperty("java.io.tmpdir");
assertEquals(expectedTmp, actualTmp);
}
@Test
public void testGetDependencyClosure() throws Exception {
Bundle bundleA = getBundleByName("org.apache.aries.jmx.test.bundlea");
Bundle bundleB = getBundleByName("org.apache.aries.jmx.test.bundleb");
BundleWiring bw = (BundleWiring) bundleB.adapt(BundleWiring.class);
List<BundleWire> initialRequiredWires = bw.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
assertEquals(1, initialRequiredWires.size());
BundleWire wire = initialRequiredWires.get(0);
Map<String, Object> capabilityAttributes = wire.getCapability().getAttributes();
assertEquals("Precondition", bundleA.getSymbolicName(), capabilityAttributes.get(Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE));
assertEquals("Precondition", new Version("1.0"), capabilityAttributes.get(Constants.BUNDLE_VERSION_ATTRIBUTE));
assertEquals("Precondition", "org.apache.aries.jmx.test.bundlea.api", capabilityAttributes.get(BundleRevision.PACKAGE_NAMESPACE));
Collection<Bundle> expectedDC = ((FrameworkWiring) context().getBundle(0).adapt(FrameworkWiring.class)).getDependencyClosure(Collections.singleton(bundleA));
Set<Long> expectedClosure = new TreeSet<Long>();
for (Bundle b : expectedDC) {
expectedClosure.add(b.getBundleId());
}
long[] actualDC = framework.getDependencyClosure(new long [] {bundleA.getBundleId()});
Set<Long> actualClosure = new TreeSet<Long>();
for (long l : actualDC) {
actualClosure.add(l);
}
assertEquals(expectedClosure, actualClosure);
}
@Test
public void testRefreshBundleAndWait() throws Exception {
FrameworkWiring frameworkWiring = (FrameworkWiring) context().getBundle(0).adapt(FrameworkWiring.class);
Bundle bundleA = getBundleByName("org.apache.aries.jmx.test.bundlea");
Bundle bundleB = getBundleByName("org.apache.aries.jmx.test.bundleb");
BundleWiring bw = (BundleWiring) bundleB.adapt(BundleWiring.class);
List<BundleWire> initialRequiredWires = bw.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
assertEquals(1, initialRequiredWires.size());
BundleWire wire = initialRequiredWires.get(0);
Map<String, Object> capabilityAttributes = wire.getCapability().getAttributes();
assertEquals("Precondition", bundleA.getSymbolicName(), capabilityAttributes.get(Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE));
assertEquals("Precondition", new Version("1.0"), capabilityAttributes.get(Constants.BUNDLE_VERSION_ATTRIBUTE));
assertEquals("Precondition", "org.apache.aries.jmx.test.bundlea.api", capabilityAttributes.get(BundleRevision.PACKAGE_NAMESPACE));
// Create an updated version of Bundle A, which an extra export and version 1.1
Manifest manifest = new Manifest();
manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.jmx.test.bundlea");
manifest.getMainAttributes().putValue(Constants.BUNDLE_VERSION, "1.1");
manifest.getMainAttributes().putValue(Constants.EXPORT_PACKAGE, "org.apache.aries.jmx.test.bundlea.api,org.apache.aries.jmx.test.bundlea.impl");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jos = new JarOutputStream(baos, manifest);
addResourceToJar("org/apache/aries/jmx/test/bundlea/api/InterfaceA.class", jos, bundleA);
addResourceToJar("org/apache/aries/jmx/test/bundlea/impl/A2.class", jos, bundleA);
jos.close();
assertEquals("Precondition", 0, frameworkWiring.getRemovalPendingBundles().size());
assertEquals(0, framework.getRemovalPendingBundles().length);
assertEquals("Precondition", 1, ((BundleRevisions) bundleA.adapt(BundleRevisions.class)).getRevisions().size());
bundleA.update(new ByteArrayInputStream(baos.toByteArray()));
assertEquals("There should be 2 revisions now", 2, ((BundleRevisions) bundleA.adapt(BundleRevisions.class)).getRevisions().size());
assertEquals("No refresh called, the bundle wiring for B should still be the old one",
bw, bundleB.adapt(BundleWiring.class));
assertEquals("Precondition", 1, frameworkWiring.getRemovalPendingBundles().size());
assertEquals(1, framework.getRemovalPendingBundles().length);
assertEquals(((Bundle) frameworkWiring.getRemovalPendingBundles().iterator().next()).getBundleId(),
framework.getRemovalPendingBundles()[0]);
assertTrue(framework.refreshBundleAndWait(bundleB.getBundleId()));
List<BundleWire> requiredWires = ((BundleWiring) bundleB.adapt(BundleWiring.class)).getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
assertEquals(2, requiredWires.size());
List<String> imported = new ArrayList<String>();
for (BundleWire w : requiredWires) {
Map<String, Object> ca = w.getCapability().getAttributes();
assertEquals(bundleA.getSymbolicName(), ca.get(Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE));
imported.add(ca.get(BundleRevision.PACKAGE_NAMESPACE).toString());
if ("org.apache.aries.jmx.test.bundlea.impl".equals(ca.get(BundleRevision.PACKAGE_NAMESPACE))) {
// Came across an issue where equinox was reporting the other package as still coming from from the 1.0 bundle
// not sure if this is a bug or not...
assertEquals(new Version("1.1"), ca.get(Constants.BUNDLE_VERSION_ATTRIBUTE));
}
}
assertEquals(Arrays.asList("org.apache.aries.jmx.test.bundlea.api", "org.apache.aries.jmx.test.bundlea.impl"), imported);
}
@Test
public void testRefreshBundlesAndWait() throws Exception {
Bundle bundleA = getBundleByName("org.apache.aries.jmx.test.bundlea");
Bundle bundleB = getBundleByName("org.apache.aries.jmx.test.bundleb");
BundleWiring bw = (BundleWiring) bundleB.adapt(BundleWiring.class);
List<BundleWire> initialRequiredWires = bw.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
assertEquals(1, initialRequiredWires.size());
BundleWire wire = initialRequiredWires.get(0);
Map<String, Object> capabilityAttributes = wire.getCapability().getAttributes();
assertEquals("Precondition", bundleA.getSymbolicName(), capabilityAttributes.get(Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE));
assertEquals("Precondition", new Version("1.0"), capabilityAttributes.get(Constants.BUNDLE_VERSION_ATTRIBUTE));
assertEquals("Precondition", "org.apache.aries.jmx.test.bundlea.api", capabilityAttributes.get(BundleRevision.PACKAGE_NAMESPACE));
// Create an updated version of Bundle A, which an extra export and version 1.1
Manifest manifest = new Manifest();
manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.jmx.test.bundlea");
manifest.getMainAttributes().putValue(Constants.BUNDLE_VERSION, "1.1");
manifest.getMainAttributes().putValue(Constants.EXPORT_PACKAGE, "org.apache.aries.jmx.test.bundlea.api,org.apache.aries.jmx.test.bundlea.impl");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jos = new JarOutputStream(baos, manifest);
addResourceToJar("org/apache/aries/jmx/test/bundlea/api/InterfaceA.class", jos, bundleA);
addResourceToJar("org/apache/aries/jmx/test/bundlea/impl/A2.class", jos, bundleA);
jos.close();
assertEquals("Precondition", 1, ((BundleRevisions) bundleA.adapt(BundleRevisions.class)).getRevisions().size());
bundleA.update(new ByteArrayInputStream(baos.toByteArray()));
assertEquals("There should be 2 revisions now", 2, ((BundleRevisions) bundleA.adapt(BundleRevisions.class)).getRevisions().size());
assertEquals("No refresh called, the bundle wiring for B should still be the old one",
bw, bundleB.adapt(BundleWiring.class));
FrameworkMBean framework = getMBean(FrameworkMBean.OBJECTNAME, FrameworkMBean.class);
CompositeData result = framework.refreshBundlesAndWait(new long[] {bundleB.getBundleId()});
assertTrue((Boolean) result.get(FrameworkMBean.SUCCESS));
assertTrue(Arrays.equals(new Long[] {bundleB.getBundleId()}, (Long []) result.get(FrameworkMBean.COMPLETED)));
List<BundleWire> requiredWires = ((BundleWiring) bundleB.adapt(BundleWiring.class)).getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
assertEquals(2, requiredWires.size());
List<String> imported = new ArrayList<String>();
for (BundleWire w : requiredWires) {
Map<String, Object> ca = w.getCapability().getAttributes();
assertEquals(bundleA.getSymbolicName(), ca.get(Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE));
imported.add(ca.get(BundleRevision.PACKAGE_NAMESPACE).toString());
if ("org.apache.aries.jmx.test.bundlea.impl".equals(ca.get(BundleRevision.PACKAGE_NAMESPACE))) {
// Came across an issue where equinox was reporting the other package as still coming from from the 1.0 bundle
// not sure if this is a bug or not...
assertEquals(new Version("1.1"), ca.get(Constants.BUNDLE_VERSION_ATTRIBUTE));
}
}
assertEquals(Arrays.asList("org.apache.aries.jmx.test.bundlea.api", "org.apache.aries.jmx.test.bundlea.impl"), imported);
}
@Test
public void testRefreshBundlesAndWait2() throws Exception {
Bundle bundleA = getBundleByName("org.apache.aries.jmx.test.bundlea");
Bundle bundleB = getBundleByName("org.apache.aries.jmx.test.bundleb");
BundleWiring bw = (BundleWiring) bundleB.adapt(BundleWiring.class);
List<BundleWire> initialRequiredWires = bw.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
assertEquals(1, initialRequiredWires.size());
BundleWire wire = initialRequiredWires.get(0);
Map<String, Object> capabilityAttributes = wire.getCapability().getAttributes();
assertEquals("Precondition", bundleA.getSymbolicName(), capabilityAttributes.get(Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE));
assertEquals("Precondition", new Version("1.0"), capabilityAttributes.get(Constants.BUNDLE_VERSION_ATTRIBUTE));
assertEquals("Precondition", "org.apache.aries.jmx.test.bundlea.api", capabilityAttributes.get(BundleRevision.PACKAGE_NAMESPACE));
// Create an updated version of Bundle A, which an extra export and version 1.1
Manifest manifest = new Manifest();
manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.jmx.test.bundlea");
manifest.getMainAttributes().putValue(Constants.BUNDLE_VERSION, "1.1");
manifest.getMainAttributes().putValue(Constants.EXPORT_PACKAGE, "org.apache.aries.jmx.test.bundlea.api,org.apache.aries.jmx.test.bundlea.impl");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jos = new JarOutputStream(baos, manifest);
addResourceToJar("org/apache/aries/jmx/test/bundlea/api/InterfaceA.class", jos, bundleA);
addResourceToJar("org/apache/aries/jmx/test/bundlea/impl/A2.class", jos, bundleA);
jos.close();
assertEquals("Precondition", 1, ((BundleRevisions) bundleA.adapt(BundleRevisions.class)).getRevisions().size());
bundleA.update(new ByteArrayInputStream(baos.toByteArray()));
assertEquals("There should be 2 revisions now", 2, ((BundleRevisions) bundleA.adapt(BundleRevisions.class)).getRevisions().size());
assertEquals("No refresh called, the bundle wiring for B should still be the old one",
bw, ((BundleWiring) bundleB.adapt(BundleWiring.class)));
FrameworkMBean framework = getMBean(FrameworkMBean.OBJECTNAME, FrameworkMBean.class);
CompositeData result = framework.refreshBundlesAndWait(null);
Set<Long> completed = new HashSet<Long>(Arrays.asList((Long []) result.get(FrameworkMBean.COMPLETED)));
assertTrue(completed.contains(bundleA.getBundleId()));
assertTrue(completed.contains(bundleB.getBundleId()));
List<BundleWire> requiredWires = ((BundleWiring) bundleB.adapt(BundleWiring.class)).getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
assertEquals(2, requiredWires.size());
List<String> imported = new ArrayList<String>();
for (BundleWire w : requiredWires) {
Map<String, Object> ca = w.getCapability().getAttributes();
assertEquals(bundleA.getSymbolicName(), ca.get(Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE));
imported.add(ca.get(BundleRevision.PACKAGE_NAMESPACE).toString());
if ("org.apache.aries.jmx.test.bundlea.impl".equals(ca.get(BundleRevision.PACKAGE_NAMESPACE))) {
// Came across an issue where equinox was reporting the other package as still coming from from the 1.0 bundle
// not sure if this is a bug or not...
assertEquals(new Version("1.1"), ca.get(Constants.BUNDLE_VERSION_ATTRIBUTE));
}
}
assertEquals(Arrays.asList("org.apache.aries.jmx.test.bundlea.api", "org.apache.aries.jmx.test.bundlea.impl"), imported);
}
private void addResourceToJar(String resourceName, JarOutputStream jos, Bundle bundle) throws IOException {
InputStream intfIs = bundle.getResource("/" + resourceName).openStream();
JarEntry entry = new JarEntry(resourceName);
jos.putNextEntry(entry);
try {
Streams.pump(intfIs, jos);
} finally {
jos.closeEntry();
}
}
@Test
public void testMBeanInterface() throws IOException {
long[] bundleIds = new long[]{1,2};
int[] newlevels = new int[]{1,1};
CompositeData compData = framework.setBundleStartLevels(bundleIds, newlevels);
assertNotNull(compData);
BatchActionResult batch2 = BatchActionResult.from(compData);
assertNotNull(batch2.getCompleted());
assertTrue(batch2.isSuccess());
assertNull(batch2.getError());
assertNull(batch2.getRemainingItems());
File file = File.createTempFile("bundletest", ".jar");
file.deleteOnExit();
Manifest man = new Manifest();
man.getMainAttributes().putValue("Manifest-Version", "1.0");
JarOutputStream jaros = new JarOutputStream(new FileOutputStream(file), man);
jaros.flush();
jaros.close();
long bundleId = 0;
try {
bundleId = framework.installBundleFromURL(file.getAbsolutePath(), file.toURI().toString());
} catch (Exception e) {
fail("Installation of test bundle shouldn't fail");
}
try{
framework.uninstallBundle(bundleId);
} catch (Exception e) {
fail("Uninstallation of test bundle shouldn't fail");
}
}
} | 8,024 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/framework/PackageStateMBeanTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.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.ops4j.pax.exam.CoreOptions.options;
import java.io.IOException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Set;
import javax.management.ObjectName;
import javax.management.openmbean.TabularData;
import org.apache.aries.jmx.AbstractIntegrationTest;
import org.junit.Before;
import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.Constants;
import org.osgi.jmx.framework.PackageStateMBean;
/**
*
*
* @version $Rev$ $Date$
*/
public class PackageStateMBeanTest extends AbstractIntegrationTest {
@Configuration
public Option[] configuration() {
return options(
jmxRuntime(),
bundlea()
);
}
@Before
public void doSetUp() {
waitForMBean(PackageStateMBean.OBJECTNAME);
}
@Test
public void testObjectName() throws Exception {
Set<ObjectName> names = mbeanServer.queryNames(new ObjectName(PackageStateMBean.OBJECTNAME + ",*"), null);
assertEquals(1, names.size());
ObjectName name = names.iterator().next();
Hashtable<String, String> props = name.getKeyPropertyList();
assertEquals(context().getProperty(Constants.FRAMEWORK_UUID), props.get("uuid"));
assertEquals(context().getBundle(0).getSymbolicName(), props.get("framework"));
}
@Test
public void testMBeanInterface() throws IOException {
PackageStateMBean packagaState = getMBean(PackageStateMBean.OBJECTNAME, PackageStateMBean.class);
assertNotNull(packagaState);
long[] exportingBundles = packagaState.getExportingBundles("org.osgi.jmx.framework", "1.7.0");
assertNotNull(exportingBundles);
assertTrue("Should find a bundle exporting org.osgi.jmx.framework", exportingBundles.length > 0);
long[] exportingBundles2 = packagaState.getExportingBundles("test", "1.0.0");
assertNull("Shouldn't find a bundle exporting test package", exportingBundles2);
long[] importingBundlesId = packagaState
.getImportingBundles("org.osgi.jmx.framework", "1.7.0", exportingBundles[0]);
assertTrue("Should find bundles importing org.osgi.jmx.framework", importingBundlesId.length > 0);
TabularData table = packagaState.listPackages();
assertNotNull("TabularData containing CompositeData with packages info shouldn't be null", table);
assertEquals("TabularData should be a type PACKAGES", PackageStateMBean.PACKAGES_TYPE, table.getTabularType());
Collection<?> colData = table.values();
assertNotNull("Collection of CompositeData shouldn't be null", colData);
assertFalse("Collection of CompositeData should contain elements", colData.isEmpty());
boolean isRemovalPending = packagaState.isRemovalPending("org.osgi.jmx.framework", "1.7.0", exportingBundles[0]);
assertFalse("Should removal pending on org.osgi.jmx.framework be false", isRemovalPending);
}
}
| 8,025 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/framework/Streams.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.framework;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Streams {
private Streams() {}
public static void pump(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[8192];
int length = 0;
int offset = 0;
while ((length = is.read(bytes, offset, bytes.length - offset)) != -1) {
offset += length;
if (offset == bytes.length) {
os.write(bytes, 0, bytes.length);
offset = 0;
}
}
if (offset != 0) {
os.write(bytes, 0, offset);
}
}
public static byte [] suck(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
pump(is, baos);
return baos.toByteArray();
} finally {
is.close();
}
}
}
| 8,026 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/framework | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/framework/wiring/BundleWiringStateMBeanTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework.wiring;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import org.apache.aries.jmx.AbstractIntegrationTest;
import org.apache.aries.jmx.codec.PropertyData;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleRevisions;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.jmx.framework.wiring.BundleWiringStateMBean;
public class BundleWiringStateMBeanTest extends AbstractIntegrationTest {
private BundleWiringStateMBean brsMBean;
private Bundle bundleA;
@Configuration
public Option[] configuration() {
return CoreOptions.options(
// new VMOption( "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000" ),
// new TimeoutOption( 0 ),
jmxRuntime(),
bundlea(),
bundleb(),
fragmentc(),
bundled()
);
}
@Before
public void doSetUp() throws Exception {
brsMBean = getMBean(BundleWiringStateMBean.OBJECTNAME, BundleWiringStateMBean.class);
bundleA = getBundleByName("org.apache.aries.jmx.test.bundlea");
}
@Test
public void testObjectName() throws Exception {
Set<ObjectName> names = mbeanServer.queryNames(new ObjectName(BundleWiringStateMBean.OBJECTNAME + ",*"), null);
assertEquals(1, names.size());
ObjectName name = names.iterator().next();
Hashtable<String, String> props = name.getKeyPropertyList();
assertEquals(context().getProperty(Constants.FRAMEWORK_UUID), props.get("uuid"));
assertEquals(context().getBundle(0).getSymbolicName(), props.get("framework"));
}
@Test
public void testGetCurrentRevisionDeclaredRequirements() throws Exception {
Bundle a = getBundleByName("org.apache.aries.jmx.test.bundlea");
BundleRevision br = (BundleRevision) a.adapt(BundleRevision.class);
List<BundleRequirement> requirements = br.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE);
CompositeData[] jmxRequirements = brsMBean.getCurrentRevisionDeclaredRequirements(a.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
Assert.assertEquals(requirements.size(), jmxRequirements.length);
Map<Map<String, Object>, Map<String, String>> expectedRequirements = requirementsToMap(requirements);
Map<Map<String, Object>, Map<String, String>> actualRequirements = jmxCapReqToMap(jmxRequirements);
Assert.assertEquals(expectedRequirements, actualRequirements);
}
@Test
public void testGetCurrentRevisionDeclaredCapabilities() throws Exception {
BundleRevision br = (BundleRevision) bundleA.adapt(BundleRevision.class);
List<BundleCapability> capabilities = br.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE);
CompositeData[] jmxCapabilities = brsMBean.getCurrentRevisionDeclaredCapabilities(bundleA.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
Assert.assertEquals(capabilities.size(), jmxCapabilities.length);
Map<Map<String, Object>, Map<String, String>> expectedCapabilities = capabilitiesToMap(capabilities);
Map<Map<String, Object>, Map<String, String>> actualCapabilities = jmxCapReqToMap(jmxCapabilities);
Assert.assertEquals(expectedCapabilities, actualCapabilities);
}
@Test
public void testGetRevisionsDeclaredRequirements() throws Exception {
BundleRevisions revisions = (BundleRevisions) bundleA.adapt(BundleRevisions.class);
Assert.assertEquals("Precondition", 1, revisions.getRevisions().size());
TabularData jmxRequirementsTable = brsMBean.getRevisionsDeclaredRequirements(bundleA.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
Assert.assertEquals(1, jmxRequirementsTable.size());
List<BundleRequirement> requirements = ((BundleRevision) revisions.getRevisions().iterator().next()).getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE);
CompositeData jmxRevRequirements = (CompositeData) jmxRequirementsTable.values().iterator().next();
CompositeData[] jmxRequirements = (CompositeData[]) jmxRevRequirements.get(BundleWiringStateMBean.REQUIREMENTS);
Map<Map<String, Object>, Map<String, String>> expectedRequirements = requirementsToMap(requirements);
Map<Map<String, Object>, Map<String, String>> actualRequirements = jmxCapReqToMap(jmxRequirements);
Assert.assertEquals(expectedRequirements, actualRequirements);
}
@Test
public void testGetRevisionsDeclaredCapabilities() throws Exception {
BundleRevisions revisions = (BundleRevisions) bundleA.adapt(BundleRevisions.class);
Assert.assertEquals("Precondition", 1, revisions.getRevisions().size());
TabularData jmxCapabilitiesTable = brsMBean.getRevisionsDeclaredCapabilities(bundleA.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
Assert.assertEquals(1, jmxCapabilitiesTable.size());
List<BundleCapability> capabilities = ((BundleRevision) revisions.getRevisions().iterator().next()).getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE);
CompositeData jmxRevCapabilities = (CompositeData) jmxCapabilitiesTable.values().iterator().next();
CompositeData[] jmxCapabilities = (CompositeData[]) jmxRevCapabilities.get(BundleWiringStateMBean.CAPABILITIES);
Map<Map<String, Object>, Map<String, String>> expectedCapabilities = capabilitiesToMap(capabilities);
Map<Map<String, Object>, Map<String, String>> actualCapabilities = jmxCapReqToMap(jmxCapabilities);
Assert.assertEquals(expectedCapabilities, actualCapabilities);
}
@Test
public void testGetCurrentWiring() throws Exception {
CompositeData jmxWiring = brsMBean.getCurrentWiring(bundleA.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
Assert.assertEquals(BundleWiringStateMBean.BUNDLE_WIRING_TYPE, jmxWiring.getCompositeType());
Assert.assertEquals(bundleA.getBundleId(), jmxWiring.get(BundleWiringStateMBean.BUNDLE_ID));
BundleWiring bw = (BundleWiring) bundleA.adapt(BundleWiring.class);
assertBundleWiring(bw, jmxWiring);
}
@Test
public void testRevisionsWiring() throws Exception {
TabularData jmxWiringTable = brsMBean.getRevisionsWiring(bundleA.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
Assert.assertEquals(1, jmxWiringTable.size());
CompositeData jmxWiring = (CompositeData) jmxWiringTable.values().iterator().next();
Assert.assertEquals(BundleWiringStateMBean.BUNDLE_WIRING_TYPE, jmxWiring.getCompositeType());
Assert.assertEquals(bundleA.getBundleId(), jmxWiring.get(BundleWiringStateMBean.BUNDLE_ID));
BundleWiring bw = (BundleWiring) bundleA.adapt(BundleWiring.class);
assertBundleWiring(bw, jmxWiring);
}
private void assertBundleWiring(BundleWiring bundleWiring, CompositeData jmxWiring) {
CompositeData[] jmxCapabilities = (CompositeData[]) jmxWiring.get(BundleWiringStateMBean.CAPABILITIES);
List<BundleCapability> capabilities = bundleWiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE);
Assert.assertEquals(capabilities.size(), jmxCapabilities.length);
Map<Map<String, Object>, Map<String, String>> expectedCapabilities = capabilitiesToMap(capabilities);
Map<Map<String, Object>, Map<String, String>> actualCapabilities = jmxCapReqToMap(jmxCapabilities);
Assert.assertEquals(expectedCapabilities, actualCapabilities);
CompositeData[] jmxRequirements = (CompositeData[]) jmxWiring.get(BundleWiringStateMBean.REQUIREMENTS);
List<BundleRequirement> requirements = bundleWiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE);
Assert.assertEquals(requirements.size(), jmxRequirements.length);
Map<Map<String, Object>, Map<String, String>> expectedRequirements = requirementsToMap(requirements);
Map<Map<String, Object>, Map<String, String>> actualRequirements = jmxCapReqToMap(jmxRequirements);
Assert.assertEquals(expectedRequirements, actualRequirements);
List<BundleWire> requiredWires = bundleWiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
CompositeData[] jmxRequiredWires = (CompositeData[]) jmxWiring.get(BundleWiringStateMBean.REQUIRED_WIRES);
Assert.assertEquals(requiredWires.size(), jmxRequiredWires.length);
Set<List<Object>> expectedRequiredWires = new HashSet<List<Object>>();
for (BundleWire wire : requiredWires) {
List<Object> data = new ArrayList<Object>();
data.add(wire.getCapability().getRevision().getBundle().getBundleId());
data.add(wire.getCapability().getAttributes());
data.add(wire.getCapability().getDirectives());
data.add(wire.getRequirement().getRevision().getBundle().getBundleId());
data.add(wire.getRequirement().getAttributes());
data.add(wire.getRequirement().getDirectives());
expectedRequiredWires.add(data);
}
Set<List<Object>> actualRequiredWires = new HashSet<List<Object>>();
for (CompositeData wire : jmxRequiredWires) {
List<Object> data = new ArrayList<Object>();
data.add(wire.get(BundleWiringStateMBean.PROVIDER_BUNDLE_ID));
// TODO bundle revision id
data.add(getJmxAttributes((CompositeData) wire.get(BundleWiringStateMBean.BUNDLE_CAPABILITY)));
data.add(getJmxDirectives((CompositeData) wire.get(BundleWiringStateMBean.BUNDLE_CAPABILITY)));
data.add(wire.get(BundleWiringStateMBean.REQUIRER_BUNDLE_ID));
data.add(getJmxAttributes((CompositeData) wire.get(BundleWiringStateMBean.BUNDLE_REQUIREMENT)));
data.add(getJmxDirectives((CompositeData) wire.get(BundleWiringStateMBean.BUNDLE_REQUIREMENT)));
actualRequiredWires.add(data);
}
Assert.assertEquals(expectedRequiredWires, actualRequiredWires);
List<BundleWire> providedWires = bundleWiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE);
CompositeData[] jmxProvidedWires = (CompositeData []) jmxWiring.get(BundleWiringStateMBean.PROVIDED_WIRES);
Assert.assertEquals(providedWires.size(), jmxProvidedWires.length);
HashSet<List<Object>> expectedProvidedWires = new HashSet<List<Object>>();
for (BundleWire wire : providedWires) {
List<Object> data = new ArrayList<Object>();
data.add(wire.getCapability().getRevision().getBundle().getBundleId());
data.add(wire.getCapability().getAttributes());
data.add(wire.getCapability().getDirectives());
data.add(wire.getRequirement().getRevision().getBundle().getBundleId());
data.add(wire.getRequirement().getAttributes());
data.add(wire.getRequirement().getDirectives());
expectedProvidedWires.add(data);
}
Set<List<Object>> actualProvidedWires = new HashSet<List<Object>>();
for (CompositeData wire : jmxProvidedWires) {
List<Object> data = new ArrayList<Object>();
data.add(wire.get(BundleWiringStateMBean.PROVIDER_BUNDLE_ID));
data.add(getJmxAttributes((CompositeData) wire.get(BundleWiringStateMBean.BUNDLE_CAPABILITY)));
data.add(getJmxDirectives((CompositeData) wire.get(BundleWiringStateMBean.BUNDLE_CAPABILITY)));
data.add(wire.get(BundleWiringStateMBean.REQUIRER_BUNDLE_ID));
data.add(getJmxAttributes((CompositeData) wire.get(BundleWiringStateMBean.BUNDLE_REQUIREMENT)));
data.add(getJmxDirectives((CompositeData) wire.get(BundleWiringStateMBean.BUNDLE_REQUIREMENT)));
actualProvidedWires.add(data);
}
Assert.assertEquals(expectedProvidedWires, actualProvidedWires);
}
@Test
public void testCurrentWiringClosure() throws Exception {
TabularData jmxWiringClosure = brsMBean.getCurrentWiringClosure(bundleA.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
CompositeData jmxWiringA = jmxWiringClosure.get(new Object [] {bundleA.getBundleId(), 0});
assertBundleWiring((BundleWiring) bundleA.adapt(BundleWiring.class), jmxWiringA);
Bundle b = context().getBundleByName("org.apache.aries.jmx.test.bundleb");
int bRevID = findRevisionID(jmxWiringA, b);
CompositeData jmxWiringB = jmxWiringClosure.get(new Object [] {b.getBundleId(), bRevID});
assertBundleWiring((BundleWiring) b.adapt(BundleWiring.class), jmxWiringB);
Bundle cm = context().getBundleByName("org.apache.felix.configadmin");
int cmRevID = findRevisionID(jmxWiringA, cm);
CompositeData jmxWiringCM = jmxWiringClosure.get(new Object [] {cm.getBundleId(), cmRevID});
assertBundleWiring((BundleWiring) cm.adapt(BundleWiring.class), jmxWiringCM);
Bundle sb = context().getBundle(0);
int sbRevID = findRevisionID(jmxWiringA, sb);
CompositeData jmxWiringSB = jmxWiringClosure.get(new Object [] {sb.getBundleId(), sbRevID});
assertBundleWiring((BundleWiring) sb.adapt(BundleWiring.class), jmxWiringSB);
}
@Test
public void testRevisionsWiringClosure() throws Exception {
TabularData jmxWiringClosure = brsMBean.getRevisionsWiringClosure(bundleA.getBundleId(), BundleRevision.PACKAGE_NAMESPACE);
CompositeData jmxWiringA = jmxWiringClosure.get(new Object [] {bundleA.getBundleId(), 0});
assertBundleWiring((BundleWiring) bundleA.adapt(BundleWiring.class), jmxWiringA);
Bundle b = context().getBundleByName("org.apache.aries.jmx.test.bundleb");
int bRevID = findRevisionID(jmxWiringA, b);
CompositeData jmxWiringB = jmxWiringClosure.get(new Object [] {b.getBundleId(), bRevID});
assertBundleWiring((BundleWiring) b.adapt(BundleWiring.class), jmxWiringB);
Bundle cm = context().getBundleByName("org.apache.felix.configadmin");
int cmRevID = findRevisionID(jmxWiringA, cm);
CompositeData jmxWiringCM = jmxWiringClosure.get(new Object [] {cm.getBundleId(), cmRevID});
assertBundleWiring((BundleWiring) cm.adapt(BundleWiring.class), jmxWiringCM);
Bundle sb = context().getBundle(0);
int sbRevID = findRevisionID(jmxWiringA, sb);
CompositeData jmxWiringSB = jmxWiringClosure.get(new Object [] {sb.getBundleId(), sbRevID});
assertBundleWiring((BundleWiring) sb.adapt(BundleWiring.class), jmxWiringSB);
}
private int findRevisionID(CompositeData jmxWiring, Bundle bundle) {
CompositeData[] requiredWires = (CompositeData []) jmxWiring.get(BundleWiringStateMBean.REQUIRED_WIRES);
for (CompositeData req : requiredWires) {
if (new Long(bundle.getBundleId()).equals(req.get(BundleWiringStateMBean.PROVIDER_BUNDLE_ID))) {
return (Integer) req.get(BundleWiringStateMBean.PROVIDER_BUNDLE_REVISION_ID);
}
}
return -1;
}
private Map<Map<String, Object>, Map<String, String>> capabilitiesToMap(List<BundleCapability> capabilities) {
Map<Map<String, Object>, Map<String, String>> map = new HashMap<Map<String,Object>, Map<String,String>>();
for (BundleCapability cap : capabilities) {
map.put(cap.getAttributes(), cap.getDirectives());
}
return map;
}
private Map<Map<String, Object>, Map<String, String>> requirementsToMap(List<BundleRequirement> requirements) {
Map<Map<String, Object>, Map<String, String>> map = new HashMap<Map<String,Object>, Map<String,String>>();
for (BundleRequirement req : requirements) {
map.put(req.getAttributes(), req.getDirectives());
}
return map;
}
private Map<Map<String, Object>, Map<String, String>> jmxCapReqToMap(CompositeData[] jmxCapabilitiesOrRequirements) {
Map<Map<String, Object>, Map<String, String>> actualCapabilities = new HashMap<Map<String,Object>, Map<String,String>>();
for (CompositeData jmxCapReq : jmxCapabilitiesOrRequirements) {
Map<String, Object> aMap = getJmxAttributes(jmxCapReq);
Map<String, String> dMap = getJmxDirectives(jmxCapReq);
actualCapabilities.put(aMap, dMap);
}
return actualCapabilities;
}
@SuppressWarnings("unchecked")
private Map<String, Object> getJmxAttributes(CompositeData jmxCapReq) {
TabularData jmxAttributes = (TabularData) jmxCapReq.get(BundleWiringStateMBean.ATTRIBUTES);
Map<String, Object> aMap = new HashMap<String, Object>();
for (CompositeData jmxAttr : (Collection<CompositeData>) jmxAttributes.values()) {
PropertyData<Object> pd = PropertyData.from(jmxAttr);
Object val = pd.getValue();
if (val instanceof Object[]) {
val = Arrays.asList((Object [])val);
}
aMap.put(pd.getKey(), val);
}
return aMap;
}
@SuppressWarnings("unchecked")
private Map<String, String> getJmxDirectives(CompositeData jmxCapReq) {
TabularData jmxDirectives = (TabularData) jmxCapReq.get(BundleWiringStateMBean.DIRECTIVES);
Map<String, String> dMap = new HashMap<String, String>();
for (CompositeData jmxDir : (Collection<CompositeData>) jmxDirectives.values()) {
dMap.put((String) jmxDir.get(BundleWiringStateMBean.KEY), (String) jmxDir.get(BundleWiringStateMBean.VALUE));
}
return dMap;
}
}
| 8,027 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/provisioning/ProvisioningServiceMBeanTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.provisioning;
import static org.junit.Assert.assertArrayEquals;
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.ops4j.pax.exam.CoreOptions.options;
import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_AGENT_CONFIG;
import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_REFERENCE;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Dictionary;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import javax.inject.Inject;
import javax.management.openmbean.TabularData;
import org.apache.aries.jmx.AbstractIntegrationTest;
import org.apache.aries.jmx.codec.PropertyData;
import org.junit.Ignore;
import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.osgi.jmx.JmxConstants;
import org.osgi.jmx.service.provisioning.ProvisioningServiceMBean;
import org.osgi.service.provisioning.ProvisioningService;
/**
*
*
* @version $Rev$ $Date$
*/
public class ProvisioningServiceMBeanTest extends AbstractIntegrationTest {
@Inject
ProvisioningService ps;
@Configuration
public Option[] configuration() {
return options(
jmxRuntime()
);
}
@Ignore("For now.. Cannot find public repo for org.eclipse.equinox.ip")
@Test
@SuppressWarnings({ "unchecked"})
public void testMBeanInterface() throws Exception {
ProvisioningServiceMBean mbean = getMBean(ProvisioningServiceMBean.OBJECTNAME, ProvisioningServiceMBean.class);
Dictionary<String, Object> info;
// add information URL (create temp zip file)
File provZip = createProvAgentConfigZip();
mbean.addInformationFromZip(provZip.toURI().toURL().toExternalForm());
//check the info has been added
info = ps.getInformation();
assertNotNull(info);
assertTrue(info.size() >= 1);
assertProvAgentConfigCorrect(info);
// test list information
TabularData data = mbean.listInformation();
assertNotNull(data);
assertEquals(JmxConstants.PROPERTIES_TYPE, data.getTabularType());
assertTrue(data.values().size() >= 1);
PropertyData<byte[]> configEntry = PropertyData.from(data.get(new Object[] {PROVISIONING_AGENT_CONFIG }));
assertNotNull(configEntry);
assertArrayEquals(new byte[] { 10, 20, 30 }, configEntry.getValue());
// test add information
PropertyData<String> reference = PropertyData.newInstance(PROVISIONING_REFERENCE, "rsh://0.0.0.0/provX");
data.put(reference.toCompositeData());
mbean.addInformation(data);
info = ps.getInformation();
assertNotNull(info);
assertTrue(info.size() >= 2);
assertProvAgentConfigCorrect(info);
String ref = (String) info.get(PROVISIONING_REFERENCE);
assertNotNull(ref);
assertEquals("rsh://0.0.0.0/provX", ref);
// test set information
data.clear();
PropertyData<String> newRef = PropertyData.newInstance(PROVISIONING_REFERENCE, "rsh://0.0.0.0/newProvRef");
data.put(newRef.toCompositeData());
mbean.setInformation(data);
info = ps.getInformation();
assertNotNull(info);
assertTrue(info.size() >= 1);
assertNull(info.get(PROVISIONING_AGENT_CONFIG));
ref = (String) info.get(PROVISIONING_REFERENCE);
assertNotNull(ref);
assertEquals("rsh://0.0.0.0/newProvRef", ref);
}
private void assertProvAgentConfigCorrect(Dictionary<String, Object> info) {
byte[] config = (byte[]) info.get(PROVISIONING_AGENT_CONFIG);
assertNotNull(config);
assertArrayEquals(new byte[] { 10, 20, 30 }, config);
}
private File createProvAgentConfigZip() throws IOException, FileNotFoundException {
File provZip = File.createTempFile("Prov-jmx-itests", ".zip");
Manifest man = new Manifest();
man.getMainAttributes().putValue("Manifest-Version", "1.0");
man.getMainAttributes().putValue("Content-Type", "application/zip");
JarOutputStream jout = new JarOutputStream(new FileOutputStream(provZip), man);
ZipEntry entry = new ZipEntry(PROVISIONING_AGENT_CONFIG);
jout.putNextEntry( entry );
jout.write(new byte[] { 10, 20, 30 });
jout.closeEntry();
jout.flush();
jout.close();
provZip.deleteOnExit();
return provZip;
}
}
| 8,028 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/permissionadmin/PermissionAdminMBeanTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.permissionadmin;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNotNull;
import static org.ops4j.pax.exam.CoreOptions.options;
import java.io.IOException;
import org.apache.aries.jmx.AbstractIntegrationTest;
import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.Bundle;
import org.osgi.jmx.service.permissionadmin.PermissionAdminMBean;
import org.osgi.service.permissionadmin.PermissionAdmin;
import org.osgi.service.permissionadmin.PermissionInfo;
/**
*
*
* @version $Rev$ $Date$
*/
public class PermissionAdminMBeanTest extends AbstractIntegrationTest {
@Configuration
public Option[] configuration() {
return options(
jmxRuntime(),
bundlea()
/* For debugging, uncomment the next two lines */
// vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=7778"),
// waitForFrameworkStartup()
);
}
@Test
public void testMBeanInterface() throws IOException {
PermissionAdminMBean mBean = getMBean(PermissionAdminMBean.OBJECTNAME, PermissionAdminMBean.class);
PermissionAdmin permAdminService = context().getService(PermissionAdmin.class);
assertNotNull(permAdminService);
String[] serviceLocation = permAdminService.getLocations();
String[] mBeanLocations = mBean.listLocations();
assertArrayEquals(serviceLocation, mBeanLocations);
PermissionInfo defPerm = new PermissionInfo("AllPermission", "*", "*");
permAdminService.setDefaultPermissions(new PermissionInfo[]{defPerm});
PermissionInfo[] permissions = permAdminService.getDefaultPermissions();
assertNotNull(permissions);
String[] encoded = toEncodedPerm(permissions);
String[] mBeanDefPermissions = mBean.listDefaultPermissions();
assertArrayEquals(encoded, mBeanDefPermissions);
Bundle a = context().getBundleByName("org.apache.aries.jmx.test.bundlea");
assertNotNull(a);
String location = a.getLocation();
PermissionInfo bundleaPerm = new PermissionInfo("ServicePermission", "ServiceA", "GET");
mBean.setPermissions(location, new String[]{bundleaPerm.getEncoded()});
String[] serviceBundleaPerm = toEncodedPerm(permAdminService.getPermissions(location));
String[] mBeanBundleaPerm = mBean.getPermissions(location);
assertNotNull(mBeanBundleaPerm);
assertArrayEquals(serviceBundleaPerm, mBeanBundleaPerm);
PermissionInfo defaultPerm = new PermissionInfo("AllPermission", "*", "GET");
mBean.setDefaultPermissions(new String[]{defaultPerm.getEncoded()});
String[] serviceDefaultPerm = toEncodedPerm(permAdminService.getDefaultPermissions());
String[] mBeanDefaultPerm = mBean.listDefaultPermissions();
assertNotNull(mBeanDefaultPerm);
assertArrayEquals(serviceDefaultPerm, mBeanDefaultPerm);
}
private String[] toEncodedPerm(PermissionInfo[] permissions){
assertNotNull(permissions);
String[] encoded = new String[permissions.length];
for (int i = 0; i < permissions.length; i++) {
PermissionInfo info = permissions[i];
encoded[i] = info.getEncoded();
}
return encoded;
}
} | 8,029 |
0 | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/cm/ConfigurationAdminMBeanTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.cm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.options;
import java.util.Dictionary;
import javax.inject.Inject;
import javax.management.openmbean.TabularData;
import org.apache.aries.jmx.AbstractIntegrationTest;
import org.apache.aries.jmx.codec.PropertyData;
import org.apache.aries.jmx.test.bundlea.api.InterfaceA;
import org.apache.aries.jmx.test.bundleb.api.InterfaceB;
import org.apache.aries.jmx.test.bundleb.api.MSF;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.jmx.service.cm.ConfigurationAdminMBean;
import org.osgi.service.cm.ConfigurationAdmin;
/**
*
*
* @version $Rev$ $Date$
*/
public class ConfigurationAdminMBeanTest extends AbstractIntegrationTest {
private ConfigurationAdminMBean mbean;
@Inject
InterfaceA managedServiceA;
@Inject
@org.ops4j.pax.exam.util.Filter("(" + Constants.SERVICE_PID + "=jmx.test.B.factory)")
MSF managedFactory;
@Inject
ConfigurationAdmin configAdmin;
@Configuration
public Option[] configuration() {
return options(
jmxRuntime(),
bundlea(),
bundleb()
);
}
@Before
public void doSetUp() throws Exception {
waitForMBean(ConfigurationAdminMBean.OBJECTNAME);
mbean = getMBean(ConfigurationAdminMBean.OBJECTNAME, ConfigurationAdminMBean.class);
assertNotNull(mbean);
}
@Ignore("ManagedServiceFactory tests failing.. " +
"Some issues surrounding creating a factory configuration and then retrieving by pid to update.. Needs investigation")
@Test
@SuppressWarnings("unchecked")
public void testMBeanInterface() throws Exception {
// get bundles
Bundle a = getBundleByName("org.apache.aries.jmx.test.bundlea");
// ManagedService operations
assertNull(managedServiceA.getConfig());
// create a configuration for A
TabularData data = mbean.getProperties("org.apache.aries.jmx.test.ServiceA");
assertEquals(0, data.size());
PropertyData<String> p1 = PropertyData.newInstance("A1", "first");
data.put(p1.toCompositeData());
PropertyData<Integer> p2 = PropertyData.newInstance("A2", 2);
data.put(p2.toCompositeData());
mbean.update("org.apache.aries.jmx.test.ServiceA", data);
Thread.sleep(1000);
Dictionary<String, Object> config = managedServiceA.getConfig();
assertNotNull(config);
assertEquals(3, config.size());
assertEquals("org.apache.aries.jmx.test.ServiceA", config.get(Constants.SERVICE_PID));
assertEquals("first", config.get("A1"));
assertEquals(2, config.get("A2"));
//delete
mbean.deleteForLocation("org.apache.aries.jmx.test.ServiceA", a.getLocation());
Thread.sleep(1000);
assertNull(managedServiceA.getConfig());
// ManagedServiceFactory operations
String cpid = mbean.createFactoryConfiguration("jmx.test.B.factory");
assertNotNull(cpid);
assertTrue(cpid.contains("jmx.test.B.factory"));
TabularData fConfig = mbean.getProperties(cpid);
assertNotNull(fConfig);
assertEquals(0, fConfig.values().size());
PropertyData<String> prop1 = PropertyData.newInstance("B1", "value1");
fConfig.put(prop1.toCompositeData());
PropertyData<Boolean> prop2 = PropertyData.newInstance("B2", true);
fConfig.put(prop2.toCompositeData());
mbean.update(cpid, fConfig);
Thread.sleep(1000);
InterfaceB configured = managedFactory.getConfigured(cpid);
assertNotNull(configured);
config = configured.getConfig();
assertNotNull(config);
assertTrue(config.size() >= 4);
assertEquals("jmx.test.B.factory", config.get(ConfigurationAdmin.SERVICE_FACTORYPID));
assertEquals(cpid, config.get(Constants.SERVICE_PID));
assertEquals("value1", config.get("B1"));
assertEquals("true", config.get("B2"));
assertEquals("jmx.test.B.factory", mbean.getFactoryPid(cpid));
mbean.delete(cpid);
Thread.sleep(1000);
assertNull(managedFactory.getConfigured(cpid));
// list operations
data = mbean.getProperties("org.apache.aries.jmx.test.ServiceA");
assertEquals(0, data.size());
p1 = PropertyData.newInstance("A1", "a1Value");
data.put(p1.toCompositeData());
mbean.update("org.apache.aries.jmx.test.ServiceA", data);
Thread.sleep(1000);
config = managedServiceA.getConfig();
assertNotNull(config);
assertEquals(2, config.size());
assertEquals("org.apache.aries.jmx.test.ServiceA", config.get(Constants.SERVICE_PID));
assertEquals("a1Value", config.get("A1"));
String[][] configurations = mbean.getConfigurations("(A1=a1Value)");
assertNotNull(configurations);
assertEquals(1, configurations.length);
assertEquals("org.apache.aries.jmx.test.ServiceA", configurations[0][0]);
assertEquals(a.getLocation(), configurations[0][1]);
// delete with filter
mbean.deleteConfigurations("(A1=a1Value)");
Thread.sleep(1000);
assertNull(managedServiceA.getConfig());
}
}
| 8,030 |
0 | Create_ds/aries/jmx/jmx-core-whiteboard/src/main/java/org/apache/aries/jmx/core | Create_ds/aries/jmx/jmx-core-whiteboard/src/main/java/org/apache/aries/jmx/core/whiteboard/Activator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT 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.jmx.core.whiteboard;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.framework.BundleState;
import org.apache.aries.jmx.framework.Framework;
import org.apache.aries.jmx.framework.PackageState;
import org.apache.aries.jmx.framework.ServiceState;
import org.apache.aries.jmx.framework.StateConfig;
import org.apache.aries.jmx.util.ObjectNameUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.jmx.framework.BundleStateMBean;
import org.osgi.jmx.framework.FrameworkMBean;
import org.osgi.jmx.framework.PackageStateMBean;
import org.osgi.jmx.framework.ServiceStateMBean;
import org.osgi.jmx.service.cm.ConfigurationAdminMBean;
import org.osgi.jmx.service.permissionadmin.PermissionAdminMBean;
import org.osgi.jmx.service.provisioning.ProvisioningServiceMBean;
import org.osgi.jmx.service.useradmin.UserAdminMBean;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.permissionadmin.PermissionAdmin;
import org.osgi.service.provisioning.ProvisioningService;
import org.osgi.service.startlevel.StartLevel;
import org.osgi.service.useradmin.UserAdmin;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
public class Activator implements BundleActivator, ServiceTrackerCustomizer
{
private ServiceTracker tracker;
private BundleContext ctx;
private ConcurrentMap<Long, ServiceRegistration> _provisioningMBeans = new ConcurrentHashMap<Long, ServiceRegistration>();
private ConcurrentMap<Long, ServiceRegistration> _userAdminMBeans = new ConcurrentHashMap<Long, ServiceRegistration>();
private ConcurrentMap<Long, ServiceRegistration> _configAdminMBeans = new ConcurrentHashMap<Long, ServiceRegistration>();
private AtomicReference<ServiceRegistration> _serviceStateMbean = new AtomicReference<ServiceRegistration>();
private AtomicReference<ServiceRegistration> _permissionAdminMbean = new AtomicReference<ServiceRegistration>();
private AtomicReference<ServiceRegistration> _packageStateMbean = new AtomicReference<ServiceRegistration>();
private AtomicReference<ServiceRegistration> _bundleState = new AtomicReference<ServiceRegistration>();
private AtomicReference<ServiceRegistration> _framework = new AtomicReference<ServiceRegistration>();
private AtomicReference<ServiceReference> _startLevel = new AtomicReference<ServiceReference>();
private AtomicReference<ServiceReference> _packageAdmin = new AtomicReference<ServiceReference>();
private static final String PACKAGE_ADMIN = "org.osgi.service.packageadmin.PackageAdmin";
private static final String START_LEVEL = "org.osgi.service.startlevel.StartLevel";
private static final String PERMISSION_ADMIN = "org.osgi.service.permissionadmin.PermissionAdmin";
private static final String CONFIG_ADMIN = "org.osgi.service.cm.ConfigurationAdmin";
private static final String USER_ADMIN = "org.osgi.service.useradmin.UserAdmin";
private static final String PROVISIONING_SERVICE = "org.osgi.service.provisioning.ProvisioningService";
private Logger logger;
private StateConfig stateConfig;
private class MBeanServiceProxy<T> implements ServiceFactory
{
private Factory<T> objectFactory;
private AtomicReference<T> result = new AtomicReference<T>();
private MBeanServiceProxy(Factory<T> factory) {
objectFactory = factory;
}
public Object getService(Bundle bundle, ServiceRegistration registration)
{
if (result.get() == null) {
result.compareAndSet(null, objectFactory.create());
}
return result.get();
}
public void ungetService(Bundle bundle, ServiceRegistration registration, Object service)
{
}
}
private interface Factory<T>
{
public abstract T create();
}
private abstract class BaseFactory<T> implements Factory<T>
{
public abstract T create(PackageAdmin pa, StartLevel sl);
public final T create()
{
StartLevel sl = null;
PackageAdmin pa = null;
ServiceReference slRef = _startLevel.get();
if (slRef != null) {
sl = (StartLevel) ctx.getService(slRef);
}
ServiceReference paRef = _packageAdmin.get();
if (paRef != null) {
pa = (PackageAdmin) ctx.getService(paRef);
}
if (pa == null) {
ctx.ungetService(slRef);
}
if (sl != null && pa != null) {
return create(pa, sl);
} else {
return null;
}
}
}
public void start(BundleContext context) throws Exception
{
ctx = context;
logger = new Logger(ctx);
Filter filter = getFilter(context, PACKAGE_ADMIN, START_LEVEL,
PERMISSION_ADMIN, CONFIG_ADMIN, USER_ADMIN,
PROVISIONING_SERVICE);
tracker = new ServiceTracker(context, filter, this);
tracker.open();
stateConfig = StateConfig.register(context);
registerMBean(ServiceStateMBean.class.getName(), new Factory<ServiceStateMBean>() {
public ServiceStateMBean create()
{
return new ServiceState(ctx, stateConfig, logger);
}
}, ServiceStateMBean.OBJECTNAME, _serviceStateMbean );
}
private Filter getFilter(BundleContext ctx, String ... services) throws InvalidSyntaxException
{
StringBuilder builder = new StringBuilder("(|");
for (String type : services) {
builder.append('(');
builder.append(Constants.OBJECTCLASS);
builder.append('=');
builder.append(type);
builder.append(')');
}
builder.append(')');
return ctx.createFilter(builder.toString());
}
public void stop(BundleContext context) throws Exception
{
stateConfig = null;
tracker.close();
}
public Object addingService(ServiceReference reference)
{
Object tracked = null;
String[] types = (String[]) reference.getProperty(Constants.OBJECTCLASS);
for (String t : types) {
if (PACKAGE_ADMIN.equals(t)) {
foundPackageAdmin(reference);
tracked = reference;
} else if (START_LEVEL.equals(t)) {
foundStartLevel(reference);
tracked = reference;
} else if (PERMISSION_ADMIN.equals(t)) {
foundPermissionAdmin(reference);
tracked = reference;
} else if (CONFIG_ADMIN.equals(t)) {
foundConfigAdmin(reference);
tracked = reference;
} else if (USER_ADMIN.equals(t)) {
foundUserAdmin(reference);
tracked = reference;
} else if (PROVISIONING_SERVICE.equals(t)) {
foundProvisioningService(reference);
tracked = reference;
}
}
return tracked;
}
private <T> void registerMBean(String type, Factory<T> factory, String objectName, AtomicReference<ServiceRegistration> result)
{
synchronized (result) {
ServiceRegistration reg = registerAnMbean(type, factory, objectName);
if (!!!result.compareAndSet(null, reg)) {
reg.unregister();
}
}
}
private <T> void registerMBean(String type, Factory<T> factory, String objectName, ConcurrentMap<Long, ServiceRegistration> mbeans,
ServiceReference referencedServices, String underlyingType)
{
try {
Class.forName(underlyingType);
if (referencedServices.isAssignableTo(ctx.getBundle(), underlyingType)) {
ServiceRegistration reg = registerAnMbean(type, factory, objectName);
Long id = (Long) reg.getReference().getProperty(Constants.SERVICE_ID);
mbeans.put(id, reg);
}
} catch (ClassNotFoundException e) {
}
}
private <T> ServiceRegistration registerAnMbean(String type, Factory<T> factory, String objectName)
{
Hashtable<String, Object> properties = new Hashtable<String, Object>();
properties.put("jmx.objectname", ObjectNameUtils.createFullObjectName(ctx, objectName));
Object service = new MBeanServiceProxy<T>(factory);
ServiceRegistration reg = ctx.registerService(type, service, properties);
return reg;
}
private void foundPermissionAdmin(final ServiceReference reference)
{
registerMBean(PermissionAdminMBean.class.getName(), new Factory<PermissionAdminMBean>() {
public PermissionAdminMBean create()
{
PermissionAdmin service = (PermissionAdmin) ctx.getService(reference);
if (service == null) return null;
else return new org.apache.aries.jmx.permissionadmin.PermissionAdmin(service);
}
}, PermissionAdminMBean.OBJECTNAME, _permissionAdminMbean);
}
private void foundProvisioningService(final ServiceReference reference)
{
registerMBean(ProvisioningServiceMBean.class.getName(), new Factory<ProvisioningServiceMBean>() {
public ProvisioningServiceMBean create()
{
ProvisioningService service = (ProvisioningService) ctx.getService(reference);
if (service == null) return null;
else return new org.apache.aries.jmx.provisioning.ProvisioningService(service);
}
}, ProvisioningServiceMBean.OBJECTNAME, _provisioningMBeans, reference, PROVISIONING_SERVICE);
}
private void foundUserAdmin(final ServiceReference reference)
{
try {
Class.forName(USER_ADMIN);
if (reference.isAssignableTo(ctx.getBundle(), USER_ADMIN)) {
registerMBean(UserAdminMBean.class.getName(), new Factory<UserAdminMBean>() {
public UserAdminMBean create()
{
UserAdmin service = (UserAdmin) ctx.getService(reference);
if (service == null) return null;
else return new org.apache.aries.jmx.useradmin.UserAdmin(service);
}
}, UserAdminMBean.OBJECTNAME, _userAdminMBeans, reference, USER_ADMIN);
}
} catch (ClassNotFoundException e) {
}
}
private void foundConfigAdmin(final ServiceReference reference)
{
registerMBean(ConfigurationAdminMBean.class.getName(), new Factory<ConfigurationAdminMBean>() {
public ConfigurationAdminMBean create()
{
ConfigurationAdmin service = (ConfigurationAdmin) ctx.getService(reference);
if (service == null) return null;
else return new org.apache.aries.jmx.cm.ConfigurationAdmin(service);
}
}, ConfigurationAdminMBean.OBJECTNAME, _configAdminMBeans, reference, CONFIG_ADMIN);
}
private void foundStartLevel(final ServiceReference reference)
{
if (_startLevel.compareAndSet(null, reference)) {
registerBundleStateAndFrameworkIfPossible();
}
}
private void foundPackageAdmin(final ServiceReference reference)
{
registerMBean(PackageStateMBean.class.getName(), new Factory<PackageStateMBean>() {
public PackageStateMBean create()
{
PackageAdmin service = (PackageAdmin) ctx.getService(reference);
if (service == null) return null;
else return new PackageState(ctx, service);
}
}, PackageStateMBean.OBJECTNAME, _packageStateMbean);
if (_packageAdmin.compareAndSet(null, reference)) {
registerBundleStateAndFrameworkIfPossible();
}
}
// This method is synchronized to ensure that notification of StartLevel and PackageAdmin
// on different threads at the same time doesn't cause problems. It only affects these services
// so it shouldn't be too expensive.
private synchronized void registerBundleStateAndFrameworkIfPossible()
{
if (_bundleState.get() == null && _startLevel.get() != null && _packageAdmin.get() != null) {
registerMBean(BundleStateMBean.class.getName(), new BaseFactory<BundleStateMBean>() {
@Override
public BundleStateMBean create(PackageAdmin pa, StartLevel sl)
{
return new BundleState(ctx, pa, sl, stateConfig, logger);
}
}, BundleStateMBean.OBJECTNAME, _bundleState);
}
if (_framework.get() == null && _startLevel.get() != null && _packageAdmin.get() != null) {
registerMBean(FrameworkMBean.class.getName(), new BaseFactory<FrameworkMBean>() {
@Override
public FrameworkMBean create(PackageAdmin pa, StartLevel sl)
{
return new Framework(ctx, sl, pa);
}
}, FrameworkMBean.OBJECTNAME, _framework);
}
}
public void modifiedService(ServiceReference reference, Object service)
{
}
public void removedService(ServiceReference reference, Object service)
{
String[] types = (String[]) reference.getProperty(Constants.OBJECTCLASS);
for (String t : types) {
if (PACKAGE_ADMIN.equals(t)) {
lostPackageAdmin(reference);
} else if (START_LEVEL.equals(t)) {
lostStartLevel(reference);
} else if (PERMISSION_ADMIN.equals(t)) {
lostPermissionAdmin(reference);
} else if (CONFIG_ADMIN.equals(t)) {
lostConfigAdmin(reference);
} else if (USER_ADMIN.equals(t)) {
lostUserAdmin(reference);
} else if (PROVISIONING_SERVICE.equals(t)) {
lostProvisioningService(reference);
}
}
}
private void lostProvisioningService(ServiceReference reference)
{
unregister(reference, _provisioningMBeans);
}
private void lostUserAdmin(ServiceReference reference)
{
unregister(reference, _userAdminMBeans);
}
private void lostConfigAdmin(ServiceReference reference)
{
unregister(reference, _configAdminMBeans);
}
private void unregister(ServiceReference reference, ConcurrentMap<Long, ServiceRegistration> mbeans)
{
Long id = (Long) reference.getProperty(Constants.SERVICE_ID);
ServiceRegistration reg = mbeans.remove(id);
if (reg != null) reg.unregister();
}
private void lostPermissionAdmin(ServiceReference reference)
{
safeUnregister(_permissionAdminMbean);
}
private void lostStartLevel(ServiceReference reference)
{
if (_startLevel.compareAndSet(reference, null)) {
safeUnregister(_bundleState);
safeUnregister(_framework);
}
}
private void lostPackageAdmin(ServiceReference reference)
{
if (_packageAdmin.compareAndSet(reference, null)) {
safeUnregister(_bundleState);
safeUnregister(_framework);
safeUnregister(_packageStateMbean);
}
}
private void safeUnregister(AtomicReference<ServiceRegistration> atomicRegistration)
{
ServiceRegistration reg = atomicRegistration.getAndSet(null);
if (reg != null) reg.unregister();
}
} | 8,031 |
0 | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/JmxConstants.java | /*
* Copyright (c) OSGi Alliance (2009). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.jmx;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.management.openmbean.ArrayType;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularType;
/**
* Constants for OSGi JMX Specification.
*
* Additionally, this class contains a number of utility types that are used in
* different places in the specification. These are {@link #LONG_ARRAY_TYPE},
* {@link #STRING_ARRAY_TYPE}, and {@link #PROPERTIES_TYPE}.
*
* @version $Rev$
* @Immutable
*/
public class JmxConstants {
/*
* Empty constructor to make sure this is not used as an object.
*/
private JmxConstants() {
// empty
}
/**
* The MBean Open type for an array of strings
*/
public static final ArrayType<String> STRING_ARRAY_TYPE = Item
.arrayType(
1,
SimpleType.STRING);
/**
* The MBean Open type for an array of longs
*/
public static final ArrayType<Long> LONG_ARRAY_TYPE = Item
.arrayType(
1,
SimpleType.LONG);
/**
* For an encoded array we need to start with ARRAY_OF. This must be
* followed by one of the names in {@link #SCALAR}.
*
*/
public final static String ARRAY_OF = "Array of ";
/**
* For an encoded vector we need to start with ARRAY_OF. This must be
* followed by one of the names in {@link #SCALAR}.
*/
public final static String VECTOR_OF = "Vector of ";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link org.osgi.framework.Version}
*/
public static final String VERSION = "Version";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link java.lang.String}
*/
public static final String STRING = "String";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link java.lang.Integer}
*/
public static final String INTEGER = "Integer";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link java.lang.Long}
*/
public static final String LONG = "Long";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link java.lang.Float}
*/
public static final String FLOAT = "Float";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link java.lang.Double}
*/
public static final String DOUBLE = "Double";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link java.lang.Byte}
*/
public static final String BYTE = "Byte";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link java.lang.Short}
*/
public static final String SHORT = "Short";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link java.lang.Character}
*/
public static final String CHARACTER = "Character";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link java.lang.Boolean}
*/
public static final String BOOLEAN = "Boolean";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link java.math.BigDecimal}
*/
public static final String BIGDECIMAL = "BigDecimal";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* {@link java.math.BigInteger}
*/
public static final String BIGINTEGER = "BigInteger";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* the <code>double</code> primitive type.
*/
public static final String P_DOUBLE = "double";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* the <code>float</code> primitive type.
*/
public static final String P_FLOAT = "float";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* the <code>long</code> primitive type.
*/
public static final String P_LONG = "long";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* the <code>int</code> primitive type.
*/
public static final String P_INT = "int";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* the <code>short</code> primitive type.
*/
public static final String P_SHORT = "short";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* the <code>byte</code> primitive type.
*/
public static final String P_BYTE = "byte";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* the <code>char</code> primitive type.
*/
public static final String P_CHAR = "char";
/**
* Value for {@link #PROPERTY_TYPE} <code>Type</code> value in the case of
* the <code>boolean</code> primitive type.
*/
public static final String P_BOOLEAN = "boolean";
/**
* A set of all scalars that can be used in the {@link #TYPE} property of a
* {@link #PROPERTIES_TYPE}. This contains the following names:
* <ul>
* <li>{@link #BIGDECIMAL}</li>
* <li>{@link #BIGINTEGER}</li>
* <li>{@link #BOOLEAN}</li>
* <li>{@link #BYTE}</li>
* <li>{@link #CHARACTER}</li>
* <li>{@link #DOUBLE}</li>
* <li>{@link #FLOAT}</li>
* <li>{@link #INTEGER}</li>
* <li>{@link #LONG}</li>
* <li>{@link #SHORT}</li>
* <li>{@link #STRING}</li>
* <li>{@link #P_BYTE}</li>
* <li>{@link #P_CHAR}</li>
* <li>{@link #P_DOUBLE}</li>
* <li>{@link #P_FLOAT}</li>
* <li>{@link #P_INT}</li>
* <li>{@link #P_LONG}</li>
* <li>{@link #P_SHORT}</li>
*/
public final static List<String> SCALAR = Collections
.unmodifiableList(Arrays
.asList(
STRING,
INTEGER,
LONG,
FLOAT,
DOUBLE,
BYTE,
SHORT,
CHARACTER,
BOOLEAN,
BIGDECIMAL,
BIGINTEGER,
P_BYTE,
P_CHAR,
P_SHORT,
P_INT,
P_LONG,
P_DOUBLE,
P_FLOAT));
/**
* The key KEY.
*/
public static final String KEY = "Key";
/**
* The key of a property. The key is {@link #KEY} and the type is
* {@link SimpleType#STRING}.
*/
public static final Item KEY_ITEM = new Item(
KEY,
"The key of the property",
SimpleType.STRING);
/**
* The key VALUE.
*/
public static final String VALUE = "Value";
/**
* The value of a property. The key is {@link #VALUE} and the type is
* {@link SimpleType#STRING}. A value will be encoded by the string given in
* {@link #TYPE}. The syntax for this type is given in {@link #TYPE_ITEM}.
*/
public static final Item VALUE_ITEM = new Item(
VALUE,
"The value of the property",
SimpleType.STRING);
/**
* The key PROPERTY_TYPE.
*
* ### can we call this value PropertyType and service type ServiceType?
*/
public static final String TYPE = "Type";
/**
* The type of the property. The key is {@link #TYPE} and the type is
* {@link SimpleType#STRING}. This string must follow the following syntax:
*
* TYPE ::= ( 'Array of ' | 'Vector of ' )? {@link #SCALAR}
*
* ### why can't we just use the class name?
*
* ### why do we have to distinguish between primitives and wrappers?
*/
public static final Item TYPE_ITEM = new Item(
TYPE,
"The type of the property",
SimpleType.STRING,
STRING,
INTEGER,
LONG,
FLOAT,
DOUBLE,
BYTE,
SHORT,
CHARACTER,
BOOLEAN,
BIGDECIMAL,
BIGINTEGER,
P_DOUBLE,
P_FLOAT,
P_LONG,
P_INT,
P_SHORT,
P_CHAR,
P_BYTE,
P_BOOLEAN);
/**
* A Composite Type describing a a single property. A property consists of
* the following items {@link #KEY_ITEM}, {@link #VALUE_ITEM}, and
* {@link #TYPE_ITEM}.
*/
public static final CompositeType PROPERTY_TYPE = Item
.compositeType(
"PROPERTY",
"This type encapsulates a key/value pair",
KEY_ITEM,
VALUE_ITEM,
TYPE_ITEM);
/**
* Describes a map with properties. The row type is {@link #PROPERTY_TYPE}.
* The index is defined to the {@link #KEY} of the property.
*/
public static final TabularType PROPERTIES_TYPE = Item
.tabularType(
"PROPERTIES",
"A table of PROPERTY",
PROPERTY_TYPE,
KEY);
/**
* The domain name of the core OSGi MBeans
*/
public static final String OSGI_CORE = "osgi.core";
/**
* The domain name of the selected OSGi compendium MBeans
*/
public static final String OSGI_COMPENDIUM = "osgi.compendium";
}
| 8,032 |
0 | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/Item.java | /*
* Copyright (c) OSGi Alliance (2009). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.jmx;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.management.openmbean.ArrayType;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.TabularType;
/**
* The item class enables the definition of open types in the appropriate
* interfaces.
*
* This class contains a number of methods that make it possible to create open
* types for {@link CompositeType}, {@link TabularType}, and {@link ArrayType}.
* The normal creation throws a checked exception, making it impossible to use
* them in a static initializer. They constructors are also not very suitable
* for static construction.
*
*
* An Item instance describes an item in a Composite Type. It groups the triplet
* of name, description, and Open Type. These Item instances allows the
* definitions of an item to stay together.
*
* @version $Rev$
* @Immutable
*/
public class Item {
/**
* The name of this item.
*/
private final String name;
/**
* The description of this item.
*/
private final String description;
/**
* The type of this item.
*/
private final OpenType type;
/**
* Create a triple of name, description, and type. This triplet is used in
* the creation of a Composite Type.
*
* @param name
* The name of the item.
* @param description
* The description of the item.
* @param type
* The Open Type of this item.
* @param restrictions
* Ignored, contains list of restrictions
*/
public Item(String name, String description, OpenType type,
String... restrictions) {
this.name = name;
this.description = description;
this.type = type;
}
/**
*
*/
/**
* Create a Tabular Type.
*
* @param name
* The name of the Tabular Type.
* @param description
* The description of the Tabular Type.
* @param rowType
* The Open Type for a row
* @param index
* The names of the items that form the index .
* @return A new Tabular Type composed from the parameters.
* @throws RuntimeException
* when the Tabular Type throws an OpenDataException
*/
static public TabularType tabularType(String name, String description,
CompositeType rowType, String... index) {
try {
return new TabularType(name, description, rowType, index);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
/**
* Create a Composite Type
*
* @param name
* The name of the Tabular Type.
* @param description
* The description of the Tabular Type.
* @param items
* The items that describe the composite type.
* @return a new Composite Type
* @throws RuntimeException
* when the Tabular Type throws an OpenDataException
*/
static public CompositeType compositeType(String name, String description,
Item... items) {
return extend(null, name, description, items);
}
/**
* Return a new Array Type.
*
* @param dim
* The dimension
* @param elementType
* The element type
* @return A new Array Type
*/
public static <T> ArrayType<T> arrayType(int dim, OpenType<T> elementType) {
try {
return new ArrayType<T>(dim, elementType);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
/**
* Extend a Composite Type by adding new items. Items can override items in
* the parent type.
*
* @param parent
* The parent type, can be <code>null</code>
* @param name
* The name of the type
* @param description
* The description of the type
* @param items
* The items that should be added/override to the parent type
* @return A new Composite Type that extends the parent type
* @throws RuntimeException
* when an OpenDataException is thrown
*/
public static CompositeType extend(CompositeType parent, String name,
String description, Item... items) {
Set<Item> all = new LinkedHashSet<Item>();
if (parent != null) {
for (Object nm : parent.keySet()) {
String key = (String) nm;
all.add(new Item(key, parent.getDescription(key),
parent.getType(key)));
}
}
Collections.addAll(all, items);
int size = all.size();
String names[] = new String[size];
String descriptions[] = new String[size];
OpenType types[] = new OpenType[size];
int m = 0;
for (Item item : all) {
names[m] = item.name;
descriptions[m] = item.description;
types[m] = item.type;
m++;
}
try {
return new CompositeType(name, description, names, descriptions,
types);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
}
| 8,033 |
0 | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/framework/ServiceStateMBean.java | /*
* Copyright (c) OSGi Alliance (2009, 2010). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.jmx.framework;
import java.io.IOException;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularType;
import org.osgi.jmx.Item;
import org.osgi.jmx.JmxConstants;
/**
* This MBean represents the Service state of the framework. This MBean also
* emits events that clients can use to get notified of the changes in the
* service state of the framework.
*
* @version $Revision$
* @ThreadSafe
*/
public interface ServiceStateMBean {
/**
* The fully qualified object name of this mbean.
*/
String OBJECTNAME = JmxConstants.OSGI_CORE
+ ":type=serviceState,version=1.7";
/**
* The key BUNDLE_IDENTIFIER, used in {@link #BUNDLE_IDENTIFIER_ITEM}.
*/
String BUNDLE_IDENTIFIER = "BundleIdentifier";
/**
* The item containing the bundle identifier in {@link #SERVICE_TYPE}. The
* key is {@link #BUNDLE_IDENTIFIER} and the type is {@link SimpleType#LONG}
* .
*/
Item BUNDLE_IDENTIFIER_ITEM = new Item(BUNDLE_IDENTIFIER,
"The identifier of the bundle the service belongs to",
SimpleType.LONG);
/**
* The key OBJECT_CLASS, used {@link #OBJECT_CLASS_ITEM}.
*/
String OBJECT_CLASS = "objectClass";
/**
* The item containing the interfaces of the service in
* {@link #SERVICE_TYPE}. The key is {@link #OBJECT_CLASS} and the type is
* {@link JmxConstants#STRING_ARRAY_TYPE}.
*/
Item OBJECT_CLASS_ITEM = new Item(
OBJECT_CLASS,
"An string array containing the interfaces under which the service has been registered",
JmxConstants.STRING_ARRAY_TYPE);
/**
* The key IDENTIFIER, used {@link #IDENTIFIER_ITEM}.
*/
String IDENTIFIER = "Identifier";
/**
* The item containing the service identifier in {@link #SERVICE_TYPE}. The
* key is {@link #IDENTIFIER} and the type is {@link SimpleType#LONG}.
*/
Item IDENTIFIER_ITEM = new Item(IDENTIFIER,
"The identifier of the service", SimpleType.LONG);
/**
* The key PROPERTIES, used in {@link #PROPERTIES_ITEM}.
*/
String PROPERTIES = "Properties";
/**
* The item containing service properties in {@link #SERVICE_TYPE}. The key
* is {@link #PROPERTIES} and the type is {@link JmxConstants#PROPERTIES_TYPE}.
*/
Item PROPERTIES_ITEM = new Item(PROPERTIES,
"The service properties", JmxConstants.PROPERTIES_TYPE);
/**
* The key USING_BUNDLES, used in {@link #USING_BUNDLES_ITEM}.
*/
String USING_BUNDLES = "UsingBundles";
/**
* The item containing the bundles using the service in
* {@link #SERVICE_TYPE}. The key is {@link #USING_BUNDLES} and the type is
* {@link JmxConstants#LONG_ARRAY_TYPE}.
*/
Item USING_BUNDLES_ITEM = new Item(USING_BUNDLES,
"The bundles using the service", JmxConstants.LONG_ARRAY_TYPE);
/**
* The Composite Type for a CompositeData representing a service. This type
* consists of:
* <ul>
* <li>{@link #BUNDLE_IDENTIFIER}</li>
* <li>{@link #IDENTIFIER}</li>
* <li>{@link #OBJECT_CLASS}</li>
* <li>{@link #USING_BUNDLES}</li>
* </ul>
*/
CompositeType SERVICE_TYPE = Item.compositeType("SERVICE",
"This type encapsulates an OSGi service", BUNDLE_IDENTIFIER_ITEM,
IDENTIFIER_ITEM, OBJECT_CLASS_ITEM, PROPERTIES_ITEM,
USING_BUNDLES_ITEM);
/**
* The Tabular Type for a Service table. The rows consists of
* {@link #SERVICE_TYPE} Composite Data and the index is {@link #IDENTIFIER}
* .
*/
TabularType SERVICES_TYPE = Item.tabularType("SERVICES",
"The table of all services", SERVICE_TYPE, IDENTIFIER);
/**
* The key BUNDLE_LOCATION, used in {@link #SERVICE_EVENT_TYPE}.
*/
String BUNDLE_LOCATION = "BundleLocation";
/**
* The item containing the bundle location in {@link #EVENT_ITEM}. The key
* is {@link #BUNDLE_LOCATION} and the the type is {@link SimpleType#STRING}
* .
*/
Item BUNDLE_LOCATION_ITEM = new Item(BUNDLE_LOCATION,
"The location of the bundle", SimpleType.STRING);
/**
* The key BUNDLE_SYMBOLIC_NAME, used in {@link #SERVICE_EVENT_TYPE}.
*/
String BUNDLE_SYMBOLIC_NAME = "BundleSymbolicName";
/**
* The item containing the symbolic name in {@link #EVENT}. The key is
* {@link #BUNDLE_SYMBOLIC_NAME} and the the type is
* {@link SimpleType#STRING}.
*/
Item BUNDLE_SYMBOLIC_NAME_ITEM = new Item(BUNDLE_SYMBOLIC_NAME,
"The symbolic name of the bundle", SimpleType.STRING);
/**
* The key EVENT, used in {@link #EVENT_ITEM}.
*/
String EVENT = "ServiceEvent";
/**
* The item containing the event type. The key is {@link #EVENT} and the
* type is {@link SimpleType#INTEGER}
*/
Item EVENT_ITEM = new Item(
EVENT,
"The eventType of the event: {REGISTERED=1, MODIFIED=2 UNREGISTERING=3}",
SimpleType.INTEGER);
/**
* The Composite Type that represents a service event. This composite
* consists of:
* <ul>
* <li>{@link #IDENTIFIER}</li>
* <li>{@link #OBJECT_CLASS}</li>
* <li>{@link #BUNDLE_LOCATION}</li>
* <li>{@link #BUNDLE_SYMBOLIC_NAME}</li>
* <li>{@link #EVENT}</li>
* </ul>
*/
CompositeType SERVICE_EVENT_TYPE = Item.compositeType("SERVICE_EVENT",
"This type encapsulates OSGi service events", IDENTIFIER_ITEM,
OBJECT_CLASS_ITEM, BUNDLE_IDENTIFIER_ITEM, BUNDLE_LOCATION_ITEM,
BUNDLE_SYMBOLIC_NAME_ITEM, EVENT_ITEM);
/**
* Answer the list of interfaces that this service implements
*
* @param serviceId
* the identifier of the service
* @return the list of interfaces
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the service indicated does not exist
*/
public String[] getObjectClass(long serviceId) throws IOException;
/**
* Answer the bundle identifier of the bundle which registered the service
*
* @param serviceId
* the identifier of the service
* @return the identifier for the bundle
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the service indicated does not exist
*/
long getBundleIdentifier(long serviceId) throws IOException;
CompositeData getService(long serviceId) throws IOException;
/**
* Answer the map of properties associated with this service
*
* @see JmxConstants#PROPERTIES_TYPE for the details of the TabularType
*
* @param serviceId
* the identifier of the service
* @return the table of properties. These include the standard mandatory
* service.id and objectClass properties as defined in the
* <code>org.osgi.framework.Constants</code> interface
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the service indicated does not exist
*/
TabularData getProperties(long serviceId) throws IOException;
CompositeData getProperty(long serviceId, String key) throws IOException;
long[] getServiceIds() throws IOException;
/**
* Answer the service state of the system in tabular form.
*
* @see #SERVICES_TYPE for the details of the TabularType
*
* @return the tabular representation of the service state
* @throws IOException
* If the operation fails
* @throws IllegalArgumentException
* if the service indicated does not exist
*/
TabularData listServices() throws IOException;
TabularData listServices(String clazz, String filter) throws IOException;
TabularData listServices(String clazz, String filter, String ... serviceTypeItems) throws IOException;
/**
* Answer the list of identifiers of the bundles that use the service
*
* @param serviceId
* the identifier of the service
* @return the list of bundle identifiers
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the service indicated does not exist
*/
long[] getUsingBundles(long serviceId) throws IOException;
}
| 8,034 |
0 | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/framework/PackageStateMBean.java | /*
* Copyright (c) OSGi Alliance (2009, 2010). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.jmx.framework;
import java.io.IOException;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularType;
import org.osgi.jmx.Item;
import org.osgi.jmx.JmxConstants;
/**
* This MBean provides information about the package state of the framework.
*
* @version $Revision$
* @ThreadSafe
*/
public interface PackageStateMBean {
/**
* The fully qualified object name of this MBean.
*/
String OBJECTNAME = JmxConstants.OSGI_CORE
+ ":type=packageState,version=1.5";
/**
* The key EXPORTING_BUNDLE, used in {@link #EXPORTING_BUNDLES_ITEM}.
*/
String EXPORTING_BUNDLES = "ExportingBundles";
/**
* The item containing the bundle identifier in {@link #PACKAGE_TYPE}. The
* key is {@link #EXPORTING_BUNDLES} and the type is
* {@link JmxConstants#LONG_ARRAY_TYPE}.
*/
Item EXPORTING_BUNDLES_ITEM = new Item(
EXPORTING_BUNDLES,
"The bundles the package belongs to",
JmxConstants.LONG_ARRAY_TYPE);
/**
* The key IMPORTING_BUNDLES, used in {@link #IMPORTING_BUNDLES_ITEM}.
*/
String IMPORTING_BUNDLES = "ImportingBundles";
/**
* The item containing the bundle identifier in {@link #PACKAGE_TYPE}. The
* key is {@link #IMPORTING_BUNDLES} and the type is {@link JmxConstants#LONG_ARRAY_TYPE}.
*/
Item IMPORTING_BUNDLES_ITEM = new Item(
IMPORTING_BUNDLES,
"The importing bundles of the package",
JmxConstants.LONG_ARRAY_TYPE);
/**
* The key NAME, used in {@link #NAME_ITEM}.
*/
String NAME = "Name";
/**
* The item containing the name of the package in {@link #PACKAGE_TYPE}.
* The key is {@link #NAME} and the type is {@link SimpleType#LONG}.
*/
Item NAME_ITEM = new Item(NAME,
"The package name",
SimpleType.STRING);
/**
* The name of the item containing the pending removal status of the package
* in the CompositeData. Used
*/
String REMOVAL_PENDING = "RemovalPending";
/**
* The item representing the removal pending status of a package. The key is
* {@link #REMOVAL_PENDING} and the type is {@link SimpleType#BOOLEAN}.
*/
Item REMOVAL_PENDING_ITEM = new Item(
REMOVAL_PENDING,
"Whether the package is pending removal",
SimpleType.BOOLEAN);
/**
* The name of the item containing the package version in the CompositeData.
* Used in {@link #VERSION_ITEM}.
*/
String VERSION = "Version";
/**
* The item containing the version of the package in {@link #PACKAGE_TYPE}.
* The key is {@link #VERSION} and the type is {@link SimpleType#STRING}.
*/
Item VERSION_ITEM = new Item(
VERSION,
"The identifier of the bundle the service belongs to",
SimpleType.STRING);
/**
* The Composite Type for a CompositeData representing a package. This type
* consists of:
* <ul>
* <li>{@link #EXPORTING_BUNDLES_ITEM}</li>
* <li>{@link #IMPORTING_BUNDLES_ITEM}</li>
* <li>{@link #NAME_ITEM}</li>
* <li>{@link #REMOVAL_PENDING_ITEM}</li>
* <li>{@link #VERSION_ITEM}</li>
* </ul>
* The key is defined as {@link #NAME} and {@link #EXPORTING_BUNDLES}
*/
CompositeType PACKAGE_TYPE = Item
.compositeType(
"PACKAGE",
"This type encapsulates an OSGi package",
EXPORTING_BUNDLES_ITEM,
IMPORTING_BUNDLES_ITEM,
NAME_ITEM,
REMOVAL_PENDING_ITEM,
VERSION_ITEM);
/**
* The Tabular Type used in {@link #listPackages()}. They key is
* {@link #NAME}, {@link #VERSION}, and {@link #EXPORTING_BUNDLES}.
*/
TabularType PACKAGES_TYPE = Item.tabularType("PACKAGES",
"A table of packages",
PACKAGE_TYPE, NAME,
VERSION, EXPORTING_BUNDLES);
/**
* Answer the identifier of the bundle exporting the package
*
* @param packageName - the package name
* @param version - the version of the package
* @return the bundle identifiers exporting such a package
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the package indicated does not exist
*/
long[] getExportingBundles(String packageName, String version)
throws IOException;
/**
* Answer the list of identifiers of the bundles importing the package
*
* @param packageName The package name
* @param version The version of the package
* @param exportingBundle The exporting bundle for the given package
* @return the list of bundle identifiers
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the package indicated does not exist
*
*/
long[] getImportingBundles(String packageName, String version,
long exportingBundle) throws IOException;
/**
* Answer the package state of the system in tabular form
*
* The Tabular Data is typed by {@link #PACKAGES_TYPE}, which has
* {@link #PACKAGE_TYPE} as its Composite Type.
*
* @return the tabular representation of the package state
* @throws IOException When fails
*/
TabularData listPackages() throws IOException;
/**
* Answer if this package is exported by a bundle which has been updated or
* uninstalled
*
* @param packageName The package name
* @param version The version of the package
* @param exportingBundle The bundle exporting the package
* @return true if this package is being exported by a bundle that has been
* updated or uninstalled.
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the package indicated does not exist
*/
boolean isRemovalPending(String packageName, String version, long exportingBundle)
throws IOException;
}
| 8,035 |
0 | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/framework/BundleStateMBean.java | /*
* Copyright (c) OSGi Alliance (2009, 2010). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.jmx.framework;
import java.io.IOException;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularType;
import org.osgi.jmx.Item;
import org.osgi.jmx.JmxConstants;
/**
* This MBean represents the Bundle state of the framework. This MBean also
* emits events that clients can use to get notified of the changes in the
* bundle state of the framework.
*
* @version $Id: f5d5197fdabb4e0c420bc47812d38fd14edb61d0 $
* @ThreadSafe
*/
public interface BundleStateMBean {
/**
* The Object Name for a Bundle State MBean.
*/
String OBJECTNAME = JmxConstants.OSGI_CORE
+ ":type=bundleState,version=1.7";
/**
* The key KEY, used in {@link #KEY_ITEM}.
*/
String KEY = "Key";
/**
* The item describing the key of a bundle header entry. The key is
* {@link #KEY} and the type is {@link SimpleType#STRING}.
*/
Item KEY_ITEM = new Item(KEY, "The bundle header key", SimpleType.STRING);
/**
* The key VALUE, used in {@link #VALUE_ITEM}.
*/
String VALUE = "Value";
/**
* The item describing the value of a bundle header entry. The key is
* {@link #VALUE} and the type is {@link SimpleType#STRING}.
*/
Item VALUE_ITEM = new Item(VALUE, "The bundle header value",
SimpleType.STRING);
/**
* The Composite Type describing an entry in bundle headers. It consists of
* {@link #KEY_ITEM} and {@link #VALUE_ITEM}.
*/
CompositeType HEADER_TYPE = Item.compositeType("HEADER",
"This type encapsulates OSGi bundle header key/value pairs",
KEY_ITEM, VALUE_ITEM);
/**
* The Tabular Type describing the type of the Tabular Data value that is
* returned from {@link #getHeaders(long)} method. The primary item is
* {@link #KEY_ITEM}.
*/
TabularType HEADERS_TYPE = Item.tabularType("HEADERS",
"The table of bundle headers",
HEADER_TYPE,
KEY);
/**
* The key LOCATION, used in {@link #LOCATION_ITEM}.
*/
String LOCATION = "Location";
/**
* The item containing the bundle location in {@link #BUNDLE_TYPE}. The key
* is {@link #LOCATION} and the the type is {@link SimpleType#STRING}.
*/
Item LOCATION_ITEM = new Item(LOCATION, "The location of the bundle",
SimpleType.STRING);
/**
* The key IDENTIFIER, used in {@link #IDENTIFIER_ITEM}.
*/
String IDENTIFIER = "Identifier";
/**
* The item containing the bundle identifier in {@link #BUNDLE_TYPE}. The
* key is {@link #IDENTIFIER} and the the type is {@link SimpleType#LONG}.
*/
Item IDENTIFIER_ITEM = new Item(IDENTIFIER, "The id of the bundle",
SimpleType.LONG);
/**
* The key SYMBOLIC_NAME, used in {@link #SYMBOLIC_NAME_ITEM}.
*/
String SYMBOLIC_NAME = "SymbolicName";
/**
* The item containing the symbolic name in {@link #BUNDLE_TYPE}. The key is
* {@link #SYMBOLIC_NAME} and the the type is {@link SimpleType#STRING}.
*/
Item SYMBOLIC_NAME_ITEM = new Item(SYMBOLIC_NAME,
"The symbolic name of the bundle", SimpleType.STRING);
/**
* The key VERSION, used in {@link #VERSION_ITEM}.
*/
String VERSION = "Version";
/**
* The item containing the symbolic name in {@link #BUNDLE_TYPE}. The key is
* {@link #SYMBOLIC_NAME} and the the type is {@link SimpleType#STRING}.
*/
Item VERSION_ITEM = new Item(VERSION, "The version of the bundle",
SimpleType.STRING);
/**
* The key START_LEVEL, used in {@link #START_LEVEL_ITEM}.
*/
String START_LEVEL = "StartLevel";
/**
* The item containing the start level in {@link #BUNDLE_TYPE}. The key is
* {@link #START_LEVEL} and the the type is {@link SimpleType#INTEGER}.
*/
Item START_LEVEL_ITEM = new Item(START_LEVEL,
"The start level of the bundle", SimpleType.INTEGER);
/**
* The key STATE, used in {@link #STATE_ITEM}.
*/
String STATE = "State";
/**
* Constant INSTALLED for the {@link #STATE}
*/
String INSTALLED = "INSTALLED";
/**
* Constant RESOLVED for the {@link #STATE}
*/
String RESOLVED = "RESOLVED";
/**
* Constant STARTING for the {@link #STATE}
*/
String STARTING = "STARTING";
/**
* Constant ACTIVE for the {@link #STATE}
*/
String ACTIVE = "ACTIVE";
/**
* Constant STOPPING for the {@link #STATE}
*/
String STOPPING = "STOPPING";
/**
* Constant UNINSTALLED for the {@link #STATE}
*/
String UNINSTALLED = "UNINSTALLED";
/**
* Constant UNKNOWN for the {@link #STATE}
*/
String UNKNOWN = "UNKNOWN";
/**
* The item containing the bundle state in {@link #BUNDLE_TYPE}. The key is
* {@link #STATE} and the the type is {@link SimpleType#STRING}. The
* returned values must be one of the following strings:
* <ul>
* <li>{@link #INSTALLED}</li>
* <li>{@link #RESOLVED}</li>
* <li>{@link #STARTING}</li>
* <li>{@link #ACTIVE}</li>
* <li>{@link #STOPPING}</li>
* <li>{@link #UNINSTALLED}</li>
* <li>{@link #UNKNOWN}</li>
* </ul>
*/
Item STATE_ITEM = new Item(STATE, "The state of the bundle",
SimpleType.STRING, INSTALLED, RESOLVED, STARTING, ACTIVE, STOPPING,
UNINSTALLED, UNKNOWN);
/**
* The key LAST_MODIFIED, used in {@link #LAST_MODIFIED_ITEM}.
*/
String LAST_MODIFIED = "LastModified";
/**
* The item containing the last modified time in the {@link #BUNDLE_TYPE}.
* The key is {@link #LAST_MODIFIED} and the the type is
* {@link SimpleType#LONG}.
*/
Item LAST_MODIFIED_ITEM = new Item(LAST_MODIFIED,
"The last modification time of the bundle", SimpleType.LONG);
/**
* The key ACTIVATION_POLICY_USED, used in {@link #ACTIVATION_POLICY_USED_ITEM}.
*/
String ACTIVATION_POLICY_USED = "ActivationPolicyUsed";
/**
* The item containing the indication whether the bundle activation policy
* must be used in {@link #BUNDLE_TYPE}. The key is {@link #ACTIVATION_POLICY_USED} and
* the type is {@link SimpleType#BOOLEAN}.
*/
Item ACTIVATION_POLICY_USED_ITEM = new Item(ACTIVATION_POLICY_USED,
"Whether the bundle activation policy must be used", SimpleType.BOOLEAN);
/**
* The key PERSISTENTLY_STARTED, used in {@link #PERSISTENTLY_STARTED_ITEM}.
*/
String PERSISTENTLY_STARTED = "PersistentlyStarted";
/**
* The item containing the indication of persistently started in
* {@link #BUNDLE_TYPE}. The key is {@link #PERSISTENTLY_STARTED} and the
* the type is {@link SimpleType#BOOLEAN}.
*/
Item PERSISTENTLY_STARTED_ITEM = new Item(PERSISTENTLY_STARTED,
"Whether the bundle is persistently started", SimpleType.BOOLEAN);
/**
* The key REMOVAL_PENDING, used in {@link #REMOVAL_PENDING_ITEM}.
*/
String REMOVAL_PENDING = "RemovalPending";
/**
* The item containing the indication of removal pending in
* {@link #BUNDLE_TYPE}. The key is {@link #REMOVAL_PENDING} and the type is
* {@link SimpleType#BOOLEAN}.
*/
Item REMOVAL_PENDING_ITEM = new Item(REMOVAL_PENDING,
"Whether the bundle is pending removal", SimpleType.BOOLEAN);
/**
* The key REQUIRED, used in {@link #REQUIRED_ITEM}.
*/
String REQUIRED = "Required";
/**
* The item containing the required status in {@link #BUNDLE_TYPE}. The key
* is {@link #REQUIRED} and the the type is {@link SimpleType#BOOLEAN}.
*/
Item REQUIRED_ITEM = new Item(REQUIRED, "Whether the bundle is required",
SimpleType.BOOLEAN);
/**
* The key FRAGMENT, used in {@link #FRAGMENT_ITEM}.
*/
String FRAGMENT = "Fragment";
/**
* The item containing the fragment status in {@link #BUNDLE_TYPE}. The key
* is {@link #FRAGMENT} and the the type is {@link SimpleType#BOOLEAN}.
*/
Item FRAGMENT_ITEM = new Item(FRAGMENT, "Whether the bundle is a fragment",
SimpleType.BOOLEAN);
/**
* The key REGISTERED_SERVICES, used in {@link #REGISTERED_SERVICES_ITEM}.
*/
String REGISTERED_SERVICES = "RegisteredServices";
/**
* The item containing the registered services of the bundle in
* {@link #BUNDLE_TYPE}. The key is {@link #REGISTERED_SERVICES} and the the
* type is {@link JmxConstants#LONG_ARRAY_TYPE}.
*/
Item REGISTERED_SERVICES_ITEM = new Item(REGISTERED_SERVICES,
"The registered services of the bundle",
JmxConstants.LONG_ARRAY_TYPE);
/**
* The key SERVICES_IN_USE, used in {@link #SERVICES_IN_USE_ITEM}.
*/
String SERVICES_IN_USE = "ServicesInUse";
/**
* The item containing the services in use by this bundle in
* {@link #BUNDLE_TYPE}. The key is {@link #SERVICES_IN_USE} and the the
* type is {@link JmxConstants#LONG_ARRAY_TYPE}.
*/
Item SERVICES_IN_USE_ITEM = new Item(SERVICES_IN_USE,
"The services in use by the bundle", JmxConstants.LONG_ARRAY_TYPE);
/**
* The key HEADERS, used in {@link #HEADERS_ITEM}.
*/
String HEADERS = "Headers";
/**
* The item containing the bundle headers in {@link #BUNDLE_TYPE}. The key
* is {@link #HEADERS} and the the type is {@link #HEADERS_TYPE}.
*/
Item HEADERS_ITEM = new Item(HEADERS, "The headers of the bundle",
HEADERS_TYPE);
/**
* The key EXPORTED_PACKAGES, used in {@link #EXPORTED_PACKAGES_ITEM}.
*/
String EXPORTED_PACKAGES = "ExportedPackages";
/**
* The item containing the exported package names in {@link #BUNDLE_TYPE}
* .The key is {@link #EXPORTED_PACKAGES} and the the type is
* {@link JmxConstants#STRING_ARRAY_TYPE}.
*/
Item EXPORTED_PACKAGES_ITEM = new Item(EXPORTED_PACKAGES,
"The exported packages of the bundle",
JmxConstants.STRING_ARRAY_TYPE);
/**
* The key IMPORTED_PACKAGES, used in {@link #EXPORTED_PACKAGES_ITEM}.
*/
String IMPORTED_PACKAGES = "ImportedPackages";
/**
* The item containing the imported package names in {@link #BUNDLE_TYPE}
* .The key is {@link #IMPORTED_PACKAGES} and the the type is
* {@link JmxConstants#STRING_ARRAY_TYPE}.
*/
Item IMPORTED_PACKAGES_ITEM = new Item(IMPORTED_PACKAGES,
"The imported packages of the bundle",
JmxConstants.STRING_ARRAY_TYPE);
/**
* The key FRAGMENTS, used in {@link #FRAGMENTS_ITEM}.
*/
String FRAGMENTS = "Fragments";
/**
* The item containing the list of fragments the bundle is host to in
* {@link #BUNDLE_TYPE}. The key is {@link #FRAGMENTS} and the type is
* {@link JmxConstants#LONG_ARRAY_TYPE}.
*/
Item FRAGMENTS_ITEM = new Item(FRAGMENTS,
"The fragments of which the bundle is host",
JmxConstants.LONG_ARRAY_TYPE);
/**
* The key HOSTS, used in {@link #HOSTS_ITEM}.
*/
String HOSTS = "Hosts";
/**
* The item containing the bundle identifiers representing the hosts in
* {@link #BUNDLE_TYPE}. The key is {@link #HOSTS} and the type is
* {@link JmxConstants#LONG_ARRAY_TYPE}
*/
Item HOSTS_ITEM = new Item(HOSTS,
"The fragments of which the bundle is host",
JmxConstants.LONG_ARRAY_TYPE);
/**
* The key REQUIRED_BUNDLES, used in {@link #REQUIRED_BUNDLES_ITEM}.
*/
String REQUIRED_BUNDLES = "RequiredBundles";
/**
* The item containing the required bundles in {@link #BUNDLE_TYPE}. The key
* is {@link #REQUIRED_BUNDLES} and the type is
* {@link JmxConstants#LONG_ARRAY_TYPE}
*/
Item REQUIRED_BUNDLES_ITEM = new Item(REQUIRED_BUNDLES,
"The required bundles the bundle", JmxConstants.LONG_ARRAY_TYPE);
/**
* The key REQUIRING_BUNDLES, used in {@link #REQUIRING_BUNDLES_ITEM}.
*/
String REQUIRING_BUNDLES = "RequiringBundles";
/**
* The item containing the bundles requiring this bundle in
* {@link #BUNDLE_TYPE}. The key is {@link #REQUIRING_BUNDLES} and the type
* is {@link JmxConstants#LONG_ARRAY_TYPE}
*/
Item REQUIRING_BUNDLES_ITEM = new Item(REQUIRING_BUNDLES,
"The bundles requiring the bundle", JmxConstants.LONG_ARRAY_TYPE);
/**
* The key EVENT, used in {@link #EVENT_ITEM}.
*/
String EVENT = "BundleEvent";
/**
* The item containing the event type. The key is {@link #EVENT} and the type is {@link SimpleType#INTEGER}
*/
Item EVENT_ITEM = new Item(
EVENT,
"The type of the event: {INSTALLED=1, STARTED=2, STOPPED=4, UPDATED=8, UNINSTALLED=16}",
SimpleType.INTEGER);
/**
* The Composite Type that represents a bundle event. This composite consists of:
* <ul>
* <li>{@link #IDENTIFIER}</li>
* <li>{@link #LOCATION}</li>
* <li>{@link #SYMBOLIC_NAME}</li>
* <li>{@link #EVENT}</li>
* </ul>
*/
CompositeType BUNDLE_EVENT_TYPE = Item.compositeType("BUNDLE_EVENT",
"This type encapsulates OSGi bundle events", IDENTIFIER_ITEM,
LOCATION_ITEM, SYMBOLIC_NAME_ITEM, EVENT_ITEM);
/**
* The Composite Type that represents a bundle. This composite consist of:
* <ul>
* <li>{@link #EXPORTED_PACKAGES}</li>
* <li>{@link #FRAGMENT}</li>
* <li>{@link #FRAGMENTS}</li>
* <li>{@link #HEADERS}</li>
* <li>{@link #HOSTS}</li>
* <li>{@link #IDENTIFIER}</li>
* <li>{@link #IMPORTED_PACKAGES}</li>
* <li>{@link #LAST_MODIFIED}</li>
* <li>{@link #LOCATION}</li>
* <li>{@link #ACTIVATION_POLICY_USED}</li>
* <li>{@link #PERSISTENTLY_STARTED}</li>
* <li>{@link #REGISTERED_SERVICES}</li>
* <li>{@link #REMOVAL_PENDING}</li>
* <li>{@link #REQUIRED}</li>
* <li>{@link #REQUIRED_BUNDLES}</li>
* <li>{@link #REQUIRING_BUNDLES}</li>
* <li>{@link #START_LEVEL}</li>
* <li>{@link #STATE}</li>
* <li>{@link #SERVICES_IN_USE}</li>
* <li>{@link #SYMBOLIC_NAME}</li>
* <li>{@link #VERSION}</li>
* </ul>
* It is used by {@link #BUNDLES_TYPE}.
*/
CompositeType BUNDLE_TYPE = Item.compositeType("BUNDLE",
"This type encapsulates OSGi bundles", EXPORTED_PACKAGES_ITEM,
FRAGMENT_ITEM, FRAGMENTS_ITEM, HEADERS_ITEM, HOSTS_ITEM,
IDENTIFIER_ITEM, IMPORTED_PACKAGES_ITEM, LAST_MODIFIED_ITEM,
LOCATION_ITEM, ACTIVATION_POLICY_USED_ITEM,
PERSISTENTLY_STARTED_ITEM, REGISTERED_SERVICES_ITEM,
REMOVAL_PENDING_ITEM, REQUIRED_ITEM, REQUIRED_BUNDLES_ITEM,
REQUIRING_BUNDLES_ITEM, START_LEVEL_ITEM, STATE_ITEM,
SERVICES_IN_USE_ITEM, SYMBOLIC_NAME_ITEM, VERSION_ITEM);
/**
* The Tabular Type for a list of bundles. The row type is
* {@link #BUNDLE_TYPE} and the index is {@link #IDENTIFIER}.
*/
TabularType BUNDLES_TYPE = Item.tabularType("BUNDLES", "A list of bundles",
BUNDLE_TYPE,
IDENTIFIER);
/** New!!
* @param id The Bundle ID
* @return The Bundle Data
* @throws IOException
*/
CompositeData getBundle(long id) throws IOException;
long[] getBundleIds() throws IOException;
/**
* Answer the list of identifiers of the bundles this bundle depends upon
*
* @param bundleIdentifier
* the bundle identifier
* @return the list of bundle identifiers
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
long[] getRequiredBundles(long bundleIdentifier) throws IOException;
/**
* Answer the bundle state of the system in tabular form.
*
* Each row of the returned table represents a single bundle. The Tabular
* Data consists of Composite Data that is type by {@link #BUNDLES_TYPE}.
*
* @return the tabular representation of the bundle state
* @throws IOException
*/
TabularData listBundles() throws IOException;
TabularData listBundles(String ... items) throws IOException;
/**
* Answer the list of exported packages for this bundle.
*
* @param bundleId
* @return the array of package names, combined with their version in the
* format <packageName;version>
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
String[] getExportedPackages(long bundleId) throws IOException;
/**
* Answer the list of the bundle ids of the fragments associated with this
* bundle
*
* @param bundleId
* @return the array of bundle identifiers
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
long[] getFragments(long bundleId) throws IOException;
/**
* Answer the headers for the bundle uniquely identified by the bundle id.
* The Tabular Data is typed by the {@link #HEADERS_TYPE}.
*
* @param bundleId
* the unique identifier of the bundle
* @return the table of associated header key and values
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
TabularData getHeaders(long bundleId) throws IOException;
TabularData getHeaders(long bundleId, String locale) throws IOException;
String getHeader(long bundleId, String key) throws IOException;
String getHeader(long bundleId, String key, String locale) throws IOException;
/**
* Answer the list of bundle ids of the bundles which host a fragment
*
* @param fragment
* the bundle id of the fragment
* @return the array of bundle identifiers
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
long[] getHosts(long fragment) throws IOException;
/**
* Answer the array of the packages imported by this bundle
*
* @param bundleId
* the bundle identifier
* @return the array of package names, combined with their version in the
* format <packageName;version>
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
String[] getImportedPackages(long bundleId) throws IOException;
/**
* Answer the last modified time of a bundle
*
* @param bundleId
* the unique identifier of a bundle
* @return the last modified time
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
long getLastModified(long bundleId) throws IOException;
/**
* Answer the list of service identifiers representing the services this
* bundle exports
*
* @param bundleId
* the bundle identifier
* @return the list of service identifiers
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
long[] getRegisteredServices(long bundleId) throws IOException;
/**
* Answer the list of identifiers of the bundles which require this bundle
*
* @param bundleIdentifier
* the bundle identifier
* @return the list of bundle identifiers
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
long[] getRequiringBundles(long bundleIdentifier) throws IOException;
/**
* Answer the list of service identifiers which refer to the the services
* this bundle is using
*
* @param bundleIdentifier
* the bundle identifier
* @return the list of service identifiers
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
long[] getServicesInUse(long bundleIdentifier) throws IOException;
/**
* Answer the start level of the bundle
*
* @param bundleId
* the identifier of the bundle
* @return the start level
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
int getStartLevel(long bundleId) throws IOException;
/**
* Answer the symbolic name of the state of the bundle
*
* @param bundleId
* the identifier of the bundle
* @return the string name of the bundle state
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
String getState(long bundleId) throws IOException;
/**
* Answer the symbolic name of the bundle
*
* @param bundleId
* the identifier of the bundle
* @return the symbolic name
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
String getSymbolicName(long bundleId) throws IOException;
/**
* Answer whether the specified bundle's autostart setting indicates that
* the activation policy declared in the bundle's manifest must be used.
*
* @param bundleId
* the identifier of the bundle
* @return true if the bundle's autostart setting indicates the activation policy
* declared in the manifest must be used. false if the bundle must be eagerly activated.
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
boolean isActivationPolicyUsed(long bundleId) throws IOException;
/**
* Answer if the bundle is persistently started when its start level is
* reached
*
* @param bundleId
* the identifier of the bundle
* @return true if the bundle is persistently started
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
boolean isPersistentlyStarted(long bundleId) throws IOException;
/**
* Answer whether the bundle is a fragment or not
*
* @param bundleId
* the identifier of the bundle
* @return true if the bundle is a fragment
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
boolean isFragment(long bundleId) throws IOException;
/**
* Answer true if the bundle is pending removal
*
* @param bundleId
* the identifier of the bundle
* @return true if the bundle is pending removal
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
boolean isRemovalPending(long bundleId) throws IOException;
/**
* Answer true if the bundle is required by another bundle
*
* @param bundleId
* the identifier of the bundle
* @return true if the bundle is required by another bundle
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
boolean isRequired(long bundleId) throws IOException;
/**
* Answer the location of the bundle.
*
* @param bundleId
* the identifier of the bundle
* @return The location string of this bundle
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
String getLocation(long bundleId) throws IOException;
/**
* Answer the location of the bundle.
*
* @param bundleId
* the identifier of the bundle
* @return The location string of this bundle
* @throws IOException
* if the operation fails
* @throws IllegalArgumentException
* if the bundle indicated does not exist
*/
String getVersion(long bundleId) throws IOException;
}
| 8,036 |
0 | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/framework/FrameworkMBean.java | /*
* Copyright (c) OSGi Alliance (2009, 2010). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.jmx.framework;
import java.io.IOException;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.SimpleType;
import org.osgi.jmx.Item;
import org.osgi.jmx.JmxConstants;
/**
* The FrameworkMbean provides mechanisms to exert control over the framework.
* For many operations, it provides a batch mechanism to avoid excessive message
* passing when interacting remotely.
*
* @version $Revision$
* @ThreadSafe
*/
public interface FrameworkMBean {
/**
* The fully qualified object name of this mbean.
*/
String OBJECTNAME = JmxConstants.OSGI_CORE
+ ":type=framework,version=1.7";
/**
* The SUCCESS, used in {@link #SUCCESS_ITEM}.
*/
String SUCCESS = "Success";
/**
* The item that indicates if this operation was successful. The key is
* {@link #SUCCESS} and the type is {@link SimpleType#BOOLEAN}. It is used
* in {@link #BATCH_ACTION_RESULT_TYPE} and
* {@link #BATCH_INSTALL_RESULT_TYPE}.
*/
Item SUCCESS_ITEM = new Item(
SUCCESS,
"Whether the operation was successful",
SimpleType.BOOLEAN);
/**
* The key ERROR, used in {@link #ERROR_ITEM}.
*/
String ERROR = "Error";
/**
* The item containing the error message of the batch operation. The key is
* {@link #ERROR} and the type is {@link SimpleType#STRING}. It is used in
* {@link #BATCH_ACTION_RESULT_TYPE} and {@link #BATCH_INSTALL_RESULT_TYPE}.
*/
Item ERROR_ITEM = new Item(
ERROR,
"The error message if unsuccessful",
SimpleType.STRING);
/**
* The key COMPLETED, used in {@link #COMPLETED_ITEM}.
*/
String COMPLETED = "Completed";
/**
* The item containing the list of bundles completing the batch operation.
* The key is {@link #COMPLETED} and the type is
* {@link JmxConstants#LONG_ARRAY_TYPE}. It is used in
* {@link #BATCH_ACTION_RESULT_TYPE} and {@link #BATCH_INSTALL_RESULT_TYPE}.
*/
Item COMPLETED_ITEM = new Item(
COMPLETED,
"The bundle ids of the successfully completed installs",
JmxConstants.LONG_ARRAY_TYPE);
/**
* The key for BUNDLE_IN_ERROR. This key is used with two different items:
* {@link #BUNDLE_IN_ERROR_ID_ITEM} and
* {@link #BUNDLE_IN_ERROR_LOCATION_ITEM} that each have a different type
* for this key. It is used in {@link #BATCH_ACTION_RESULT_TYPE} and
* {@link #BATCH_INSTALL_RESULT_TYPE}.
*/
String BUNDLE_IN_ERROR = "BundleInError";
/**
* The item containing the bundle which caused the error during the batch
* operation. This item describes the bundle in error as an id. The key is
* {@link #BUNDLE_IN_ERROR} and the type is {@link SimpleType#LONG}. It is
* used in {@link #BATCH_ACTION_RESULT_TYPE}.
*
* @see #BUNDLE_IN_ERROR_LOCATION_ITEM BUNDLE_IN_ERROR_LOCATION_ITEM for the
* item that has a location for the bundle in error.
*/
Item BUNDLE_IN_ERROR_ID_ITEM = new Item(
BUNDLE_IN_ERROR,
"The id of the bundle causing the error",
SimpleType.LONG);
/**
* The key REMAINING, used in {@link #REMAINING_ID_ITEM} and
* {@link #REMAINING_LOCATION_ITEM}.
*/
String REMAINING = "Remaining";
/**
* The item containing the list of remaining bundles unprocessed by the
* failing batch operation. The key is {@link #REMAINING} and the type is
* {@link JmxConstants#LONG_ARRAY_TYPE}. It is used in
* {@link #BATCH_ACTION_RESULT_TYPE} and {@link #BATCH_INSTALL_RESULT_TYPE}.
*/
Item REMAINING_ID_ITEM = new Item(
REMAINING,
"The ids of the remaining bundles",
JmxConstants.LONG_ARRAY_TYPE);
/**
* The Composite Type for a batch action result.
* {@link #refreshBundle(long)} and {@link #refreshBundles(long[])}.
* Notice that a batch action result returns uses an id for the
* {@link #BUNDLE_IN_ERROR} while the {@link #BATCH_INSTALL_RESULT_TYPE}
* uses a location.
*
* This Composite Type consists of the following items:
* <ul>
* <li>{@link #BUNDLE_IN_ERROR_ID_ITEM}</li>
* <li>{@link #COMPLETED_ITEM}</li>
* <li>{@link #ERROR_ITEM}</li>
* <li>{@link #REMAINING_ID_ITEM}</li>
* <li>{@link #SUCCESS_ITEM}</li>
* </ul>
*/
CompositeType BATCH_ACTION_RESULT_TYPE = Item
.compositeType(
"BUNDLE_ACTION_RESULT",
"This type encapsulates a bundle batch install action result",
BUNDLE_IN_ERROR_ID_ITEM,
COMPLETED_ITEM,
ERROR_ITEM,
REMAINING_ID_ITEM,
SUCCESS_ITEM
);
/**
* The item containing the bundle which caused the error during the batch
* operation. This item describes the bundle in error as a location. The key
* is {@link #BUNDLE_IN_ERROR} and the type is {@link SimpleType#STRING}. It
* is used in {@link #BATCH_INSTALL_RESULT_TYPE}.
*
* @see #BUNDLE_IN_ERROR_ID_ITEM BUNDLE_IN_ERROR_ID_ITEM for the item that
* has the id for the bundle in error.
*/
Item BUNDLE_IN_ERROR_LOCATION_ITEM = new Item(
BUNDLE_IN_ERROR,
"The location of the bundle causing the error",
SimpleType.STRING);
/**
* The item containing the list of remaining bundles unprocessed by the
* failing batch operation. The key is {@link #REMAINING} and the type is
* {@link JmxConstants#STRING_ARRAY_TYPE}. It is used in
* {@link #BATCH_ACTION_RESULT_TYPE} and {@link #BATCH_INSTALL_RESULT_TYPE}.
*/
Item REMAINING_LOCATION_ITEM = new Item(
REMAINING,
"The locations of the remaining bundles",
JmxConstants.STRING_ARRAY_TYPE);
/**
* The Composite Type which represents the result of a batch install
* operation. It is used in {@link #installBundles(String[])} and
* {@link #installBundlesFromURL(String[], String[])}.
*
* This Composite Type consists of the following items:
* <ul>
* <li>{@link #BUNDLE_IN_ERROR_LOCATION_ITEM}</li>
* <li>{@link #COMPLETED_ITEM}</li>
* <li>{@link #ERROR_ITEM}</li>
* <li>{@link #REMAINING_LOCATION_ITEM P }</li>
* <li>{@link #SUCCESS_ITEM}</li>
* </ul>
*/
CompositeType BATCH_INSTALL_RESULT_TYPE = Item
.compositeType(
"BATCH_INSTALL_RESULT",
"This type encapsulates a bundle batch install action result",
BUNDLE_IN_ERROR_LOCATION_ITEM,
COMPLETED_ITEM,
ERROR_ITEM,
REMAINING_LOCATION_ITEM,
SUCCESS_ITEM
);
/**
* The Composite Type which represents the result of a batch resolve
* operation. It is used in {@link #refreshBundlesAndWait(String[])}.
*
* This Composite Type consists of the following items:
* <ul>
* <li>{@link #COMPLETED_ITEM}</li>
* <li>{@link #SUCCESS_ITEM}</li>
* </ul>
*/
CompositeType BATCH_RESOLVE_RESULT_TYPE = Item
.compositeType(
"BATCH_RESOLVE_RESULT",
"This type encapsulates a bundle batch resolve action result",
COMPLETED_ITEM,
SUCCESS_ITEM);
/**
* Returns the dependency closure for the specified bundles.
*
* <p>
* A graph of bundles is computed starting with the specified bundles. The
* graph is expanded by adding any bundle that is either wired to a package
* that is currently exported by a bundle in the graph or requires a bundle
* in the graph. The graph is fully constructed when there is no bundle
* outside the graph that is wired to a bundle in the graph. The graph may
* contain {@code UNINSTALLED} bundles that are
* {@link #getRemovalPendingBundles() removal pending}.
*
* @param bundles The initial bundles IDs for which to generate the dependency
* closure.
* @return A bundle ID array containing a snapshot of the dependency closure of
* the specified bundles, or an empty array if there were no
* specified bundles.
* @throws IOException if the operation failed
*/
long[] getDependencyClosure(long[] bundles) throws IOException;
/**
* Retrieve the framework start level
*
* @return the framework start level
* @throws IOException if the operation failed
*/
int getFrameworkStartLevel() throws IOException;
/**
* Answer the initial start level assigned to a bundle when it is first
* started
*
* @return the start level
* @throws IOException if the operation failed
*/
int getInitialBundleStartLevel() throws IOException;
/**
* Returns the value of the specified property. If the key is not found in
* the Framework properties, the system properties are then searched. The
* method returns {@code null} if the property is not found.
*
* @param key The name of the requested property.
* @return The value of the requested property, or {@code null} if the
* property is undefined.
* @throws IOException if the operation failed
*/
String getProperty(String key) throws IOException;
/**
* Returns the bundles IDs that have non-current, in use bundle wirings. This
* is typically the bundles which have been updated or uninstalled since the
* last call to {@link #refreshBundles(long[])}.
*
* @return A bundle ID array containing a snapshot of the bundles which
* have non-current, in use bundle wirings, or an empty
* array if there are no such bundles.
* @throws IOException if the operation failed
*/
long[] getRemovalPendingBundles() throws IOException;
/**
* Install the bundle indicated by the bundleLocations
*
* @param location the location of the bundle to install
* @return the bundle id the installed bundle
* @throws IOException if the operation does not succeed
*/
long installBundle(String location) throws IOException;
/**
* Install the bundle indicated by the bundleLocations
*
* @param location the location to assign to the bundle
* @param url the URL which will supply the bytes for the bundle
* @return the bundle id the installed bundle
* @throws IOException if the operation does not succeed
*/
long installBundleFromURL(String location, String url) throws IOException;
/**
* Batch install the bundles indicated by the list of bundleLocationUrls
*
* @see #BATCH_INSTALL_RESULT_TYPE BATCH_INSTALL_RESULT_TYPE for the precise
* specification of the CompositeData type representing the returned
* result.
*
* @param locations the array of locations of the bundles to install
* @return the resulting state from executing the operation
* @throws IOException if the operation does not succeed
*/
CompositeData installBundles(String[] locations) throws IOException;
/**
* Batch install the bundles indicated by the list of bundleLocationUrls
*
* @see #BATCH_INSTALL_RESULT_TYPE BATCH_INSTALL_RESULT_TYPE
* BatchBundleResult for the precise specification of the CompositeData
* type representing the returned result.
*
* @param locations the array of locations to assign to the installed
* bundles
* @param urls the array of urls which supply the bundle bytes
* @return the resulting state from executing the operation
* @throws IOException if the operation does not succeed
*/
CompositeData installBundlesFromURL(String[] locations, String[] urls)
throws IOException;
/**
* Force the update, replacement or removal of the packages identified by
* the specified bundle.
*
* @param bundleIdentifier the bundle identifier
* @throws IOException if the operation failed
*/
void refreshBundle(long bundleIdentifier) throws IOException;
boolean refreshBundleAndWait(long bundleIdentifier) throws IOException;
/**
* Force the update, replacement or removal of the packages identified by
* the list of bundles.
*
* @param bundleIdentifiers The identifiers of the bundles to refresh, or
* <code>null</code> for all bundles with packages pending removal.
* @throws IOException if the operation failed
*/
void refreshBundles(long[] bundleIdentifiers) throws IOException;
CompositeData refreshBundlesAndWait(long[] bundleIdentifiers) throws IOException;
/**
* Resolve the bundle indicated by the unique symbolic name and version
*
* @param bundleIdentifier the bundle identifier
* @return <code>true</code> if the bundle was resolved, false otherwise
* @throws IOException if the operation does not succeed
* @throws IllegalArgumentException if the bundle indicated does not exist
*/
boolean resolveBundle(long bundleIdentifier) throws IOException;
/**
* Batch resolve the bundles indicated by the list of bundle identifiers
*
* @param bundleIdentifiers The identifiers of the bundles to resolve, or
* <code>null</code> to resolve all unresolved bundles.
* @return <code>true</code> if the bundles were resolved, false otherwise
* @throws IOException if the operation does not succeed
*/
boolean resolveBundles(long[] bundleIdentifiers) throws IOException;
/**
* Same as {@link #resolveBundles(long[])} but with a more detailed return type.
* @param bundleIdentifiers
* @return
* @throws IOException
*/
CompositeData resolve(long[] bundleIdentifiers) throws IOException;
/**
* Restart the framework by updating the system bundle
*
* @throws IOException if the operation failed
*/
void restartFramework() throws IOException;
/**
* Set the start level for the bundle identifier
*
* @param bundleIdentifier the bundle identifier
* @param newlevel the new start level for the bundle
* @throws IOException if the operation failed
*/
void setBundleStartLevel(long bundleIdentifier, int newlevel)
throws IOException;
/**
* Set the start levels for the list of bundles.
*
* @see #BATCH_ACTION_RESULT_TYPE BATCH_ACTION_RESULT_TYPE for the precise
* specification of the CompositeData type representing the returned
* result.
*
* @param bundleIdentifiers the array of bundle identifiers
* @param newlevels the array of new start level for the bundles
* @return the resulting state from executing the operation
* @throws IOException if the operation failed
*/
CompositeData setBundleStartLevels(long[] bundleIdentifiers, int[] newlevels)
throws IOException;
/**
* Set the start level for the framework
*
* @param newlevel the new start level
* @throws IOException if the operation failed
*/
void setFrameworkStartLevel(int newlevel) throws IOException;
/**
* Set the initial start level assigned to a bundle when it is first started
*
* @param newlevel the new start level
* @throws IOException if the operation failed
*/
void setInitialBundleStartLevel(int newlevel) throws IOException;
/**
* Shutdown the framework by stopping the system bundle
*
* @throws IOException if the operation failed
*/
void shutdownFramework() throws IOException;
/**
* Start the bundle indicated by the bundle identifier
*
* @param bundleIdentifier the bundle identifier
* @throws IOException if the operation does not succeed
* @throws IllegalArgumentException if the bundle indicated does not exist
*/
void startBundle(long bundleIdentifier) throws IOException;
/**
* Batch start the bundles indicated by the list of bundle identifier
*
* @see #BATCH_ACTION_RESULT_TYPE BATCH_ACTION_RESULT_TYPE for the precise
* specification of the CompositeData type representing the returned
* result.
*
* @param bundleIdentifiers the array of bundle identifiers
* @return the resulting state from executing the operation
* @throws IOException if the operation does not succeed
*/
CompositeData startBundles(long[] bundleIdentifiers) throws IOException;
/**
* Stop the bundle indicated by the bundle identifier
*
* @param bundleIdentifier the bundle identifier
* @throws IOException if the operation does not succeed
* @throws IllegalArgumentException if the bundle indicated does not exist
*/
void stopBundle(long bundleIdentifier) throws IOException;
/**
* Batch stop the bundles indicated by the list of bundle identifier
*
* @see #BATCH_ACTION_RESULT_TYPE BATCH_ACTION_RESULT_TYPE for the precise
* specification of the CompositeData type representing the returned
* result.
*
* @param bundleIdentifiers the array of bundle identifiers
* @return the resulting state from executing the operation
* @throws IOException if the operation does not succeed
*/
CompositeData stopBundles(long[] bundleIdentifiers) throws IOException;
/**
* Uninstall the bundle indicated by the bundle identifier
*
* @param bundleIdentifier the bundle identifier
* @throws IOException if the operation does not succeed
* @throws IllegalArgumentException if the bundle indicated does not exist
*/
void uninstallBundle(long bundleIdentifier) throws IOException;
/**
* Batch uninstall the bundles indicated by the list of bundle identifiers
*
* @see #BATCH_ACTION_RESULT_TYPE BATCH_ACTION_RESULT_TYPE for the precise
* specification of the CompositeData type representing the returned
* result.
*
* @param bundleIdentifiers the array of bundle identifiers
* @return the resulting state from executing the operation
* @throws IOException if the operation does not succeed
*/
CompositeData uninstallBundles(long[] bundleIdentifiers) throws IOException;
/**
* Update the bundle indicated by the bundle identifier
*
* @param bundleIdentifier the bundle identifier
* @throws IOException if the operation does not succeed
* @throws IllegalArgumentException if the bundle indicated does not exist
*/
void updateBundle(long bundleIdentifier) throws IOException;
/**
* Update the bundle identified by the bundle identifier
*
* @param bundleIdentifier the bundle identifier
* @param url the URL to use to update the bundle
* @throws IOException if the operation does not succeed
* @throws IllegalArgumentException if the bundle indicated does not exist
*/
void updateBundleFromURL(long bundleIdentifier, String url) throws IOException;
/**
* Batch update the bundles indicated by the list of bundle identifier.
*
* @see #BATCH_ACTION_RESULT_TYPE BATCH_ACTION_RESULT_TYPE for the precise
* specification of the CompositeData type representing the returned
* result.
*
* @param bundleIdentifiers the array of bundle identifiers
* @return the resulting state from executing the operation
* @throws IOException if the operation does not succeed
*/
CompositeData updateBundles(long[] bundleIdentifiers) throws IOException;
/**
* Update the bundle uniquely identified by the bundle symbolic name and
* version using the contents of the supplied urls.
*
* @see #BATCH_ACTION_RESULT_TYPE BATCH_ACTION_RESULT_TYPE for the precise
* specification of the CompositeData type representing the returned
* result.
*
* @param bundleIdentifiers the array of bundle identifiers
* @param urls the array of URLs to use to update the bundles
* @return the resulting state from executing the operation
* @throws IOException if the operation does not succeed
* @throws IllegalArgumentException if the bundle indicated does not exist
*/
CompositeData updateBundlesFromURL(long[] bundleIdentifiers, String[] urls)
throws IOException;
/**
* Update the framework by updating the system bundle.
*
* @throws IOException if the operation failed
*/
void updateFramework() throws IOException;
} | 8,037 |
0 | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/framework | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/framework/wiring/BundleWiringStateMBean.java | /*
* Copyright (c) OSGi Alliance (2010, 2012). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.jmx.framework.wiring;
import java.io.IOException;
import javax.management.JMException;
import javax.management.openmbean.ArrayType;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularType;
import org.osgi.jmx.Item;
import org.osgi.jmx.JmxConstants;
/**
* This MBean represents the bundle wiring state.
* <p>
* It can be used to retrieve the declared capabilities, declared requirements,
* and wiring for the current and past revisions of bundles.
*
* @ThreadSafe
*/
public interface BundleWiringStateMBean {
/**
* The Object Name prefix for this mbean. The full object name also contains
* the framework name and uuid as properties.
*/
String OBJECTNAME = JmxConstants.OSGI_CORE + ":type=wiringState,version=1.1";
/**
* The key of {@link #KEY_ITEM}.
*/
String KEY = "Key";
/**
* The item containing the key of a capability or requirement directive.
* Used in {@link #DIRECTIVE_TYPE}. The key is {@link #KEY} and the type is
* a String.
*/
Item KEY_ITEM = new Item(KEY, "The directive key", SimpleType.STRING);
/**
* The key of {@link #VALUE}.
*/
String VALUE = "Value";
/**
* The item containing the value of a capability or requirement directive.
* Used in {@link #DIRECTIVE_TYPE}. They key is {@link #VALUE} and the type
* is a String.
*/
Item VALUE_ITEM = new Item(VALUE, "The directive value", SimpleType.STRING);
/**
* The Composite Type that represents a directive for a capability or
* requirement. The composite consists of:
* <ul>
* <li>{@link #KEY}</li>
* <li>{@link #VALUE}</li>
* </ul>
*/
CompositeType DIRECTIVE_TYPE = Item.compositeType("DIRECTIVE", "Describes a directive of a capability or requirement", KEY_ITEM, VALUE_ITEM);
/**
* The Tabular Type that holds the directives for a capability or
* requirement. The row type is {@link #DIRECTIVE_TYPE} and the index is
* {@link #KEY}.
*/
TabularType DIRECTIVES_TYPE = Item.tabularType("DIRECTIVES", "Describes the directives of a capability or requirement", DIRECTIVE_TYPE, KEY);
/**
* The key of {@link #DIRECTIVES_ITEM}.
*/
String DIRECTIVES = "Directives";
/**
* The item containing the directives of a capability or requirement. Used
* in {@link #BUNDLE_REQUIREMENT_TYPE} and {@link #BUNDLE_CAPABILITY_TYPE}.
* The key is {@link #DIRECTIVES} and the type is {@link #DIRECTIVES_TYPE}.
*/
Item DIRECTIVES_ITEM = new Item(DIRECTIVES, "The directives of a capability or requirement", DIRECTIVES_TYPE);
/**
* The Tabular Type that holds the attributes for a capability or
* requirements. The row type is {@link JmxConstants#PROPERTY_TYPE} and the
* index is {@link JmxConstants#KEY}.
*/
TabularType ATTRIBUTES_TYPE = Item.tabularType("ATTRIBUTES", "Describes attributes of a capability or requirement", JmxConstants.PROPERTY_TYPE, JmxConstants.KEY);
/**
* The key of {@link #ATTRIBUTES_ITEM}.
*/
String ATTRIBUTES = "Attributes";
/**
* The item containing the attributes of a capability or requirement. Used
* in {@link #BUNDLE_REQUIREMENT_TYPE} and {@link #BUNDLE_CAPABILITY_TYPE}.
* The key is {@link #ATTRIBUTES} and the type is {@link #ATTRIBUTES_TYPE}.
*/
Item ATTRIBUTES_ITEM = new Item(ATTRIBUTES, "The attributes of a capability or requirement", ATTRIBUTES_TYPE);
/**
* The key of {@link #NAMESPACE_ITEM}.
*/
String NAMESPACE = "Namespace";
/**
* The item containing the namespace for a capability or requirement. Used
* in {@link #BUNDLE_REQUIREMENT_TYPE} and {@link #BUNDLE_CAPABILITY_TYPE}.
* The key is {@link #NAMESPACE} and the type is a String.
*/
Item NAMESPACE_ITEM = new Item(NAMESPACE, "The namespace of a capability or requirement", SimpleType.STRING);
/**
* The Composite Type that represents the requirement of a bundle.
*
* The composite consists of:
* <ul>
* <li>{@link #NAMESPACE}</li>
* <li>{@link #ATTRIBUTES}</li>
* <li>{@link #DIRECTIVES}</li>
* </ul>
*/
CompositeType BUNDLE_REQUIREMENT_TYPE = Item.compositeType("BUNDLE_REQUIREMENT", "Describes the requirement of a bundle", ATTRIBUTES_ITEM, DIRECTIVES_ITEM, NAMESPACE_ITEM);
/**
* The Composite Type that represents the capability of a bundle.
*
* The composite consists of:
* <ul>
* <li>{@link #NAMESPACE}</li>
* <li>{@link #ATTRIBUTES}</li>
* <li>{@link #DIRECTIVES}</li>
* </ul>
*/
CompositeType BUNDLE_CAPABILITY_TYPE = Item.compositeType("BUNDLE_CAPABILITY", "Describes the capability of a bundle", ATTRIBUTES_ITEM, DIRECTIVES_ITEM, NAMESPACE_ITEM);
/**
* The key of {@link #PROVIDER_BUNDLE_ID_ITEM}.
*/
String PROVIDER_BUNDLE_ID = "ProviderBundleId";
/**
* The item containing the provider bundle ID in {@link #BUNDLE_WIRE_TYPE}.
* The key is {@link #PROVIDER_BUNDLE_ID} and the type is a long.
*/
Item PROVIDER_BUNDLE_ID_ITEM = new Item(PROVIDER_BUNDLE_ID, "The identifier of the bundle that is the provider of the capability", SimpleType.LONG);
/**
* The key of {@link #REQUIRER_BUNDLE_ID_ITEM}.
*/
String REQUIRER_BUNDLE_ID = "RequirerBundleId";
/**
* The item containing the requirer bundle ID in {@link #BUNDLE_WIRE_TYPE}.
* The key is {@link #REQUIRER_BUNDLE_ID} and the type is long.
*/
Item REQUIRER_BUNDLE_ID_ITEM = new Item(REQUIRER_BUNDLE_ID, "The identifier of the bundle that is the requirer of the requirement", SimpleType.LONG);
/**
* The key of {@link #BUNDLE_REQUIREMENT_ITEM}.
*/
String BUNDLE_REQUIREMENT = "BundleRequirement";
/**
* The item containing a requirement for a bundle in
* {@link #BUNDLE_WIRE_TYPE}. The key is {@link #BUNDLE_REQUIREMENT} and the
* type is {@link #BUNDLE_REQUIREMENT_TYPE}.
*/
Item BUNDLE_REQUIREMENT_ITEM = new Item(BUNDLE_REQUIREMENT, "The wired requirements of a bundle", BUNDLE_REQUIREMENT_TYPE);
/**
* The key of {@link #BUNDLE_CAPABILITY_ITEM}.
*/
String BUNDLE_CAPABILITY = "BundleCapability";
/**
* The item containing a capability for a bundle in
* {@link #BUNDLE_WIRE_TYPE}. The key is {@link #BUNDLE_CAPABILITY} and the
* type is {@link #BUNDLE_CAPABILITY_TYPE}.
*/
Item BUNDLE_CAPABILITY_ITEM = new Item(BUNDLE_CAPABILITY, "The wired capabilities of a bundle", BUNDLE_CAPABILITY_TYPE);
/**
* The key of {@link #PROVIDER_BUNDLE_REVISION_ID_ITEM}.
*/
String PROVIDER_BUNDLE_REVISION_ID = "ProviderBundleRevisionId";
/**
* The local ID of a provider revision in {@link #BUNDLE_WIRE_TYPE}. This ID
* is local to the result where it resides and has no defined meaning across
* multiple invocations. The key is {@link #PROVIDER_BUNDLE_REVISION_ID} and
* the type is an int.
*/
Item PROVIDER_BUNDLE_REVISION_ID_ITEM = new Item(PROVIDER_BUNDLE_REVISION_ID, "A local id for the bundle revision that is the provider of the capability", SimpleType.INTEGER);
/**
* The key of {@link #REQUIRER_BUNDLE_REVISION_ID_ITEM}.
*/
String REQUIRER_BUNDLE_REVISION_ID = "RequirerBundleRevisionId";
/**
* The local ID of a requirer revision in {@link #BUNDLE_WIRE_TYPE}. This ID
* is local to the result where it resides and has no defined meaning across
* multiple invocations. The key is {@link #REQUIRER_BUNDLE_REVISION_ID} and
* the type is an int.
*/
Item REQUIRER_BUNDLE_REVISION_ID_ITEM = new Item(REQUIRER_BUNDLE_REVISION_ID, "A local id for the bundle revision that is the requirer of the requirement", SimpleType.INTEGER);
/**
* The Composite type that represents a bundle wire describing the live
* association between a provider of a capability and a requirer of the
* corresponding requirement.
* <p/>
* The composite consists of:
* <ul>
* <li>{@link #BUNDLE_REQUIREMENT}</li>
* <li>{@link #BUNDLE_CAPABILITY}</li>
* <li>{@link #PROVIDER_BUNDLE_ID}</li>
* <li>{@link #PROVIDER_BUNDLE_REVISION_ID}</li>
* <li>{@link #REQUIRER_BUNDLE_ID}</li>
* <li>{@link #REQUIRER_BUNDLE_REVISION_ID}</li>
* </ul>
*/
CompositeType BUNDLE_WIRE_TYPE = Item.compositeType("BUNDLE_WIRE",
"Describes the live association between a provider and a requirer",
BUNDLE_REQUIREMENT_ITEM,
BUNDLE_CAPABILITY_ITEM,
PROVIDER_BUNDLE_ID_ITEM,
PROVIDER_BUNDLE_REVISION_ID_ITEM,
REQUIRER_BUNDLE_ID_ITEM,
REQUIRER_BUNDLE_REVISION_ID_ITEM);
/**
* An array of {@link #BUNDLE_WIRE_TYPE}s.
*/
ArrayType BUNDLE_WIRES_TYPE_ARRAY = Item.arrayType(1, BUNDLE_WIRE_TYPE);
/**
* The key of {@link #BUNDLE_REVISION_ID_ITEM}.
*/
String BUNDLE_REVISION_ID = "BundleRevisionId";
/**
* The item containing a bundle revision ID. A bundle revision ID is always
* local to the result of a JMX invocation and do not have a defined meaning
* across invocation calls. They are used where a result can potentially
* contain multiple revisions of the same bundle. The key is
* {@link #BUNDLE_REVISION_ID} and the type is an integer.
*/
Item BUNDLE_REVISION_ID_ITEM = new Item(BUNDLE_REVISION_ID, "The local identifier of the bundle revision", SimpleType.INTEGER);
/**
* The key of {@link #BUNDLE_ID_ITEM}.
*/
String BUNDLE_ID = "BundleId";
/**
* The item containing a bundle ID. They key is {@link #BUNDLE_ID} and the
* type is a long.
*/
Item BUNDLE_ID_ITEM = new Item(BUNDLE_ID, "The bundle identifier of the bundle revision", SimpleType.LONG);
/**
* An array of {@link #BUNDLE_REQUIREMENT_TYPE}s.
*/
ArrayType REQUIREMENT_TYPE_ARRAY = Item.arrayType(1, BUNDLE_REQUIREMENT_TYPE);
/**
* An array of {@link #BUNDLE_CAPABILITY_TYPE}s.
*/
ArrayType CAPABILITY_TYPE_ARRAY = Item.arrayType(1, BUNDLE_CAPABILITY_TYPE);
/**
* The key of {@link #REQUIREMENTS_ITEM}.
*/
String REQUIREMENTS = "Requirements";
/**
* The item containing the requirements in
* {@link #REVISION_REQUIREMENTS_TYPE} and {@link #BUNDLE_WIRING_TYPE}. The
* key is {@link #REQUIREMENTS} and the type is
* {@link #REQUIREMENT_TYPE_ARRAY}.
*/
Item REQUIREMENTS_ITEM = new Item(REQUIREMENTS, "The bundle requirements of a bundle revision wiring", REQUIREMENT_TYPE_ARRAY);
/**
* The Composite Type that represents the requirements of a revision. The
* composite consists of:
* <ul>
* <li>{@link #BUNDLE_REVISION_ID}</li>
* <li>{@link #REQUIREMENTS}</li>
* </ul>
*/
CompositeType REVISION_REQUIREMENTS_TYPE = Item.compositeType("REVISION_REQUIREMENTS", "Describes the requirements for a bundle revision", BUNDLE_REVISION_ID_ITEM, REQUIREMENTS_ITEM);
/**
* The Tabular Type that hold the requirements of a revision. The row type
* is {@link #REVISION_REQUIREMENTS_TYPE} and the index is
* {@link #BUNDLE_REVISION_ID}.
*/
TabularType REVISIONS_REQUIREMENTS_TYPE = Item.tabularType("REVISIONS_REQUIREMENTS", "The bundle requirements for all bundle revisions", REVISION_REQUIREMENTS_TYPE, BUNDLE_REVISION_ID);
/**
* The key of {@link #CAPABILITIES_ITEM}.
*/
String CAPABILITIES = "Capabilities";
/**
* The item containing the capabilities in
* {@link #REVISION_CAPABILITIES_TYPE} and {@link #BUNDLE_WIRING_TYPE}. The
* key is {@link #CAPABILITIES} and the type is
* {@link #CAPABILITY_TYPE_ARRAY}.
*/
Item CAPABILITIES_ITEM = new Item(CAPABILITIES, "The bundle capabilities of a bundle revision wiring", CAPABILITY_TYPE_ARRAY);
/**
* The Composite Type that represents the capabilities for a revision. The
* composite consists of:
* <ul>
* <li>{@link #BUNDLE_REVISION_ID}</li>
* <li>{@link #CAPABILITIES}</li>
* </ul>
*/
CompositeType REVISION_CAPABILITIES_TYPE = Item.compositeType("REVISION_CAPABILITIES", "Describes the capabilities for a bundle revision", BUNDLE_REVISION_ID_ITEM, CAPABILITIES_ITEM);
/**
* The Tabular Type that holds the capabilities of a revision. The row type
* is {@link #REVISION_CAPABILITIES_TYPE} and the index is
* {@link #BUNDLE_REVISION_ID}.
*/
TabularType REVISIONS_CAPABILITIES_TYPE = Item.tabularType("REVISIONS_CAPABILITIES", "The bundle capabilities for all bundle revisions", REVISION_CAPABILITIES_TYPE, BUNDLE_REVISION_ID);
/**
* The key of {@link #PROVIDED_WIRES_ITEM}.
*/
String PROVIDED_WIRES = "ProvidedWires";
/**
* The item containing the provided wires in {@link #BUNDLE_WIRING_TYPE}.
* The key is {@link #PROVIDED_WIRES} and the type is
* {@link #BUNDLE_WIRES_TYPE_ARRAY}.
*/
Item PROVIDED_WIRES_ITEM = new Item(PROVIDED_WIRES, "The bundle wires to the capabilities provided by this bundle wiring.", BUNDLE_WIRES_TYPE_ARRAY);
/**
* The key of {@link #REQUIRED_WIRES_ITEM}.
*/
String REQUIRED_WIRES = "RequiredWires";
/**
* The item containing the required wires in {@link #BUNDLE_WIRING_TYPE}.
* The key is {@link #REQUIRED_WIRES} and the type is
* {@link #BUNDLE_WIRES_TYPE_ARRAY}.
*/
Item REQUIRED_WIRES_ITEM = new Item(REQUIRED_WIRES, "The bundle wires to requirements in use by this bundle wiring", BUNDLE_WIRES_TYPE_ARRAY);
/**
* The Composite Type that represents a bundle wiring. The composite
* consists of:
* <ul>
* <li>{@link #BUNDLE_ID}</li>
* <li>{@link #BUNDLE_REVISION_ID}</li>
* <li>{@link #REQUIREMENTS}</li>
* <li>{@link #CAPABILITIES}</li>
* <li>{@link #REQUIRED_WIRES}</li>
* <li>{@link #PROVIDED_WIRES}</li>
* </ul>
*/
CompositeType BUNDLE_WIRING_TYPE = Item.compositeType("BUNDLE_WIRING",
"Describes the runtime association between a provider and a requirer",
BUNDLE_ID_ITEM,
BUNDLE_REVISION_ID_ITEM,
REQUIREMENTS_ITEM,
CAPABILITIES_ITEM,
REQUIRED_WIRES_ITEM,
PROVIDED_WIRES_ITEM);
/**
* The Tabular Type to hold the wiring of a number of bundles. The row type
* is {@link #BUNDLE_WIRING_TYPE} and the index is the combination of the
* {@link #BUNDLE_ID} and the {@link #BUNDLE_REVISION_ID}.
*/
TabularType BUNDLES_WIRING_TYPE = Item.tabularType("BUNDLES_WIRING", "The bundle wiring for all bundle revisions", BUNDLE_WIRING_TYPE, BUNDLE_ID, BUNDLE_REVISION_ID);
/**
* Returns the requirements for the current bundle revision.
*
* @see #REQUIREMENT_TYPE_ARRAY for the details of the CompositeData.
*
* @param bundleId The bundle ID.
* @param namespace The namespace of the requirements to be returned by this
* operation.
* @return the declared requirements for the current revision of
* {@code bundleId} and {@code namespace}.
* @throws JMException if there is a JMX problem.
* @throws IOException if the connection could not be made because of a
* communication problem.
*/
CompositeData[] getCurrentRevisionDeclaredRequirements(long bundleId, String namespace) throws IOException, JMException;
/**
* Returns the capabilities for the current bundle revision.
*
* @see #CAPABILITY_TYPE_ARRAY for the details of the CompositeData.
*
* @param bundleId The bundle ID.
* @param namespace The namespace of the capabilities to be returned by this
* operation.
* @return the declared capabilities for the current revision of
* {@code bundleId} and {@code namespace}.
* @throws JMException if there is a JMX problem.
* @throws IOException if the connection could not be made because of a
* communication problem.
*/
CompositeData[] getCurrentRevisionDeclaredCapabilities(long bundleId, String namespace) throws IOException, JMException;
/**
* Returns the bundle wiring for the current bundle revision.
*
* @see #BUNDLE_WIRING_TYPE for the details of the CompositeData.
*
* @param bundleId The bundle ID.
* @param namespace The namespace of the requirements and capabilities for
* which to return information.
* @return the wiring information for the current revision of
* {@code bundleId} and {@code namespace}.
* @throws JMException if there is a JMX problem.
* @throws IOException if the connection could not be made because of a
* communication problem.
*/
CompositeData getCurrentWiring(long bundleId, String namespace) throws IOException, JMException;
/**
* Returns the bundle wiring closure for the current revision of the
* specified bundle. The wiring closure contains all the wirings from the
* root bundle revision to all bundle revisions it is wired to and all their
* transitive wirings.
*
* @see #BUNDLES_WIRING_TYPE for the details of the TabularData.
*
* @param rootBundleId the root bundle of the closure.
* @param namespace The namespace of the requirements and capabilities for
* which to return information.
* @return a tabular representation of all the wirings in the closure. The
* bundle revision IDs only have meaning in the context of the
* current result. The revision of the rootBundle is set to 0.
* Therefore the root bundle of the closure can be looked up in the
* table by its bundle ID and revision 0.
* @throws JMException if there is a JMX problem.
* @throws IOException if the connection could not be made because of a
* communication problem.
*/
TabularData getCurrentWiringClosure(long rootBundleId, String namespace) throws IOException, JMException;
/**
* Returns the requirements for all revisions of the bundle.
*
* @see #REVISIONS_REQUIREMENTS_TYPE for the details of TabularData.
*
* The requirements are in no particular order, and may change in
* subsequent calls to this operation.
*
* @param bundleId The bundle ID.
* @param namespace The namespace of the requirements to be returned by this
* operation.
* @return the declared requirements for all revisions of {@code bundleId}.
* @throws JMException if there is a JMX problem.
* @throws IOException if the connection could not be made because of a
* communication problem.
*/
TabularData getRevisionsDeclaredRequirements(long bundleId, String namespace) throws IOException, JMException;
/**
* Returns the capabilities for all revisions of the bundle.
*
* @see #REVISIONS_CAPABILITIES_TYPE for the details of TabularData.
*
* The capabilities are in no particular order, and may change in
* subsequent calls to this operation.
*
* @param bundleId The bundle ID.
* @param namespace The namespace of the capabilities to be returned by this
* operation.
* @return the declared capabilities for all revisions of {@code bundleId}
* @throws JMException if there is a JMX problem.
* @throws IOException if the connection could not be made because of a
* communication problem.
*/
TabularData getRevisionsDeclaredCapabilities(long bundleId, String namespace) throws IOException, JMException;
/**
* Returns the bundle wirings for all revisions of the bundle.
*
* @see #BUNDLES_WIRING_TYPE for the details of TabularData.
*
* The bundle wirings are in no particular order, and may change in
* subsequent calls to this operations.
*
* @param bundleId The bundle ID.
* @param namespace The namespace of the requirements and capabilities for
* which to return information.
* @return the wiring information for all revisions of {@code bundleId} and
* {@code namespace}.
* @throws JMException if there is a JMX problem.
* @throws IOException if the connection could not be made because of a
* communication problem.
*/
TabularData getRevisionsWiring(long bundleId, String namespace) throws IOException, JMException;
/**
* Returns the bundle wiring closure for all revisions of the specified
* bundle. The wiring closure contains all the wirings from the root bundle
* revision to all bundle revisions it is wired to and all their transitive
* wirings.
*
* @see #BUNDLES_WIRING_TYPE for the details of TabularData.
*
* The bundle wirings are in no particular order, and may change in
* subsequent calls to this operation. Furthermore, the bundle revision
* IDs are local and cannot be reused across invocations.
*
* @param rootBundleId The root bundle ID.
* @param namespace The namespace of the requirements and capabilities for
* which to return information.
* @return a tabular representation of all the wirings in the closure. The
* bundle revision IDs only have meaning in the context of the
* current result.
* @throws JMException if there is a JMX problem.
* @throws IOException if the connection could not be made because of a
* communication problem.
*/
TabularData getRevisionsWiringClosure(long rootBundleId, String namespace) throws IOException, JMException;
}
| 8,038 |
0 | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/service | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/service/useradmin/UserAdminMBean.java | /*
* Copyright (c) OSGi Alliance (2009, 2012). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.jmx.service.useradmin;
import java.io.IOException;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import org.osgi.jmx.Item;
import org.osgi.jmx.JmxConstants;
/**
* This MBean provides the management interface to the OSGi User Manager Service
*
* @version $Id: 08b1bb0c33e5266fe66917197cf52c8f157a0843 $
* @ThreadSafe
*/
public interface UserAdminMBean {
/**
* User Admin MBean object name.
*/
String OBJECTNAME = JmxConstants.OSGI_COMPENDIUM + ":service=useradmin,version=1.1";
/**
* The key NAME, used in {@link #NAME_ITEM}.
*/
String NAME = "Name";
/**
* The item for the user name for an authorization object. The key is
* {@link #NAME} and the type is {@link SimpleType#STRING}.
*/
Item NAME_ITEM = new Item(NAME, "The user name for this authorization object", SimpleType.STRING);
/**
* The key ROLES, used in {@link #ROLES_ITEM}.
*/
String ROLES = "Roles";
/**
* The item containing the roles for this authorization object. The key is
* {@link #ROLES}. and the type is {@link JmxConstants#STRING_ARRAY_TYPE}.
*/
Item ROLES_ITEM = new Item(ROLES, "The names of the roles encapsulated by this auth object", JmxConstants.STRING_ARRAY_TYPE);
/**
* The Composite Type for an Authorization object. It consists of the
* {@link #NAME_ITEM} and {@link #ROLES_ITEM} items.
*/
CompositeType AUTORIZATION_TYPE = Item.compositeType("AUTHORIZATION", "An authorization object defines which roles has a user got", NAME_ITEM, ROLES_ITEM);
/**
* The Role TYPE key, used in {@link #TYPE_ITEM}.
*/
String TYPE = "Type";
/**
* The item containing the type of the roles encapsulated by this
* authorization object. The key is {@link #TYPE} and the type is
* {@link SimpleType#INTEGER}.
*/
Item TYPE_ITEM = new Item(TYPE, "An integer representing type of the role: {0=Role,1=user,2=group}", SimpleType.INTEGER);
/**
* The PROPERTIES key, used in {@link #PROPERTIES_ITEM}.
*/
String PROPERTIES = "Properties";
/**
* The item containing the properties of a Role. The key is
* {@link #PROPERTIES} and the type is {@link JmxConstants#PROPERTIES_TYPE}.
*/
Item PROPERTIES_ITEM = new Item(PROPERTIES, "A properties as defined by org.osgi.service.useradmin.Role", JmxConstants.PROPERTIES_TYPE);
/**
* The Composite Type for a Role. It contains the following items:
* <ul>
* <li>{@link #NAME}</li>
* <li>{@link #TYPE}</li>
* <li>{@link #PROPERTIES}</li>
* </ul>
*
*/
CompositeType ROLE_TYPE = Item.compositeType("ROLE", "Mapping of org.osgi.service.useradmin.Role for remote management purposes. User and Group extend Role", NAME_ITEM, TYPE_ITEM);
/**
* The CREDENTIALS key, used in {@link #CREDENTIALS_ITEM}.
*/
String CREDENTIALS = "Credentials";
/**
* The item containing the credentials of a user. The key is
* {@link #CREDENTIALS} and the type is {@link JmxConstants#PROPERTIES_TYPE}
* .
*/
Item CREDENTIALS_ITEM = new Item(CREDENTIALS, "The credentials for this user", JmxConstants.PROPERTIES_TYPE);
/**
* A Composite Type for a User. A User contains its Role description and
* adds the credentials. It extends {@link #ROLE_TYPE} and adds
* {@link #CREDENTIALS_ITEM}.
*
* This type extends the {@link #ROLE_TYPE}. It adds:
* <ul>
* <li>{@link #CREDENTIALS}</li>
* </ul>
*/
CompositeType USER_TYPE = Item.extend(ROLE_TYPE, "USER", "Mapping of org.osgi.service.useradmin.User for remote management purposes. User extends Role");
/**
* The MEMBERS key, used in {@link #MEMBERS_ITEM}.
*/
String MEMBERS = "Members";
/**
* The item containing the members of a group. The key is {@link #MEMBERS}
* and the type is {@link JmxConstants#STRING_ARRAY_TYPE}. It is used in
* {@link #GROUP_TYPE}.
*/
Item MEMBERS_ITEM = new Item(MEMBERS, "The members of this group", JmxConstants.STRING_ARRAY_TYPE);
/**
* The REQUIRED_MEMBERS key, used in {@link #REQUIRED_MEMBERS_ITEM}.
*/
String REQUIRED_MEMBERS = "RequiredMembers";
/**
* The item containing the required members of a group. The key is
* {@link #REQUIRED_MEMBERS} and the type is
* {@link JmxConstants#STRING_ARRAY_TYPE}. It is used in {@link #GROUP_TYPE}
* .
*/
Item REQUIRED_MEMBERS_ITEM = new Item(REQUIRED_MEMBERS, "The required members of this group", JmxConstants.STRING_ARRAY_TYPE);
/**
* The Composite Type for a Group. It extends {@link #USER_TYPE} and adds
* {@link #MEMBERS_ITEM}, and {@link #REQUIRED_MEMBERS_ITEM}.
*
* This type extends the {@link #USER_TYPE}. It adds:
* <ul>
* <li>{@link #MEMBERS}</li>
* <li>{@link #REQUIRED_MEMBERS}</li>
* </ul>
* If there are no members or required members an empty array is returned in
* the respective items.
*/
CompositeType GROUP_TYPE = Item.extend(USER_TYPE,
"GROUP",
"Mapping of org.osgi.service.useradmin.Group for remote management purposes. Group extends User which in turn extends Role",
MEMBERS_ITEM,
REQUIRED_MEMBERS_ITEM);
/**
* Add credentials to a user, associated with the supplied key
*
* @param key The key of the credential to add
* @param value The value of the credential to add
* @param username The name of the user that gets the credential.
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the username is not a User
*/
void addCredential(String key, byte[] value, String username) throws IOException;
/**
* Add credentials to a user, associated with the supplied key
*
* @param key The key of the credential to add
* @param value The value of the credential to add
* @param username The name of the user that gets the credential.
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the username is not a User
*/
void addCredentialString(String key, String value, String username) throws IOException;
/**
* Add a member to the group.
*
* @param groupname The group name that receives the {@code rolename} as
* member.
* @param rolename The {@code rolename} (User or Group) that must be added.
* @return {@code true} if the role was added to the group
* @throws IOException if the operation fails
* @throws IllegalArgumentException if an invalid group name or role name is
* specified
*
*/
boolean addMember(String groupname, String rolename) throws IOException;
/**
* Add or update a property on a role
*
* @param key The key of the property to add
* @param value The value of the property to add ({@code String})
* @param rolename The role name
* @throws IOException if the operation fails
* @throws IllegalArgumentException if an invalid role name is specified
*/
void addPropertyString(String key, String value, String rolename) throws IOException;
/**
* Add or update a property on a role.
*
* @param key The added property key
* @param value The added byte[] property value
* @param rolename The role name that receives the property
* @throws IOException if the operation fails
* @throws IllegalArgumentException if an invalid role name is specified
*/
void addProperty(String key, byte[] value, String rolename) throws IOException;
/**
* Add a required member to the group
*
* @param groupname The group name that is addded
* @param rolename The role that
* @return true if the role was added to the group
* @throws IOException if the operation fails
* @throws IllegalArgumentException if an invalid group name or role name is
* specified
*/
boolean addRequiredMember(String groupname, String rolename) throws IOException;
/**
* Create a User
*
* @param name Name of the user to create
* @throws IOException if the operation fails
*/
void createUser(String name) throws IOException;
/**
* Create a Group
*
* @param name Name of the group to create
* @throws IOException if the operation fails
*/
void createGroup(String name) throws IOException;
/**
* This method was specified in error and must not be used.
*
* @param name Ignored.
* @throws IOException This method will throw an exception if called.
* @deprecated This method was specified in error. It does not function and
* must not be used. Use either {@link #createUser(String)} or
* {@link #createGroup(String)}.
*/
void createRole(String name) throws IOException;
/**
* Answer the authorization for the user name.
*
* The Composite Data is typed by {@link #AUTORIZATION_TYPE}.
*
* @param user The user name
* @return the Authorization typed by {@link #AUTORIZATION_TYPE}.
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the user name is not a User
*/
CompositeData getAuthorization(String user) throws IOException;
/**
* Answer the credentials associated with a user.
*
* The returned Tabular Data is typed by
* {@link JmxConstants#PROPERTIES_TYPE}.
*
* @param username The user name
* @return the credentials associated with the user, see
* {@link JmxConstants#PROPERTIES_TYPE}
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the user name is not a User
*/
TabularData getCredentials(String username) throws IOException;
/**
* Answer the Group associated with the group name.
*
* The returned Composite Data is typed by {@link #GROUP_TYPE}
*
* @param groupname The group name
* @return the Group, see {@link #GROUP_TYPE}
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the group name is not a Group
*/
CompositeData getGroup(String groupname) throws IOException;
/**
* Answer the list of group names
*
* @return The list of group names
* @throws IOException if the operation fails
*/
String[] listGroups() throws IOException;
/**
* Answer the list of group names
*
* @param filter The filter to apply
* @return The list of group names
* @throws IOException if the operation fails
*/
String[] getGroups(String filter) throws IOException;
/**
* Answer the list of implied roles for a user
*
* @param username The name of the user that has the implied roles
* @return The list of role names
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the username is not a User
*/
String[] getImpliedRoles(String username) throws IOException;
/**
* Answer the the user names which are members of the group
*
* @param groupname The name of the group to get the members from
* @return The list of user names
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the groupname is not a Group
*/
String[] getMembers(String groupname) throws IOException;
/**
* Answer the properties associated with a role.
*
* The returned Tabular Data is typed by
* {@link JmxConstants#PROPERTIES_TYPE}.
*
* @param rolename The name of the role to get properties from
* @return the properties associated with the role, see
* {@link JmxConstants#PROPERTIES_TYPE}
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the rolename is not a role
*/
TabularData getProperties(String rolename) throws IOException;
/**
* Answer the list of user names which are required members of this group
*
* @param groupname The name of the group to get the required members from
* @return The list of user names
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the group name is not a Group
*/
String[] getRequiredMembers(String groupname) throws IOException;
/**
* Answer the role associated with a name.
*
* The returned Composite Data is typed by {@link #ROLE_TYPE}.
*
* @param name The name of the role to get the data from
* @return the Role, see {@link #ROLE_TYPE}
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the name is not a role
*/
CompositeData getRole(String name) throws IOException;
/**
* Answer the list of role names in the User Admin database
*
* @return The list of role names
* @throws IOException if the operation fails
*/
String[] listRoles() throws IOException;
/**
* Answer the list of role names which match the supplied filter
*
* @param filter The string representation of the
* {@code org.osgi.framework.Filter} that is used to filter the roles
* by applying to the properties, if {@code null} all roles are
* returned.
*
* @return The list the role names
* @throws IOException if the operation fails
*/
String[] getRoles(String filter) throws IOException;
/**
* Answer the User associated with the user name.
*
* The returned Composite Data is typed by {@link #USER_TYPE}.
*
* @param username The name of the requested user
* @return The User, see {@link #USER_TYPE}
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the username is not a User
*/
CompositeData getUser(String username) throws IOException;
/**
* Answer the user name with the given property key-value pair from the User
* Admin service database.
*
* @param key The key to compare
* @param value The value to compare
* @return The User
* @throws IOException if the operation fails
*/
String getUserWithProperty(String key, String value) throws IOException;
/**
* Answer the list of user names in the User Admin database
*
* @return The list of user names
* @throws IOException if the operation fails
*/
String[] listUsers() throws IOException;
/**
* Answer the list of user names in the User Admin database
*
* @param filter The filter to apply
* @return The list of user names
* @throws IOException if the operation fails
*/
String[] getUsers(String filter) throws IOException;
/**
* Remove the credential associated with the given user
*
* @param key The key of the credential to remove
* @param username The name of the user for which the credential must be
* removed
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the username is not a User
*/
void removeCredential(String key, String username) throws IOException;
/**
* Remove a role from the group
*
* @param groupname The group name
* @param rolename
* @return true if the role was removed from the group
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the groupname is not a Group
*/
boolean removeMember(String groupname, String rolename) throws IOException;
/**
* Remove a property from a role
*
* @param key
* @param rolename
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the rolename is not a role
*/
void removeProperty(String key, String rolename) throws IOException;
/**
* Remove the Role associated with the name
*
* @param name
* @return true if the remove succeeded
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the name is not a role
*/
boolean removeRole(String name) throws IOException;
/**
* Remove the Group associated with the name
*
* @param name
* @return true if the remove succeeded
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the name is not a Group
*/
boolean removeGroup(String name) throws IOException;
/**
* Remove the User associated with the name
*
* @param name
* @return true if the remove succeeded
* @throws IOException if the operation fails
* @throws IllegalArgumentException if the name is not a User
*/
boolean removeUser(String name) throws IOException;
}
| 8,039 |
0 | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/service | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/service/provisioning/ProvisioningServiceMBean.java | /*
* Copyright (c) OSGi Alliance (2009, 2010). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.jmx.service.provisioning;
import java.io.IOException;
import javax.management.openmbean.TabularData;
import org.osgi.jmx.JmxConstants;
/**
* This MBean represents the management interface to the OSGi Initial
* Provisioning Service
*
* @version $Revision$
* @ThreadSafe
*/
public interface ProvisioningServiceMBean {
/**
* Provisioning MBean object name.
*/
String OBJECTNAME = JmxConstants.OSGI_COMPENDIUM
+ ":service=provisioning,version=1.2";
/**
* Processes the <code>ZipInputStream</code> contents of the provided
* zipURL and extracts information to add to the Provisioning Information
* dictionary, as well as, install/update and start bundles. This method
* causes the <code>PROVISIONING_UPDATE_COUNT</code> to be incremented.
*
* @param zipURL the String form of the URL that will be resolved into a
* <code>ZipInputStream</code> which will be used to add key/value
* pairs to the Provisioning Information dictionary and install and
* start bundles. If a <code>ZipEntry</code> does not have an
* <code>Extra</code> field that corresponds to one of the four
* defined MIME types (<code>MIME_STRING</code>,
* <code>MIME_BYTE_ARRAY</code>,<code>MIME_BUNDLE</code>, and
* <code>MIME_BUNDLE_URL</code>) in will be silently ignored.
* @throws IOException if an error occurs while processing the
* ZipInputStream of the URL. No additions will be made to the
* Provisioning Information dictionary and no bundles must be
* started or installed.
*/
public void addInformationFromZip(String zipURL) throws IOException;
/**
* Adds the key/value pairs contained in <code>info</code> to the
* Provisioning Information dictionary. This method causes the
* <code>PROVISIONING_UPDATE_COUNT</code> to be incremented.
*
* @see JmxConstants#PROPERTIES_TYPE for details of the Tabular Data
*
* @param info the set of Provisioning Information key/value pairs to add to
* the Provisioning Information dictionary. Any keys are values that
* are of an invalid type will be silently ignored.
* @throws IOException if the operation fails
*/
public void addInformation(TabularData info) throws IOException;
/**
* Returns a table representing the Provisioning Information Dictionary.
*
* @see JmxConstants#PROPERTIES_TYPE for details of the Tabular Data
*
* @throws IOException if the operation fails
* @return The table representing the manager dictionary.
*/
public TabularData listInformation() throws IOException;
/**
* Replaces the Provisioning Information dictionary with the entries of the
* supplied table. This method causes the
* <code>PROVISIONING_UPDATE_COUNT</code> to be incremented.
*
* @see JmxConstants#PROPERTIES_TYPE for details of the Tabular Data
*
* @param info the new set of Provisioning Information key/value pairs. Any
* keys are values that are of an invalid type will be silently
* ignored.
* @throws IOException if the operation fails
*/
public void setInformation(TabularData info) throws IOException;
}
| 8,040 |
0 | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/service | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/service/permissionadmin/PermissionAdminMBean.java | /*
* Copyright (c) OSGi Alliance (2009). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.jmx.service.permissionadmin;
import java.io.IOException;
import org.osgi.jmx.JmxConstants;
/**
* This MBean represents the OSGi Permission Manager Service
*
* @version $Rev$
*/
public interface PermissionAdminMBean {
/**
* Permission Admin MBean object name.
*/
String OBJECTNAME = JmxConstants.OSGI_CORE
+ ":service=permissionadmin,version=1.2";
/**
* Answer the bundle locations that have permissions assigned to them
*
* @return the bundle locations
* @throws IOException if the operation fails
*/
String[] listLocations() throws IOException;
/**
* Answer the list of encoded permissions of the bundle specified by the
* bundle location
*
* @param location location identifying the bundle
* @return the array of String encoded permissions
* @throws IOException if the operation fails
*/
String[] getPermissions(String location) throws IOException;
/**
* Set the default permissions assigned to bundle locations that have no
* assigned permissions
*
* @param encodedPermissions the string encoded permissions
* @throws IOException if the operation fails
*/
void setDefaultPermissions(String[] encodedPermissions) throws IOException;
/**
* Answer the list of encoded permissions representing the default
* permissions assigned to bundle locations that have no assigned
* permissions
*
* @return the array of String encoded permissions
* @throws IOException if the operation fails
*/
String[] listDefaultPermissions() throws IOException;
/**
* Set the permissions on the bundle specified by the bundle location
*
* @param location the location of the bundle
* @param encodedPermissions the string encoded permissions to set
* @throws IOException if the operation fails
*/
void setPermissions(String location, String[] encodedPermissions)
throws IOException;
}
| 8,041 |
0 | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/service | Create_ds/aries/jmx/jmx-api/src/main/java/org/osgi/jmx/service/cm/ConfigurationAdminMBean.java | /*
* Copyright (c) OSGi Alliance (2009, 2010). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.jmx.service.cm;
import java.io.IOException;
import javax.management.openmbean.TabularData;
import org.osgi.jmx.JmxConstants;
/**
* This MBean provides the management interface to the OSGi Configuration
* Administration Service.
*
* @version $Revision$
* @ThreadSafe
*/
public interface ConfigurationAdminMBean {
/**
* The object name for this mbean.
*/
String OBJECTNAME = JmxConstants.OSGI_COMPENDIUM+":service=cm,version=1.3";
/**
* Create a new configuration instance for the supplied persistent id of the
* factory, answering the PID of the created configuration
*
* @param factoryPid the persistent id of the factory
* @return the PID of the created configuration
* @throws IOException if the operation failed
*/
String createFactoryConfiguration(String factoryPid) throws IOException;
/**
* Create a factory configuration for the supplied persistent id of the
* factory and the bundle location bound to bind the created configuration
* to, answering the PID of the created configuration
*
* @param factoryPid the persistent id of the factory
* @param location the bundle location
* @return the pid of the created configuation
* @throws IOException if the operation failed
*/
String createFactoryConfigurationForLocation(String factoryPid, String location)
throws IOException;
/**
* Delete the configuration
*
* @param pid the persistent identifier of the configuration
* @throws IOException if the operation fails
*/
void delete(String pid) throws IOException;
/**
* Delete the configuration
*
* @param pid the persistent identifier of the configuration
* @param location the bundle location
* @throws IOException if the operation fails
*/
void deleteForLocation(String pid, String location) throws IOException;
/**
* Delete the configurations matching the filter specification.
*
* @param filter the string representation of the
* <code>org.osgi.framework.Filter</code>
* @throws IOException if the operation failed
* @throws IllegalArgumentException if the filter is invalid
*/
void deleteConfigurations(String filter) throws IOException;
/**
* Answer the bundle location the configuration is bound to
*
* @param pid the persistent identifier of the configuration
* @return the bundle location
* @throws IOException if the operation fails
*/
String getBundleLocation(String pid) throws IOException;
/**
* Answer the factory PID if the configuration is a factory configuration,
* null otherwise.
*
* @param pid the persistent identifier of the configuration
* @return the factory PID
* @throws IOException if the operation fails
*/
String getFactoryPid(String pid) throws IOException;
/**
* Answer the factory PID if the configuration is a factory configuration,
* null otherwise.
*
* @param pid the persistent identifier of the configuration
* @param location the bundle location
* @return the factory PID
* @throws IOException if the operation fails
*/
String getFactoryPidForLocation(String pid, String location) throws IOException;
/**
* Answer the contents of the configuration <p/>
*
* @see JmxConstants#PROPERTIES_TYPE for the details of the TabularType
*
* @param pid the persistent identifier of the configuration
* @return the table of contents
* @throws IOException if the operation fails
*/
TabularData getProperties(String pid) throws IOException;
/**
* Answer the contents of the configuration <p/>
*
* @see JmxConstants#PROPERTIES_TYPE for the details of the TabularType
*
* @param pid the persistent identifier of the configuration
* @param location the bundle location
* @return the table of contents
* @throws IOException if the operation fails
*/
TabularData getPropertiesForLocation(String pid, String location) throws IOException;
/**
* Answer the list of PID/Location pairs of the configurations managed by
* this service
*
* @param filter the string representation of the
* <code>org.osgi.framework.Filter</code>
* @return the list of configuration PID/Location pairs
* @throws IOException if the operation failed
* @throws IllegalArgumentException if the filter is invalid
*/
String[][] getConfigurations(String filter) throws IOException;
/**
* Set the bundle location the configuration is bound to
*
* @param pid the persistent identifier of the configuration
* @param location the bundle location
* @throws IOException if the operation fails
*/
void setBundleLocation(String pid, String location) throws IOException;
/**
* Update the configuration with the supplied properties For each property
* entry, the following row is supplied <p/>
*
* @see JmxConstants#PROPERTIES_TYPE for the details of the TabularType
*
* @param pid the persistent identifier of the configuration
* @param properties the table of properties
* @throws IOException if the operation fails
*/
void update(String pid, TabularData properties) throws IOException;
/**
* Update the configuration with the supplied properties For each property
* entry, the following row is supplied <p/>
*
* @see JmxConstants#PROPERTIES_TYPE for the details of the TabularType
*
* @param pid the persistent identifier of the configuration
* @param location the bundle location
* @param properties the table of properties
* @throws IOException if the operation fails
*/
void updateForLocation(String pid, String location, TabularData properties)
throws IOException;
} | 8,042 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/test/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/test/java/org/apache/aries/jmx/blueprint/impl/BlueprintStateTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.impl;
import org.apache.aries.jmx.blueprint.BlueprintStateMBean;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.osgi.framework.BundleContext;
//@RunWith(JMock.class)
public class BlueprintStateTest {
// private Mockery mockery = new JUnit4Mockery();
// private BlueprintState state;
//
// private BundleContext mockContext;
//
// @Before
// public void setUp() throws Exception {
// mockContext = mockery.mock(BundleContext.class);
//
// state = new BlueprintState(mockContext);
// }
@Test
public void testGetBlueprintBundleIds(){
}
@Test
public void testGetLastEvent(){
}
@Test
public void testGetLastEvents(){
}
}
| 8,043 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/test/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/test/java/org/apache/aries/jmx/blueprint/impl/BlueprintMetadataTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.impl;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
@RunWith(JMock.class)
public class BlueprintMetadataTest {
private BlueprintMetadata metadata;
private Mockery mockery = new JUnit4Mockery();
private BundleContext mockContext;
private Bundle mockBundle;
private ServiceReference[] mockServiceReferences = new ServiceReference[1];
//private ServiceReference mockServiceReference;
private BlueprintContainer mockContainer;
private ServiceMetadata mockServiceMetadata;
private BeanMetadata mockBeanMetadata;
@Before
public void setUp() throws Exception {
mockContext = mockery.mock(BundleContext.class);
mockBundle = mockery.mock(Bundle.class);
mockServiceReferences[0] = mockery.mock(ServiceReference.class);
mockContainer = mockery.mock(BlueprintContainer.class);
mockServiceMetadata = mockery.mock(ServiceMetadata.class);
mockBeanMetadata = mockery.mock(BeanMetadata.class);
metadata = new BlueprintMetadata(mockContext);
}
@After
public void tearDown() throws Exception {
}
@Test
public void validGetBlueprintContainerServiceId() throws Exception {
final long bundleId = 12;
final long serviceId = 7117;
mockery.checking(new Expectations() {
{
allowing(mockContext).getBundle(bundleId);
will(returnValue(mockBundle));
oneOf(mockContext).getServiceReferences(with(any(String.class)), with(any(String.class)));
will(returnValue(mockServiceReferences));
}
});
// is there any need?
mockery.checking(new Expectations() {
{
allowing(mockBundle).getSymbolicName();
will(returnValue("org.apache.geronimo.blueprint.testXXX"));
allowing(mockBundle).getVersion();
will(returnValue(Version.emptyVersion));
}
});
mockery.checking(new Expectations() {
{
allowing(mockServiceReferences[0]).getProperty(Constants.SERVICE_ID);
will(returnValue(serviceId));
}
});
assertEquals(serviceId, metadata.getBlueprintContainerServiceId(bundleId));
}
@Test
public void invalidParaInGetBlueprintContainerServiceId() throws Exception
{
mockery.checking(new Expectations() {
{
allowing(mockContext).getBundle(with(any(Long.class)));
will(returnValue(null));
}
});
try{
metadata.getBlueprintContainerServiceId(-10);
} catch(Exception ex)
{
assertTrue(ex instanceof IllegalArgumentException);
}
}
@Test
public void cannotFindAssociatedContainerServiceId() throws Exception
{
final long bundleId = 12;
mockery.checking(new Expectations() {
{
allowing(mockContext).getBundle(bundleId);
will(returnValue(mockBundle));
oneOf(mockContext).getServiceReferences(with(any(String.class)), with(any(String.class)));
//return null if no services are registered which satisfy the search
will(returnValue(null));
}
});
// is there any need?
mockery.checking(new Expectations() {
{
allowing(mockBundle).getSymbolicName();
will(returnValue("org.apache.geronimo.blueprint.testXXX"));
allowing(mockBundle).getVersion();
will(returnValue(Version.emptyVersion));
}
});
assertEquals(-1, metadata.getBlueprintContainerServiceId(bundleId));
}
@Test
public void normalBlueprintContainerServiceIds() throws Exception {
final long serviceId = 7117;
final long [] serviceIds = new long[]{serviceId};
mockery.checking(new Expectations() {
{
oneOf(mockContext).getServiceReferences(with(any(String.class)), with(any(String.class)));
will(returnValue(mockServiceReferences));
}
});
mockery.checking(new Expectations() {
{
allowing(mockServiceReferences[0]).getProperty(Constants.SERVICE_ID);
will(returnValue(serviceId));
}
});
assertArrayEquals(serviceIds, metadata.getBlueprintContainerServiceIds());
}
@Test
public void noBlueprintContainerServiceIds() throws Exception
{//It is impossible according to osgi spec, here just test the robustness of code
mockery.checking(new Expectations() {
{
oneOf(mockContext).getServiceReferences(with(any(String.class)), with(any(String.class)));
//return null if no services are registered which satisfy the search
will(returnValue(null));
}
});
assertNull(metadata.getBlueprintContainerServiceIds());
}
@Test
public void nomalGetComponentIds() throws Exception {
final long serviceId = 7117;
final Set cidset = getAsSet(new String[]{".component-1", ".component-2", ".component-5"});
mockery.checking(new Expectations(){
{
oneOf(mockContext).getServiceReferences(with(any(String.class)), with(any(String.class)));
will(returnValue(mockServiceReferences));
oneOf(mockContext).getService(mockServiceReferences[0]);
will(returnValue(mockContainer));
}
});
mockery.checking(new Expectations(){
{
oneOf(mockContainer).getComponentIds();
will(returnValue(cidset));
}
});
assertEquals(cidset, getAsSet(metadata.getComponentIds(serviceId)));
}
@Test
public void normalGetComponentIdsByType() throws Exception {
final long serviceId = 7117;
final String [] cidarray = new String[]{".component-1"};
final Collection cMetadatas = new ArrayList();
cMetadatas.add(mockServiceMetadata);
mockery.checking(new Expectations(){
{
oneOf(mockContext).getServiceReferences(with(any(String.class)), with(any(String.class)));
will(returnValue(mockServiceReferences));
oneOf(mockContext).getService(mockServiceReferences[0]);
will(returnValue(mockContainer));
}
});
mockery.checking(new Expectations(){
{
oneOf(mockContainer).getMetadata(ServiceMetadata.class);
will(returnValue(cMetadatas));
}
});
mockery.checking(new Expectations(){
{
oneOf(mockServiceMetadata).getId();
will(returnValue(cidarray[0]));
}
});
assertArrayEquals(cidarray,
metadata.getComponentIdsByType(serviceId, BlueprintMetadataMBean.SERVICE_METADATA));
}
public void invalidParaInGetComponentIdsByType() throws Exception {
final long serviceId = 7117;
mockery.checking(new Expectations(){
{
allowing(mockContext).getServiceReferences(with(any(String.class)), with(any(String.class)));
will(returnValue(mockServiceReferences));
allowing(mockContext).getService(mockServiceReferences[0]);
will(returnValue(mockContainer));
}
});
try {
metadata.getComponentIdsByType(serviceId, null);
}catch(Exception ex)
{
assertTrue(ex instanceof IllegalArgumentException);
}
try {
metadata.getComponentIdsByType(serviceId, BlueprintMetadataMBean.COMPONENT_METADATA);
}catch(Exception ex)
{
assertTrue(ex instanceof IllegalArgumentException);
}
}
@Test
public void testGetComponentMetadata() throws Exception {
final long serviceId = 7117;
final String componentId = ".component-1";
final String [] cidarray = new String[]{componentId};
final List emptyList = new ArrayList();
mockery.checking(new Expectations(){
{
oneOf(mockContext).getServiceReferences(with(any(String.class)), with(any(String.class)));
will(returnValue(mockServiceReferences));
oneOf(mockContext).getService(mockServiceReferences[0]);
will(returnValue(mockContainer));
}
});
mockery.checking(new Expectations(){
{
oneOf(mockContainer).getComponentMetadata(componentId);
will(returnValue(mockBeanMetadata));
}
});
mockery.checking(new Expectations(){
{
allowing(mockBeanMetadata).getDependsOn();
will(returnValue(emptyList));
allowing(mockBeanMetadata).getArguments();
will(returnValue(emptyList));
allowing(mockBeanMetadata).getFactoryComponent();
will(returnValue(null));
allowing(mockBeanMetadata).getProperties();
will(returnValue(emptyList));
ignoring(mockBeanMetadata);
}
});
metadata.getComponentMetadata(serviceId, componentId);
mockery.assertIsSatisfied();
}
@Test
public void fail2GetBlueprintContainer() throws Exception
{
final long serviceId = 7117;
mockery.checking(new Expectations(){
{
exactly(3).of(mockContext).getServiceReferences(with(any(String.class)), with(any(String.class)));
will(returnValue(null));
}
});
try{
metadata.getComponentIds(serviceId);
}catch(Exception ex)
{
assertTrue(ex instanceof IOException);
}
try{
metadata.getComponentIdsByType(serviceId, BlueprintMetadataMBean.SERVICE_METADATA);
}catch(Exception ex)
{
assertTrue(ex instanceof IOException);
}
try{
metadata.getComponentMetadata(serviceId, "xxxx");
}catch(Exception ex)
{
assertTrue(ex instanceof IOException);
}
}
private Set getAsSet(String[] data) {
Set dataSet = new HashSet();
dataSet.addAll(Arrays.asList(data));
return dataSet;
}
}
| 8,044 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/impl/Activator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.impl;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.apache.aries.jmx.blueprint.BlueprintStateMBean;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Activator implements BundleActivator {
private static final Logger LOGGER = LoggerFactory.getLogger("org.apache.aries.jmx.blueprint");
protected BundleContext bundleContext;
protected ObjectName blueprintStateName;
protected ObjectName blueprintMetadataName;
protected ServiceTracker mbeanServiceTracker;
public void start(BundleContext context) throws Exception {
this.bundleContext = context;
this.blueprintStateName = new ObjectName(BlueprintStateMBean.OBJECTNAME);
this.blueprintMetadataName = new ObjectName(BlueprintMetadataMBean.OBJECTNAME);
// create MBeanServerServiceTracker
// if there has been already a MBeanServer Service in place, this MBeanServerServiceTracker won't miss it
mbeanServiceTracker = new ServiceTracker(bundleContext, MBeanServer.class.getCanonicalName(),
new MBeanServerServiceTracker());
LOGGER.debug("Awaiting MBeanServer service registration");
mbeanServiceTracker.open();
}
public void stop(BundleContext context) throws Exception {
mbeanServiceTracker.close();
}
class MBeanServerServiceTracker implements ServiceTrackerCustomizer {
public Object addingService(ServiceReference servicereference) {
try {
LOGGER.debug("Adding MBeanServer: {}", servicereference);
final MBeanServer mbeanServer = (MBeanServer) bundleContext.getService(servicereference);
if (mbeanServer != null) {
Activator.this.registerMBeans(mbeanServer);
}
return mbeanServer;
} catch (RuntimeException e) {
LOGGER.error("uncaught exception in addingService", e);
throw e;
}
}
public void removedService(ServiceReference servicereference, Object obj) {
try {
LOGGER.debug("Removing MBeanServer: {}", servicereference);
Activator.this.deregisterMBeans((MBeanServer) obj);
} catch (Throwable e) {
LOGGER.debug("uncaught exception in removedService", e);
}
}
public void modifiedService(ServiceReference servicereference, Object obj) {
// no op
}
}
protected void registerMBeans(MBeanServer mbeanServer) {
// register BlueprintStateMBean to MBean server
LOGGER.debug("Registering bundle state monitor with MBeanServer: {} with name: {}",
mbeanServer, blueprintStateName);
try {
StandardMBean blueprintState = new RegistrableStandardEmitterMBean(new BlueprintState(bundleContext), BlueprintStateMBean.class);
mbeanServer.registerMBean(blueprintState, blueprintStateName);
} catch (InstanceAlreadyExistsException e) {
LOGGER.debug("Cannot register BlueprintStateMBean");
} catch (MBeanRegistrationException e) {
LOGGER.error("Cannot register BlueprintStateMBean", e);
} catch (NotCompliantMBeanException e) {
LOGGER.error("Cannot register BlueprintStateMBean", e);
}
// register BlueprintMetadataMBean to MBean server
LOGGER.debug("Registering bundle metadata monitor with MBeanServer: {} with name: {}",
mbeanServer, blueprintMetadataName);
try {
StandardMBean blueprintMetadata = new StandardMBean(new BlueprintMetadata(bundleContext), BlueprintMetadataMBean.class);
mbeanServer.registerMBean(blueprintMetadata, blueprintMetadataName);
} catch (InstanceAlreadyExistsException e) {
LOGGER.debug("Cannot register BlueprintMetadataMBean");
} catch (MBeanRegistrationException e) {
LOGGER.error("Cannot register BlueprintMetadataMBean", e);
} catch (NotCompliantMBeanException e) {
LOGGER.error("Cannot register BlueprintMetadataMBean", e);
}
}
protected void deregisterMBeans(MBeanServer mbeanServer) {
// unregister BlueprintStateMBean from MBean server
try {
mbeanServer.unregisterMBean(blueprintStateName);
} catch (InstanceNotFoundException e) {
LOGGER.debug("BlueprintStateMBean not found on deregistration");
} catch (MBeanRegistrationException e) {
LOGGER.error("BlueprintStateMBean deregistration problem");
}
// unregister BlueprintMetadataMBean from MBean server
try {
mbeanServer.unregisterMBean(blueprintMetadataName);
} catch (InstanceNotFoundException e) {
LOGGER.debug("BlueprintMetadataMBean not found on deregistration");
} catch (MBeanRegistrationException e) {
LOGGER.error("BlueprintMetadataMBean deregistration problem");
}
}
}
| 8,045 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/impl/RegistrableStandardEmitterMBean.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.blueprint.impl;
import javax.management.*;
/**
* The <code>StandardMBean</code> does not appear to delegate correctly to the underlying MBean implementation. Due to
* issues surrounding the <code>MBeanRegistration</code> callback methods and <code>NotificationEmmitter</code> methods,
* this subclass was introduced to force the delegation
*
* @version $Rev$ $Date$
*/
public class RegistrableStandardEmitterMBean extends StandardMBean implements MBeanRegistration, NotificationEmitter {
public <T> RegistrableStandardEmitterMBean(T impl, Class<T> intf) throws NotCompliantMBeanException {
super(impl, intf);
}
/**
* @see javax.management.StandardMBean#getMBeanInfo()
*/
public MBeanInfo getMBeanInfo() {
MBeanInfo mbeanInfo = super.getMBeanInfo();
if (mbeanInfo != null) {
MBeanNotificationInfo[] notificationInfo;
Object impl = getImplementation();
if (impl instanceof NotificationEmitter) {
notificationInfo = ((NotificationEmitter) (impl)).getNotificationInfo();
} else {
notificationInfo = new MBeanNotificationInfo[0];
}
mbeanInfo = new MBeanInfo(mbeanInfo.getClassName(), mbeanInfo.getDescription(), mbeanInfo.getAttributes(),
mbeanInfo.getConstructors(), mbeanInfo.getOperations(), notificationInfo);
}
return mbeanInfo;
}
/**
* @see javax.management.MBeanRegistration#postDeregister()
*/
public void postDeregister() {
Object impl = getImplementation();
if (impl instanceof MBeanRegistration) {
((MBeanRegistration) impl).postDeregister();
}
}
/**
* @see javax.management.MBeanRegistration#postRegister(Boolean)
*/
public void postRegister(Boolean registrationDone) {
Object impl = getImplementation();
if (impl instanceof MBeanRegistration) {
((MBeanRegistration) impl).postRegister(registrationDone);
}
}
/**
* @see javax.management.MBeanRegistration#preDeregister()
*/
public void preDeregister() throws Exception {
Object impl = getImplementation();
if (impl instanceof MBeanRegistration) {
((MBeanRegistration) impl).preDeregister();
}
}
/**
* @see javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName)
*/
public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
ObjectName result = name;
Object impl = getImplementation();
if (impl instanceof MBeanRegistration) {
result = ((MBeanRegistration) impl).preRegister(server, name);
}
return result;
}
/**
* @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener,
* javax.management.NotificationFilter, Object)
*/
public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
throws ListenerNotFoundException {
Object impl = getImplementation();
if (impl instanceof NotificationEmitter) {
((NotificationEmitter) (impl)).removeNotificationListener(listener, filter, handback);
}
}
/**
* @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener,
* javax.management.NotificationFilter, Object)
*/
public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
throws IllegalArgumentException {
Object impl = getImplementation();
if (impl instanceof NotificationEmitter) {
((NotificationEmitter) (impl)).addNotificationListener(listener, filter, handback);
}
}
/**
* @see javax.management.NotificationBroadcaster#getNotificationInfo()
*/
public MBeanNotificationInfo[] getNotificationInfo() {
MBeanNotificationInfo[] result;
Object impl = getImplementation();
if (impl instanceof NotificationEmitter) {
result = ((NotificationEmitter) (impl)).getNotificationInfo();
} else {
result = new MBeanNotificationInfo[0];
}
return result;
}
/**
* @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)
*/
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
Object impl = getImplementation();
if (impl instanceof NotificationEmitter) {
((NotificationEmitter) (impl)).removeNotificationListener(listener);
}
}
}
| 8,046 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/impl/BlueprintMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.impl;
import java.io.IOException;
import java.util.Collection;
import javax.management.openmbean.CompositeData;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.apache.aries.jmx.blueprint.codec.BPMetadata;
import org.apache.aries.jmx.blueprint.codec.Util;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
public class BlueprintMetadata implements BlueprintMetadataMBean {
BundleContext bundleContext;
public BlueprintMetadata(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
/*
* (non-Javadoc)
*
* @see org.apache.aries.jmx.blueprint.BlueprintMetadataMBean#getBlueprintContainerServiceId(long)
*/
public long getBlueprintContainerServiceId(long bundleId) throws IOException {
Bundle bpBundle = bundleContext.getBundle(bundleId);
if (null == bpBundle)
throw new IllegalArgumentException("Invalid bundle id " + bundleId);
String filter = "(&(osgi.blueprint.container.symbolicname=" // no similar one in interfaces
+ bpBundle.getSymbolicName() + ")(osgi.blueprint.container.version=" + bpBundle.getVersion() + "))";
ServiceReference[] serviceReferences = null;
try {
serviceReferences = bundleContext.getServiceReferences(BlueprintContainer.class.getName(), filter);
} catch (InvalidSyntaxException e) {
throw new RuntimeException(e);
}
if (serviceReferences == null || serviceReferences.length < 1)
return -1;
else
return (Long) serviceReferences[0].getProperty(Constants.SERVICE_ID);
}
public long[] getBlueprintContainerServiceIds() throws IOException {
ServiceReference[] serviceReferences = null;
try {
serviceReferences = bundleContext.getServiceReferences(BlueprintContainer.class.getName(), null);
} catch (InvalidSyntaxException e) {
throw new RuntimeException(e);
}
if (serviceReferences == null || serviceReferences.length < 1)
return null;
long[] serviceIds = new long[serviceReferences.length];
for (int i = 0; i < serviceReferences.length; i++) {
serviceIds[i] = (Long) serviceReferences[i].getProperty(Constants.SERVICE_ID);
}
return serviceIds;
}
public String[] getComponentIds(long containerServiceId) throws IOException {
BlueprintContainer container = getBlueprintContainer(containerServiceId);
return (String[]) container.getComponentIds().toArray(new String[0]);
}
/*
*
* type could be Bean, Service, serviceReference (non-Javadoc)
*
* @see org.apache.aries.jmx.blueprint.BlueprintMetadataMBean#getComponentIdsByType(long, java.lang.String)
*/
public String[] getComponentIdsByType(long containerServiceId, String type) throws IOException {
BlueprintContainer container = getBlueprintContainer(containerServiceId);
Collection<? extends ComponentMetadata> components;
if (type.equals(BlueprintMetadataMBean.SERVICE_METADATA)) {
components = container.getMetadata(ServiceMetadata.class);
} else if (type.equals(BlueprintMetadataMBean.BEAN_METADATA)) {
components = container.getMetadata(BeanMetadata.class);
} else if (type.equals(BlueprintMetadataMBean.SERVICE_REFERENCE_METADATA)) {
components = container.getMetadata(ServiceReferenceMetadata.class);
} else {
throw new IllegalArgumentException("Unrecognized component type: " + type);
}
String ids[] = new String[components.size()];
int i = 0;
for (ComponentMetadata component : components) {
// from compendium 121.4.8, in-line managers can not be retrieved by getMetadata, which will return null.
// Because in-line managers are actually the object values.
// Here we ignore it.
if(null == component)
continue;
ids[i++] = component.getId();
}
return ids;
}
public CompositeData getComponentMetadata(long containerServiceId, String componentId) throws IOException {
BlueprintContainer container = getBlueprintContainer(containerServiceId);
ComponentMetadata componentMetadata = container.getComponentMetadata(componentId);
BPMetadata metadata = Util.metadata2BPMetadata(componentMetadata);
return metadata.asCompositeData();
}
private BlueprintContainer getBlueprintContainer(long containerServiceId) throws IOException {
String filter = "(" + Constants.SERVICE_ID + "=" + containerServiceId + ")";
ServiceReference[] serviceReferences = null;
try {
serviceReferences = bundleContext.getServiceReferences(BlueprintContainer.class.getName(), filter);
} catch (InvalidSyntaxException e) {
throw new IOException(e);
}
if (serviceReferences == null || serviceReferences.length <1) {
throw new IOException("Invalid BlueprintContainer service id: " + containerServiceId);
}
return (BlueprintContainer) bundleContext.getService(serviceReferences[0]);
}
}
| 8,047 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/impl/BlueprintState.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.impl;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.apache.aries.jmx.blueprint.BlueprintStateMBean;
import org.apache.aries.jmx.blueprint.codec.OSGiBlueprintEvent;
import org.apache.aries.util.AriesFrameworkUtil;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.blueprint.container.BlueprintEvent;
import org.osgi.service.blueprint.container.BlueprintListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BlueprintState extends NotificationBroadcasterSupport implements BlueprintStateMBean, MBeanRegistration {
// notification type description
public static String BLUEPRINT_EVENT = "org.osgi.blueprint.event";
private static final Logger LOGGER = LoggerFactory.getLogger(BlueprintState.class);
private BundleContext context;
private ServiceRegistration listenerReg;
private Map<Long, CompositeData> dataMap = new HashMap<Long, CompositeData>();
private ExecutorService eventDispatcher;
private AtomicInteger notificationSequenceNumber = new AtomicInteger(1);
private AtomicInteger registrations = new AtomicInteger(0);
public BlueprintState(BundleContext context) {
this.context = context;
}
public synchronized long[] getBlueprintBundleIds() throws IOException {
Long[] bundleIdKeys = dataMap.keySet().toArray(new Long[dataMap.size()]);
long[] bundleIds = new long[bundleIdKeys.length];
for (int i = 0; i < bundleIdKeys.length; i++) {
bundleIds[i] = bundleIdKeys[i];
}
return bundleIds;
}
public synchronized CompositeData getLastEvent(long bundleId) throws IOException {
return dataMap.get(bundleId);
}
public synchronized TabularData getLastEvents() throws IOException {
TabularDataSupport table = new TabularDataSupport(BlueprintStateMBean.OSGI_BLUEPRINT_EVENTS_TYPE);
table.putAll(dataMap);
return table;
}
public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
// no op
return name;
}
public void postRegister(Boolean registrationDone) {
// reg listener
if (registrationDone && registrations.incrementAndGet() == 1) {
BlueprintListener listener = new BlueprintStateListener();
eventDispatcher = Executors.newSingleThreadExecutor(new JMXThreadFactory("JMX OSGi Blueprint State Event Dispatcher"));
listenerReg = context.registerService(BlueprintListener.class.getName(), listener, null);
}
}
public void preDeregister() throws Exception {
// no op
}
public void postDeregister() {
if (registrations.decrementAndGet() < 1) {
AriesFrameworkUtil.safeUnregisterService(listenerReg);
if (eventDispatcher != null) {
eventDispatcher.shutdown();
}
}
}
protected synchronized void onEvent(BlueprintEvent event) {
CompositeData data = new OSGiBlueprintEvent(event).asCompositeData();
dataMap.put(event.getBundle().getBundleId(), data);
if (!event.isReplay()) {
final Notification notification = new Notification(EVENT_TYPE, OBJECTNAME,
notificationSequenceNumber.getAndIncrement());
try {
notification.setUserData(data);
eventDispatcher.submit(new Runnable() {
public void run() {
sendNotification(notification);
}
});
} catch (RejectedExecutionException re) {
LOGGER.warn("Task rejected for JMX Notification dispatch of event ["
+ event + "] - Dispatcher may have been shutdown");
} catch (Exception e) {
LOGGER.warn("Exception occured on JMX Notification dispatch for event [" + event + "]", e);
}
}
}
/**
* @see javax.management.NotificationBroadcasterSupport#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
String[] types = new String[] { BLUEPRINT_EVENT };
String name = Notification.class.getName();
String description = "A BlueprintEvent issued from the Blueprint Extender describing a blueprint bundle lifecycle change";
MBeanNotificationInfo info = new MBeanNotificationInfo(types, name, description);
return new MBeanNotificationInfo[] { info };
}
private class BlueprintStateListener implements BlueprintListener {
public void blueprintEvent(BlueprintEvent event) {
onEvent(event);
}
}
public static class JMXThreadFactory implements ThreadFactory {
private final ThreadFactory factory = Executors.defaultThreadFactory();
private final String name;
public JMXThreadFactory(String name) {
this.name = name;
}
public Thread newThread(Runnable r) {
final Thread t = factory.newThread(r);
t.setName(name);
t.setDaemon(true);
return t;
}
}
}
| 8,048 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/OSGiBlueprintEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintStateMBean;
import org.osgi.service.blueprint.container.BlueprintEvent;
/**
* <p>
* This class represents the CODEC for the composite data representing a OSGi
* BlueprintEvent
* <p>
* It serves as both the documentation of the type structure and as the
* codification of the mechanism to convert to/from the CompositeData.
* <p>
* The structure of the composite data is:
* <p>
* - bundleId : long<br>
* - extenderBundleId : long<br>
* - eventType : int<br>
* - replay : boolean<br>
* - timestamp : long<br>
* - dependencies : String[]<br>
* - exceptionMessage : String
*/
public class OSGiBlueprintEvent implements TransferObject{
private long bundleId;
private long extenderBundleId;
private int eventType;
private boolean replay;
private long timestamp;
private String[] dependencies;
private String exceptionMessage;
/**
* Construct an OSGiBlueprintEvent from the supplied BlueprintEvent
*
* @param event
* - the event to represent
*/
public OSGiBlueprintEvent(BlueprintEvent event) {
this(event.getBundle().getBundleId(),
event.getExtenderBundle().getBundleId(),
event.getType(),
event.isReplay(),
event.getTimestamp(),
event.getDependencies(),
(event.getCause() == null) ? null : event.getCause().getMessage());
}
/**
* Construct an OSGiBlueprintEvent from the CompositeData representing the
* event
*
* @param data
* - the CompositeData representing the event.
*/
@SuppressWarnings("boxing")
public OSGiBlueprintEvent(CompositeData data) {
this((Long) data.get(BlueprintStateMBean.BUNDLE_ID),
(Long) data.get(BlueprintStateMBean.EXTENDER_BUNDLE_ID),
(Integer) data.get(BlueprintStateMBean.EVENT_TYPE),
(Boolean) data.get(BlueprintStateMBean.REPLAY),
(Long) data.get(BlueprintStateMBean.TIMESTAMP),
(String[]) data.get(BlueprintStateMBean.DEPENDENCIES),
(String) data.get(BlueprintStateMBean.EXCEPTION_MESSAGE));
}
/**
* Construct the OSGiBlueprintEvent
*
* @param bundleId
* @param extenderBundleId
* @param eventType
* @param replay
* @param timestamp
* @param dependencies
* @param exceptionMessage
*/
public OSGiBlueprintEvent(long bundleId, long extenderBundleId, int eventType, boolean replay, long timestamp, String[] dependencies, String exceptionMessage){
this.bundleId = bundleId;
this.extenderBundleId = extenderBundleId;
this.eventType = eventType;
this.replay = replay;
this.timestamp = timestamp;
this.dependencies = dependencies;
this.exceptionMessage = exceptionMessage;
}
/**
* Answer the receiver encoded as CompositeData
*
* @return the CompositeData encoding of the receiver.
*/
@SuppressWarnings("boxing")
public CompositeData asCompositeData() {
Map<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintStateMBean.BUNDLE_ID, bundleId);
items.put(BlueprintStateMBean.EXTENDER_BUNDLE_ID, extenderBundleId);
items.put(BlueprintStateMBean.EVENT_TYPE, eventType);
items.put(BlueprintStateMBean.REPLAY, replay);
items.put(BlueprintStateMBean.TIMESTAMP, timestamp);
items.put(BlueprintStateMBean.DEPENDENCIES, dependencies);
items.put(BlueprintStateMBean.EXCEPTION_MESSAGE, exceptionMessage);
try {
return new CompositeDataSupport(BlueprintStateMBean.OSGI_BLUEPRINT_EVENT_TYPE, items);
} catch (OpenDataException e) {
throw new IllegalStateException("Cannot form blueprint event open data", e);
}
}
public long getBundleId() {
return bundleId;
}
public long getExtenderBundleId() {
return extenderBundleId;
}
public int getEventType() {
return eventType;
}
public boolean isReplay() {
return replay;
}
public long getTimestamp() {
return timestamp;
}
public String[] getDependencies() {
return dependencies;
}
public String getExceptionMessage() {
return exceptionMessage;
}
}
| 8,049 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPCollectionMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
public class BPCollectionMetadata implements BPNonNullMetadata {
private String collectionClass;
private String valueType;
private BPMetadata[] values;
public BPCollectionMetadata(CompositeData collection) {
collectionClass = (String) collection.get(BlueprintMetadataMBean.COLLECTION_CLASS);
valueType = (String) collection.get(BlueprintMetadataMBean.VALUE_TYPE);
Byte[][] arrays = (Byte[][]) collection.get(BlueprintMetadataMBean.VALUES);
values = new BPMetadata[arrays.length];
for (int i = 0; i < values.length; i++) {
values[i] = Util.boxedBinary2BPMetadata((Byte[]) arrays[i]);
}
}
public BPCollectionMetadata(CollectionMetadata collection) {
collectionClass = collection.getCollectionClass().getCanonicalName();
valueType = collection.getValueType();
values = new BPMetadata[collection.getValues().size()];
int i = 0;
for (Object value : collection.getValues()) {
values[i++] = Util.metadata2BPMetadata((Metadata) value);
}
}
public CompositeData asCompositeData() {
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.COLLECTION_CLASS, collectionClass);
items.put(BlueprintMetadataMBean.VALUE_TYPE, valueType);
Byte[][] arrays = new Byte[values.length][];
for (int i = 0; i < arrays.length; i++) {
arrays[i] = Util.bpMetadata2BoxedBinary(values[i]);
}
items.put(BlueprintMetadataMBean.VALUES, arrays);
try {
return new CompositeDataSupport(BlueprintMetadataMBean.COLLECTION_METADATA_TYPE, items);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public String getCollectionClass() {
return collectionClass;
}
public String getValueType() {
return valueType;
}
public BPMetadata[] getValues() {
return values;
}
}
| 8,050 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/TransferObject.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import javax.management.openmbean.CompositeData;
public interface TransferObject {
CompositeData asCompositeData();
}
| 8,051 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPRegistrationListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.RegistrationListener;
public class BPRegistrationListener implements TransferObject {
private BPTarget listenerComponent;
private String registrationMethod;
private String unregistrationMethod;
public BPRegistrationListener(CompositeData listener) {
registrationMethod = (String) listener.get(BlueprintMetadataMBean.REGISTRATION_METHOD);
unregistrationMethod = (String) listener.get(BlueprintMetadataMBean.UNREGISTRATION_METHOD);
Byte[] buf = (Byte[]) listener.get(BlueprintMetadataMBean.LISTENER_COMPONENT);
listenerComponent = (BPTarget) Util.boxedBinary2BPMetadata(buf);
}
public BPRegistrationListener(RegistrationListener listener) {
registrationMethod = listener.getRegistrationMethod();
unregistrationMethod = listener.getUnregistrationMethod();
listenerComponent = (BPTarget) Util.metadata2BPMetadata(listener.getListenerComponent());
}
public CompositeData asCompositeData() {
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.REGISTRATION_METHOD, registrationMethod);
items.put(BlueprintMetadataMBean.UNREGISTRATION_METHOD, unregistrationMethod);
items.put(BlueprintMetadataMBean.LISTENER_COMPONENT, Util.bpMetadata2BoxedBinary(listenerComponent));
try {
return new CompositeDataSupport(BlueprintMetadataMBean.REGISTRATION_LISTENER_TYPE, items);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public BPTarget getListenerComponent() {
return listenerComponent;
}
public String getRegistrationMethod() {
return registrationMethod;
}
public String getUnregistrationMethod() {
return unregistrationMethod;
}
}
| 8,052 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/Util.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.management.openmbean.CompositeData;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.CollectionMetadata;
import org.osgi.service.blueprint.reflect.IdRefMetadata;
import org.osgi.service.blueprint.reflect.MapMetadata;
import org.osgi.service.blueprint.reflect.Metadata;
import org.osgi.service.blueprint.reflect.NullMetadata;
import org.osgi.service.blueprint.reflect.PropsMetadata;
import org.osgi.service.blueprint.reflect.RefMetadata;
import org.osgi.service.blueprint.reflect.ReferenceListMetadata;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
import org.osgi.service.blueprint.reflect.ValueMetadata;
public class Util {
public static BPMetadata metadata2BPMetadata(Metadata metadata) {
if(null == metadata)
return null;
// target first
if (metadata instanceof BeanMetadata)
return new BPBeanMetadata((BeanMetadata) metadata);
if (metadata instanceof ReferenceMetadata)
return new BPReferenceMetadata((ReferenceMetadata) metadata);
if (metadata instanceof RefMetadata)
return new BPRefMetadata((RefMetadata) metadata);
// others
if (metadata instanceof CollectionMetadata)
return new BPCollectionMetadata((CollectionMetadata) metadata);
if (metadata instanceof ServiceMetadata)
return new BPServiceMetadata((ServiceMetadata) metadata);
if (metadata instanceof ReferenceListMetadata)
return new BPReferenceListMetadata((ReferenceListMetadata) metadata);
if (metadata instanceof IdRefMetadata)
return new BPIdRefMetadata((IdRefMetadata) metadata);
if (metadata instanceof MapMetadata)
return new BPMapMetadata((MapMetadata) metadata);
if (metadata instanceof PropsMetadata)
return new BPPropsMetadata((PropsMetadata) metadata);
if (metadata instanceof ValueMetadata)
return new BPValueMetadata((ValueMetadata) metadata);
// null last
if (metadata instanceof NullMetadata)
return new BPNullMetadata((NullMetadata) metadata);
throw new RuntimeException("Unknown metadata type");
}
public static BPMetadata binary2BPMetadata(byte[] buf) {
if(null == buf)
return null;
ByteArrayInputStream inBytes = new ByteArrayInputStream(buf);
ObjectInputStream inObject;
CompositeData metadata;
try {
inObject = new ObjectInputStream(inBytes);
metadata = (CompositeData) inObject.readObject();
inObject.close();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
String typename = metadata.getCompositeType().getTypeName();
// target first
if (typename.equals(BlueprintMetadataMBean.BEAN_METADATA))
return new BPBeanMetadata(metadata);
if (typename.equals(BlueprintMetadataMBean.REFERENCE_METADATA))
return new BPReferenceMetadata(metadata);
if (typename.equals(BlueprintMetadataMBean.REF_METADATA))
return new BPRefMetadata(metadata);
// others
if (typename.equals(BlueprintMetadataMBean.COLLECTION_METADATA))
return new BPCollectionMetadata(metadata);
if (typename.equals(BlueprintMetadataMBean.SERVICE_METADATA))
return new BPServiceMetadata(metadata);
if (typename.equals(BlueprintMetadataMBean.REFERENCE_LIST_METADATA))
return new BPReferenceListMetadata(metadata);
if (typename.equals(BlueprintMetadataMBean.ID_REF_METADATA))
return new BPIdRefMetadata(metadata);
if (typename.equals(BlueprintMetadataMBean.MAP_METADATA))
return new BPMapMetadata(metadata);
if (typename.equals(BlueprintMetadataMBean.PROPS_METADATA))
return new BPPropsMetadata(metadata);
if (typename.equals(BlueprintMetadataMBean.VALUE_METADATA))
return new BPValueMetadata(metadata);
// null last
if (metadata instanceof NullMetadata)
return new BPNullMetadata(metadata);
throw new RuntimeException("Unknown metadata type");
}
public static byte[] bpMetadata2Binary(BPMetadata metadata) {
if(null == metadata)
return null;
ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
ObjectOutputStream outObject;
try {
outObject = new ObjectOutputStream(outBytes);
outObject.writeObject(metadata.asCompositeData());
outObject.close();
} catch (IOException e) {// there is no io op
throw new RuntimeException(e);
}
return outBytes.toByteArray();
}
public static Byte[] bpMetadata2BoxedBinary(BPMetadata metadata)
{
if(null == metadata)
return null;
byte [] src = bpMetadata2Binary(metadata);
Byte [] res = new Byte[src.length];
for(int i=0;i<src.length;i++)
{
res[i] = src[i];
}
return res;
}
public static BPMetadata boxedBinary2BPMetadata(Byte[] buf) {
if(null == buf)
return null;
byte [] unbox = new byte[buf.length];
for(int i=0;i<buf.length;i++)
{
unbox[i] = buf[i];
}
return binary2BPMetadata(unbox);
}
}
| 8,053 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPIdRefMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.IdRefMetadata;
public class BPIdRefMetadata implements BPNonNullMetadata {
private String componentId;
public BPIdRefMetadata(CompositeData idRef) {
componentId = (String) idRef.get(BlueprintMetadataMBean.COMPONENT_ID);
}
public BPIdRefMetadata(IdRefMetadata idRef) {
componentId = idRef.getComponentId();
}
public CompositeData asCompositeData() {
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.COMPONENT_ID, componentId);
try {
return new CompositeDataSupport(BlueprintMetadataMBean.ID_REF_METADATA_TYPE, items);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public String getComponentId() {
return componentId;
}
}
| 8,054 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPServiceMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.RegistrationListener;
import org.osgi.service.blueprint.reflect.ServiceMetadata;
public class BPServiceMetadata extends BPComponentMetadata {
private int autoExport;
private String[] interfaces;
private int ranking;
private BPRegistrationListener[] listeners;
private BPMapEntry[] properties;
private BPTarget serviceComponent;
public BPServiceMetadata(CompositeData service) {
super(service);
autoExport = (Integer) service.get(BlueprintMetadataMBean.AUTO_EXPORT);
interfaces = (String[]) service.get(BlueprintMetadataMBean.INTERFACES);
ranking = (Integer) service.get(BlueprintMetadataMBean.RANKING);
CompositeData[] cd_listeners = (CompositeData[]) service.get(BlueprintMetadataMBean.REGISTRATION_LISTENERS);
listeners = new BPRegistrationListener[cd_listeners.length];
for (int i = 0; i < listeners.length; i++) {
listeners[i] = new BPRegistrationListener(cd_listeners[i]);
}
CompositeData[] cd_props = (CompositeData[]) service.get(BlueprintMetadataMBean.SERVICE_PROPERTIES);
properties = new BPMapEntry[cd_props.length];
for (int i = 0; i < properties.length; i++) {
properties[i] = new BPMapEntry(cd_props[i]);
}
Byte[] buf = (Byte[]) service.get(BlueprintMetadataMBean.SERVICE_COMPONENT);
serviceComponent = (BPTarget) Util.boxedBinary2BPMetadata(buf);
}
public BPServiceMetadata(ServiceMetadata service) {
super(service);
autoExport = service.getAutoExport();
interfaces = (String[])service.getInterfaces().toArray(new String[0]);
ranking = service.getRanking();
listeners = new BPRegistrationListener[service.getRegistrationListeners().size()];
int i = 0;
for (Object listener : service.getRegistrationListeners()) {
listeners[i++] = new BPRegistrationListener((RegistrationListener) listener);
}
properties = new BPMapEntry[service.getServiceProperties().size()];
i = 0;
for (Object prop : service.getServiceProperties()) {
properties[i++] = new BPMapEntry((MapEntry) prop);
}
serviceComponent = (BPTarget) Util.metadata2BPMetadata(service.getServiceComponent());
}
protected Map<String, Object> getItemsMap() {
Map<String, Object> items = super.getItemsMap();
items.put(BlueprintMetadataMBean.AUTO_EXPORT, autoExport);
items.put(BlueprintMetadataMBean.INTERFACES, interfaces);
items.put(BlueprintMetadataMBean.RANKING, ranking);
CompositeData[] cd_listeners = new CompositeData[listeners.length];
for (int i = 0; i < listeners.length; i++) {
cd_listeners[i] = listeners[i].asCompositeData();
}
items.put(BlueprintMetadataMBean.REGISTRATION_LISTENERS, cd_listeners);
CompositeData[] cd_props = new CompositeData[properties.length];
for (int i = 0; i < properties.length; i++) {
cd_props[i] = properties[i].asCompositeData();
}
items.put(BlueprintMetadataMBean.SERVICE_PROPERTIES, cd_props);
items.put(BlueprintMetadataMBean.SERVICE_COMPONENT, Util.bpMetadata2BoxedBinary(serviceComponent));
return items;
}
public CompositeData asCompositeData() {
try {
return new CompositeDataSupport(BlueprintMetadataMBean.SERVICE_METADATA_TYPE, getItemsMap());
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public int getAutoExport() {
return autoExport;
}
public String[] getInterfaces() {
return interfaces;
}
public int getRanking() {
return ranking;
}
public BPRegistrationListener[] getRegistrationListeners() {
return listeners;
}
public BPTarget getServiceComponent() {
return serviceComponent;
}
public BPMapEntry[] getServiceProperties() {
return properties;
}
}
| 8,055 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPBeanMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.BeanArgument;
import org.osgi.service.blueprint.reflect.BeanMetadata;
import org.osgi.service.blueprint.reflect.BeanProperty;
public class BPBeanMetadata extends BPComponentMetadata implements BPTarget {
private String className;
private String destroyMethod;
private String factoryMethod;
private String initMethod;
private String scope;
private BPBeanArgument[] arguments;
private BPBeanProperty[] properties;
private BPTarget factoryComponent;
public BPBeanMetadata(CompositeData bean) {
super(bean);
className = (String) bean.get(BlueprintMetadataMBean.CLASS_NAME);
destroyMethod = (String) bean.get(BlueprintMetadataMBean.DESTROY_METHOD);
factoryMethod = (String) bean.get(BlueprintMetadataMBean.FACTORY_METHOD);
initMethod = (String) bean.get(BlueprintMetadataMBean.INIT_METHOD);
scope = (String) bean.get(BlueprintMetadataMBean.SCOPE);
Byte[] buf = (Byte[]) bean.get(BlueprintMetadataMBean.FACTORY_COMPONENT);
factoryComponent = (BPTarget) Util.boxedBinary2BPMetadata(buf);
CompositeData[] cd_args = (CompositeData[]) bean.get(BlueprintMetadataMBean.ARGUMENTS);
arguments = new BPBeanArgument[cd_args.length];
for (int i = 0; i < arguments.length; i++) {
arguments[i] = new BPBeanArgument(cd_args[i]);
}
CompositeData[] cd_props = (CompositeData[]) bean.get(BlueprintMetadataMBean.PROPERTIES);
properties = new BPBeanProperty[cd_props.length];
for (int i = 0; i < properties.length; i++) {
properties[i] = new BPBeanProperty(cd_props[i]);
}
}
public BPBeanMetadata(BeanMetadata bean) {
super(bean);
className = bean.getClassName();
destroyMethod = bean.getDestroyMethod();
factoryMethod = bean.getFactoryMethod();
initMethod = bean.getInitMethod();
scope = bean.getScope();
factoryComponent = (BPTarget) Util.metadata2BPMetadata(bean.getFactoryComponent());
arguments = new BPBeanArgument[bean.getArguments().size()];
int i = 0;
for (Object arg : bean.getArguments()) {
arguments[i++] = new BPBeanArgument((BeanArgument) arg);
}
properties = new BPBeanProperty[bean.getProperties().size()];
i = 0;
for (Object prop : bean.getProperties()) {
properties[i++] = new BPBeanProperty((BeanProperty) prop);
}
}
protected Map<String, Object> getItemsMap() {
Map<String, Object> items = super.getItemsMap();
// add its fields to the map
items.put(BlueprintMetadataMBean.CLASS_NAME, className);
items.put(BlueprintMetadataMBean.DESTROY_METHOD, destroyMethod);
items.put(BlueprintMetadataMBean.FACTORY_METHOD, factoryMethod);
items.put(BlueprintMetadataMBean.INIT_METHOD, initMethod);
items.put(BlueprintMetadataMBean.SCOPE, scope);
items.put(BlueprintMetadataMBean.FACTORY_COMPONENT, Util.bpMetadata2BoxedBinary(factoryComponent));
CompositeData[] cd_args = new CompositeData[arguments.length];
for (int i = 0; i < arguments.length; i++) {
cd_args[i] = arguments[i].asCompositeData();
}
items.put(BlueprintMetadataMBean.ARGUMENTS, cd_args);
CompositeData[] cd_props = new CompositeData[properties.length];
for (int i = 0; i < properties.length; i++) {
cd_props[i] = properties[i].asCompositeData();
}
items.put(BlueprintMetadataMBean.PROPERTIES, cd_props);
return items;
}
public CompositeData asCompositeData() {
try {
return new CompositeDataSupport(BlueprintMetadataMBean.BEAN_METADATA_TYPE, getItemsMap());
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public BPBeanArgument[] getArguments() {
return arguments;
}
public String getClassName() {
return className;
}
public String getDestroyMethod() {
return destroyMethod;
}
public BPTarget getFactoryComponent() {
return factoryComponent;
}
public String getFactoryMethod() {
return factoryMethod;
}
public String getInitMethod() {
return initMethod;
}
public BPBeanProperty[] getProperties() {
return properties;
}
public String getScope() {
return scope;
}
}
| 8,056 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPReferenceListMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.ReferenceListMetadata;
public class BPReferenceListMetadata extends BPServiceReferenceMetadata {
private int memberType;
public BPReferenceListMetadata(CompositeData ref_list) {
super(ref_list);
memberType = (Integer) ref_list.get(BlueprintMetadataMBean.MEMBER_TYPE);
}
public BPReferenceListMetadata(ReferenceListMetadata ref_list) {
super(ref_list);
memberType = ref_list.getMemberType();
}
protected Map<String, Object> getItemsMap() {
Map<String, Object> items = super.getItemsMap();
items.put(BlueprintMetadataMBean.MEMBER_TYPE, memberType);
return items;
}
public CompositeData asCompositeData() {
try {
return new CompositeDataSupport(BlueprintMetadataMBean.REFERENCE_LIST_METADATA_TYPE, getItemsMap());
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public int getMemberType() {
return memberType;
}
}
| 8,057 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPRefMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.RefMetadata;
public class BPRefMetadata implements BPNonNullMetadata, BPTarget {
private String componentId;
public BPRefMetadata(CompositeData ref) {
componentId = (String) ref.get(BlueprintMetadataMBean.COMPONENT_ID);
}
public BPRefMetadata(RefMetadata ref) {
componentId = ref.getComponentId();
}
public CompositeData asCompositeData() {
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.COMPONENT_ID, componentId);
try {
return new CompositeDataSupport(BlueprintMetadataMBean.REF_METADATA_TYPE, items);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public String getComponentId() {
return componentId;
}
}
| 8,058 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPValueMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.ValueMetadata;
public class BPValueMetadata implements BPNonNullMetadata {
private String stringValue;
private String type;
public BPValueMetadata(CompositeData value) {
stringValue = (String) value.get(BlueprintMetadataMBean.STRING_VALUE);
type = (String) value.get(BlueprintMetadataMBean.TYPE);
}
public BPValueMetadata(ValueMetadata value) {
stringValue = value.getStringValue();
type = value.getType();
}
public CompositeData asCompositeData() {
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.STRING_VALUE, stringValue);
items.put(BlueprintMetadataMBean.TYPE, type);
try {
return new CompositeDataSupport(BlueprintMetadataMBean.VALUE_METADATA_TYPE, items);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public String getStringValue() {
return stringValue;
}
public String getType() {
return type;
}
}
| 8,059 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPMapMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.MapMetadata;
public class BPMapMetadata implements BPNonNullMetadata {
private String keyType;
private String valueType;
private BPMapEntry[] entries;
public BPMapMetadata(CompositeData map) {
keyType = (String) map.get(BlueprintMetadataMBean.KEY_TYPE);
valueType = (String) map.get(BlueprintMetadataMBean.VALUE_TYPE);
CompositeData[] cd_entries = (CompositeData[]) map.get(BlueprintMetadataMBean.ENTRIES);
entries = new BPMapEntry[cd_entries.length];
for (int i = 0; i < entries.length; i++) {
entries[i] = new BPMapEntry(cd_entries[i]);
}
}
public BPMapMetadata(MapMetadata map) {
keyType = map.getKeyType();
valueType = map.getValueType();
entries = new BPMapEntry[map.getEntries().size()];
int i = 0;
for (Object arg : map.getEntries()) {
entries[i++] = new BPMapEntry((MapEntry) arg);
}
}
public CompositeData asCompositeData() {
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.KEY_TYPE, keyType);
items.put(BlueprintMetadataMBean.VALUE_TYPE, valueType);
CompositeData[] cd_entries = new CompositeData[entries.length];
for (int i = 0; i < entries.length; i++) {
cd_entries[i] = entries[i].asCompositeData();
}
items.put(BlueprintMetadataMBean.ENTRIES, cd_entries);
try {
return new CompositeDataSupport(BlueprintMetadataMBean.MAP_METADATA_TYPE, items);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public BPMapEntry[] getEntries() {
return entries;
}
public String getKeyType() {
return keyType;
}
public String getValueType() {
return valueType;
}
}
| 8,060 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPPropsMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.MapEntry;
import org.osgi.service.blueprint.reflect.PropsMetadata;
public class BPPropsMetadata implements BPNonNullMetadata {
BPMapEntry[] entries;
public BPPropsMetadata(CompositeData props) {
CompositeData[] cd_entries = (CompositeData[]) props.get(BlueprintMetadataMBean.ENTRIES);
entries = new BPMapEntry[cd_entries.length];
for (int i = 0; i < entries.length; i++) {
entries[i] = new BPMapEntry(cd_entries[i]);
}
}
public BPPropsMetadata(PropsMetadata props) {
entries = new BPMapEntry[props.getEntries().size()];
int i = 0;
for (Object arg : props.getEntries()) {
entries[i++] = new BPMapEntry((MapEntry) arg);
}
}
public CompositeData asCompositeData() {
CompositeData[] cd_entries = new CompositeData[entries.length];
for (int i = 0; i < entries.length; i++) {
cd_entries[i] = entries[i].asCompositeData();
}
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.ENTRIES, cd_entries);
try {
return new CompositeDataSupport(BlueprintMetadataMBean.PROPS_METADATA_TYPE, items);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public BPMapEntry[] getEntries() {
return entries;
}
}
| 8,061 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
public interface BPMetadata extends TransferObject{
// marker interface
}
| 8,062 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPMapEntry.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.MapEntry;
public class BPMapEntry implements TransferObject {
private BPNonNullMetadata key;
private BPMetadata value;
public BPMapEntry(CompositeData entry) {
Byte[] buf = (Byte[]) entry.get(BlueprintMetadataMBean.KEY);
key = (BPNonNullMetadata) Util.boxedBinary2BPMetadata(buf);
buf = (Byte[]) entry.get(BlueprintMetadataMBean.VALUE);
value = Util.boxedBinary2BPMetadata(buf);
}
public BPMapEntry(MapEntry entry) {
key = (BPNonNullMetadata) Util.metadata2BPMetadata(entry.getKey());
value = Util.metadata2BPMetadata(entry.getValue());
}
public CompositeData asCompositeData() {
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.KEY, Util.bpMetadata2BoxedBinary(key));
items.put(BlueprintMetadataMBean.VALUE, Util.bpMetadata2BoxedBinary(value));
try {
return new CompositeDataSupport(BlueprintMetadataMBean.MAP_ENTRY_TYPE, items);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public BPNonNullMetadata getKey() {
return key;
}
public BPMetadata getValue() {
return value;
}
}
| 8,063 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPReferenceListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.ReferenceListener;
public class BPReferenceListener implements TransferObject {
private String bindMethod;
private String unbindMethod;
private BPTarget listenerComponent;
public BPReferenceListener(CompositeData listener) {
bindMethod = (String) listener.get(BlueprintMetadataMBean.BIND_METHOD);
unbindMethod = (String) listener.get(BlueprintMetadataMBean.UNBIND_METHOD);
Byte[] buf = (Byte[]) listener.get(BlueprintMetadataMBean.LISTENER_COMPONENT);
listenerComponent = (BPTarget) Util.boxedBinary2BPMetadata(buf);
}
public BPReferenceListener(ReferenceListener listener) {
bindMethod = listener.getBindMethod();
unbindMethod = listener.getUnbindMethod();
listenerComponent = (BPTarget) Util.metadata2BPMetadata(listener.getListenerComponent());
}
public CompositeData asCompositeData() {
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.BIND_METHOD, bindMethod);
items.put(BlueprintMetadataMBean.UNBIND_METHOD, unbindMethod);
items.put(BlueprintMetadataMBean.LISTENER_COMPONENT, Util.bpMetadata2BoxedBinary(listenerComponent));
try {
return new CompositeDataSupport(BlueprintMetadataMBean.REFERENCE_LISTENER_TYPE, items);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public String getBindMethod() {
return bindMethod;
}
public BPTarget getListenerComponent() {
return listenerComponent;
}
public String getUnbindMethod() {
return unbindMethod;
}
}
| 8,064 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPBeanArgument.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.BeanArgument;
public class BPBeanArgument implements TransferObject {
private int index;
private BPMetadata value;
private String valueType;
public BPBeanArgument(CompositeData argument) {
index = (Integer) argument.get(BlueprintMetadataMBean.INDEX);
Byte[] buf = (Byte[]) argument.get(BlueprintMetadataMBean.VALUE);
value = Util.boxedBinary2BPMetadata(buf);
valueType = (String) argument.get(BlueprintMetadataMBean.VALUE_TYPE);
}
public BPBeanArgument(BeanArgument argument) {
index = argument.getIndex();
value = Util.metadata2BPMetadata(argument.getValue());
valueType = argument.getValueType();
}
public CompositeData asCompositeData() {
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.INDEX, index);
items.put(BlueprintMetadataMBean.VALUE, Util.bpMetadata2BoxedBinary(value));
items.put(BlueprintMetadataMBean.VALUE_TYPE, valueType);
try {
return new CompositeDataSupport(BlueprintMetadataMBean.BEAN_ARGUMENT_TYPE, items);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public int getIndex() {
return index;
}
public BPMetadata getValue() {
return value;
}
public String getValueType() {
return valueType;
}
}
| 8,065 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPTarget.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
public interface BPTarget extends BPNonNullMetadata{
// marker interface
}
| 8,066 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPServiceReferenceMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.ReferenceListener;
import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
public abstract class BPServiceReferenceMetadata extends BPComponentMetadata {
private int availability;
private String componentName;
private String filter;
private String $interface;
private BPReferenceListener[] listeners;
protected BPServiceReferenceMetadata(CompositeData reference) {
super(reference);
availability = (Integer) reference.get(BlueprintMetadataMBean.AVAILABILITY);
componentName = (String) reference.get(BlueprintMetadataMBean.COMPONENT_NAME);
filter = (String) reference.get(BlueprintMetadataMBean.FILTER);
$interface = (String) reference.get(BlueprintMetadataMBean.INTERFACE);
CompositeData[] cd_listeners = (CompositeData[]) reference.get(BlueprintMetadataMBean.REFERENCE_LISTENERS);
listeners = new BPReferenceListener[cd_listeners.length];
for (int i = 0; i < listeners.length; i++) {
listeners[i] = new BPReferenceListener(cd_listeners[i]);
}
}
protected BPServiceReferenceMetadata(ServiceReferenceMetadata reference) {
super(reference);
availability = reference.getAvailability();
componentName = reference.getComponentName();
filter = reference.getFilter();
$interface = reference.getInterface();
listeners = new BPReferenceListener[reference.getReferenceListeners().size()];
int i = 0;
for (Object listener : reference.getReferenceListeners()) {
listeners[i++] = new BPReferenceListener((ReferenceListener) listener);
}
}
protected Map<String, Object> getItemsMap() {
Map<String, Object> items = super.getItemsMap();
// itself
items.put(BlueprintMetadataMBean.AVAILABILITY, availability);
items.put(BlueprintMetadataMBean.COMPONENT_NAME, componentName);
items.put(BlueprintMetadataMBean.FILTER, filter);
items.put(BlueprintMetadataMBean.INTERFACE, $interface);
CompositeData[] cd_listeners = new CompositeData[listeners.length];
for (int i = 0; i < listeners.length; i++) {
cd_listeners[i] = listeners[i].asCompositeData();
}
items.put(BlueprintMetadataMBean.REFERENCE_LISTENERS, cd_listeners);
return items;
}
public int getAvailability() {
return availability;
}
public String getComponentName() {
return componentName;
}
public String getFilter() {
return filter;
}
public String getInterface() {
return $interface;
}
public BPReferenceListener[] getReferenceListeners() {
return listeners;
}
}
| 8,067 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPBeanProperty.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.BeanProperty;
public class BPBeanProperty implements TransferObject {
private String name;
private BPMetadata value;
public BPBeanProperty(CompositeData property) {
name = (String) property.get(BlueprintMetadataMBean.NAME);
Byte[] buf = (Byte[]) property.get(BlueprintMetadataMBean.VALUE);
value = Util.boxedBinary2BPMetadata(buf);
}
public BPBeanProperty(BeanProperty property) {
name = property.getName();
value = Util.metadata2BPMetadata(property.getValue());
}
public CompositeData asCompositeData() {
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.NAME, name);
items.put(BlueprintMetadataMBean.VALUE, Util.bpMetadata2BoxedBinary(value));
try {
return new CompositeDataSupport(BlueprintMetadataMBean.BEAN_PROPERTY_TYPE, items);
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public String getName() {
return name;
}
public BPMetadata getValue() {
return value;
}
}
| 8,068 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPNullMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.NullMetadata;
public class BPNullMetadata implements BPMetadata {
public BPNullMetadata(CompositeData Null) {
//do nothing ?
}
public BPNullMetadata(NullMetadata Null) {
//do nothing ?
}
public CompositeData asCompositeData() {
try {
return new CompositeDataSupport(
BlueprintMetadataMBean.NULL_METADATA_TYPE,
new String[]{BlueprintMetadataMBean.PLACEHOLDER},
new Object[]{null});
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
}
| 8,069 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPReferenceMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.OpenDataException;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.ReferenceMetadata;
public class BPReferenceMetadata extends BPServiceReferenceMetadata implements BPTarget {
private long timeout;
public BPReferenceMetadata(CompositeData reference) {
super(reference);
timeout = (Long) reference.get(BlueprintMetadataMBean.TIMEOUT);
}
public BPReferenceMetadata(ReferenceMetadata reference) {
super(reference);
timeout = reference.getTimeout();
}
protected Map<String, Object> getItemsMap() {
Map<String, Object> items = super.getItemsMap();
items.put(BlueprintMetadataMBean.TIMEOUT, timeout);
return items;
}
public CompositeData asCompositeData() {
try {
return new CompositeDataSupport(BlueprintMetadataMBean.REFERENCE_METADATA_TYPE, getItemsMap());
} catch (OpenDataException e) {
throw new RuntimeException(e);
}
}
public long getTimeout() {
return timeout;
}
}
| 8,070 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPComponentMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
import java.util.HashMap;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean;
import org.osgi.service.blueprint.reflect.ComponentMetadata;
public abstract class BPComponentMetadata implements BPNonNullMetadata {
private int activation;
private String[] dependsOn;
private String id;
@SuppressWarnings("boxing")
protected BPComponentMetadata(CompositeData component) {
activation = (Integer) component.get(BlueprintMetadataMBean.ACTIVATION);
dependsOn = (String[]) component.get(BlueprintMetadataMBean.DEPENDS_ON);
id = (String) component.get(BlueprintMetadataMBean.ID);
}
protected BPComponentMetadata(ComponentMetadata component) {
activation = component.getActivation();
dependsOn = (String[])component.getDependsOn().toArray(new String[0]);
id = (String) component.getId();
}
protected Map<String, Object> getItemsMap() {
HashMap<String, Object> items = new HashMap<String, Object>();
items.put(BlueprintMetadataMBean.ACTIVATION, activation);
items.put(BlueprintMetadataMBean.DEPENDS_ON, dependsOn);
items.put(BlueprintMetadataMBean.ID, id);
return items;
}
public int getActivation() {
return activation;
}
public String[] getDependsOn() {
return dependsOn;
}
public String getId() {
return id;
}
}
| 8,071 |
0 | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint | Create_ds/aries/jmx/jmx-blueprint-core/src/main/java/org/apache/aries/jmx/blueprint/codec/BPNonNullMetadata.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.aries.jmx.blueprint.codec;
public interface BPNonNullMetadata extends BPMetadata {
// marker interface
}
| 8,072 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/CompendiumHandlerTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.management.StandardMBean;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.junit.After;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceReference;
public class CompendiumHandlerTest {
protected AbstractCompendiumHandler target;
@After
public void tearDown(){
target = null;
}
@Test
public void testAddingServiceWillInitiateMBeanRegistration() throws Exception {
Bundle mockSystemBundle = mock(Bundle.class);
when(mockSystemBundle.getSymbolicName()).thenReturn("the.sytem.bundle");
Object service = new Object();
ServiceReference reference = mock(ServiceReference.class);
when(reference.getProperty(Constants.SERVICE_ID)).thenReturn(1L);
when(reference.getProperty(Constants.OBJECTCLASS)).thenReturn("the class");
BundleContext bundleContext = mock(BundleContext.class);
when(bundleContext.getProperty(Constants.FRAMEWORK_UUID)).thenReturn("some-uuid");
when(bundleContext.getService(reference)).thenReturn(service);
when(bundleContext.getBundle(0)).thenReturn(mockSystemBundle);
Logger agentLogger = mock(Logger.class);
JMXAgentContext agentContext = mock(JMXAgentContext.class);
when(agentContext.getBundleContext()).thenReturn(bundleContext);
when(agentContext.getLogger()).thenReturn(agentLogger);
AbstractCompendiumHandler concreteHandler = new CompendiumHandler(agentContext, "org.osgi.service.Xxx");
target = spy(concreteHandler);
target.addingService(reference);
//service only got once
verify(bundleContext).getService(reference);
//template method is invoked
verify(target).constructInjectMBean(service);
//registration is invoked on context
verify(agentContext).registerMBean(target);
}
@Test
public void testRemovedServiceWillUnregisterMBean() throws Exception{
Object service = new Object();
ServiceReference reference = mock(ServiceReference.class);
when(reference.getProperty(Constants.SERVICE_ID)).thenReturn(1L);
when(reference.getProperty(Constants.OBJECTCLASS)).thenReturn("the class");
BundleContext bundleContext = mock(BundleContext.class);
Logger agentLogger = mock(Logger.class);
JMXAgentContext agentContext = mock(JMXAgentContext.class);
when(agentContext.getBundleContext()).thenReturn(bundleContext);
when(agentContext.getLogger()).thenReturn(agentLogger);
AbstractCompendiumHandler concreteHandler = new CompendiumHandler(agentContext, "org.osgi.service.Xxx");
target = spy(concreteHandler);
target.trackedId.set(1);
String name = "osgi.compendium:service=xxx,version=1.0";
doReturn(name).when(target).getName();
target.removedService(reference, service);
//service unget
verify(bundleContext).ungetService(reference);
//unregister is invoked on context
verify(agentContext).unregisterMBean(target);
}
/*
* Concrete implementation used for test
*/
class CompendiumHandler extends AbstractCompendiumHandler {
protected CompendiumHandler(JMXAgentContext agentContext, Filter filter) {
super(agentContext, filter);
}
protected CompendiumHandler(JMXAgentContext agentContext, String clazz) {
super(agentContext, clazz);
}
protected StandardMBean constructInjectMBean(Object targetService) {
return null;
}
public String getBaseName() {
return null;
}
}
}
| 8,073 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/useradmin/UserAdminTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.useradmin;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import org.apache.aries.jmx.codec.AuthorizationData;
import org.apache.aries.jmx.codec.GroupData;
import org.apache.aries.jmx.codec.RoleData;
import org.apache.aries.jmx.codec.UserData;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.osgi.jmx.JmxConstants;
import org.osgi.service.useradmin.Authorization;
import org.osgi.service.useradmin.Group;
import org.osgi.service.useradmin.Role;
import org.osgi.service.useradmin.User;
/**
* UserAdminMBean test case.
*
* @version $Rev$ $Date$
*/
public class UserAdminTest {
@Mock
private org.osgi.service.useradmin.UserAdmin userAdmin;
private UserAdmin mbean;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mbean = new UserAdmin(userAdmin);
}
/**
* Test method for
* {@link org.apache.aries.jmx.useradmin.UserAdmin#addCredential(java.lang.String, byte[], java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testAddCredential() throws IOException {
User user1 = Mockito.mock(User.class);
Dictionary<String, Object> credentials = new Hashtable<String, Object>();
Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getCredentials()).thenReturn(credentials);
mbean.addCredential("password", new byte[] { 1, 2 }, "user1");
Assert.assertArrayEquals(new byte[] { 1, 2 }, (byte[]) credentials.get("password"));
}
/**
* Test method for
* {@link org.apache.aries.jmx.useradmin.UserAdmin#addCredentialString(String, String, String)}
* .
*
* @throws IOException
*/
@Test
public void testAddCredentialString() throws IOException {
User user1 = Mockito.mock(User.class);
Dictionary<String, Object> credentials = new Hashtable<String, Object>();
Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getCredentials()).thenReturn(credentials);
mbean.addCredentialString("password", "1234", "user1");
Assert.assertEquals("1234", (String) credentials.get("password"));
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#addMember(java.lang.String, java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testAddMember() throws IOException {
Group group1 = Mockito.mock(Group.class);
User user1 = Mockito.mock(User.class);
Mockito.when(userAdmin.getRole("group1")).thenReturn(group1);
Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
Mockito.when(group1.getType()).thenReturn(Role.GROUP);
Mockito.when(group1.addMember(user1)).thenReturn(true);
boolean isAdded = mbean.addMember("group1", "user1");
Assert.assertTrue(isAdded);
Mockito.verify(group1).addMember(user1);
}
/**
* Test method for
* {@link org.apache.aries.jmx.useradmin.UserAdmin#addPropertyString(String, String, String)}
* .
*
* @throws IOException
*/
@Test
public void testAddPropertyString() throws IOException {
User user1 = Mockito.mock(User.class);
Dictionary<String, Object> props = new Hashtable<String, Object>();
Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getProperties()).thenReturn(props);
mbean.addPropertyString("key", "1234", "user1");
Assert.assertEquals("1234", (String) props.get("key"));
}
/**
* Test method for
* {@link org.apache.aries.jmx.useradmin.UserAdmin#addProperty(java.lang.String, byte[], java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testAddProperty() throws IOException {
User user1 = Mockito.mock(User.class);
Dictionary<String, Object> props = new Hashtable<String, Object>();
Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getProperties()).thenReturn(props);
mbean.addProperty("key", new byte[] { 1, 2 }, "user1");
Assert.assertArrayEquals(new byte[] { 1, 2 }, (byte[]) props.get("key"));
}
/**
* Test method for
* {@link org.apache.aries.jmx.useradmin.UserAdmin#addRequiredMember(java.lang.String, java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testAddRequiredMember() throws IOException {
Group group1 = Mockito.mock(Group.class);
User user1 = Mockito.mock(User.class);
Mockito.when(userAdmin.getRole("group1")).thenReturn(group1);
Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
Mockito.when(group1.getType()).thenReturn(Role.GROUP);
Mockito.when(group1.addRequiredMember(user1)).thenReturn(true);
boolean isAdded = mbean.addRequiredMember("group1", "user1");
Assert.assertTrue(isAdded);
Mockito.verify(group1).addRequiredMember(user1);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#createGroup(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testCreateGroup() throws IOException {
mbean.createGroup("group1");
Mockito.verify(userAdmin).createRole("group1", Role.GROUP);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#createRole(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testCreateRole() throws IOException {
try {
mbean.createRole("role1");
Assert.fail("Function did not throw exception as expected");
} catch (IOException e) {
// expected
}
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#createUser(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testCreateUser() throws IOException {
mbean.createUser("user1");
Mockito.verify(userAdmin).createRole("user1", Role.USER);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getAuthorization(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testGetAuthorization() throws IOException {
Authorization auth = Mockito.mock(Authorization.class);
User user = Mockito.mock(User.class);
Mockito.when(user.getType()).thenReturn(Role.USER);
Mockito.when(userAdmin.getAuthorization(user)).thenReturn(auth);
Mockito.when(userAdmin.getRole("role1")).thenReturn(user);
Mockito.when(auth.getName()).thenReturn("auth1");
Mockito.when(auth.getRoles()).thenReturn(new String[]{"role1"});
CompositeData data = mbean.getAuthorization("role1");
Assert.assertNotNull(data);
AuthorizationData authData = AuthorizationData.from(data);
Assert.assertNotNull(authData);
Assert.assertEquals("auth1", authData.getName());
Assert.assertArrayEquals(new String[] { "role1" }, authData.getRoles());
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getCredentials(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testGetCredentials() throws IOException {
User user1 = Mockito.mock(User.class);
Dictionary<String, Object> properties = new Hashtable<String, Object>();
properties.put("key", "value");
Mockito.when(user1.getCredentials()).thenReturn(properties);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(userAdmin.getRole(Mockito.anyString())).thenReturn(user1);
TabularData data = mbean.getCredentials("user1");
Assert.assertNotNull(data);
Assert.assertEquals(JmxConstants.PROPERTIES_TYPE, data.getTabularType());
CompositeData composite = data.get(new Object[] { "key" });
Assert.assertNotNull(composite);
Assert.assertEquals("key", (String) composite.get(JmxConstants.KEY));
Assert.assertEquals("value", (String) composite.get(JmxConstants.VALUE));
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getGroup(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testGetGroup() throws IOException {
Group group1 = Mockito.mock(Group.class);
Mockito.when(group1.getType()).thenReturn(Role.GROUP);
Mockito.when(group1.getName()).thenReturn("group1");
Role role1 = Mockito.mock(Role.class);
Mockito.when(role1.getName()).thenReturn("role1");
Role role2 = Mockito.mock(Role.class);
Mockito.when(role2.getName()).thenReturn("role2");
Mockito.when(group1.getRequiredMembers()).thenReturn(new Role[] { role1 });
Mockito.when(group1.getMembers()).thenReturn(new Role[] { role2 });
Mockito.when(userAdmin.getRole(Mockito.anyString())).thenReturn(group1);
CompositeData data = mbean.getGroup("group1");
Assert.assertNotNull(data);
GroupData group = GroupData.from(data);
Assert.assertNotNull(group);
Assert.assertEquals("group1", group.getName());
Assert.assertEquals(Role.GROUP, group.getType());
Assert.assertArrayEquals(new String[] { "role2" }, group.getMembers());
Assert.assertArrayEquals(new String[] { "role1" }, group.getRequiredMembers());
Mockito.verify(userAdmin).getRole(Mockito.anyString());
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getGroups(java.lang.String)}.
*
* @throws Exception
*/
@Test
public void testGetGroups() throws Exception {
Group group1 = Mockito.mock(Group.class);
Mockito.when(group1.getType()).thenReturn(Role.GROUP);
Mockito.when(group1.getName()).thenReturn("group1");
Mockito.when(userAdmin.getRoles("name=group1")).thenReturn(new Role[] { group1 });
String[] groups = mbean.getGroups("name=group1");
Assert.assertArrayEquals(new String[] { "group1" }, groups);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getImpliedRoles(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testGetImpliedRoles() throws IOException {
User user1 = Mockito.mock(User.class);
Authorization auth = Mockito.mock(Authorization.class);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(auth.getRoles()).thenReturn(new String[] { "role1" });
Mockito.when(userAdmin.getRole("role1")).thenReturn(user1);
Mockito.when(userAdmin.getAuthorization(user1)).thenReturn(auth);
String[] roles = mbean.getImpliedRoles("role1");
Assert.assertArrayEquals(new String[] { "role1" }, roles);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getMembers(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testGetMembers() throws IOException {
Group group1 = Mockito.mock(Group.class);
Mockito.when(group1.getType()).thenReturn(Role.GROUP);
Mockito.when(group1.getName()).thenReturn("group1");
User user1 = Mockito.mock(Group.class);
Mockito.when(user1.getName()).thenReturn("user1");
Mockito.when(group1.getMembers()).thenReturn(new Role[] { user1 });
Mockito.when(userAdmin.getRole("group1")).thenReturn(group1);
String[] members = mbean.getMembers("group1");
Assert.assertArrayEquals(new String[] { "user1" }, members);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getProperties(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testGetProperties() throws IOException {
User user1 = Mockito.mock(User.class);
Dictionary<String, Object> properties = new Hashtable<String, Object>();
properties.put("key", "value");
Mockito.when(user1.getProperties()).thenReturn(properties);
Mockito.when(userAdmin.getRole(Mockito.anyString())).thenReturn(user1);
TabularData data = mbean.getProperties("user1");
Assert.assertNotNull(data);
Assert.assertEquals(JmxConstants.PROPERTIES_TYPE, data.getTabularType());
CompositeData composite = data.get(new Object[] { "key" });
Assert.assertNotNull(composite);
Assert.assertEquals("key", (String) composite.get(JmxConstants.KEY));
Assert.assertEquals("value", (String) composite.get(JmxConstants.VALUE));
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getRequiredMembers(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testGetRequiredMembers() throws IOException {
Group group1 = Mockito.mock(Group.class);
Mockito.when(group1.getType()).thenReturn(Role.GROUP);
Mockito.when(group1.getName()).thenReturn("group1");
User user1 = Mockito.mock(Group.class);
Mockito.when(user1.getName()).thenReturn("user1");
Mockito.when(group1.getRequiredMembers()).thenReturn(new Role[] { user1 });
Mockito.when(userAdmin.getRole("group1")).thenReturn(group1);
String[] members = mbean.getRequiredMembers("group1");
Assert.assertArrayEquals(new String[] { "user1" }, members);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getRole(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testGetRole() throws IOException {
User user1 = Mockito.mock(User.class);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getName()).thenReturn("user1");
Mockito.when(userAdmin.getRole(Mockito.anyString())).thenReturn(user1);
CompositeData data = mbean.getRole("user1");
Assert.assertNotNull(data);
RoleData role = RoleData.from(data);
Assert.assertNotNull(role);
Assert.assertEquals("user1", role.getName());
Assert.assertEquals(Role.USER, role.getType());
Mockito.verify(userAdmin).getRole(Mockito.anyString());
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getRoles(java.lang.String)}.
*
* @throws Exception
*/
@Test
public void testGetRoles() throws Exception {
User user1 = Mockito.mock(User.class);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getName()).thenReturn("user1");
Mockito.when(userAdmin.getRoles("name=user1")).thenReturn(new Role[] { user1 });
String[] roles = mbean.getRoles("name=user1");
Assert.assertArrayEquals(new String[] { "user1" }, roles);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getUser(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testGetUser() throws IOException {
User user1 = Mockito.mock(User.class);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getName()).thenReturn("user1");
Mockito.when(userAdmin.getRole(Mockito.anyString())).thenReturn(user1);
CompositeData data = mbean.getUser("user1");
Assert.assertNotNull(data);
UserData user = UserData.from(data);
Assert.assertNotNull(user);
Assert.assertEquals("user1", user.getName());
Assert.assertEquals(Role.USER, user.getType());
Mockito.verify(userAdmin).getRole(Mockito.anyString());
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getUserWithProperty(String, String)}.
*
* @throws IOException
*/
@Test
public void testGetUserString() throws IOException {
User user1 = Mockito.mock(User.class);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getName()).thenReturn("user1");
Mockito.when(userAdmin.getUser("key", "valuetest")).thenReturn(user1);
String username = mbean.getUserWithProperty("key", "valuetest");
Assert.assertEquals(username, "user1");
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#getUsers(java.lang.String)}.
*
* @throws Exception
*/
@Test
public void testGetUsers() throws Exception {
User user1 = Mockito.mock(User.class);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getName()).thenReturn("user1");
Mockito.when(userAdmin.getRoles("name=user1")).thenReturn(new Role[] { user1 });
String[] roles = mbean.getUsers("name=user1");
Assert.assertArrayEquals(new String[] { "user1" }, roles);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#listGroups()}.
*
* @throws Exception
*/
@Test
public void testListGroups() throws Exception {
Group group1 = Mockito.mock(Group.class);
Mockito.when(group1.getType()).thenReturn(Role.GROUP);
Mockito.when(group1.getName()).thenReturn("group1");
Group group2 = Mockito.mock(Group.class);
Mockito.when(group2.getType()).thenReturn(Role.GROUP);
Mockito.when(group2.getName()).thenReturn("group2");
Mockito.when(userAdmin.getRoles(null)).thenReturn(new Role[] { group1, group2 });
String[] groups = mbean.listGroups();
Assert.assertArrayEquals(new String[] { "group1", "group2" }, groups);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#listRoles()}.
*
* @throws Exception
*/
@Test
public void testListRoles() throws Exception {
User user1 = Mockito.mock(User.class);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getName()).thenReturn("user1");
User user2 = Mockito.mock(User.class);
Mockito.when(user2.getType()).thenReturn(Role.USER);
Mockito.when(user2.getName()).thenReturn("user2");
Mockito.when(userAdmin.getRoles(null)).thenReturn(new Role[] { user1, user2 });
String[] roles = mbean.listRoles();
Assert.assertArrayEquals(new String[] { "user1", "user2" }, roles);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#listUsers()}.
*
* @throws Exception
*/
@Test
public void testListUsers() throws Exception {
User user1 = Mockito.mock(User.class);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getName()).thenReturn("user1");
User user2 = Mockito.mock(User.class);
Mockito.when(user2.getType()).thenReturn(Role.USER);
Mockito.when(user2.getName()).thenReturn("user2");
Mockito.when(userAdmin.getRoles(null)).thenReturn(new Role[] { user1, user2 });
String[] roles = mbean.listUsers();
Assert.assertArrayEquals(new String[] { "user1", "user2" }, roles);
}
/**
* Test method for
* {@link org.apache.aries.jmx.useradmin.UserAdmin#removeCredential(java.lang.String, java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testRemoveCredential() throws IOException {
User user1 = Mockito.mock(User.class);
Dictionary<String, Object> cred = new Hashtable<String, Object>();
Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getCredentials()).thenReturn(cred);
mbean.removeCredential("key", "user1");
Assert.assertEquals(0, cred.size());
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#removeGroup(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testRemoveGroup() throws IOException {
Mockito.when(userAdmin.removeRole("group1")).thenReturn(true);
boolean isRemoved = mbean.removeGroup("group1");
Assert.assertTrue(isRemoved);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#removeMember(java.lang.String, java.lang.String)}
* .
*
* @throws IOException
*/
@Test
public void testRemoveMember() throws IOException {
Group group1 = Mockito.mock(Group.class);
User user1 = Mockito.mock(User.class);
Mockito.when(userAdmin.getRole("group1")).thenReturn(group1);
Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
Mockito.when(group1.getType()).thenReturn(Role.GROUP);
Mockito.when(group1.removeMember(user1)).thenReturn(true);
boolean isAdded = mbean.removeMember("group1", "user1");
Assert.assertTrue(isAdded);
Mockito.verify(group1).removeMember(user1);
}
/**
* Test method for
* {@link org.apache.aries.jmx.useradmin.UserAdmin#removeProperty(java.lang.String, java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testRemoveProperty() throws IOException {
User user1 = Mockito.mock(User.class);
Dictionary<String, Object> props = new Hashtable<String, Object>();
Mockito.when(userAdmin.getRole("user1")).thenReturn(user1);
Mockito.when(user1.getType()).thenReturn(Role.USER);
Mockito.when(user1.getProperties()).thenReturn(props);
mbean.removeProperty("key", "user1");
Assert.assertEquals(0, props.size());
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#removeRole(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testRemoveRole() throws IOException {
Mockito.when(userAdmin.removeRole("role1")).thenReturn(true);
boolean isRemoved = mbean.removeRole("role1");
Assert.assertTrue(isRemoved);
}
/**
* Test method for {@link org.apache.aries.jmx.useradmin.UserAdmin#removeUser(java.lang.String)}.
*
* @throws IOException
*/
@Test
public void testRemoveUser() throws IOException {
Mockito.when(userAdmin.removeRole("user1")).thenReturn(true);
boolean isRemoved = mbean.removeUser("user1");
Assert.assertTrue(isRemoved);
}
}
| 8,074 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/util/FrameworkUtilsTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.util;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleDependencies;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleExportedPackages;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleIds;
import static org.apache.aries.jmx.util.FrameworkUtils.getBundleImportedPackages;
import static org.apache.aries.jmx.util.FrameworkUtils.getRegisteredServiceIds;
import static org.apache.aries.jmx.util.FrameworkUtils.getServiceIds;
import static org.apache.aries.jmx.util.FrameworkUtils.getServicesInUseByBundle;
import static org.apache.aries.jmx.util.FrameworkUtils.isBundlePendingRemoval;
import static org.apache.aries.jmx.util.FrameworkUtils.isBundleRequiredByOthers;
import static org.apache.aries.jmx.util.FrameworkUtils.resolveService;
import static org.junit.Assert.assertArrayEquals;
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.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.packageadmin.RequiredBundle;
/**
*
*
*
* @version $Rev$ $Date$
*/
public class FrameworkUtilsTest {
@Test
public void testGetBundleIds() throws Exception {
assertEquals(0, getBundleIds((Bundle[])null).length);
assertEquals(0, getBundleIds(new Bundle[0]).length);
Bundle b1 = mock(Bundle.class);
when(b1.getBundleId()).thenReturn(new Long(47));
Bundle b2 = mock(Bundle.class);
when(b2.getBundleId()).thenReturn(new Long(23));
assertArrayEquals(new long[] { 47 , 23 }, getBundleIds(new Bundle[] { b1, b2 }));
}
@Test
public void testResolveService() throws Exception {
BundleContext context = mock(BundleContext.class);
ServiceReference reference = mock(ServiceReference.class);
when(context.getAllServiceReferences(anyString(), anyString())).thenReturn(new ServiceReference[] { reference });
ServiceReference result = resolveService(context, 998);
assertNotNull(result);
}
@Test
public void testGetServiceIds() throws Exception {
assertEquals(0, getServiceIds(null).length);
assertEquals(0, getServiceIds(new ServiceReference[0]).length);
ServiceReference s1 = mock(ServiceReference.class);
when(s1.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(15));
ServiceReference s2 = mock(ServiceReference.class);
when(s2.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(5));
ServiceReference s3 = mock(ServiceReference.class);
when(s3.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(25));
assertArrayEquals(new long[] { 15, 5, 25 },
getServiceIds(new ServiceReference[] {s1, s2, s3} ) );
}
@Test
public void testGetBundleExportedPackages() throws Exception {
Bundle bundle = mock(Bundle.class);
PackageAdmin admin = mock(PackageAdmin.class);
assertEquals(0, getBundleExportedPackages(bundle, admin).length);
ExportedPackage exported = mock(ExportedPackage.class);
when(exported.getName()).thenReturn("org.apache.aries.jmx");
when(exported.getVersion()).thenReturn(new Version("1.0.0"));
when(admin.getExportedPackages(bundle)).thenReturn(new ExportedPackage[] { exported });
assertArrayEquals(new String[] { "org.apache.aries.jmx;1.0.0"} , getBundleExportedPackages(bundle, admin));
}
@Test
public void testGetBundleImportedPackages() throws Exception {
Bundle bundle = mock(Bundle.class);
BundleContext context = mock(BundleContext.class);
Bundle b1 = mock(Bundle.class);
Bundle b2 = mock(Bundle.class);
Bundle b3 = mock(Bundle.class);
when(context.getBundles()).thenReturn(new Bundle[] { bundle, b1, b2, b3 });
ExportedPackage ep1 = mock(ExportedPackage.class);
when(ep1.getImportingBundles()).thenReturn(new Bundle[] { bundle, b2, b3 });
when(ep1.getName()).thenReturn("org.apache.aries.jmx.b1");
when(ep1.getVersion()).thenReturn(Version.emptyVersion);
ExportedPackage ep2 = mock(ExportedPackage.class);
when(ep2.getImportingBundles()).thenReturn(new Bundle[] { bundle, b3 });
when(ep2.getName()).thenReturn("org.apache.aries.jmx.b2");
when(ep2.getVersion()).thenReturn(Version.parseVersion("2.0.1"));
PackageAdmin admin = mock(PackageAdmin.class);
when(admin.getExportedPackages(b1)).thenReturn(new ExportedPackage[] { ep1 });
when(admin.getExportedPackages(b2)).thenReturn(new ExportedPackage[] { ep2 });
when(admin.getExportedPackages(b3)).thenReturn(null);
//check first with DynamicImport
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(Constants.DYNAMICIMPORT_PACKAGE, "*");
when(bundle.getHeaders()).thenReturn(headers);
assertArrayEquals(new String[] { "org.apache.aries.jmx.b1;0.0.0" , "org.apache.aries.jmx.b2;2.0.1"}
, getBundleImportedPackages(context, bundle, admin));
//check with ImportPackage statement
headers.remove(Constants.DYNAMICIMPORT_PACKAGE);
String importPackageStatement = "org.apache.aries.jmx.b1;version=0.0.0;resolution:=optional,org.apache.aries.jmx.b2;attribute:=value;version=\"[2.0, 3.0)\"";
headers.put(Constants.IMPORT_PACKAGE, importPackageStatement);
when(admin.getExportedPackages("org.apache.aries.jmx.b1")).thenReturn(new ExportedPackage[] { ep1 });
when(admin.getExportedPackages("org.apache.aries.jmx.b2")).thenReturn(new ExportedPackage[] { ep2 });
assertArrayEquals(new String[] { "org.apache.aries.jmx.b1;0.0.0" , "org.apache.aries.jmx.b2;2.0.1"}
, getBundleImportedPackages(context, bundle, admin));
}
@Test
public void testGetRegisteredServiceIds() throws Exception {
Bundle bundle = mock(Bundle.class);
ServiceReference s1 = mock(ServiceReference.class);
when(s1.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(56));
ServiceReference s2 = mock(ServiceReference.class);
when(s2.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(5));
ServiceReference s3 = mock(ServiceReference.class);
when(s3.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(34));
when(bundle.getRegisteredServices()).thenReturn(new ServiceReference[] { s1, s2, s3 });
assertArrayEquals(new long[] { 56, 5, 34}, getRegisteredServiceIds(bundle));
}
@Test
public void testGetServicesInUseByBundle() throws Exception {
Bundle bundle = mock(Bundle.class);
ServiceReference s1 = mock(ServiceReference.class);
when(s1.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(15));
ServiceReference s2 = mock(ServiceReference.class);
when(s2.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(16));
ServiceReference s3 = mock(ServiceReference.class);
when(s3.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(17));
when(bundle.getServicesInUse()).thenReturn(new ServiceReference[] { s1, s2, s3 });
assertArrayEquals(new long[] { 15, 16, 17 }, getServicesInUseByBundle(bundle));
}
@Test
public void testIsBundlePendingRemoval() throws Exception {
Bundle bundle = mock(Bundle.class);
when(bundle.getSymbolicName()).thenReturn("org.apache.testb");
RequiredBundle reqBundle = mock(RequiredBundle.class);
when(reqBundle.getBundle()).thenReturn(bundle);
when(reqBundle.isRemovalPending()).thenReturn(true);
PackageAdmin admin = mock(PackageAdmin.class);
when(admin.getRequiredBundles("org.apache.testb")).thenReturn(new RequiredBundle[] { reqBundle });
assertTrue(isBundlePendingRemoval(bundle, admin));
}
@Test
public void testIsBundleRequiredByOthers() throws Exception {
Bundle bundle = mock(Bundle.class);
when(bundle.getSymbolicName()).thenReturn("org.apache.testb");
RequiredBundle reqBundle = mock(RequiredBundle.class);
when(reqBundle.getBundle()).thenReturn(bundle);
when(reqBundle.getRequiringBundles()).thenReturn(new Bundle[0]);
PackageAdmin admin = mock(PackageAdmin.class);
when(admin.getRequiredBundles("org.apache.testb")).thenReturn(new RequiredBundle[] { reqBundle });
assertFalse(isBundleRequiredByOthers(bundle, admin));
Bundle user = mock(Bundle.class);
when(reqBundle.getRequiringBundles()).thenReturn(new Bundle[] { user });
assertTrue(isBundleRequiredByOthers(bundle, admin));
}
@Test
public void testGetBundleDependencies() throws Exception {
Bundle bundle = mock(Bundle.class);
BundleContext context = mock(BundleContext.class);
Bundle b1 = mock(Bundle.class);
when(b1.getSymbolicName()).thenReturn("b1");
when(b1.getBundleId()).thenReturn(new Long(44));
Bundle b2 = mock(Bundle.class);
when(b2.getSymbolicName()).thenReturn("b2");
when(b2.getBundleId()).thenReturn(new Long(55));
Bundle b3 = mock(Bundle.class);
when(b3.getSymbolicName()).thenReturn("b3");
when(b3.getBundleId()).thenReturn(new Long(66));
when(context.getBundles()).thenReturn(new Bundle[] { bundle, b1, b2, b3 });
Dictionary<String, String> headers = new Hashtable<String, String>();
when(bundle.getHeaders()).thenReturn(headers);
PackageAdmin admin = mock(PackageAdmin.class);
assertEquals(0, getBundleDependencies(context, bundle, admin).length);
RequiredBundle rb1 = mock(RequiredBundle.class);
when(rb1.getBundle()).thenReturn(b1);
when(rb1.getRequiringBundles()).thenReturn(new Bundle[] { bundle, b2 });
RequiredBundle rb2 = mock(RequiredBundle.class);
when(rb2.getBundle()).thenReturn(b2);
when(rb2.getRequiringBundles()).thenReturn(new Bundle[] { b1 });
RequiredBundle rb3 = mock(RequiredBundle.class);
when(rb3.getBundle()).thenReturn(b3);
when(rb3.getRequiringBundles()).thenReturn(new Bundle[] { bundle, b1, b2 });
headers.put(Constants.REQUIRE_BUNDLE, "b1;bundle-version=\"1.0.0\",b3;bundle-version=\"2.0.0\"");
when(admin.getRequiredBundles("b1")).thenReturn(new RequiredBundle[] { rb1 });
when(admin.getRequiredBundles("b2")).thenReturn(new RequiredBundle[] { rb2 });
when(admin.getRequiredBundles("b3")).thenReturn(new RequiredBundle[] { rb3 });
assertEquals(toSet(new long[] { 44, 66 }), toSet(getBundleDependencies(context, bundle, admin)));
}
private static Set<Long> toSet(long[] array) {
Set<Long> set = new HashSet<Long>();
for (long value : array) {
set.add(value);
}
return set;
}
}
| 8,075 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/util/TypeUtilsTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.util;
import static org.apache.aries.jmx.util.TypeUtils.fromDictionary;
import static org.apache.aries.jmx.util.TypeUtils.fromString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Map;
import org.junit.Test;
public class TypeUtilsTest {
@Test
public void testMapFromDictionary() throws Exception{
Dictionary<String, String> dictionary = new Hashtable<String, String>();
dictionary.put("one", "1");
dictionary.put("two", "2");
Map<String,String> map = fromDictionary(dictionary);
assertEquals(2, map.size());
assertEquals("1", map.get("one"));
assertEquals("2", map.get("two"));
}
@Test
public void testFromString() throws Exception {
String value;
value = "1";
Integer integerValue = fromString(Integer.class, value);
assertEquals(new Integer(1), integerValue);
int intValue = fromString(Integer.TYPE, value);
assertEquals(1, intValue);
Long wrappedLongValue = fromString(Long.class, value);
assertEquals(Long.valueOf(1), wrappedLongValue);
long longValue = fromString(Long.TYPE, value);
assertEquals(1, longValue);
Double wrappedDoubleValue = fromString(Double.class, value);
assertEquals(Double.valueOf(1), wrappedDoubleValue);
double doubleValue = fromString(Double.TYPE, value);
assertEquals(1, doubleValue, 0);
Float wrappedFloatValue = fromString(Float.class, value);
assertEquals(Float.valueOf(1), wrappedFloatValue);
float floatValue = fromString(Float.TYPE, value);
assertEquals(1, floatValue, 0);
Short shortValue = fromString(Short.class, value);
assertEquals(Short.valueOf(value), shortValue);
Byte byteValue = fromString(Byte.class, value);
assertEquals(Byte.valueOf(value), byteValue);
value = "true";
assertTrue(fromString(Boolean.class, value));
assertTrue(fromString(Boolean.TYPE, value));
char charValue = fromString(Character.TYPE, "a");
assertEquals('a', charValue);
Character characterValue = fromString(Character.class, "a");
assertEquals(Character.valueOf('a'), characterValue);
BigDecimal bigDecimal = fromString(BigDecimal.class, "2");
assertEquals(new BigDecimal("2"), bigDecimal);
BigInteger bigInteger = fromString(BigInteger.class, "2");
assertEquals(new BigInteger("2"), bigInteger);
String stringValue = fromString(String.class, value);
assertEquals(stringValue, value);
}
}
| 8,076 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/framework/PackageStateTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import java.io.IOException;
import java.util.Collection;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Version;
import org.osgi.jmx.framework.PackageStateMBean;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
/**
* {@link PackageStateMBean} test case.
*
*
* @version $Rev$ $Date$
*/
public class PackageStateTest {
@Mock
private BundleContext context;
@Mock
private PackageAdmin admin;
private PackageState mbean;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mbean = new PackageState(context, admin);
}
@Test
public void testGetExportingBundles() throws IOException {
ExportedPackage exported = Mockito.mock(ExportedPackage.class);
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
Mockito.when(exported.getExportingBundle()).thenReturn(bundle);
Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(5));
ExportedPackage exported2 = Mockito.mock(ExportedPackage.class);
Bundle bundle2 = Mockito.mock(Bundle.class);
Mockito.when(exported2.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
Mockito.when(exported2.getExportingBundle()).thenReturn(bundle2);
Mockito.when(bundle2.getBundleId()).thenReturn(Long.valueOf(6));
Mockito.when(admin.getExportedPackages(Mockito.anyString())).thenReturn(new ExportedPackage[]{exported, exported2});
long[] ids = mbean.getExportingBundles("test", "1.0.0");
Assert.assertNotNull(ids);
Assert.assertArrayEquals(new long[]{5,6}, ids);
}
@Test
public void testGetImportingBundles() throws IOException {
ExportedPackage exported = Mockito.mock(ExportedPackage.class);
Bundle bundle = Mockito.mock(Bundle.class);
Bundle exportingBundle = Mockito.mock(Bundle.class);
Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
Mockito.when(exported.getExportingBundle()).thenReturn(exportingBundle);
Mockito.when(exportingBundle.getBundleId()).thenReturn(Long.valueOf(2));
Mockito.when(exported.getImportingBundles()).thenReturn(new Bundle[]{bundle});
Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(4));
Mockito.when(admin.getExportedPackages(Mockito.anyString())).thenReturn(new ExportedPackage[]{exported});
long[] ids = mbean.getImportingBundles("test", "1.0.0", 2);
Assert.assertArrayEquals(new long[]{4}, ids);
}
@Test
public void testIsRemovalPending() throws IOException {
ExportedPackage exported = Mockito.mock(ExportedPackage.class);
Bundle expBundle = Mockito.mock(Bundle.class);
Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
Mockito.when(exported.isRemovalPending()).thenReturn(true);
Mockito.when(exported.getExportingBundle()).thenReturn(expBundle);
Mockito.when(expBundle.getBundleId()).thenReturn(Long.valueOf(2));
Mockito.when(admin.getExportedPackages(Mockito.anyString())).thenReturn(new ExportedPackage[]{exported});
boolean isRemoval = mbean.isRemovalPending("test", "1.0.0", Long.valueOf(2));
Assert.assertTrue(isRemoval);
}
@Test
public void testListPackages() throws IOException {
Bundle bundle = Mockito.mock(Bundle.class);
Bundle impBundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundles()).thenReturn(new Bundle[]{bundle});
ExportedPackage exported = Mockito.mock(ExportedPackage.class);
Mockito.when(exported.getVersion()).thenReturn(Version.parseVersion("1.0.0"));
Mockito.when(exported.getImportingBundles()).thenReturn(new Bundle[]{impBundle});
Mockito.when(exported.getName()).thenReturn("test");
Mockito.when(exported.getExportingBundle()).thenReturn(bundle);
Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(4));
Mockito.when(impBundle.getBundleId()).thenReturn(Long.valueOf(5));
Mockito.when(admin.getExportedPackages(bundle)).thenReturn(new ExportedPackage[]{exported});
TabularData table = mbean.listPackages();
Assert.assertEquals(PackageStateMBean.PACKAGES_TYPE,table.getTabularType());
Collection values = table.values();
Assert.assertEquals(1, values.size());
CompositeData data = (CompositeData) values.iterator().next();
Long[] exportingBundles = (Long[])data.get(PackageStateMBean.EXPORTING_BUNDLES);
Assert.assertArrayEquals(new Long[]{Long.valueOf(4)}, exportingBundles);
String name = (String) data.get(PackageStateMBean.NAME);
Assert.assertEquals("test", name);
String version = (String) data.get(PackageStateMBean.VERSION);
Assert.assertEquals("1.0.0", version);
}
}
| 8,077 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/framework/BundleStateMBeanHandlerTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.agent.JMXAgent;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;
/**
*
*
* @version $Rev$ $Date$
*/
public class BundleStateMBeanHandlerTest {
@Test
public void testOpenAndClose() throws Exception {
BundleContext context = mock(BundleContext.class);
when(context.getProperty(Constants.FRAMEWORK_UUID)).thenReturn("some-uuid");
Logger logger = mock(Logger.class);
Bundle mockSystemBundle = mock(Bundle.class);
when(mockSystemBundle.getSymbolicName()).thenReturn("the.sytem.bundle");
when(context.getBundle(0)).thenReturn(mockSystemBundle);
ServiceReference packageAdminRef = mock(ServiceReference.class);
PackageAdmin packageAdmin = mock(PackageAdmin.class);
when(context.getServiceReference(PackageAdmin.class.getName())).thenReturn(packageAdminRef);
when(context.getService(packageAdminRef)).thenReturn(packageAdmin);
ServiceReference startLevelRef = mock(ServiceReference.class);
StartLevel startLevel = mock(StartLevel.class);
when(context.getServiceReference(StartLevel.class.getName())).thenReturn(startLevelRef);
when(context.getService(startLevelRef)).thenReturn(startLevel);
JMXAgent agent = mock(JMXAgent.class);
JMXAgentContext agentContext = new JMXAgentContext(context, agent, logger);
BundleStateMBeanHandler handler = new BundleStateMBeanHandler(agentContext, new StateConfig());
handler.open();
assertNotNull(handler.getMbean());
handler.close();
verify(context).ungetService(packageAdminRef);
verify(context).ungetService(startLevelRef);
}
}
| 8,078 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/framework/FrameworkTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import java.io.IOException;
import java.io.InputStream;
import javax.management.openmbean.CompositeData;
import org.apache.aries.jmx.codec.BatchActionResult;
import org.apache.aries.jmx.codec.BatchInstallResult;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.jmx.framework.FrameworkMBean;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;
/**
* {@link FrameworkMBean} test case.
*
*
* @version $Rev$ $Date$
*/
public class FrameworkTest {
@Mock
private StartLevel startLevel;
@Mock
private PackageAdmin admin;
@Mock
private BundleContext context;
private Framework mbean;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mbean = new Framework(context, startLevel, admin);
}
@Test
public void testGetFrameworkStartLevel() throws IOException {
Mockito.when(startLevel.getStartLevel()).thenReturn(1);
int level = mbean.getFrameworkStartLevel();
Assert.assertEquals(1, level);
}
@Test
public void testGetInitialBundleStartLevel() throws IOException {
Mockito.when(startLevel.getInitialBundleStartLevel()).thenReturn(2);
int level = mbean.getInitialBundleStartLevel();
Mockito.verify(startLevel).getInitialBundleStartLevel();
Assert.assertEquals(2, level);
}
@Test
public void testInstallBundle() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.installBundle("file:test.jar")).thenReturn(bundle);
Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(2));
long bundleId = mbean.installBundle("file:test.jar");
Assert.assertEquals(2, bundleId);
Mockito.reset(context);
Mockito.when(context.installBundle("file:test2.jar")).thenThrow(new BundleException("location doesn't exist"));
try {
mbean.installBundle("file:test2.jar");
Assert.fail("Shouldn't go to this stage, location doesn't exist");
} catch (IOException e) {
// ok
}
}
@Test
public void testInstallBundleFromURL() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.installBundle(Mockito.anyString(), Mockito.any(InputStream.class))).thenReturn(bundle);
Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(2));
Framework spiedMBean = Mockito.spy(mbean);
InputStream stream = Mockito.mock(InputStream.class);
Mockito.doReturn(stream).when(spiedMBean).createStream("test.jar");
long bundleId = spiedMBean.installBundleFromURL("file:test.jar", "test.jar");
Assert.assertEquals(2, bundleId);
Mockito.reset(context);
Mockito.doReturn(stream).when(spiedMBean).createStream(Mockito.anyString());
Mockito.when(context.installBundle(Mockito.anyString(), Mockito.any(InputStream.class))).thenThrow(
new BundleException("location doesn't exist"));
try {
spiedMBean.installBundleFromURL("file:test2.jar", "test.jar");
Assert.fail("Shouldn't go to this stage, location doesn't exist");
} catch (IOException e) {
// ok
}
}
@Test
public void testInstallBundles() throws Exception {
String[] locations = new String[] { "file:test.jar" };
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.installBundle("file:test.jar")).thenReturn(bundle);
Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(2));
CompositeData data = mbean.installBundles(locations);
BatchInstallResult batch = BatchInstallResult.from(data);
Assert.assertNotNull(batch);
Assert.assertEquals(2, batch.getCompleted()[0]);
Assert.assertTrue(batch.isSuccess());
Assert.assertNull(batch.getError());
Assert.assertNull(batch.getRemainingLocationItems());
Mockito.reset(context);
Mockito.when(context.installBundle("file:test.jar")).thenThrow(new BundleException("location doesn't exist"));
CompositeData data2 = mbean.installBundles(locations);
BatchInstallResult batch2 = BatchInstallResult.from(data2);
Assert.assertNotNull(batch2);
Assert.assertNotNull(batch2.getCompleted());
Assert.assertEquals(0, batch2.getCompleted().length);
Assert.assertFalse(batch2.isSuccess());
Assert.assertNotNull(batch2.getError());
Assert.assertEquals("file:test.jar", batch2.getBundleInError());
Assert.assertNotNull(batch2.getRemainingLocationItems());
Assert.assertEquals(0, batch2.getRemainingLocationItems().length);
}
@Test
public void testInstallBundlesFromURL() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.installBundle(Mockito.anyString(), Mockito.any(InputStream.class))).thenReturn(bundle);
Mockito.when(bundle.getBundleId()).thenReturn(Long.valueOf(2));
Framework spiedMBean = Mockito.spy(mbean);
InputStream stream = Mockito.mock(InputStream.class);
Mockito.doReturn(stream).when(spiedMBean).createStream(Mockito.anyString());
CompositeData data = spiedMBean.installBundlesFromURL(new String[] { "file:test.jar" }, new String[] { "test.jar" });
Assert.assertNotNull(data);
BatchInstallResult batch = BatchInstallResult.from(data);
Assert.assertEquals(2, batch.getCompleted()[0]);
Assert.assertTrue(batch.isSuccess());
Assert.assertNull(batch.getError());
Assert.assertNull(batch.getRemainingLocationItems());
Mockito.reset(context);
Mockito.when(spiedMBean.createStream(Mockito.anyString())).thenReturn(stream);
Mockito.when(context.installBundle(Mockito.anyString(), Mockito.any(InputStream.class))).thenThrow(
new BundleException("location doesn't exist"));
CompositeData data2 = spiedMBean.installBundlesFromURL(new String[] { "file:test.jar" }, new String[] { "test.jar" });
BatchInstallResult batch2 = BatchInstallResult.from(data2);
Assert.assertNotNull(batch2);
Assert.assertNotNull(batch2.getCompleted());
Assert.assertEquals(0, batch2.getCompleted().length);
Assert.assertFalse(batch2.isSuccess());
Assert.assertNotNull(batch2.getError());
Assert.assertEquals("file:test.jar", batch2.getBundleInError());
Assert.assertNotNull(batch2.getRemainingLocationItems());
Assert.assertEquals(0, batch2.getRemainingLocationItems().length);
}
@Test
public void testRefreshBundle() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(1)).thenReturn(bundle);
mbean.refreshBundle(1);
Mockito.verify(admin).refreshPackages((Bundle[]) Mockito.any());
try {
mbean.refreshBundle(2);
Assert.fail("IOException should be thrown");
} catch (IOException e) {
// expected
}
}
@Test
public void testRefreshBundles() throws IOException {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(1)).thenReturn(bundle);
mbean.refreshBundles(new long[] { 1 });
Mockito.verify(admin).refreshPackages((Bundle[]) Mockito.any());
mbean.refreshBundles(null);
Mockito.verify(admin).refreshPackages(null);
}
@Test
public void testResolveBundle() throws IOException {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(1)).thenReturn(bundle);
mbean.resolveBundle(1);
Mockito.verify(admin).resolveBundles(new Bundle[] { bundle });
}
@Test
public void testResolveBundles() throws IOException {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(1)).thenReturn(bundle);
// Mockito.when(context.getBundles()).thenReturn(new Bundle [] { bundle });
mbean.resolveBundles(new long[] { 1 });
Mockito.verify(admin).resolveBundles(new Bundle[] { bundle });
mbean.resolveBundles(null);
Mockito.verify(admin).resolveBundles(null);
}
@Test
public void testRestartFramework() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(0)).thenReturn(bundle);
mbean.restartFramework();
Mockito.verify(bundle).update();
}
@Test
public void testSetBundleStartLevel() throws IOException {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(2)).thenReturn(bundle);
mbean.setBundleStartLevel(2, 1);
Mockito.verify(startLevel).setBundleStartLevel(bundle, 1);
}
@Test
public void testSetBundleStartLevels() throws IOException {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(2)).thenReturn(bundle);
CompositeData data = mbean.setBundleStartLevels(new long[] { 2 }, new int[] { 2 });
Mockito.verify(startLevel).setBundleStartLevel(bundle, 2);
BatchActionResult batch = BatchActionResult.from(data);
Assert.assertEquals(2, batch.getCompleted()[0]);
Assert.assertTrue(batch.isSuccess());
Assert.assertNull(batch.getError());
Assert.assertNull(batch.getRemainingItems());
CompositeData data2 = mbean.setBundleStartLevels(new long[] { 2 }, new int[] { 2, 4 });
BatchActionResult batch2 = BatchActionResult.from(data2);
Assert.assertNull(batch2.getCompleted());
Assert.assertFalse(batch2.isSuccess());
Assert.assertNotNull(batch2.getError());
Assert.assertNull(batch2.getRemainingItems());
}
@Test
public void testSetFrameworkStartLevel() throws IOException {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(0)).thenReturn(bundle);
mbean.setFrameworkStartLevel(1);
Mockito.verify(startLevel).setStartLevel(1);
}
@Test
public void testSetInitialBundleStartLevel() throws IOException {
mbean.setInitialBundleStartLevel(5);
Mockito.verify(startLevel).setInitialBundleStartLevel(5);
}
@Test
public void testShutdownFramework() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(0)).thenReturn(bundle);
mbean.shutdownFramework();
Mockito.verify(bundle).stop();
}
@Test
public void testStartBundle() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(5)).thenReturn(bundle);
mbean.startBundle(5);
Mockito.verify(bundle).start();
Mockito.reset(context);
Mockito.when(context.getBundle(6)).thenReturn(bundle);
Mockito.doThrow(new BundleException("")).when(bundle).start();
try {
mbean.startBundle(6);
Assert.fail("Shouldn't go to this stage, BundleException was thrown");
} catch (IOException ioe) {
// expected
}
Mockito.when(context.getBundle(6)).thenReturn(null);
try {
mbean.startBundle(6);
Assert.fail("IOException should be thrown");
} catch (IOException e) {
//expected
}
}
@Test
public void testStartBundles() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(5)).thenReturn(bundle);
CompositeData data = mbean.startBundles(new long[] { 5 });
Mockito.verify(bundle).start();
BatchActionResult batch = BatchActionResult.from(data);
Assert.assertEquals(5, batch.getCompleted()[0]);
Assert.assertTrue(batch.isSuccess());
Assert.assertNull(batch.getError());
Assert.assertNull(batch.getRemainingItems());
CompositeData data2 = mbean.startBundles(null);
BatchActionResult batch2 = BatchActionResult.from(data2);
Assert.assertNull(batch2.getCompleted());
Assert.assertFalse(batch2.isSuccess());
Assert.assertNotNull(batch2.getError());
Assert.assertNull(batch2.getRemainingItems());
}
@Test
public void testStopBundle() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(5)).thenReturn(bundle);
mbean.stopBundle(5);
Mockito.verify(bundle).stop();
Mockito.when(context.getBundle(5)).thenReturn(null);
try {
mbean.stopBundle(5);
Assert.fail("IOException should be thrown");
} catch (IOException e) {
//expected
}
}
@Test
public void testStopBundles() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(5)).thenReturn(bundle);
CompositeData data = mbean.stopBundles(new long[] { 5 });
Mockito.verify(bundle).stop();
BatchActionResult batch = BatchActionResult.from(data);
Assert.assertEquals(5, batch.getCompleted()[0]);
Assert.assertTrue(batch.isSuccess());
Assert.assertNull(batch.getError());
Assert.assertNull(batch.getRemainingItems());
CompositeData data2 = mbean.stopBundles(null);
BatchActionResult batch2 = BatchActionResult.from(data2);
Assert.assertNull(batch2.getCompleted());
Assert.assertFalse(batch2.isSuccess());
Assert.assertNotNull(batch2.getError());
Assert.assertNull(batch2.getRemainingItems());
}
@Test
public void testUninstallBundle() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(5)).thenReturn(bundle);
mbean.uninstallBundle(5);
Mockito.verify(bundle).uninstall();
}
@Test
public void testUninstallBundles() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(5)).thenReturn(bundle);
CompositeData data = mbean.uninstallBundles(new long[] { 5 });
Mockito.verify(bundle).uninstall();
BatchActionResult batch = BatchActionResult.from(data);
Assert.assertEquals(5, batch.getCompleted()[0]);
Assert.assertTrue(batch.isSuccess());
Assert.assertNull(batch.getError());
Assert.assertNull(batch.getRemainingItems());
CompositeData data2 = mbean.uninstallBundles(null);
BatchActionResult batch2 = BatchActionResult.from(data2);
Assert.assertNull(batch2.getCompleted());
Assert.assertFalse(batch2.isSuccess());
Assert.assertNotNull(batch2.getError());
Assert.assertNull(batch2.getRemainingItems());
}
@Test
public void testUpdateBundle() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(5)).thenReturn(bundle);
mbean.updateBundle(5);
Mockito.verify(bundle).update();
}
@Test
public void testUpdateBundleFromUrl() throws Exception {
Framework spiedMBean = Mockito.spy(mbean);
InputStream stream = Mockito.mock(InputStream.class);
Mockito.doReturn(stream).when(spiedMBean).createStream(Mockito.anyString());
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(5)).thenReturn(bundle);
spiedMBean.updateBundleFromURL(5, "file:test.jar");
Mockito.verify(bundle).update(stream);
}
@Test
public void testUpdateBundles() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(5)).thenReturn(bundle);
CompositeData data = mbean.updateBundles(new long[] { 5 });
Mockito.verify(bundle).update();
BatchActionResult batch = BatchActionResult.from(data);
Assert.assertEquals(5, batch.getCompleted()[0]);
Assert.assertTrue(batch.isSuccess());
Assert.assertNull(batch.getError());
Assert.assertNull(batch.getRemainingItems());
CompositeData data2 = mbean.updateBundles(null);
BatchActionResult batch2 = BatchActionResult.from(data2);
Assert.assertNull(batch2.getCompleted());
Assert.assertFalse(batch2.isSuccess());
Assert.assertNotNull(batch2.getError());
Assert.assertNull(batch2.getRemainingItems());
Mockito.reset(bundle);
CompositeData data3 = mbean.updateBundles(new long[] { 6 });
Mockito.when(context.getBundle(6)).thenReturn(bundle);
Mockito.doThrow(new BundleException("")).when(bundle).update();
BatchActionResult batch3 = BatchActionResult.from(data3);
Assert.assertEquals(0, batch3.getCompleted().length);
Assert.assertFalse(batch3.isSuccess());
Assert.assertNotNull(batch3.getError());
Assert.assertEquals(6, batch3.getBundleInError());
Bundle bundle6 = Mockito.mock(Bundle.class);
Bundle bundle8 = Mockito.mock(Bundle.class);
Bundle bundle7 = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(6)).thenReturn(bundle6);
Mockito.when(context.getBundle(8)).thenReturn(bundle8);
Mockito.when(context.getBundle(7)).thenReturn(bundle7);
Mockito.doThrow(new BundleException("")).when(bundle8).update();
CompositeData data4 = mbean.updateBundles(new long[] { 6, 8, 7 });
BatchActionResult batch4 = BatchActionResult.from(data4);
Mockito.verify(bundle6).update();
Assert.assertEquals(1, batch4.getCompleted().length);
// should contain only bundleid 6
Assert.assertEquals(6, batch4.getCompleted()[0]);
Assert.assertFalse(batch4.isSuccess());
Assert.assertNotNull(batch4.getError());
Assert.assertEquals(8, batch4.getBundleInError());
Assert.assertEquals(1, batch4.getRemainingItems().length);
// should contain only bundleid 7
Assert.assertEquals(7, batch4.getRemainingItems()[0]);
}
@Test
public void testUpdateBundlesFromURL() throws Exception {
Framework spiedMBean = Mockito.spy(mbean);
InputStream stream = Mockito.mock(InputStream.class);
Mockito.doReturn(stream).when(spiedMBean).createStream(Mockito.anyString());
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(5)).thenReturn(bundle);
CompositeData data = spiedMBean.updateBundlesFromURL(new long[] { 5 }, new String[] { "file:test.jar" });
Mockito.verify(bundle).update(stream);
BatchActionResult batch = BatchActionResult.from(data);
Assert.assertEquals(5, batch.getCompleted()[0]);
Assert.assertTrue(batch.isSuccess());
Assert.assertNull(batch.getError());
Assert.assertNull(batch.getRemainingItems());
CompositeData data2 = spiedMBean.updateBundlesFromURL(new long[] { 2, 4 }, new String[] { "file:test.jar" });
BatchActionResult batch2 = BatchActionResult.from(data2);
Assert.assertFalse(batch2.isSuccess());
Assert.assertNotNull(batch2.getError());
Assert.assertNotNull(batch2.getError());
Assert.assertNull(batch2.getRemainingItems());
}
@Test
public void testUpdateFramework() throws Exception {
Bundle bundle = Mockito.mock(Bundle.class);
Mockito.when(context.getBundle(0)).thenReturn(bundle);
mbean.restartFramework();
Mockito.verify(bundle).update();
}
}
| 8,079 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/framework/ServiceStateMBeanHandlerTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.agent.JMXAgent;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
/**
*
*
* @version $Rev$ $Date$
*/
public class ServiceStateMBeanHandlerTest {
@Test
public void testOpen() throws Exception {
BundleContext context = mock(BundleContext.class);
when(context.getProperty(Constants.FRAMEWORK_UUID)).thenReturn("some-uuid");
Logger logger = mock(Logger.class);
Bundle mockSystemBundle = mock(Bundle.class);
when(mockSystemBundle.getSymbolicName()).thenReturn("the.sytem.bundle");
when(context.getBundle(0)).thenReturn(mockSystemBundle);
JMXAgent agent = mock(JMXAgent.class);
JMXAgentContext agentContext = new JMXAgentContext(context, agent, logger);
ServiceStateMBeanHandler handler = new ServiceStateMBeanHandler(agentContext, new StateConfig());
handler.open();
assertNotNull(handler.getMbean());
}
}
| 8,080 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/framework/ServiceStateTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.junit.Assert.assertArrayEquals;
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.mockito.Mockito.atMost;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_IDENTIFIER;
import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_LOCATION;
import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_SYMBOLIC_NAME;
import static org.osgi.jmx.framework.ServiceStateMBean.EVENT;
import static org.osgi.jmx.framework.ServiceStateMBean.IDENTIFIER;
import static org.osgi.jmx.framework.ServiceStateMBean.OBJECTNAME;
import static org.osgi.jmx.framework.ServiceStateMBean.OBJECT_CLASS;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import javax.management.AttributeChangeNotification;
import javax.management.MBeanServer;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import org.apache.aries.jmx.Logger;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.osgi.framework.AllServiceListener;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
/**
*
*
* @version $Rev$ $Date$
*/
public class ServiceStateTest {
private void createService(StateConfig stateConfig, final List<Notification> received,
final List<AttributeChangeNotification> attributeChanges) throws Exception {
BundleContext context = mock(BundleContext.class);
Logger logger = mock(Logger.class);
ServiceState serviceState = new ServiceState(context, stateConfig, logger);
ServiceReference reference = mock(ServiceReference.class);
Bundle b1 = mock(Bundle.class);
when(b1.getBundleId()).thenReturn(new Long(9));
when(b1.getSymbolicName()).thenReturn("bundle");
when(b1.getLocation()).thenReturn("file:/location");
when(reference.getBundle()).thenReturn(b1);
when(reference.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(44));
when(reference.getProperty(Constants.OBJECTCLASS)).thenReturn(new String[] {"org.apache.aries.jmx.Mock"});
when(context.getAllServiceReferences(null, null)).thenReturn(new ServiceReference[] {reference});
ServiceEvent registeredEvent = mock(ServiceEvent.class);
when(registeredEvent.getServiceReference()).thenReturn(reference);
when(registeredEvent.getType()).thenReturn(ServiceEvent.REGISTERED);
ServiceEvent modifiedEvent = mock(ServiceEvent.class);
when(modifiedEvent.getServiceReference()).thenReturn(reference);
when(modifiedEvent.getType()).thenReturn(ServiceEvent.MODIFIED);
MBeanServer server = mock(MBeanServer.class);
//setup for notification
ObjectName objectName = new ObjectName(OBJECTNAME);
serviceState.preRegister(server, objectName);
serviceState.postRegister(true);
//add NotificationListener to receive the events
serviceState.addNotificationListener(new NotificationListener() {
public void handleNotification(Notification notification, Object handback) {
if (notification instanceof AttributeChangeNotification) {
attributeChanges.add((AttributeChangeNotification) notification);
} else {
received.add(notification);
}
}
}, null, null);
// capture the ServiceListener registered with BundleContext to issue ServiceEvents
ArgumentCaptor<AllServiceListener> argument = ArgumentCaptor.forClass(AllServiceListener.class);
verify(context).addServiceListener(argument.capture());
//send events
AllServiceListener serviceListener = argument.getValue();
serviceListener.serviceChanged(registeredEvent);
serviceListener.serviceChanged(modifiedEvent);
//shutdown dispatcher via unregister callback
serviceState.postDeregister();
//check the ServiceListener is cleaned up
verify(context).removeServiceListener(serviceListener);
ExecutorService dispatcher = serviceState.getEventDispatcher();
assertTrue(dispatcher.isShutdown());
dispatcher.awaitTermination(2, TimeUnit.SECONDS);
assertTrue(dispatcher.isTerminated());
}
@Test
public void testNotificationsForServiceEvents() throws Exception {
StateConfig stateConfig = new StateConfig();
//holders for Notifications captured
List<Notification> received = new LinkedList<Notification>();
List<AttributeChangeNotification> attributeChanges = new LinkedList<AttributeChangeNotification>();
createService(stateConfig, received, attributeChanges);
assertEquals(2, received.size());
Notification registered = received.get(0);
assertEquals(1, registered.getSequenceNumber());
CompositeData data = (CompositeData) registered.getUserData();
assertEquals(new Long(44), data.get(IDENTIFIER));
assertEquals(new Long(9), data.get(BUNDLE_IDENTIFIER));
assertEquals("file:/location", data.get(BUNDLE_LOCATION));
assertEquals("bundle", data.get(BUNDLE_SYMBOLIC_NAME));
assertArrayEquals(new String[] {"org.apache.aries.jmx.Mock" }, (String[]) data.get(OBJECT_CLASS));
assertEquals(ServiceEvent.REGISTERED, data.get(EVENT));
Notification modified = received.get(1);
assertEquals(2, modified.getSequenceNumber());
data = (CompositeData) modified.getUserData();
assertEquals(new Long(44), data.get(IDENTIFIER));
assertEquals(new Long(9), data.get(BUNDLE_IDENTIFIER));
assertEquals("file:/location", data.get(BUNDLE_LOCATION));
assertEquals("bundle", data.get(BUNDLE_SYMBOLIC_NAME));
assertArrayEquals(new String[] {"org.apache.aries.jmx.Mock" }, (String[]) data.get(OBJECT_CLASS));
assertEquals(ServiceEvent.MODIFIED, data.get(EVENT));
assertEquals(1, attributeChanges.size());
AttributeChangeNotification ac = attributeChanges.get(0);
assertEquals("ServiceIds", ac.getAttributeName());
assertEquals(0, ((long [])ac.getOldValue()).length);
assertEquals(1, ((long [])ac.getNewValue()).length);
assertEquals(44L, ((long [])ac.getNewValue())[0]);
}
@Test
public void testNotificationsForServiceEventsDisabled() throws Exception {
StateConfig stateConfig = new StateConfig();
stateConfig.setServiceChangeNotificationEnabled(false);
//holders for Notifications captured
List<Notification> received = new LinkedList<Notification>();
List<AttributeChangeNotification> attributeChanges = new LinkedList<AttributeChangeNotification>();
createService(stateConfig, received, attributeChanges);
assertEquals(0, received.size());
}
@Test
public void testLifeCycleOfNotificationSupport() throws Exception {
BundleContext context = mock(BundleContext.class);
Logger logger = mock(Logger.class);
ServiceState serviceState = new ServiceState(context, new StateConfig(), logger);
MBeanServer server1 = mock(MBeanServer.class);
MBeanServer server2 = mock(MBeanServer.class);
ObjectName objectName = new ObjectName(OBJECTNAME);
serviceState.preRegister(server1, objectName);
serviceState.postRegister(true);
// capture the ServiceListener registered with BundleContext to issue ServiceEvents
ArgumentCaptor<AllServiceListener> argument = ArgumentCaptor.forClass(AllServiceListener.class);
verify(context).addServiceListener(argument.capture());
AllServiceListener serviceListener = argument.getValue();
assertNotNull(serviceListener);
ExecutorService dispatcher = serviceState.getEventDispatcher();
//do registration with another server
serviceState.preRegister(server2, objectName);
serviceState.postRegister(true);
// check no more actions on BundleContext
argument = ArgumentCaptor.forClass(AllServiceListener.class);
verify(context, atMost(1)).addServiceListener(argument.capture());
assertEquals(1, argument.getAllValues().size());
//do one unregister
serviceState.postDeregister();
//verify bundleListener not invoked
verify(context, never()).removeServiceListener(serviceListener);
assertFalse(dispatcher.isShutdown());
//do second unregister and check cleanup
serviceState.postDeregister();
verify(context).removeServiceListener(serviceListener);
assertTrue(dispatcher.isShutdown());
dispatcher.awaitTermination(2, TimeUnit.SECONDS);
assertTrue(dispatcher.isTerminated());
}
@Test
public void testAttributeNotificationDisabled() throws Exception {
StateConfig stateConfig = new StateConfig();
stateConfig.setAttributeChangeNotificationEnabled(false);
//holders for Notifications captured
List<AttributeChangeNotification> attributeChanges = new LinkedList<AttributeChangeNotification>();
createService(stateConfig, new LinkedList<Notification>(), attributeChanges);
assertEquals(0, attributeChanges.size());
}
}
| 8,081 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/framework/BundleStateTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.framework;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.osgi.jmx.framework.BundleStateMBean.OBJECTNAME;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import javax.management.AttributeChangeNotification;
import javax.management.MBeanServer;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.codec.BundleEventData;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;
public class BundleStateTest {
private void createBundle(StateConfig stateConfig, final List<Notification> received,
final List<AttributeChangeNotification> attributeChanges) throws Exception {
BundleContext context = mock(BundleContext.class);
when(context.getBundles()).thenReturn(new Bundle [] {});
PackageAdmin admin = mock(PackageAdmin.class);
StartLevel startLevel = mock(StartLevel.class);
Logger logger = mock(Logger.class);
BundleState bundleState = new BundleState(context, admin, startLevel, stateConfig, logger);
Bundle b1 = mock(Bundle.class);
when(b1.getBundleId()).thenReturn(new Long(9));
when(b1.getSymbolicName()).thenReturn("bundle");
when(b1.getLocation()).thenReturn("file:/location");
BundleEvent installedEvent = mock(BundleEvent.class);
when(installedEvent.getBundle()).thenReturn(b1);
when(installedEvent.getType()).thenReturn(BundleEvent.INSTALLED);
BundleEvent resolvedEvent = mock(BundleEvent.class);
when(resolvedEvent.getBundle()).thenReturn(b1);
when(resolvedEvent.getType()).thenReturn(BundleEvent.RESOLVED);
MBeanServer server = mock(MBeanServer.class);
//setup for notification
ObjectName objectName = new ObjectName(OBJECTNAME);
bundleState.preRegister(server, objectName);
bundleState.postRegister(true);
//add NotificationListener to receive the events
bundleState.addNotificationListener(new NotificationListener() {
public void handleNotification(Notification notification, Object handback) {
if (notification instanceof AttributeChangeNotification) {
attributeChanges.add((AttributeChangeNotification) notification);
} else {
received.add(notification);
}
}
}, null, null);
// capture the BundleListener registered with BundleContext to issue BundleEvents
ArgumentCaptor<BundleListener> argument = ArgumentCaptor.forClass(BundleListener.class);
verify(context).addBundleListener(argument.capture());
//send events
BundleListener listener = argument.getValue();
listener.bundleChanged(installedEvent);
listener.bundleChanged(resolvedEvent);
//shutdown dispatcher via unregister callback
bundleState.postDeregister();
//check the BundleListener is cleaned up
verify(context).removeBundleListener(listener);
ExecutorService dispatcher = bundleState.getEventDispatcher();
assertTrue(dispatcher.isShutdown());
dispatcher.awaitTermination(2, TimeUnit.SECONDS);
assertTrue(dispatcher.isTerminated());
}
@Test
public void testNotificationsForBundleEvents() throws Exception {
StateConfig stateConfig = new StateConfig();
//holders for Notifications captured
List<Notification> received = new LinkedList<Notification>();
List<AttributeChangeNotification> attributeChanges = new LinkedList<AttributeChangeNotification>();
createBundle(stateConfig, received, attributeChanges);
assertEquals(2, received.size());
Notification installed = received.get(0);
assertEquals(1, installed.getSequenceNumber());
CompositeData installedCompositeData = (CompositeData) installed.getUserData();
BundleEventData installedData = BundleEventData.from(installedCompositeData);
assertEquals("bundle", installedData.getBundleSymbolicName());
assertEquals(9, installedData.getBundleId());
assertEquals("file:/location", installedData.getLocation());
assertEquals(BundleEvent.INSTALLED, installedData.getEventType());
Notification resolved = received.get(1);
assertEquals(2, resolved.getSequenceNumber());
CompositeData resolvedCompositeData = (CompositeData) resolved.getUserData();
BundleEventData resolvedData = BundleEventData.from(resolvedCompositeData);
assertEquals("bundle", resolvedData.getBundleSymbolicName());
assertEquals(9, resolvedData.getBundleId());
assertEquals("file:/location", resolvedData.getLocation());
assertEquals(BundleEvent.RESOLVED, resolvedData.getEventType());
assertEquals(1, attributeChanges.size());
AttributeChangeNotification ac = attributeChanges.get(0);
assertEquals("BundleIds", ac.getAttributeName());
assertEquals(0, ((long [])ac.getOldValue()).length);
assertEquals(1, ((long [])ac.getNewValue()).length);
assertEquals(9L, ((long [])ac.getNewValue())[0]);
}
@Test
public void testNotificationsForBundleEventsDisabled() throws Exception {
StateConfig stateConfig = new StateConfig();
stateConfig.setBundleChangeNotificationEnabled(false);
//holders for Notifications captured
List<Notification> received = new LinkedList<Notification>();
List<AttributeChangeNotification> attributeChanges = new LinkedList<AttributeChangeNotification>();
createBundle(stateConfig, received, attributeChanges);
assertEquals(0, received.size());
}
@Test
public void testLifeCycleOfNotificationSupport() throws Exception {
BundleContext context = mock(BundleContext.class);
PackageAdmin admin = mock(PackageAdmin.class);
StartLevel startLevel = mock(StartLevel.class);
Logger logger = mock(Logger.class);
BundleState bundleState = new BundleState(context, admin, startLevel, new StateConfig(), logger);
MBeanServer server1 = mock(MBeanServer.class);
MBeanServer server2 = mock(MBeanServer.class);
ObjectName objectName = new ObjectName(OBJECTNAME);
bundleState.preRegister(server1, objectName);
bundleState.postRegister(true);
// capture the BundleListener registered with BundleContext
ArgumentCaptor<BundleListener> argument = ArgumentCaptor.forClass(BundleListener.class);
verify(context).addBundleListener(argument.capture());
assertEquals(1, argument.getAllValues().size());
BundleListener listener = argument.getValue();
assertNotNull(listener);
ExecutorService dispatcher = bundleState.getEventDispatcher();
//do registration with another server
bundleState.preRegister(server2, objectName);
bundleState.postRegister(true);
// check no more actions on BundleContext
argument = ArgumentCaptor.forClass(BundleListener.class);
verify(context, atMost(1)).addBundleListener(argument.capture());
assertEquals(1, argument.getAllValues().size());
//do one unregister
bundleState.postDeregister();
//verify bundleListener not invoked
verify(context, never()).removeBundleListener(listener);
assertFalse(dispatcher.isShutdown());
//do second unregister and check cleanup
bundleState.postDeregister();
verify(context).removeBundleListener(listener);
assertTrue(dispatcher.isShutdown());
dispatcher.awaitTermination(2, TimeUnit.SECONDS);
assertTrue(dispatcher.isTerminated());
}
@Test
public void testAttributeNotificationDisabled() throws Exception {
StateConfig stateConfig = new StateConfig();
stateConfig.setAttributeChangeNotificationEnabled(false);
//holders for Notifications captured
List<AttributeChangeNotification> attributeChanges = new LinkedList<AttributeChangeNotification>();
createBundle(stateConfig, new LinkedList<Notification>(), attributeChanges);
assertEquals(0, attributeChanges.size());
}
}
| 8,082 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/codec/ServiceDataTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.osgi.jmx.JmxConstants.BOOLEAN;
import static org.osgi.jmx.JmxConstants.KEY;
import static org.osgi.jmx.JmxConstants.LONG;
import static org.osgi.jmx.JmxConstants.P_BOOLEAN;
import static org.osgi.jmx.JmxConstants.STRING;
import static org.osgi.jmx.JmxConstants.TYPE;
import static org.osgi.jmx.JmxConstants.VALUE;
import static org.osgi.jmx.framework.BundleStateMBean.IDENTIFIER;
import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_IDENTIFIER;
import static org.osgi.jmx.framework.ServiceStateMBean.OBJECT_CLASS;
import static org.osgi.jmx.framework.ServiceStateMBean.PROPERTIES;
import static org.osgi.jmx.framework.ServiceStateMBean.SERVICE_TYPE;
import static org.osgi.jmx.framework.ServiceStateMBean.USING_BUNDLES;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.jmx.JmxConstants;
import org.osgi.jmx.framework.ServiceStateMBean;
/**
* @version $Rev$ $Date$
*/
public class ServiceDataTest {
@Test
public void testToCompositeData() throws Exception {
ServiceReference<?> reference = mock(ServiceReference.class);
Bundle bundle = mock(Bundle.class);
String[] interfaces = new String[] { "org.apache.aries.jmx.Test", "org.apache.aries.jmx.Mock" };
Bundle b1 = mock(Bundle.class);
when(b1.getBundleId()).thenReturn(new Long(6));
Bundle b2 = mock(Bundle.class);
when(b2.getBundleId()).thenReturn(new Long(9));
when(reference.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(98));
when(reference.getBundle()).thenReturn(bundle);
when(bundle.getBundleId()).thenReturn(new Long(34));
when(reference.getProperty(Constants.OBJECTCLASS)).thenReturn(interfaces);
when(reference.getUsingBundles()).thenReturn(new Bundle[] { b1, b2 });
when(reference.getPropertyKeys()).thenReturn( new String[] {"x.vendor", "x.domain", "x.index", "x.optimized" } );
when(reference.getProperty("x.vendor")).thenReturn("aries");
when(reference.getProperty("x.domain")).thenReturn("test");
when(reference.getProperty("x.index")).thenReturn(new Long(67));
when(reference.getProperty("x.optimized")).thenReturn(true);
ServiceData serviceData = new ServiceData(reference);
CompositeData compositeData = serviceData.toCompositeData();
assertEquals(new Long(98), compositeData.get(IDENTIFIER));
assertEquals(new Long(34), compositeData.get(BUNDLE_IDENTIFIER));
assertArrayEquals( new Long[] {new Long(6), new Long(9)}, (Long[]) compositeData.get(USING_BUNDLES));
assertArrayEquals(interfaces, (String[]) compositeData.get(OBJECT_CLASS));
TabularData propertiesTable = (TabularData) compositeData.get(PROPERTIES);
@SuppressWarnings("unchecked")
Collection<CompositeData> propertyData = (Collection<CompositeData>) propertiesTable.values();
assertEquals(4, propertyData.size());
for (CompositeData propertyRow: propertyData) {
String key = (String) propertyRow.get(KEY);
if (key.equals("x.vendor")) {
assertEquals("aries", propertyRow.get(VALUE));
assertEquals(STRING, propertyRow.get(TYPE));
} else if (key.equals("x.domain")) {
assertEquals("test", propertyRow.get(VALUE));
assertEquals(STRING, propertyRow.get(TYPE));
} else if (key.equals("x.index")) {
assertEquals("67", propertyRow.get(VALUE));
assertEquals(LONG, propertyRow.get(TYPE));
} else if (key.equals("x.optimized")) {
assertEquals("true", propertyRow.get(VALUE));
assertEquals(BOOLEAN, propertyRow.get(TYPE));
} else {
fail("unknown key parsed from properties");
}
}
}
@Test
public void testFromCompositeData() throws Exception {
Map<String, Object> items = new HashMap<String, Object>();
items.put(IDENTIFIER, new Long(99));
items.put(BUNDLE_IDENTIFIER, new Long(5));
items.put(USING_BUNDLES, new Long[] { new Long(10), new Long(11) });
items.put(OBJECT_CLASS, new String[] { "org.apache.aries.jmx.Test", "org.apache.aries.jmx.Mock" });
TabularData propertyTable = new TabularDataSupport(JmxConstants.PROPERTIES_TYPE);
propertyTable.put(PropertyData.newInstance("a", true).toCompositeData());
propertyTable.put(PropertyData.newInstance("b", "value").toCompositeData());
propertyTable.put(PropertyData.newInstance("c", new int[] {1, 2}).toCompositeData());
propertyTable.put(PropertyData.newInstance("d", new Long[] {new Long(3), new Long(4)}).toCompositeData());
items.put(ServiceStateMBean.PROPERTIES, propertyTable);
CompositeData compositeData = new CompositeDataSupport(SERVICE_TYPE, items);
ServiceData data = ServiceData.from(compositeData);
assertEquals(99, data.getServiceId());
assertEquals(5, data.getBundleId());
assertArrayEquals(new long[] {10, 11}, data.getUsingBundles());
assertArrayEquals(new String[] { "org.apache.aries.jmx.Test", "org.apache.aries.jmx.Mock" }, data.getServiceInterfaces());
List<PropertyData<? extends Object>> properties = data.getProperties();
assertEquals(4, properties.size());
for (PropertyData<? extends Object> property: properties) {
if (property.getKey().equals("a")) {
assertTrue((Boolean) property.getValue());
assertEquals(P_BOOLEAN, property.getEncodedType());
} else if (property.getKey().equals("b")) {
assertEquals("value", property.getValue());
assertEquals(STRING, property.getEncodedType());
} else if (property.getKey().equals("c")) {
assertArrayEquals(new int[] { 1, 2 }, (int[]) property.getValue());
assertEquals("Array of int", property.getEncodedType());
assertEquals("1,2", property.getEncodedValue());
} else if (property.getKey().equals("d")) {
assertArrayEquals(new Long[] {new Long(3), new Long(4) }, (Long[]) property.getValue());
assertEquals("Array of Long", property.getEncodedType());
assertEquals("3,4", property.getEncodedValue());
} else {
fail("unknown key parsed from properties");
}
}
}
}
| 8,083 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/codec/BundleEventDataTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.osgi.jmx.framework.BundleStateMBean.BUNDLE_EVENT_TYPE;
import static org.osgi.jmx.framework.BundleStateMBean.EVENT;
import static org.osgi.jmx.framework.BundleStateMBean.IDENTIFIER;
import static org.osgi.jmx.framework.BundleStateMBean.LOCATION;
import static org.osgi.jmx.framework.BundleStateMBean.SYMBOLIC_NAME;
import java.util.HashMap;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleEvent;
/**
*
*
* @version $Rev$ $Date$
*/
public class BundleEventDataTest {
@Test
public void testToCompositeData() throws Exception {
BundleEvent event = mock(BundleEvent.class);
Bundle bundle = mock(Bundle.class);
when(event.getBundle()).thenReturn(bundle);
when(bundle.getSymbolicName()).thenReturn("test");
when(bundle.getBundleId()).thenReturn(new Long(4));
when(bundle.getLocation()).thenReturn("location");
when(event.getType()).thenReturn(BundleEvent.INSTALLED);
BundleEventData eventData = new BundleEventData(event);
CompositeData eventCompositeData = eventData.toCompositeData();
assertEquals(new Long(4), (Long) eventCompositeData.get(IDENTIFIER));
assertEquals("test", (String) eventCompositeData.get(SYMBOLIC_NAME));
assertEquals(new Integer(BundleEvent.INSTALLED), (Integer) eventCompositeData.get(EVENT));
assertEquals("location", (String) eventCompositeData.get(LOCATION));
}
@Test
public void testFrom() throws Exception {
Map<String, Object> items = new HashMap<String, Object>();
items.put(IDENTIFIER, new Long(7));
items.put(SYMBOLIC_NAME, "t");
items.put(LOCATION, "l");
items.put(EVENT, BundleEvent.RESOLVED);
CompositeData compositeData = new CompositeDataSupport(BUNDLE_EVENT_TYPE, items);
BundleEventData event = BundleEventData.from(compositeData);
assertEquals(7, event.getBundleId());
assertEquals("t", event.getBundleSymbolicName());
assertEquals("l", event.getLocation());
assertEquals(BundleEvent.RESOLVED, event.getEventType());
}
}
| 8,084 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/codec/BundleDataTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.osgi.jmx.framework.BundleStateMBean.ACTIVATION_POLICY_USED;
import static org.osgi.jmx.framework.BundleStateMBean.BUNDLES_TYPE;
import static org.osgi.jmx.framework.BundleStateMBean.BUNDLE_TYPE;
import static org.osgi.jmx.framework.BundleStateMBean.EXPORTED_PACKAGES;
import static org.osgi.jmx.framework.BundleStateMBean.FRAGMENT;
import static org.osgi.jmx.framework.BundleStateMBean.FRAGMENTS;
import static org.osgi.jmx.framework.BundleStateMBean.HEADERS;
import static org.osgi.jmx.framework.BundleStateMBean.HEADERS_TYPE;
import static org.osgi.jmx.framework.BundleStateMBean.HEADER_TYPE;
import static org.osgi.jmx.framework.BundleStateMBean.HOSTS;
import static org.osgi.jmx.framework.BundleStateMBean.IDENTIFIER;
import static org.osgi.jmx.framework.BundleStateMBean.IMPORTED_PACKAGES;
import static org.osgi.jmx.framework.BundleStateMBean.KEY;
import static org.osgi.jmx.framework.BundleStateMBean.LAST_MODIFIED;
import static org.osgi.jmx.framework.BundleStateMBean.LOCATION;
import static org.osgi.jmx.framework.BundleStateMBean.PERSISTENTLY_STARTED;
import static org.osgi.jmx.framework.BundleStateMBean.REGISTERED_SERVICES;
import static org.osgi.jmx.framework.BundleStateMBean.REMOVAL_PENDING;
import static org.osgi.jmx.framework.BundleStateMBean.REQUIRED;
import static org.osgi.jmx.framework.BundleStateMBean.REQUIRED_BUNDLES;
import static org.osgi.jmx.framework.BundleStateMBean.REQUIRING_BUNDLES;
import static org.osgi.jmx.framework.BundleStateMBean.SERVICES_IN_USE;
import static org.osgi.jmx.framework.BundleStateMBean.START_LEVEL;
import static org.osgi.jmx.framework.BundleStateMBean.STATE;
import static org.osgi.jmx.framework.BundleStateMBean.SYMBOLIC_NAME;
import static org.osgi.jmx.framework.BundleStateMBean.VALUE;
import static org.osgi.jmx.framework.BundleStateMBean.VERSION;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.apache.aries.jmx.codec.BundleData.Header;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.packageadmin.RequiredBundle;
import org.osgi.service.startlevel.StartLevel;
/**
*
*
* @version $Rev$ $Date$
*/
public class BundleDataTest {
@Test
public void testToCompositeData() throws Exception {
Bundle bundle = mock(Bundle.class);
BundleContext context = mock(BundleContext.class);
PackageAdmin packageAdmin = mock(PackageAdmin.class);
StartLevel startLevel = mock(StartLevel.class);
Bundle b1 = mock(Bundle.class);
when(b1.getSymbolicName()).thenReturn("b1");
when(b1.getBundleId()).thenReturn(new Long(44));
Bundle b2 = mock(Bundle.class);
when(b2.getSymbolicName()).thenReturn("b2");
when(b2.getBundleId()).thenReturn(new Long(55));
Bundle b3 = mock(Bundle.class);
when(b3.getSymbolicName()).thenReturn("b3");
when(b3.getBundleId()).thenReturn(new Long(66));
when(context.getBundles()).thenReturn(new Bundle[] { bundle, b1, b2, b3 });
when(bundle.getSymbolicName()).thenReturn("test");
when(bundle.getVersion()).thenReturn(Version.emptyVersion);
when(bundle.getBundleId()).thenReturn(new Long(1));
when(bundle.getLastModified()).thenReturn(new Long(12345));
when(bundle.getLocation()).thenReturn("location");
//headers
Dictionary<String, String> headers = new Hashtable<String, String>();
headers.put(Constants.BUNDLE_SYMBOLICNAME, "test");
headers.put(Constants.BUNDLE_VERSION, "0.0.0");
when(bundle.getHeaders()).thenReturn(headers);
//exported packages
ExportedPackage exported = mock(ExportedPackage.class);
when(exported.getName()).thenReturn("org.apache.aries.jmx");
when(exported.getVersion()).thenReturn(new Version("1.0.0"));
when(exported.getExportingBundle()).thenReturn(bundle);
when(packageAdmin.getExportedPackages(bundle)).thenReturn(new ExportedPackage[] { exported });
//imported packages
ExportedPackage ep1 = mock(ExportedPackage.class);
when(ep1.getImportingBundles()).thenReturn(new Bundle[] { bundle, b2, b3 });
when(ep1.getName()).thenReturn("org.apache.aries.jmx.b1");
when(ep1.getVersion()).thenReturn(Version.emptyVersion);
when(ep1.getExportingBundle()).thenReturn(b1);
ExportedPackage ep2 = mock(ExportedPackage.class);
when(ep2.getImportingBundles()).thenReturn(new Bundle[] { bundle, b3 });
when(ep2.getName()).thenReturn("org.apache.aries.jmx.b2");
when(ep2.getVersion()).thenReturn(Version.parseVersion("2.0.1"));
when(ep2.getExportingBundle()).thenReturn(b2);
headers.put(Constants.DYNAMICIMPORT_PACKAGE, "*");
when(packageAdmin.getExportedPackages(b1)).thenReturn(new ExportedPackage[] { ep1 });
when(packageAdmin.getExportedPackages(b2)).thenReturn(new ExportedPackage[] { ep2 });
when(packageAdmin.getExportedPackages(b3)).thenReturn(null);
//required bundles
RequiredBundle rb1 = mock(RequiredBundle.class);
when(rb1.getBundle()).thenReturn(b1);
when(rb1.getRequiringBundles()).thenReturn(new Bundle[] { bundle, b2 });
RequiredBundle rb2 = mock(RequiredBundle.class);
when(rb2.getBundle()).thenReturn(b2);
when(rb2.getRequiringBundles()).thenReturn(new Bundle[] { b1 });
RequiredBundle rb3 = mock(RequiredBundle.class);
when(rb3.getBundle()).thenReturn(b3);
when(rb3.getRequiringBundles()).thenReturn(new Bundle[] { bundle, b1, b2 });
headers.put(Constants.REQUIRE_BUNDLE, "b1;bundle-version=\"1.0.0\",b3;bundle-version=\"2.0.0\"");
when(packageAdmin.getRequiredBundles("b1")).thenReturn(new RequiredBundle[] { rb1 });
when(packageAdmin.getRequiredBundles("b2")).thenReturn(new RequiredBundle[] { rb2 });
when(packageAdmin.getRequiredBundles("b3")).thenReturn(new RequiredBundle[] { rb3 });
//services in use
ServiceReference s1 = mock(ServiceReference.class);
when(s1.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(15));
ServiceReference s2 = mock(ServiceReference.class);
when(s2.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(16));
ServiceReference s3 = mock(ServiceReference.class);
when(s3.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(17));
when(bundle.getServicesInUse()).thenReturn(new ServiceReference[] { s1, s2, s3 });
BundleData b = new BundleData(context, bundle, packageAdmin, startLevel);
CompositeData compositeData = b.toCompositeData();
assertEquals("test", compositeData.get(SYMBOLIC_NAME));
assertEquals("0.0.0", compositeData.get(VERSION));
TabularData headerTable = (TabularData) compositeData.get(HEADERS);
assertEquals(4, headerTable.values().size());
CompositeData header = headerTable.get(new Object[]{Constants.BUNDLE_SYMBOLICNAME});
assertNotNull(header);
String value = (String) header.get(VALUE);
assertEquals("test", value);
String key = (String)header.get(KEY);
assertEquals(Constants.BUNDLE_SYMBOLICNAME, key);
TabularData bundleTable = new TabularDataSupport(BUNDLES_TYPE);
bundleTable.put(b.toCompositeData());
CompositeData bundleData = bundleTable.get(new Object[]{Long.valueOf(1)});
assertNotNull(bundleData);
String location = (String) bundleData.get(LOCATION);
assertEquals("location", location);
assertArrayEquals(new String[] { "org.apache.aries.jmx;1.0.0"} , (String[]) compositeData.get(EXPORTED_PACKAGES));
assertArrayEquals(new String[] { "org.apache.aries.jmx.b1;0.0.0" , "org.apache.aries.jmx.b2;2.0.1"}, (String[]) compositeData.get(IMPORTED_PACKAGES));
assertEquals(toSet(new long[] { 44, 55, 66 }), toSet((Long[]) compositeData.get(REQUIRED_BUNDLES)));
assertArrayEquals(new Long[] { new Long(15), new Long(16), new Long(17) },(Long[]) compositeData.get(SERVICES_IN_USE));
assertEquals("UNKNOWN", compositeData.get(STATE)); //default no return stub
assertEquals(0,((Long[]) compositeData.get(HOSTS)).length);
assertEquals(0, ((Long[]) compositeData.get(FRAGMENTS)).length);
}
@Test
public void testFromCompositeData() throws Exception {
Map<String, Object> items = new HashMap<String, Object>();
items.put(EXPORTED_PACKAGES, new String[] { "org.apache.aries.jmx;1.0.0"});
items.put(FRAGMENT, false);
items.put(FRAGMENTS, new Long[0]);
items.put(HOSTS, new Long[0]);
items.put(IDENTIFIER, new Long(3));
items.put(IMPORTED_PACKAGES, new String[] { "org.apache.aries.jmx.b1;0.0.0" , "org.apache.aries.jmx.b2;2.0.1"});
items.put(LAST_MODIFIED, new Long(8797));
items.put(LOCATION, "");
items.put(ACTIVATION_POLICY_USED, true);
items.put(PERSISTENTLY_STARTED, false);
items.put(REGISTERED_SERVICES, new Long[0]);
items.put(REMOVAL_PENDING, false);
items.put(REQUIRED, true);
items.put(REQUIRED_BUNDLES, new Long[] { new Long(44), new Long(66) });
items.put(REQUIRING_BUNDLES, new Long[0]);
items.put(SERVICES_IN_USE, new Long[] { new Long(15), new Long(16), new Long(17) });
items.put(START_LEVEL, 1);
items.put(STATE, "ACTIVE");
items.put(SYMBOLIC_NAME, "test");
items.put(VERSION, "0.0.0");
TabularData headerTable = new TabularDataSupport(HEADERS_TYPE);
headerTable.put(new Header("a", "a").toCompositeData());
headerTable.put(new Header("b", "b").toCompositeData());
items.put(HEADERS, headerTable);
CompositeData compositeData = new CompositeDataSupport(BUNDLE_TYPE, items);
BundleData b = BundleData.from(compositeData);
assertEquals("test", b.getSymbolicName());
assertEquals("0.0.0", b.getVersion());
assertEquals(2, b.getHeaders().size());
assertArrayEquals(new String[] { "org.apache.aries.jmx;1.0.0"} , b.getExportedPackages());
assertArrayEquals(new String[] { "org.apache.aries.jmx.b1;0.0.0" , "org.apache.aries.jmx.b2;2.0.1"}, b.getImportedPackages());
assertArrayEquals(new long[] { 44, 66 }, b.getRequiredBundles());
assertArrayEquals(new long[] { 15, 16, 17 }, b.getServicesInUse());
assertEquals("ACTIVE", b.getState()); //default no return stub
assertEquals(0, b.getHosts().length);
assertEquals(0, b.getFragments().length);
}
@Test
public void testHeaderToCompositeData() throws Exception{
Header h1 = new Header("a", "b");
CompositeData compositeData = h1.toCompositeData();
assertEquals("a", compositeData.get(KEY));
assertEquals("b", compositeData.get(VALUE));
}
@Test
public void testHeaderFromCompositeData() throws Exception {
CompositeData compositeData = new CompositeDataSupport(HEADER_TYPE, new String[] { KEY, VALUE } , new String [] { "c", "d" });
Header header = Header.from(compositeData);
assertEquals("c", header.getKey());
assertEquals("d", header.getValue());
}
private static Set<Long> toSet(long[] array) {
Set<Long> set = new HashSet<Long>();
for (long value : array) {
set.add(value);
}
return set;
}
private static Set<Long> toSet(Long[] array) {
Set<Long> set = new HashSet<Long>();
for (Long value : array) {
set.add(value);
}
return set;
}
}
| 8,085 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/codec/PropertyDataTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.osgi.jmx.JmxConstants.BIGINTEGER;
import static org.osgi.jmx.JmxConstants.BOOLEAN;
import static org.osgi.jmx.JmxConstants.CHARACTER;
import static org.osgi.jmx.JmxConstants.DOUBLE;
import static org.osgi.jmx.JmxConstants.INTEGER;
import static org.osgi.jmx.JmxConstants.KEY;
import static org.osgi.jmx.JmxConstants.PROPERTY_TYPE;
import static org.osgi.jmx.JmxConstants.P_BOOLEAN;
import static org.osgi.jmx.JmxConstants.P_CHAR;
import static org.osgi.jmx.JmxConstants.P_DOUBLE;
import static org.osgi.jmx.JmxConstants.P_INT;
import static org.osgi.jmx.JmxConstants.STRING;
import static org.osgi.jmx.JmxConstants.TYPE;
import static org.osgi.jmx.JmxConstants.VALUE;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import org.junit.Test;
/**
*
*
* @version $Rev$ $Date$
*/
public class PropertyDataTest {
@Test
public void testToCompositeDataForPrimitiveTypes() throws Exception {
PropertyData<Integer> intData = PropertyData.newInstance("test", 1);
CompositeData intCData = intData.toCompositeData();
assertEquals("test", intCData.get(KEY));
assertEquals("1", intCData.get(VALUE));
assertEquals(P_INT, intCData.get(TYPE));
PropertyData<Double> doubleData = PropertyData.newInstance("test", 1.0);
CompositeData doubleCData = doubleData.toCompositeData();
assertEquals("test", doubleCData.get(KEY));
assertEquals("1.0", doubleCData.get(VALUE));
assertEquals(P_DOUBLE, doubleCData.get(TYPE));
PropertyData<Character> charData = PropertyData.newInstance("test", 'c');
CompositeData charCData = charData.toCompositeData();
assertEquals("test", charCData.get(KEY));
assertEquals("c", charCData.get(VALUE));
assertEquals(P_CHAR, charCData.get(TYPE));
PropertyData<Boolean> booleanData = PropertyData.newInstance("test", true);
CompositeData booleanCData = booleanData.toCompositeData();
assertEquals("test", booleanCData.get(KEY));
assertEquals("true", booleanCData.get(VALUE));
assertEquals(P_BOOLEAN, booleanCData.get(TYPE));
}
@Test
public void testFromCompositeDataForPrimitiveTypes() throws Exception {
Map<String, Object> items = new HashMap<String, Object>();
items.put(KEY, "key");
items.put(VALUE, "1");
items.put(TYPE, P_INT);
CompositeData compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
PropertyData<Integer> intData = PropertyData.from(compositeData);
assertEquals("key", intData.getKey());
assertEquals(new Integer(1), intData.getValue());
assertEquals(P_INT, intData.getEncodedType());
assertTrue(intData.isEncodingPrimitive());
items.clear();
items.put(KEY, "key");
items.put(VALUE, "1.0");
items.put(TYPE, P_DOUBLE);
compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
PropertyData<Double> doubleData = PropertyData.from(compositeData);
assertEquals("key", doubleData.getKey());
assertEquals(Double.valueOf(1.0), doubleData.getValue());
assertEquals(P_DOUBLE, doubleData.getEncodedType());
assertTrue(doubleData.isEncodingPrimitive());
items.clear();
items.put(KEY, "key");
items.put(VALUE, "a");
items.put(TYPE, P_CHAR);
compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
PropertyData<Character> charData = PropertyData.from(compositeData);
assertEquals("key", charData.getKey());
assertEquals(Character.valueOf('a'), charData.getValue());
assertEquals(P_CHAR, charData.getEncodedType());
assertTrue(charData.isEncodingPrimitive());
items.clear();
items.put(KEY, "key");
items.put(VALUE, "true");
items.put(TYPE, P_BOOLEAN);
compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
PropertyData<Boolean> booleanData = PropertyData.from(compositeData);
assertEquals("key", booleanData.getKey());
assertTrue(booleanData.getValue());
assertEquals(P_BOOLEAN, booleanData.getEncodedType());
assertTrue(booleanData.isEncodingPrimitive());
}
@Test
public void testToCompositeDataForWrapperTypes() {
PropertyData<Integer> intData = PropertyData.newInstance("test", new Integer(1));
CompositeData intCData = intData.toCompositeData();
assertEquals("test", intCData.get(KEY));
assertEquals("1", intCData.get(VALUE));
assertEquals(INTEGER, intCData.get(TYPE));
PropertyData<Double> doubleData = PropertyData.newInstance("test", new Double(1.0));
CompositeData doubleCData = doubleData.toCompositeData();
assertEquals("test", doubleCData.get(KEY));
assertEquals("1.0", doubleCData.get(VALUE));
assertEquals(DOUBLE, doubleCData.get(TYPE));
PropertyData<Character> charData = PropertyData.newInstance("test", Character.valueOf('c'));
CompositeData charCData = charData.toCompositeData();
assertEquals("test", charCData.get(KEY));
assertEquals("c", charCData.get(VALUE));
assertEquals(CHARACTER, charCData.get(TYPE));
PropertyData<Boolean> booleanData = PropertyData.newInstance("test", Boolean.TRUE);
CompositeData booleanCData = booleanData.toCompositeData();
assertEquals("test", booleanCData.get(KEY));
assertEquals("true", booleanCData.get(VALUE));
assertEquals(BOOLEAN, booleanCData.get(TYPE));
}
@Test
public void testFromCompositeDataForWrapperTypes() throws Exception {
Map<String, Object> items = new HashMap<String, Object>();
items.put(KEY, "key");
items.put(VALUE, "1");
items.put(TYPE, INTEGER);
CompositeData compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
PropertyData<Integer> intData = PropertyData.from(compositeData);
assertEquals("key", intData.getKey());
assertEquals(new Integer(1), intData.getValue());
assertEquals(INTEGER, intData.getEncodedType());
assertFalse(intData.isEncodingPrimitive());
items.clear();
items.put(KEY, "key");
items.put(VALUE, "1.0");
items.put(TYPE, DOUBLE);
compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
PropertyData<Double> doubleData = PropertyData.from(compositeData);
assertEquals("key", doubleData.getKey());
assertEquals(Double.valueOf(1.0), doubleData.getValue());
assertEquals(DOUBLE, doubleData.getEncodedType());
assertFalse(doubleData.isEncodingPrimitive());
items.clear();
items.put(KEY, "key");
items.put(VALUE, "a");
items.put(TYPE, CHARACTER);
compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
PropertyData<Character> charData = PropertyData.from(compositeData);
assertEquals("key", charData.getKey());
assertEquals(Character.valueOf('a'), charData.getValue());
assertEquals(CHARACTER, charData.getEncodedType());
assertFalse(charData.isEncodingPrimitive());
items.clear();
items.put(KEY, "key");
items.put(VALUE, "true");
items.put(TYPE, BOOLEAN);
compositeData = new CompositeDataSupport(PROPERTY_TYPE, items);
PropertyData<Boolean> booleanData = PropertyData.from(compositeData);
assertEquals("key", booleanData.getKey());
assertTrue(booleanData.getValue());
assertEquals(BOOLEAN, booleanData.getEncodedType());
assertFalse(booleanData.isEncodingPrimitive());
}
@Test
public void testToFromCompositeDataForAdditionalTypes() {
PropertyData<String> stringData = PropertyData.newInstance("test", "value");
CompositeData stringCData = stringData.toCompositeData();
assertEquals("test", stringCData.get(KEY));
assertEquals("value", stringCData.get(VALUE));
assertEquals(STRING, stringCData.get(TYPE));
stringData = PropertyData.from(stringCData);
assertEquals("test", stringData.getKey());
assertEquals("value", stringData.getValue());
assertEquals(STRING, stringData.getEncodedType());
PropertyData<BigInteger> bigIntData = PropertyData.newInstance("test", new BigInteger("1"));
CompositeData bigIntCData = bigIntData.toCompositeData();
assertEquals("test", bigIntCData.get(KEY));
assertEquals("1", bigIntCData.get(VALUE));
assertEquals(BIGINTEGER, bigIntCData.get(TYPE));
bigIntData = PropertyData.from(bigIntCData);
assertEquals("test", bigIntData.getKey());
assertEquals(new BigInteger("1"), bigIntData.getValue());
assertEquals(BIGINTEGER, bigIntData.getEncodedType());
}
@Test
public void testToFromCompositeDataForArrayTypes() {
//long[]
long[] primitiveLongValues = new long[] { 1, 2, 3 };
PropertyData<long[]> primitiveLongArrayData = PropertyData.newInstance("test", primitiveLongValues);
CompositeData primitiveLongArrayCData = primitiveLongArrayData.toCompositeData();
assertEquals("test", primitiveLongArrayCData.get(KEY));
assertEquals("1,2,3", primitiveLongArrayCData.get(VALUE));
assertEquals("Array of long", primitiveLongArrayCData.get(TYPE));
primitiveLongArrayData = PropertyData.from(primitiveLongArrayCData);
assertEquals("test", primitiveLongArrayData.getKey());
assertEquals("Array of long", primitiveLongArrayData.getEncodedType());
assertArrayEquals(primitiveLongValues, primitiveLongArrayData.getValue());
//Long[]
Long[] longValues = new Long[] { new Long(4), new Long(5), new Long(6) };
PropertyData<Long[]> longArrayData = PropertyData.newInstance("test", longValues);
CompositeData longArrayCData = longArrayData.toCompositeData();
assertEquals("test", longArrayCData.get(KEY));
assertEquals("4,5,6", longArrayCData.get(VALUE));
assertEquals("Array of Long", longArrayCData.get(TYPE));
longArrayData = PropertyData.from(longArrayCData);
assertEquals("test", longArrayData.getKey());
assertEquals("Array of Long", longArrayData.getEncodedType());
assertArrayEquals(longValues, longArrayData.getValue());
//char[]
char[] primitiveCharValues = new char[] { 'a', 'b', 'c' };
PropertyData<char[]> primitiveCharArrayData = PropertyData.newInstance("test", primitiveCharValues);
CompositeData primitiveCharArrayCData = primitiveCharArrayData.toCompositeData();
assertEquals("test", primitiveCharArrayCData.get(KEY));
assertEquals("a,b,c", primitiveCharArrayCData.get(VALUE));
assertEquals("Array of char", primitiveCharArrayCData.get(TYPE));
primitiveCharArrayData = PropertyData.from(primitiveCharArrayCData);
assertEquals("test", primitiveCharArrayData.getKey());
assertEquals("Array of char", primitiveCharArrayData.getEncodedType());
assertArrayEquals(primitiveCharValues, primitiveCharArrayData.getValue());
//Character[]
Character[] charValues = new Character[] { 'a', 'b', 'c' };
PropertyData<Character[]> charArrayData = PropertyData.newInstance("test", charValues);
CompositeData charArrayCData = charArrayData.toCompositeData();
assertEquals("test", charArrayCData.get(KEY));
assertEquals("a,b,c", charArrayCData.get(VALUE));
assertEquals("Array of Character", charArrayCData.get(TYPE));
charArrayData = PropertyData.from(charArrayCData);
assertEquals("test", charArrayData.getKey());
assertEquals("Array of Character", charArrayData.getEncodedType());
assertArrayEquals(charValues, charArrayData.getValue());
}
@Test
public void testToFromCompositeDataForVector() {
Vector<Long> vector = new Vector<Long>();
vector.add(new Long(40));
vector.add(new Long(50));
vector.add(new Long(60));
PropertyData<Vector<Long>> vectorPropertyData = PropertyData.newInstance("test", vector);
CompositeData vectorCompositeData = vectorPropertyData.toCompositeData();
assertEquals("test", vectorCompositeData.get(KEY));
assertEquals("40,50,60", vectorCompositeData.get(VALUE));
assertEquals("Vector of Long", vectorCompositeData.get(TYPE));
vectorPropertyData = PropertyData.from(vectorCompositeData);
assertEquals("test", vectorPropertyData.getKey());
assertEquals("Vector of Long", vectorPropertyData.getEncodedType());
assertArrayEquals(vector.toArray(new Long[vector.size()]), vectorPropertyData.getValue().toArray(new Long[vector.size()]));
}
@Test
public void testToFromCompositeDataForList() {
List<String> sl = new ArrayList<String>();
sl.add("A");
sl.add("B");
PropertyData<List<String>> pd = PropertyData.newInstance("test", sl);
CompositeData cd = pd.toCompositeData();
assertEquals("test", cd.get(KEY));
assertEquals("A,B", cd.get(VALUE));
assertEquals("Array of String", cd.get(TYPE));
PropertyData<String []> pd2 = PropertyData.from(cd);
assertEquals("test", pd2.getKey());
assertEquals("Array of String", pd2.getEncodedType());
assertArrayEquals(new String [] {"A", "B"}, pd2.getValue());
}
@Test
public void testToFromCompositeDataForList2() {
List<Long> sl = new ArrayList<Long>();
sl.add(Long.MAX_VALUE);
PropertyData<List<Long>> pd = PropertyData.newInstance("test", sl);
CompositeData cd = pd.toCompositeData();
assertEquals("test", cd.get(KEY));
assertEquals(new Long(Long.MAX_VALUE).toString(), cd.get(VALUE));
assertEquals("Array of Long", cd.get(TYPE));
PropertyData<Long []> pd2 = PropertyData.from(cd);
assertEquals("test", pd2.getKey());
assertEquals("Array of Long", pd2.getEncodedType());
assertArrayEquals(new Long [] {Long.MAX_VALUE}, pd2.getValue());
}
}
| 8,086 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/codec/ServiceEventDataTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.codec;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_IDENTIFIER;
import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_LOCATION;
import static org.osgi.jmx.framework.ServiceStateMBean.BUNDLE_SYMBOLIC_NAME;
import static org.osgi.jmx.framework.ServiceStateMBean.EVENT;
import static org.osgi.jmx.framework.ServiceStateMBean.IDENTIFIER;
import static org.osgi.jmx.framework.ServiceStateMBean.OBJECT_CLASS;
import static org.osgi.jmx.framework.ServiceStateMBean.SERVICE_EVENT_TYPE;
import java.util.HashMap;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
/**
*
*
* @version $Rev$ $Date$
*/
public class ServiceEventDataTest {
@Test
public void testToCompositeData() throws Exception {
ServiceEvent event = mock(ServiceEvent.class);
ServiceReference reference = mock(ServiceReference.class);
Bundle bundle = mock(Bundle.class);
when(event.getType()).thenReturn(ServiceEvent.REGISTERED);
when(event.getServiceReference()).thenReturn(reference);
when(reference.getProperty(Constants.SERVICE_ID)).thenReturn(new Long(44));
when(reference.getProperty(Constants.OBJECTCLASS)).thenReturn(new String[] {"org.apache.aries.jmx.Mock"});
when(reference.getBundle()).thenReturn(bundle);
when(bundle.getBundleId()).thenReturn(new Long(1));
when(bundle.getLocation()).thenReturn("string");
when(bundle.getSymbolicName()).thenReturn("org.apache.aries.jmx.core");
ServiceEventData eventData = new ServiceEventData(event);
CompositeData data = eventData.toCompositeData();
assertEquals(new Long(44), data.get(IDENTIFIER));
assertEquals(new Long(1), data.get(BUNDLE_IDENTIFIER));
assertEquals("string", data.get(BUNDLE_LOCATION));
assertEquals("org.apache.aries.jmx.core", data.get(BUNDLE_SYMBOLIC_NAME));
assertArrayEquals(new String[] {"org.apache.aries.jmx.Mock" }, (String[]) data.get(OBJECT_CLASS));
assertEquals(ServiceEvent.REGISTERED, data.get(EVENT));
}
@Test
public void testFrom() throws Exception {
Map<String, Object> items = new HashMap<String, Object>();
items.put(IDENTIFIER, new Long(7));
items.put(BUNDLE_IDENTIFIER, new Long(67));
items.put(BUNDLE_LOCATION, "string");
items.put(BUNDLE_SYMBOLIC_NAME, "test");
items.put(OBJECT_CLASS, new String[] {"org.apache.aries.jmx.Mock" });
items.put(EVENT, ServiceEvent.MODIFIED);
CompositeData compositeData = new CompositeDataSupport(SERVICE_EVENT_TYPE, items);
ServiceEventData event = ServiceEventData.from(compositeData);
assertEquals(7, event.getServiceId());
assertEquals(67, event.getBundleId());
assertArrayEquals(new String[] {"org.apache.aries.jmx.Mock" }, event.getServiceInterfaces());
assertEquals("test", event.getBundleSymbolicName());
assertEquals("string", event.getBundleLocation());
assertEquals(ServiceEvent.MODIFIED, event.getEventType());
}
}
| 8,087 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/provisioning/ProvisioningServiceMBeanHandlerTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.provisioning;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import javax.management.StandardMBean;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.service.provisioning.ProvisioningService;
/**
*
*
* @version $Rev$ $Date$
*/
public class ProvisioningServiceMBeanHandlerTest {
@Test
public void testConstructInjectMBean() {
BundleContext bundleContext = mock(BundleContext.class);
Logger agentLogger = mock(Logger.class);
JMXAgentContext agentContext = new JMXAgentContext(bundleContext, null, agentLogger);
ProvisioningService provService = mock(ProvisioningService.class);
ProvisioningServiceMBeanHandler handler = new ProvisioningServiceMBeanHandler(agentContext);
StandardMBean mbean = handler.constructInjectMBean(provService);
assertNotNull(mbean);
}
}
| 8,088 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/provisioning/ProvisioningServiceTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.provisioning;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.osgi.jmx.JmxConstants.PROPERTIES_TYPE;
import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_AGENT_CONFIG;
import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_REFERENCE;
import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_RSH_SECRET;
import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_SPID;
import static org.osgi.service.provisioning.ProvisioningService.PROVISIONING_UPDATE_COUNT;
import java.io.InputStream;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.zip.ZipInputStream;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.apache.aries.jmx.codec.PropertyData;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
/**
*
*
* @version $Rev$ $Date$
*/
public class ProvisioningServiceTest {
@Test
public void testAddInformationFromZip() throws Exception {
org.osgi.service.provisioning.ProvisioningService provService = mock(org.osgi.service.provisioning.ProvisioningService.class);
ProvisioningService mbean = new ProvisioningService(provService);
ProvisioningService spiedMBean = spy(mbean);
InputStream is = mock(InputStream.class);
doReturn(is).when(spiedMBean).createStream("file://prov.zip");
spiedMBean.addInformationFromZip("file://prov.zip");
verify(provService).addInformation(any(ZipInputStream.class));
verify(is).close();
}
@Test
@SuppressWarnings("unchecked")
public void testAddInformationWithTabularData() throws Exception {
org.osgi.service.provisioning.ProvisioningService provService = mock(org.osgi.service.provisioning.ProvisioningService.class);
ProvisioningService mbean = new ProvisioningService(provService);
TabularData data = new TabularDataSupport(PROPERTIES_TYPE);
PropertyData<byte[]> p1 = PropertyData.newInstance(PROVISIONING_AGENT_CONFIG, new byte[] { 20, 30, 40 });
data.put(p1.toCompositeData());
PropertyData<String> p2 = PropertyData.newInstance(PROVISIONING_SPID, "x.test");
data.put(p2.toCompositeData());
mbean.addInformation(data);
ArgumentCaptor<Dictionary> dictionaryArgument = ArgumentCaptor.forClass(Dictionary.class);
verify(provService).addInformation(dictionaryArgument.capture());
Dictionary<String, Object> info = dictionaryArgument.getValue();
assertEquals(2, info.size() );
assertArrayEquals(new byte[] { 20, 30, 40 }, (byte[]) info.get(PROVISIONING_AGENT_CONFIG));
assertEquals("x.test", info.get(PROVISIONING_SPID));
}
@Test
public void testListInformation() throws Exception {
org.osgi.service.provisioning.ProvisioningService provService = mock(org.osgi.service.provisioning.ProvisioningService.class);
ProvisioningService mbean = new ProvisioningService(provService);
Dictionary<String, Object> info = new Hashtable<String, Object>();
info.put(PROVISIONING_AGENT_CONFIG, new byte[] { 20, 30, 40 });
info.put(PROVISIONING_SPID, "x.test");
info.put(PROVISIONING_REFERENCE, "rsh://0.0.0.0/provX");
info.put(PROVISIONING_RSH_SECRET, new byte[] { 15, 25, 35 });
info.put(PROVISIONING_UPDATE_COUNT, 1);
when(provService.getInformation()).thenReturn(info);
TabularData provData = mbean.listInformation();
assertNotNull(provData);
assertEquals(PROPERTIES_TYPE, provData.getTabularType());
assertEquals(5, provData.values().size());
PropertyData<byte[]> agentConfig = PropertyData.from(provData.get(new Object[]{ PROVISIONING_AGENT_CONFIG }));
assertArrayEquals(new byte[] { 20, 30, 40 }, agentConfig.getValue());
PropertyData<String> spid = PropertyData.from(provData.get(new Object[] { PROVISIONING_SPID }));
assertEquals("x.test", spid.getValue());
PropertyData<String> ref = PropertyData.from(provData.get(new Object[] { PROVISIONING_REFERENCE }));
assertEquals("rsh://0.0.0.0/provX", ref.getValue());
PropertyData<byte[]> sec = PropertyData.from(provData.get(new Object[] { PROVISIONING_RSH_SECRET }));
assertArrayEquals(new byte[] { 15, 25, 35 }, sec.getValue());
PropertyData<Integer> count = PropertyData.from(provData.get(new Object[] { PROVISIONING_UPDATE_COUNT }));
assertEquals(new Integer(1), count.getValue());
}
@Test
@SuppressWarnings("unchecked")
public void testSetInformation() throws Exception {
org.osgi.service.provisioning.ProvisioningService provService = mock(org.osgi.service.provisioning.ProvisioningService.class);
ProvisioningService mbean = new ProvisioningService(provService);
TabularData data = new TabularDataSupport(PROPERTIES_TYPE);
PropertyData<String> p1 = PropertyData.newInstance(PROVISIONING_REFERENCE, "rsh://0.0.0.0/provX");
data.put(p1.toCompositeData());
PropertyData<String> p2 = PropertyData.newInstance(PROVISIONING_SPID, "x.test");
data.put(p2.toCompositeData());
mbean.setInformation(data);
ArgumentCaptor<Dictionary> dictionaryArgument = ArgumentCaptor.forClass(Dictionary.class);
verify(provService).setInformation(dictionaryArgument.capture());
Dictionary<String, Object> info = dictionaryArgument.getValue();
assertEquals(2, info.size() );
assertEquals("rsh://0.0.0.0/provX", info.get(PROVISIONING_REFERENCE));
assertEquals("x.test", info.get(PROVISIONING_SPID));
}
}
| 8,089 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/permissionadmin/PermissionAdminTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.permissionadmin;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.osgi.jmx.service.permissionadmin.PermissionAdminMBean;
import org.osgi.service.permissionadmin.PermissionInfo;
/**
* {@link PermissionAdminMBean} test case.
*
*
* @version $Rev$ $Date$
*/
public class PermissionAdminTest {
@Mock
private org.osgi.service.permissionadmin.PermissionAdmin permAdmin;
private PermissionAdminMBean mbean;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mbean = new PermissionAdmin(permAdmin);
}
@Test
public void testGetPermissions() throws IOException {
PermissionInfo info = new PermissionInfo("Admin", "test", "get");
PermissionInfo[] permInfos = new PermissionInfo[] { info, info };
Mockito.when(permAdmin.getPermissions(Mockito.anyString())).thenReturn(permInfos);
String[] permissions = mbean.getPermissions("test");
Assert.assertNotNull(permissions);
Assert.assertEquals(2, permissions.length);
Assert.assertArrayEquals("Checks encoded permissions", new String[] { info.getEncoded(), info.getEncoded() },
permissions);
Mockito.reset(permAdmin);
Mockito.when(permAdmin.getPermissions(Mockito.anyString())).thenReturn(null);
String[] permissions2 = mbean.getPermissions("test");
Assert.assertNull(permissions2);
}
@Test
public void testListDefaultPermissions() throws IOException {
PermissionInfo info = new PermissionInfo("Admin", "test", "get");
PermissionInfo[] permInfos = new PermissionInfo[] { info, info };
Mockito.when(permAdmin.getDefaultPermissions()).thenReturn(permInfos);
String[] permissions = mbean.listDefaultPermissions();
Assert.assertNotNull(permissions);
Assert.assertEquals(2, permissions.length);
Assert.assertArrayEquals("Checks encoded default permissions", new String[] { info.getEncoded(), info.getEncoded() },
permissions);
Mockito.reset(permAdmin);
Mockito.when(permAdmin.getDefaultPermissions()).thenReturn(null);
String[] permissions2 = mbean.listDefaultPermissions();
Assert.assertNull(permissions2);
}
@Test
public void testListLocations() throws IOException {
String[] locations1 = new String[] { "test1", "test2" };
Mockito.when(permAdmin.getLocations()).thenReturn(locations1);
String[] locations2 = mbean.listLocations();
Assert.assertNotNull(locations2);
Assert.assertEquals(2, locations2.length);
Assert.assertSame(locations1, locations2);
}
@Test
public void testSetDefaultPermissions() throws IOException {
PermissionInfo info1 = new PermissionInfo("Admin", "test", "get");
PermissionInfo info2 = new PermissionInfo("Admin", "test2", "get");
PermissionInfo[] permInfos = new PermissionInfo[] { info1, info2 };
String[] encodedPermissions = new String[2];
int i = 0;
for (PermissionInfo info : permInfos) {
encodedPermissions[i++] = info.getEncoded();
}
mbean.setDefaultPermissions(encodedPermissions);
Mockito.verify(permAdmin).setDefaultPermissions(permInfos);
}
@Test
public void testSetPermissions() throws IOException {
PermissionInfo info1 = new PermissionInfo("Admin", "test", "set");
PermissionInfo info2 = new PermissionInfo("Admin", "test2", "set");
PermissionInfo[] permInfos = new PermissionInfo[] { info1, info2 };
String[] encodedPermissions = new String[2];
int i = 0;
for (PermissionInfo info : permInfos) {
encodedPermissions[i++] = info.getEncoded();
}
mbean.setPermissions("test", encodedPermissions);
Mockito.verify(permAdmin).setPermissions("test", permInfos);
}
}
| 8,090 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/cm/ConfigurationAdminMBeanHandlerTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.cm;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import javax.management.StandardMBean;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.service.cm.ConfigurationAdmin;
/**
*
*
* @version $Rev$ $Date$
*/
public class ConfigurationAdminMBeanHandlerTest {
@Test
public void testConstructInjectMBean() {
BundleContext bundleContext = mock(BundleContext.class);
Logger agentLogger = mock(Logger.class);
JMXAgentContext agentContext = new JMXAgentContext(bundleContext, null, agentLogger);
ConfigurationAdmin cAdmin = mock(ConfigurationAdmin.class);
ConfigurationAdminMBeanHandler handler = new ConfigurationAdminMBeanHandler(agentContext);
StandardMBean mbean = handler.constructInjectMBean(cAdmin);
assertNotNull(mbean);
}
}
| 8,091 |
0 | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/test/java/org/apache/aries/jmx/cm/ConfigurationAdminTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.cm;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.osgi.jmx.JmxConstants.PROPERTIES_TYPE;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import org.apache.aries.jmx.codec.PropertyData;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.osgi.framework.Constants;
import org.osgi.service.cm.Configuration;
/**
*
*
* @version $Rev$ $Date$
*/
public class ConfigurationAdminTest {
@Test
public void testCreateFactoryConfiguration() throws Exception {
org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
String fpid = "org.apache.aries.jmx.mock.factory";
Configuration config = mock(Configuration.class);
when(admin.createFactoryConfiguration(eq(fpid))).thenReturn(config);
when(admin.createFactoryConfiguration(eq(fpid), anyString())).thenReturn(config);
when(config.getPid()).thenReturn(fpid + "-1260133982371-0");
ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
assertEquals(fpid + "-1260133982371-0", mbean.createFactoryConfiguration(fpid));
assertEquals(fpid + "-1260133982371-0", mbean.createFactoryConfigurationForLocation(fpid, "/bundlex"));
}
@Test
public void testDelete() throws Exception {
org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
String pid = "org.apache.aries.jmx.mock";
Configuration config = mock(Configuration.class);
when(admin.getConfiguration(pid, null)).thenReturn(config);
ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
mbean.delete(pid);
verify(config).delete();
reset(config);
when(admin.getConfiguration(pid, "location")).thenReturn(config);
mbean.deleteForLocation(pid, "location");
verify(config).delete();
}
@Test
public void testDeleteConfigurations() throws Exception {
org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
String filter = "(" + Constants.SERVICE_PID + "=org.apache.aries.jmx.mock)";
Configuration a = mock(Configuration.class);
Configuration b = mock(Configuration.class);
when(admin.listConfigurations(filter)).thenReturn(new Configuration[] { a, b });
ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
mbean.deleteConfigurations(filter);
verify(a).delete();
verify(b).delete();
}
@Test
public void testGetBundleLocation() throws Exception {
org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
String pid = "org.apache.aries.jmx.mock";
Configuration config = mock(Configuration.class);
when(admin.getConfiguration(pid, null)).thenReturn(config);
when(config.getBundleLocation()).thenReturn("/location");
ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
assertEquals("/location", mbean.getBundleLocation(pid));
}
@Test
public void testGetConfigurations() throws Exception {
org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
String factoryPid = "org.apache.aries.jmx.factory.mock";
String filter = "(" + org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID + "=org.apache.aries.jmx.factory.mock)";
String location = "../location";
Configuration a = mock(Configuration.class);
when(a.getPid()).thenReturn(factoryPid + "-2160133952674-0");
when(a.getBundleLocation()).thenReturn(location);
Configuration b = mock(Configuration.class);
when(b.getPid()).thenReturn(factoryPid + "-1260133982371-1");
when(b.getBundleLocation()).thenReturn(location);
when(admin.listConfigurations(filter)).thenReturn(new Configuration[] { a, b});
ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
String[][] result = mbean.getConfigurations(filter);
assertEquals(2, result.length);
assertArrayEquals(new String[]{ factoryPid + "-2160133952674-0", location }, result[0] );
assertArrayEquals(new String[]{ factoryPid + "-1260133982371-1", location }, result[1] );
}
@Test
public void testGetFactoryPid() throws Exception {
org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
String factoryPid = "org.apache.aries.jmx.factory.mock";
Configuration config = mock(Configuration.class);
when(admin.getConfiguration(eq(factoryPid + "-1260133982371-0"), anyString())).thenReturn(config);
when(config.getFactoryPid()).thenReturn(factoryPid);
ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
assertEquals(factoryPid, mbean.getFactoryPid(factoryPid + "-1260133982371-0"));
assertEquals(factoryPid, mbean.getFactoryPidForLocation(factoryPid + "-1260133982371-0", "location"));
}
@Test
public void testGetProperties() throws Exception {
org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
String pid = "org.apache.aries.jmx.mock";
Configuration config = mock(Configuration.class);
Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put("one", "value");
props.put("two", 2);
when(admin.getConfiguration(eq(pid), anyString())).thenReturn(config);
when(config.getProperties()).thenReturn(props);
ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
TabularData properties = mbean.getPropertiesForLocation(pid, null);
assertNotNull(properties);
assertEquals(PROPERTIES_TYPE, properties.getTabularType());
assertEquals(2, properties.values().size());
PropertyData<? extends Object> oneData = PropertyData.from(properties.get(new Object[]{ "one"}));
assertEquals("value", oneData.getValue());
PropertyData<? extends Object> twoData = PropertyData.from(properties.get(new Object[]{ "two"}));
assertEquals(2, twoData.getValue());
assertEquals("2", twoData.getEncodedValue());
}
@Test
public void testSetBundleLocation() throws Exception {
org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
String pid = "org.apache.aries.jmx.mock";
Configuration config = mock(Configuration.class);
when(admin.getConfiguration(pid, null)).thenReturn(config);
ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
mbean.setBundleLocation(pid, "file:/newlocation");
ArgumentCaptor<String> locationArgument = ArgumentCaptor.forClass(String.class);
verify(config).setBundleLocation(locationArgument.capture());
assertEquals("file:/newlocation", locationArgument.getValue());
}
@SuppressWarnings("unchecked")
@Test
public void testUpdateTabularData() throws Exception {
TabularData data = new TabularDataSupport(PROPERTIES_TYPE);
PropertyData<String> p1 = PropertyData.newInstance("one", "first");
data.put(p1.toCompositeData());
PropertyData<Integer> p2 = PropertyData.newInstance("two", 3);
data.put(p2.toCompositeData());
org.osgi.service.cm.ConfigurationAdmin admin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
String pid = "org.apache.aries.jmx.mock";
Configuration config = mock(Configuration.class);
when(admin.getConfiguration(pid, null)).thenReturn(config);
ConfigurationAdmin mbean = new ConfigurationAdmin(admin);
mbean.updateForLocation(pid, null, data);
ArgumentCaptor<Dictionary> props = ArgumentCaptor.forClass(Dictionary.class);
verify(config).update(props.capture());
Dictionary configProperties = props.getValue();
assertEquals("first", configProperties.get("one"));
assertEquals(3, configProperties.get("two"));
}
}
| 8,092 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/MBeanServiceTracker.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx;
import javax.management.MBeanServer;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
/**
* <p>This class <tt>MBeanServiceTracker</tt> represents {@link ServiceTracker} for {@link MBeanServer}'s
* registered as services.
* Tracking all registered MBeanServers in ServiceRegistry.</p>
* @see ServiceTracker
* @version $Rev$ $Date$
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class MBeanServiceTracker extends ServiceTracker {
private JMXAgentContext agentContext;
/**
* Constructs new MBeanServiceTracker.
* @param agentContext agent context.
*/
public MBeanServiceTracker(JMXAgentContext agentContext) {
super(agentContext.getBundleContext(), MBeanServer.class.getName(), null);
this.agentContext = agentContext;
}
/**
* <p>Register MBeans using {@link JMXAgentContext#registerMBeans(MBeanServer)}
* when MBeanServer service is discovered</p>
* @see ServiceTracker#addingService(ServiceReference)
*/
public Object addingService(final ServiceReference reference) {
final MBeanServer mbeanServer = (MBeanServer) super.addingService(reference);
Logger logger = agentContext.getLogger();
logger.log(LogService.LOG_DEBUG, "Discovered MBean server " + mbeanServer);
agentContext.registerMBeans(mbeanServer);
return mbeanServer;
}
/**
* <p>Unregister MBeans using {@link JMXAgentContext#unregisterMBeans(MBeanServer)}
* when MBeanServer service is removed (unregistered from ServiceRegistry) or
* tracker is closed</p>
* @see ServiceTracker#removedService(ServiceReference, Object)
*/
public void removedService(final ServiceReference reference, Object service) {
final MBeanServer mbeanServer = (MBeanServer) service;
Logger logger = agentContext.getLogger();
logger.log(LogService.LOG_DEBUG, "MBean server " + mbeanServer+ " is unregistered from ServiceRegistry");
agentContext.unregisterMBeans(mbeanServer);
super.removedService(reference, service);
}
}
| 8,093 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/JMXThreadFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class JMXThreadFactory implements ThreadFactory {
private final ThreadFactory factory = Executors.defaultThreadFactory();
private final String name;
public JMXThreadFactory(String name) {
this.name = name;
}
public Thread newThread(Runnable r) {
final Thread t = factory.newThread(r);
t.setName(name);
t.setDaemon(true);
return t;
}
}
| 8,094 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/MBeanHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx;
import javax.management.StandardMBean;
/**
* <p>Represents JMX OSGi MBeans handler.
* Storing information about holden MBean.</p>
*
* @version $Rev$ $Date$
*/
public interface MBeanHandler {
/**
* Gets MBean holden by handler.
* @return MBean @see {@link StandardMBean}.
*/
StandardMBean getMbean();
/**
* Starts handler.
*/
void open();
/**
* Stops handler.
*/
void close();
/**
* Gets name of the MBean.
* @return MBean name.
*/
String getName();
} | 8,095 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/Logger.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
/**
* <p>This <tt>Logger</tt> class represents ServiceTracker for LogService.
* It provides methods for logging messages. If LogService is not available it logs to stdout.</p>
*
* @see org.osgi.service.log.LogService
* @see org.osgi.util.tracker.ServiceTracker
* @version $Rev$ $Date$
*/
@SuppressWarnings("rawtypes")
public class Logger extends ServiceTracker implements LogService {
/**
* Constructs new Logger(ServiceTracker for LogService).
*
* @param context bundle context.
*/
@SuppressWarnings("unchecked")
public Logger(BundleContext context) {
super(context, LogService.class.getName(), null);
}
/**
* @see org.osgi.service.log.LogService#log(int, java.lang.String)
*/
public void log(int level, String message) {
LogService logService = (LogService) getService();
if (logService != null) {
logService.log(level, message);
}
}
/**
* @see org.osgi.service.log.LogService#log(int, java.lang.String, java.lang.Throwable)
*/
public void log(int level, String message, Throwable exception) {
LogService logService = (LogService) getService();
if (logService != null) {
logService.log(level, message, exception);
}
}
/**
* @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String)
*/
public void log(ServiceReference ref, int level, String message) {
LogService logService = (LogService) getService();
if (logService != null) {
logService.log(ref, level, message);
}
}
/**
* @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String,
* java.lang.Throwable)
*/
public void log(ServiceReference ref, int level, String message, Throwable exception) {
LogService logService = (LogService) getService();
if (logService != null) {
logService.log(ref, level, message, exception);
}
}
}
| 8,096 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/Activator.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx;
import org.apache.aries.jmx.agent.JMXAgent;
import org.apache.aries.jmx.agent.JMXAgentImpl;
import org.apache.aries.jmx.framework.StateConfig;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.service.log.LogService;
/**
* <p>Activator for JMX OSGi bundle.</p>
*
* @version $Rev$ $Date$
*/
public class Activator implements BundleActivator {
private JMXAgent agent;
private Logger logger;
/**
* <p>Called when JMX OSGi bundle starts.
* This method creates and starts JMX agent.</p>
*
* @see org.osgi.framework.BundleActivator#start(BundleContext)
*/
public void start(BundleContext context) throws Exception {
StateConfig stateConfig = StateConfig.register(context);
logger = new Logger(context);
//starting logger
logger.open();
logger.log(LogService.LOG_DEBUG, "Starting JMX OSGi bundle");
agent = new JMXAgentImpl(context, stateConfig, logger);
agent.start();
}
/**
* <p>Called when JMX OSGi bundle stops.
* This method stops agent and logger @see {@link Logger}.</p>
*
* @see org.osgi.framework.BundleActivator#stop(BundleContext)
*/
public void stop(BundleContext bc) throws Exception {
if (logger != null) {
logger.log(LogService.LOG_DEBUG, "Stopping JMX OSGi bundle");
}
if (agent != null) {
agent.stop();
}
if (logger != null) {
logger.close();
}
}
}
| 8,097 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/AbstractCompendiumHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx;
import java.util.concurrent.atomic.AtomicLong;
import javax.management.StandardMBean;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.apache.aries.jmx.util.ObjectNameUtils;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
/**
* <p>
* Abstract implementation of {@link MBeanHandler} that provides a template with basic tracking of an optional
* compendium service. MBeanHandler implementations that manage a {@link StandardMBean} that is backed by a single OSGi
* compendium service should extend this class and implement the {@linkplain #constructInjectMBean(Object)} and
* {@linkplain #getName()} methods
* </p>
*
* @see MBeanHandler
*
* @version $Rev$ $Date$
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public abstract class AbstractCompendiumHandler extends ServiceTracker implements MBeanHandler {
protected final JMXAgentContext agentContext;
protected StandardMBean mbean;
protected final AtomicLong trackedId = new AtomicLong();
/**
*
* @param agentContext
* @param filter
*/
protected AbstractCompendiumHandler(JMXAgentContext agentContext, Filter filter) {
super(agentContext.getBundleContext(), filter, null);
this.agentContext = agentContext;
}
/**
*
* @param agentContext
* @param clazz
*/
protected AbstractCompendiumHandler(JMXAgentContext agentContext, String clazz) {
super(agentContext.getBundleContext(), clazz, null);
this.agentContext = agentContext;
}
/*
* (non-Javadoc)
*
* @see org.osgi.util.tracker.ServiceTracker#addingService(org.osgi.framework.ServiceReference)
*/
public Object addingService(ServiceReference reference) {
Logger logger = agentContext.getLogger();
Object trackedService = null;
long serviceId = (Long) reference.getProperty(Constants.SERVICE_ID);
//API stipulates versions for compendium services with static ObjectName
//This shouldn't happen but added as a consistency check
if (trackedId.compareAndSet(0, serviceId)) {
logger.log(LogService.LOG_INFO, "Registering MBean with ObjectName [" + getName() + "] for service with "
+ Constants.SERVICE_ID + " [" + serviceId + "]");
trackedService = context.getService(reference);
mbean = constructInjectMBean(trackedService);
agentContext.registerMBean(AbstractCompendiumHandler.this);
} else {
String serviceDescription = getServiceDescription(reference);
logger.log(LogService.LOG_WARNING, "Detected secondary ServiceReference for [" + serviceDescription
+ "] with " + Constants.SERVICE_ID + " [" + serviceId + "] Only 1 instance will be JMX managed");
}
return trackedService;
}
/*
* (non-Javadoc)
*
* @see org.osgi.util.tracker.ServiceTracker#removedService(org.osgi.framework.ServiceReference, java.lang.Object)
*/
public void removedService(ServiceReference reference, Object service) {
Logger logger = agentContext.getLogger();
long serviceID = (Long) reference.getProperty(Constants.SERVICE_ID);
if (trackedId.compareAndSet(serviceID, 0)) {
logger.log(LogService.LOG_INFO, "Unregistering MBean with ObjectName [" + getName() + "] for service with "
+ Constants.SERVICE_ID + " [" + serviceID + "]");
agentContext.unregisterMBean(AbstractCompendiumHandler.this);
context.ungetService(reference);
} else {
String serviceDescription = getServiceDescription(reference);
logger.log(LogService.LOG_WARNING, "ServiceReference for [" + serviceDescription + "] with "
+ Constants.SERVICE_ID + " [" + serviceID + "] is not currently JMX managed");
}
}
private String getServiceDescription(ServiceReference reference) {
String serviceDescription = (String) reference.getProperty(Constants.SERVICE_DESCRIPTION);
if (serviceDescription == null) {
Object obj = reference.getProperty(Constants.OBJECTCLASS);
if (obj instanceof String[]) {
StringBuilder sb = new StringBuilder();
for (String s : (String[]) obj) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(s);
}
serviceDescription = sb.toString();
} else {
serviceDescription = obj.toString();
}
}
return serviceDescription;
}
/**
* Gets the <code>StandardMBean</code> managed by this handler when the backing service is available or null
*
* @see org.apache.aries.jmx.MBeanHandler#getMbean()
*/
public StandardMBean getMbean() {
return mbean;
}
/**
* Implement this method to construct an appropriate {@link StandardMBean} instance which is backed by the supplied
* service tracked by this handler
*
* @param targetService
* the compendium service tracked by this handler
* @return The <code>StandardMBean</code> instance whose registration lifecycle will be managed by this handler
*/
protected abstract StandardMBean constructInjectMBean(Object targetService);
/**
* The base name of the MBean. Will be expanded with the framework name and the UUID.
* @return
*/
protected abstract String getBaseName();
/**
* @see org.apache.aries.jmx.MBeanHandler#getName()
*/
public String getName() {
return ObjectNameUtils.createFullObjectName(context, getBaseName());
}
}
| 8,098 |
0 | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx | Create_ds/aries/jmx/jmx-core/src/main/java/org/apache/aries/jmx/useradmin/UserAdminMBeanHandler.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aries.jmx.useradmin;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
import org.apache.aries.jmx.AbstractCompendiumHandler;
import org.apache.aries.jmx.Logger;
import org.apache.aries.jmx.MBeanHandler;
import org.apache.aries.jmx.agent.JMXAgentContext;
import org.osgi.jmx.service.permissionadmin.PermissionAdminMBean;
import org.osgi.jmx.service.useradmin.UserAdminMBean;
import org.osgi.service.log.LogService;
/**
* <p>
* <tt>UserAdminMBeanHandler</tt> represents MBeanHandler which
* holding information about {@link PermissionAdminMBean}.</p>
* @see AbstractCompendiumHandler
* @see MBeanHandler
*
* @version $Rev$ $Date$
*/
public class UserAdminMBeanHandler extends AbstractCompendiumHandler {
/**
* Constructs new UserAdminMBeanHandler.
*
* @param agentContext JMXAgentContext instance.
*/
public UserAdminMBeanHandler(JMXAgentContext agentContext) {
super(agentContext, "org.osgi.service.useradmin.UserAdmin");
}
/**
* @see org.apache.aries.jmx.AbstractCompendiumHandler#constructInjectMBean(java.lang.Object)
*/
@Override
protected StandardMBean constructInjectMBean(Object targetService) {
UserAdminMBean uaMBean = new UserAdmin((org.osgi.service.useradmin.UserAdmin) targetService);
StandardMBean mbean = null;
try {
mbean = new StandardMBean(uaMBean, UserAdminMBean.class);
} catch (NotCompliantMBeanException e) {
Logger logger = agentContext.getLogger();
logger.log(LogService.LOG_ERROR, "Not compliant MBean", e);
}
return mbean;
}
/**
* @see org.apache.aries.jmx.AbstractCompendiumHandler#getBaseName()
*/
public String getBaseName() {
return UserAdminMBean.OBJECTNAME;
}
}
| 8,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.