use of javax.management.InvalidAttributeValueException in project jdk8u_jdk by JetBrains.
the class RequiredModelMBean method getAttribute.
/**
* Returns the value of a specific attribute defined for this
* ModelMBean.
* The last value returned by an attribute may be cached in the
* attribute's descriptor.
* The valid value will be in the 'value' field if there is one.
* If the 'currencyTimeLimit' field in the descriptor is:
* <UL>
* <LI> <b><0</b> Then the value is not cached and is never valid.
* The getter method is invoked for the attribute.
* The 'value' and 'lastUpdatedTimeStamp' fields are cleared.</LI>
* <LI> <b>=0</b> Then the value is always cached and always valid.
* The 'value' field is returned. If there is no'value' field
* then the getter method is invoked for the attribute.
* The 'lastUpdatedTimeStamp' field and `value' fields are set
* to the attribute's value and the current time stamp.</LI>
* <LI> <b>>0</b> Represents the number of seconds that the 'value'
* field is valid.
* The 'value' field is no longer valid when
* 'lastUpdatedTimeStamp' + 'currencyTimeLimit' > Now.
* <UL>
* <LI>When 'value' is valid, 'value' is returned.</LI>
* <LI>When 'value' is no longer valid then the getter
* method is invoked for the attribute.
* The 'lastUpdatedTimeStamp' field and `value' fields
* are updated.</LI>
* </UL></LI>
* </UL>
*
* <p><b>Note:</b> because of inconsistencies in previous versions of
* this specification, it is recommended not to use negative or zero
* values for <code>currencyTimeLimit</code>. To indicate that a
* cached value is never valid, omit the
* <code>currencyTimeLimit</code> field. To indicate that it is
* always valid, use a very large number for this field.</p>
*
* <p>If the 'getMethod' field contains the name of a valid
* operation descriptor, then the method described by the
* operation descriptor is executed. The response from the
* method is returned as the value of the attribute. If the
* operation fails or the returned value is not compatible with
* the declared type of the attribute, an exception will be thrown.</p>
*
* <p>If no 'getMethod' field is defined then the default value of the
* attribute is returned. If the returned value is not compatible with
* the declared type of the attribute, an exception will be thrown.</p>
*
* <p>The declared type of the attribute is the String returned by
* {@link ModelMBeanAttributeInfo#getType()}. A value is compatible
* with this type if one of the following is true:
* <ul>
* <li>the value is null;</li>
* <li>the declared name is a primitive type name (such as "int")
* and the value is an instance of the corresponding wrapper
* type (such as java.lang.Integer);</li>
* <li>the name of the value's class is identical to the declared name;</li>
* <li>the declared name can be loaded by the value's class loader and
* produces a class to which the value can be assigned.</li>
* </ul>
*
* <p>In this implementation, in every case where the getMethod needs to
* be called, because the method is invoked through the standard "invoke"
* method and thus needs operationInfo, an operation must be specified
* for that getMethod so that the invocation works correctly.</p>
*
* @param attrName A String specifying the name of the
* attribute to be retrieved. It must match the name of a
* ModelMBeanAttributeInfo.
*
* @return The value of the retrieved attribute from the
* descriptor 'value' field or from the invocation of the
* operation in the 'getMethod' field of the descriptor.
*
* @exception AttributeNotFoundException The specified attribute is
* not accessible in the MBean.
* The following cases may result in an AttributeNotFoundException:
* <UL>
* <LI> No ModelMBeanInfo was found for the Model MBean.</LI>
* <LI> No ModelMBeanAttributeInfo was found for the specified
* attribute name.</LI>
* <LI> The ModelMBeanAttributeInfo isReadable method returns
* 'false'.</LI>
* </UL>
* @exception MBeanException Wraps one of the following Exceptions:
* <UL>
* <LI> {@link InvalidAttributeValueException}: A wrong value type
* was received from the attribute's getter method or
* no 'getMethod' field defined in the descriptor for
* the attribute and no default value exists.</LI>
* <LI> {@link ServiceNotFoundException}: No
* ModelMBeanOperationInfo defined for the attribute's
* getter method or no descriptor associated with the
* ModelMBeanOperationInfo or the managed resource is
* null.</LI>
* <LI> {@link InvalidTargetObjectTypeException} The 'targetType'
* field value is not 'objectReference'.</LI>
* <LI> An Exception thrown by the managed object's getter.</LI>
* </UL>
* @exception ReflectionException Wraps an {@link java.lang.Exception}
* thrown while trying to invoke the getter.
* @exception RuntimeOperationsException Wraps an
* {@link IllegalArgumentException}: The attribute name in
* parameter is null.
*
* @see #setAttribute(javax.management.Attribute)
**/
public Object getAttribute(String attrName) throws AttributeNotFoundException, MBeanException, ReflectionException {
if (attrName == null)
throw new RuntimeOperationsException(new IllegalArgumentException("attributeName must not be null"), "Exception occurred trying to get attribute of a " + "RequiredModelMBean");
final String mth = "getAttribute(String)";
final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER);
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Entry with " + attrName);
}
/* Check attributeDescriptor for getMethod */
Object response;
try {
if (modelMBeanInfo == null)
throw new AttributeNotFoundException("getAttribute failed: ModelMBeanInfo not found for " + attrName);
ModelMBeanAttributeInfo attrInfo = modelMBeanInfo.getAttribute(attrName);
Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor();
if (attrInfo == null)
throw new AttributeNotFoundException("getAttribute failed:" + " ModelMBeanAttributeInfo not found for " + attrName);
Descriptor attrDescr = attrInfo.getDescriptor();
if (attrDescr != null) {
if (!attrInfo.isReadable())
throw new AttributeNotFoundException("getAttribute failed: " + attrName + " is not readable ");
response = resolveForCacheValue(attrDescr);
/* return current cached value */
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "*** cached value is " + response);
}
if (response == null) {
/* no cached value, run getMethod */
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "**** cached value is null - getting getMethod");
}
String attrGetMethod = (String) (attrDescr.getFieldValue("getMethod"));
if (attrGetMethod != null) {
/* run method from operations descriptor */
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "invoking a getMethod for " + attrName);
}
Object getResponse = invoke(attrGetMethod, new Object[] {}, new String[] {});
if (getResponse != null) {
// error/validity check return value here
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "got a non-null response " + "from getMethod\n");
}
response = getResponse;
// change cached value in attribute descriptor
Object objctl = attrDescr.getFieldValue("currencyTimeLimit");
String ctl;
if (objctl != null)
ctl = objctl.toString();
else
ctl = null;
if ((ctl == null) && (mmbDesc != null)) {
objctl = mmbDesc.getFieldValue("currencyTimeLimit");
if (objctl != null)
ctl = objctl.toString();
else
ctl = null;
}
if ((ctl != null) && !(ctl.equals("-1"))) {
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "setting cached value and " + "lastUpdatedTime in descriptor");
}
attrDescr.setField("value", response);
final String stamp = String.valueOf((new Date()).getTime());
attrDescr.setField("lastUpdatedTimeStamp", stamp);
attrInfo.setDescriptor(attrDescr);
modelMBeanInfo.setDescriptor(attrDescr, "attribute");
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "new descriptor is " + attrDescr);
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "AttributeInfo descriptor is " + attrInfo.getDescriptor());
final String attStr = modelMBeanInfo.getDescriptor(attrName, "attribute").toString();
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "modelMBeanInfo: AttributeInfo " + "descriptor is " + attStr);
}
}
} else {
// response was invalid or really returned null
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "got a null response from getMethod\n");
}
response = null;
}
} else {
// not getMethod so return descriptor (default) value
String qualifier = "";
response = attrDescr.getFieldValue("value");
if (response == null) {
qualifier = "default ";
response = attrDescr.getFieldValue("default");
}
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "could not find getMethod for " + attrName + ", returning descriptor " + qualifier + "value");
}
// !! cast response to right class
}
}
// make sure response class matches type field
final String respType = attrInfo.getType();
if (response != null) {
String responseClass = response.getClass().getName();
if (!respType.equals(responseClass)) {
boolean wrongType = false;
boolean primitiveType = false;
boolean correspondingTypes = false;
for (int i = 0; i < primitiveTypes.length; i++) {
if (respType.equals(primitiveTypes[i])) {
primitiveType = true;
if (responseClass.equals(primitiveWrappers[i]))
correspondingTypes = true;
break;
}
}
if (primitiveType) {
// inequality may come from primitive/wrapper class
if (!correspondingTypes)
wrongType = true;
} else {
// inequality may come from type subclassing
boolean subtype;
try {
final Class respClass = response.getClass();
final Exception[] caughException = new Exception[1];
AccessControlContext stack = AccessController.getContext();
Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {
@Override
public Class<?> run() {
try {
ReflectUtil.checkPackageAccess(respType);
ClassLoader cl = respClass.getClassLoader();
return Class.forName(respType, true, cl);
} catch (Exception e) {
caughException[0] = e;
}
return null;
}
}, stack, acc);
if (caughException[0] != null) {
throw caughException[0];
}
subtype = c.isInstance(response);
} catch (Exception e) {
subtype = false;
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Exception: ", e);
}
}
if (!subtype)
wrongType = true;
}
if (wrongType) {
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Wrong response type '" + respType + "'");
}
// back right attribute type
throw new MBeanException(new InvalidAttributeValueException("Wrong value type received for get attribute"), "An exception occurred while trying to get an " + "attribute value through a RequiredModelMBean");
}
}
}
} else {
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "getMethod failed " + attrName + " not in attributeDescriptor\n");
}
throw new MBeanException(new InvalidAttributeValueException("Unable to resolve attribute value, " + "no getMethod defined in descriptor for attribute"), "An exception occurred while trying to get an " + "attribute value through a RequiredModelMBean");
}
} catch (MBeanException mbe) {
throw mbe;
} catch (AttributeNotFoundException t) {
throw t;
} catch (Exception e) {
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "getMethod failed with " + e.getMessage() + " exception type " + (e.getClass()).toString());
}
throw new MBeanException(e, "An exception occurred while trying " + "to get an attribute value: " + e.getMessage());
}
if (tracing) {
MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Exit");
}
return response;
}
use of javax.management.InvalidAttributeValueException in project oxTrust by GluuFederation.
the class ScimResourceUtil method deleteFromResource.
/**
* Returns a SCIM resource with the same data found in <code>origin</code> object, except for the attribute referenced
* by <code>path</code> being removed from the output. In other words, this method nullifies an attribute.
* @param origin The resource having the the original data
* @param path An attribute path (in dot notation). Examples could be: <code>displayName, emails.type, addresses,
* meta.lastModified</code>.
* @param extensions A list of <code>Extension</code>s associated to <code>origin</code> Object
* @return The resulting object: data in origin without the attribute referenced by <code>path</code>
* @throws InvalidAttributeValueException If there is an attempt to remove an attribute annotated as {@link Attribute#isRequired()
* required} or {@link org.gluu.oxtrust.model.scim2.AttributeDefinition.Mutability#READ_ONLY read-only}
*/
public static BaseScimResource deleteFromResource(BaseScimResource origin, String path, List<Extension> extensions) throws InvalidAttributeValueException {
Field f = IntrospectUtil.findFieldFromPath(origin.getClass(), path);
if (f != null) {
Attribute attrAnnot = f.getAnnotation(Attribute.class);
if (attrAnnot != null && (attrAnnot.mutability().equals(READ_ONLY) || attrAnnot.isRequired()))
throw new InvalidAttributeValueException("Cannot remove read-only or required attribute " + path);
}
Map<String, Object> map = mapper.convertValue(origin, new TypeReference<Map<String, Object>>() {
});
traversalClass tclass = new traversalClass(origin.getClass());
if (// Extensions stuff
f == null)
deleteCustomAttribute(map, path, extensions);
else
tclass.traverseDelete(map, path);
return mapper.convertValue(map, origin.getClass());
}
use of javax.management.InvalidAttributeValueException in project oxTrust by GluuFederation.
the class FidoDeviceWebService method updateDevice.
@Path("{id}")
@PUT
@Consumes({ MEDIA_TYPE_SCIM_JSON, MediaType.APPLICATION_JSON })
@Produces({ MEDIA_TYPE_SCIM_JSON + UTF8_CHARSET_FRAGMENT, MediaType.APPLICATION_JSON + UTF8_CHARSET_FRAGMENT })
@HeaderParam("Accept")
@DefaultValue(MEDIA_TYPE_SCIM_JSON)
@ProtectedApi
@RefAdjusted
@ApiOperation(value = "Update device", response = FidoDeviceResource.class)
public Response updateDevice(FidoDeviceResource fidoDeviceResource, @PathParam("id") String id, @QueryParam(QUERY_PARAM_ATTRIBUTES) String attrsList, @QueryParam(QUERY_PARAM_EXCLUDED_ATTRS) String excludedAttrsList) {
Response response;
try {
log.debug("Executing web service method. updateDevice");
String userId = fidoDeviceResource.getUserId();
GluuCustomFidoDevice device = fidoDeviceService.getGluuCustomFidoDeviceById(userId, id);
if (device == null)
throw new SCIMException("Resource " + id + " not found");
FidoDeviceResource updatedResource = new FidoDeviceResource();
transferAttributesToFidoResource(device, updatedResource, endpointUrl, userId);
long now = System.currentTimeMillis();
updatedResource.getMeta().setLastModified(ISODateTimeFormat.dateTime().withZoneUTC().print(now));
updatedResource = (FidoDeviceResource) ScimResourceUtil.transferToResourceReplace(fidoDeviceResource, updatedResource, extService.getResourceExtensions(updatedResource.getClass()));
transferAttributesToDevice(updatedResource, device);
fidoDeviceService.updateGluuCustomFidoDevice(device);
String json = resourceSerializer.serialize(updatedResource, attrsList, excludedAttrsList);
response = Response.ok(new URI(updatedResource.getMeta().getLocation())).entity(json).build();
} catch (SCIMException e) {
log.error(e.getMessage());
response = getErrorResponse(Response.Status.NOT_FOUND, ErrorScimType.INVALID_VALUE, e.getMessage());
} catch (InvalidAttributeValueException e) {
log.error(e.getMessage());
response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.MUTABILITY, e.getMessage());
} catch (Exception e) {
log.error("Failure at updateDevice method", e);
response = getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Unexpected error: " + e.getMessage());
}
return response;
}
use of javax.management.InvalidAttributeValueException in project oxTrust by GluuFederation.
the class UserWebService method patchUser.
@Path("{id}")
@PATCH
@Consumes({ MEDIA_TYPE_SCIM_JSON, MediaType.APPLICATION_JSON })
@Produces({ MEDIA_TYPE_SCIM_JSON + UTF8_CHARSET_FRAGMENT, MediaType.APPLICATION_JSON + UTF8_CHARSET_FRAGMENT })
@HeaderParam("Accept")
@DefaultValue(MEDIA_TYPE_SCIM_JSON)
@ProtectedApi
@RefAdjusted
@ApiOperation(value = "PATCH operation", notes = "https://tools.ietf.org/html/rfc7644#section-3.5.2", response = UserResource.class)
public Response patchUser(PatchRequest request, @PathParam("id") String id, @QueryParam(QUERY_PARAM_ATTRIBUTES) String attrsList, @QueryParam(QUERY_PARAM_EXCLUDED_ATTRS) String excludedAttrsList) {
Response response;
try {
log.debug("Executing web service method. patchUser");
UserResource user = new UserResource();
// person is not null (check associated decorator method)
GluuCustomPerson person = personService.getPersonByInum(id);
// Fill user instance with all info from person
scim2UserService.transferAttributesToUserResource(person, user, endpointUrl);
// Apply patches one by one in sequence
for (PatchOperation po : request.getOperations()) {
// Handle special case: https://github.com/GluuFederation/oxTrust/issues/800
if (po.getType().equals(REMOVE) && po.getPath().equals("pairwiseIdentitifers")) {
// If this block weren't here, the implementation will throw error because read-only attribute cannot be altered
// Note the path is intentionally mistyped, see class member in UserResource
person.setOxPPID(null);
user.setPairwiseIdentitifers(null);
scim2UserService.removePPIDsBranch(person.getDn());
} else
user = (UserResource) scim2PatchService.applyPatchOperation(user, po);
}
// Throws exception if final representation does not pass overall validation
log.debug("patchUser. Revising final resource representation still passes validations");
executeDefaultValidation(user);
ScimResourceUtil.adjustPrimarySubAttributes(user);
// Update timestamp
String now = ISODateTimeFormat.dateTime().withZoneUTC().print(System.currentTimeMillis());
user.getMeta().setLastModified(now);
// Replaces the information found in person with the contents of user
scim2UserService.replacePersonInfo(person, user, endpointUrl);
String json = resourceSerializer.serialize(user, attrsList, excludedAttrsList);
response = Response.ok(new URI(user.getMeta().getLocation())).entity(json).build();
} catch (InvalidAttributeValueException e) {
log.error(e.getMessage(), e);
response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.MUTABILITY, e.getMessage());
} catch (SCIMException e) {
response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.INVALID_SYNTAX, e.getMessage());
} catch (Exception e) {
log.error("Failure at patchUser method", e);
response = getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Unexpected error: " + e.getMessage());
}
return response;
}
use of javax.management.InvalidAttributeValueException in project oxTrust by GluuFederation.
the class UserWebService method updateUser.
/**
* This implementation differs from spec in the following aspects:
* - Passing a null value for an attribute, does not modify the attribute in the destination, however passing an
* empty array for a multivalued attribute does clear the attribute. Thus, to clear single-valued attribute, PATCH
* operation should be used
*/
@Path("{id}")
@PUT
@Consumes({ MEDIA_TYPE_SCIM_JSON, MediaType.APPLICATION_JSON })
@Produces({ MEDIA_TYPE_SCIM_JSON + UTF8_CHARSET_FRAGMENT, MediaType.APPLICATION_JSON + UTF8_CHARSET_FRAGMENT })
@HeaderParam("Accept")
@DefaultValue(MEDIA_TYPE_SCIM_JSON)
@ProtectedApi
@RefAdjusted
@ApiOperation(value = "Update user", notes = "Update user (https://tools.ietf.org/html/rfc7644#section-3.5.1)", response = UserResource.class)
public Response updateUser(@ApiParam(value = "User", required = true) UserResource user, @PathParam("id") String id, @QueryParam(QUERY_PARAM_ATTRIBUTES) String attrsList, @QueryParam(QUERY_PARAM_EXCLUDED_ATTRS) String excludedAttrsList) {
Response response;
try {
log.debug("Executing web service method. updateUser");
UserResource updatedResource = scim2UserService.updateUser(id, user, endpointUrl);
String json = resourceSerializer.serialize(updatedResource, attrsList, excludedAttrsList);
response = Response.ok(new URI(updatedResource.getMeta().getLocation())).entity(json).build();
} catch (InvalidAttributeValueException e) {
log.error(e.getMessage());
response = getErrorResponse(Response.Status.BAD_REQUEST, ErrorScimType.MUTABILITY, e.getMessage());
} catch (Exception e) {
log.error("Failure at updateUser method", e);
response = getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Unexpected error: " + e.getMessage());
}
return response;
}
Aggregations